{"version":3,"file":"forge.cjs","names":[],"sources":["../../../src/batteries/orchestration/forge.ts"],"sourcesContent":["/**\n * The model-facing tool forge for the orchestration battery.\n *\n * @module @nhtio/adk/batteries/orchestration/forge\n *\n * @remarks\n * This file is the ONLY place the wire↔IR conversion happens, and the ONLY place a model-facing\n * tool is constructed for orchestration. A tool call cannot transmit a class instance, so on the\n * wire a reference is `{$ref: {node, select, path?, branchId?}}` and a template hole is\n * `{$param: {path}}` — single-key wrappers whose keys are RESERVED — and the IR uses real\n * {@link NodeRef}/{@link ParamRef} instances. {@link hydrateRefs} converts wire→IR on the way in\n * and {@link dehydrateRefs} converts IR→wire on the way out, so a model reading a plan back sees\n * the same `$ref`/`$param` shape it writes. Nothing else in the battery ever sees the wire form.\n *\n * Three surfaces, three threat models:\n *\n * - **Tier A — `'front'`**, what a conversational agent sees: `list_templates`,\n *   `instantiate_plan`, `author_plan`. The from-scratch path passes the owner's request VERBATIM\n *   and UNPARSED — pre-parsing their words into categories is what discarded\n *   \"at the Holly Springs Walgreens\" in the prior art — and every return is RENDERED PROSE, never\n *   raw JSON, because a model that re-reads its own JSON echo tends to re-plan rather than\n *   continue.\n * - **Tier B — `'authoring'`**, graph mechanics, exposed only inside an authoring sub-dispatch:\n *   `create_plan`, `add_node`, `set_node_config`, `connect_nodes`, `remove_node`,\n *   `disconnect_edge`, `clone_plan`, `get_plan`, `validate_plan`, `freeze_plan`,\n *   `unfreeze_plan`, `submit_plan`, `plan_status`, `raw_plan`, `raw_diff`, plus the scoped\n *   reading pair `plan_outline` / `plan_read`.\n * - **Tier C is NOT a tool tier** — it is `runtime.invocable`, the allowlist of what a staged\n *   `call` may invoke. Deliberately separate from the agent's tool surface: adding an agent tool\n *   never adds it here. The allowlist and the registry are the SAME object — the prior art's\n *   worst wart was ten names listed against a registry with zero callers, so author-time\n *   validation passed and fire-time threw \"not registered\". There is no second list.\n *\n * Mutation tools return SCOPED PROSE, not the whole projected plan. The prior art returned\n * everything so the model always re-read current state; that was written for a large window and\n * is precisely the context problem here — 40 nodes echoed on every edit. Each mutation returns\n * what changed, what it now connects to, and any new issues, BOUNDED regardless of plan size.\n *\n * `submit_plan`/`freeze_plan` call {@link freezePlan} and surface each refusal with its\n * model-addressed message. The prior art's \"the dry run produced no finding\" refusal is ABSENT —\n * there is no dry run — and the reachability plus unedited-placeholder checks carry the weight it\n * used to.\n */\n\n// This file constructs `Tool`, the documented CONTRIBUTING §13 exception for a battery whose job\n// is to mint model-facing tool instances. See CONTRIBUTING.md §13 \"Battery design — no concrete\n// core-class coupling\": `src/batteries/tools/**` and `src/batteries/orchestration/forge.ts` (by\n// analogy with `media/forge.ts` and `dispatch_reasoner.ts`) construct `Tool` because a tool\n// genuinely IS a core `Tool` instance and there is no lesser-coupled representation. That is why\n// this module sits at its own subpath rather than in the battery barrel.\nimport { renderPlan } from './render'\nimport { validator } from '@nhtio/validation'\nimport { NodeRef, ParamRef } from './encoding'\nimport { rawPlan, rawOps, rawDiff } from './raw'\nimport { planOutline, planRead } from './outline'\nimport { freezePlan, collectIssues } from './validation'\nimport { Tool, SpooledJsonArtifact } from '@nhtio/adk/common'\nimport { approvePlan, computeAuthoritySet } from './approval'\nimport { isObject, isInstanceOf } from '../../lib/utils/guards'\nimport { runToolGate } from '@nhtio/adk/batteries/tools/_shared'\nimport { validateTemplate, instantiateTemplate } from './templates'\nimport type { PlanStore } from './store'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { InvocableTools, PredicateEvaluator } from './types'\nimport type { ToolGateFn } from '@nhtio/adk/batteries/tools/_shared'\nimport type {\n  PlanTemplate,\n  PlanOp,\n  PlanNode,\n  PlanEdge,\n  PlanNodeKind,\n  EdgeHandle,\n  NodeId,\n  PlanId,\n  PlanIssue,\n  AuthorityClaim,\n  ApprovalRecord,\n  RawPlanView,\n  PlanBounds,\n  EncodableValue,\n  ArgValue,\n} from './types'\n\n// ─── the reserved wire keys ──────────────────────────────────────────────────\n/** The single reserved wire key for a node-output reference. A wire `{$ref: {...}}` hydrates to a {@link NodeRef}. */\nconst REF_KEY = '$ref'\n/** The single reserved wire key for a template hole. A wire `{$param: {...}}` hydrates to a {@link ParamRef}. */\nconst PARAM_KEY = '$param'\n\n/** The exact node kinds a plan may carry. Frozen here so the vocabulary a model reads is the vocabulary the fold accepts. */\nconst NODE_KINDS = [\n  'entry',\n  'call',\n  'reason',\n  'transform',\n  'branch',\n  'select',\n  'join',\n] as const satisfies readonly PlanNodeKind[]\n\n/** The edge handles a model may write, grouped by the source node kind they apply to — frozen so the grammar is never guessed. */\nconst HANDLES_BY_KIND: Record<PlanNodeKind, readonly EdgeHandle[]> = {\n  entry: ['always'],\n  call: ['always', 'error'],\n  reason: ['always', 'error'],\n  transform: ['always', 'error'],\n  branch: ['match', 'no_match', 'default', 'error'],\n  select: ['default', 'error'],\n  join: ['always', 'error'],\n}\n\n/**\n * The graph-grammar vocabulary appended to every relevant tool description, so a model never\n * guesses a node kind, edge handle, or node-kind→handle applicability rule. Generated from the\n * same `NODE_KINDS` / `HANDLES_BY_KIND` tables the fold and freeze enforce, so it cannot drift\n * from either.\n */\nconst NODE_VOCABULARY = [\n  '',\n  'NODE GRAMMAR — the only node kinds are: ' + NODE_KINDS.join(', ') + '.',\n  'EDGE HANDLES — the handle an edge may carry depends on its source node kind:',\n  ...NODE_KINDS.map((k) => `  · ${k} → ${HANDLES_BY_KIND[k].join(' | ')}`),\n  'A `select` node requires a `default` edge. On a node settling, every edge whose handle applies',\n  'to that outcome fires once; on a FAILURE only `error` edges fire (`always` is a success-path edge,',\n  'not a finally). Node ids are snake_case (no `/`, no leading `.`); edge ids match',\n  '/^[A-Za-z0-9_-]{1,64}$/. References are written on the wire as {\"$ref\":{\"node\",\"select\",\"path?\",\"branchId?\"}}',\n  'and template holes as {\"$param\":{\"path\"}} — the `$ref`/`$param` keys are reserved.',\n].join('\\n')\n\n// ─── wire↔IR conversion ──────────────────────────────────────────────────────\n/**\n * The wire form of a {@link NodeRef}: a single-key wrapper whose key is the reserved `$ref`.\n *\n * @remarks\n * This is a tool-input shape; it never appears in the IR. {@link hydrateRefs} rebuilds a real\n * {@link NodeRef} instance from it, and {@link dehydrateRefs} emits it from one.\n */\ntype WireNodeRef = {\n  [REF_KEY]: { node: NodeId; select: NodeRef['select']; path?: string; branchId?: unknown }\n}\n/**\n * The wire form of a {@link ParamRef}: a single-key wrapper whose key is the reserved `$param`.\n */\ntype WireParamRef = { [PARAM_KEY]: { path: string } }\n\n/** True when `value` is the wire form of a {@link NodeRef} — exactly the one reserved key. */\nconst isWireNodeRef = (value: unknown): value is WireNodeRef =>\n  isObject(value) &&\n  Object.keys(value).length === 1 &&\n  Object.prototype.hasOwnProperty.call(value, REF_KEY) &&\n  isObject((value as Record<string, unknown>)[REF_KEY])\n\n/** True when `value` is the wire form of a {@link ParamRef} — exactly the one reserved key. */\nconst isWireParamRef = (value: unknown): value is WireParamRef =>\n  isObject(value) &&\n  Object.keys(value).length === 1 &&\n  Object.prototype.hasOwnProperty.call(value, PARAM_KEY) &&\n  isObject((value as Record<string, unknown>)[PARAM_KEY])\n\n/**\n * Rebuild a real {@link NodeRef} instance from its wire form, carrying `branchId` through\n * unchanged (it is itself an encodable record on the wire — the IR type is structural).\n */\nconst hydrateNodeRef = (w: WireNodeRef): NodeRef => {\n  const b = w[REF_KEY]\n  return new NodeRef(b.node, b.select, b.path, b.branchId as NodeRef['branchId'])\n}\n\n/** Rebuild a real {@link ParamRef} instance from its wire form. */\nconst hydrateParamRef = (w: WireParamRef): ParamRef => new ParamRef(w[PARAM_KEY].path)\n\n/**\n * Recursively convert wire references to IR instances throughout a value.\n *\n * @remarks\n * Walks plain-object/array spines only; every other value (a `Date`, `RegExp`, `Map`, typed\n * array, bigint, …) rides through unchanged, the same distinction `encoding.ts`'s\n * `isPlainObject` makes. A `{$ref:…}` becomes a {@link NodeRef}, a `{$param:…}` becomes a\n * {@link ParamRef}; a plain object that merely LOOKS like a reference but carries extra keys is\n * left alone, because the reserved keys are single-key wrappers by contract.\n *\n * @param value - The wire value to hydrate.\n * @returns The IR value, with references rebuilt as real class instances.\n */\n/**\n * True for a PLAIN object — prototype `Object.prototype` or `null`.\n *\n * @remarks\n * The same distinction `ops.ts`'s spine copy and `encoding.ts`'s digest sort already make, and it\n * is here for the same reason: `isObject` is true for `Date`, `Map`, `Set`, `RegExp` and typed\n * arrays, so rebuilding \"an object\" from `Object.keys` flattens every one of them. A `Date` has no\n * enumerable own keys, so it comes back `{}` — the staged argument is simply gone.\n */\nconst isPlainRecord = (v: unknown): v is Record<string, unknown> => {\n  if (v === null || typeof v !== 'object') return false\n  const proto = Object.getPrototypeOf(v)\n  return proto === Object.prototype || proto === null\n}\n\nconst hydrateRefs = (value: unknown): unknown => {\n  if (Array.isArray(value)) return value.map(hydrateRefs)\n  if (isWireNodeRef(value)) return hydrateNodeRef(value)\n  if (isWireParamRef(value)) return hydrateParamRef(value)\n  if (isPlainRecord(value)) {\n    // A PLAIN record — rebuild a fresh one so a caller's input is never mutated. The guard must\n    // be `isPlainRecord` rather than `isObject`: the latter is true for `Date`/`Map`/`Set`/\n    // `RegExp`/typed arrays, and rebuilding those from `Object.keys` returns `{}` — the staged\n    // value silently erased on its way into the plan.\n    const out: Record<string, unknown> = {}\n    for (const key of Object.keys(value)) out[key] = hydrateRefs(value[key])\n    return out\n  }\n  // Encoder-owned (or primitive) — pass through UNTOUCHED so the encoder can serialise it\n  // faithfully and the plan digest stays lossless.\n  return value\n}\n\n/**\n * Recursively convert IR reference instances back to their wire form throughout a value.\n *\n * @remarks\n * The inverse of {@link hydrateRefs}: a {@link NodeRef} becomes `{$ref:…}`, a {@link ParamRef}\n * becomes `{$param:…}`, and everything else rides through. Used on the way OUT so a model\n * reading a plan back sees the same `$ref`/`$param` shape it writes.\n *\n * @param value - The IR value to dehydrate.\n * @returns The wire value, with references emitted as single-key wrappers.\n */\nconst dehydrateRefs = (value: unknown): unknown => {\n  if (Array.isArray(value)) return value.map(dehydrateRefs)\n  if (isInstanceOf(value, 'NodeRef', NodeRef)) {\n    const r = value as NodeRef\n    return { [REF_KEY]: { node: r.node, select: r.select, path: r.path, branchId: r.branchId } }\n  }\n  if (isInstanceOf(value, 'ParamRef', ParamRef)) {\n    return { [PARAM_KEY]: { path: (value as ParamRef).path } }\n  }\n  if (isPlainRecord(value)) {\n    const out: Record<string, unknown> = {}\n    for (const key of Object.keys(value)) out[key] = dehydrateRefs(value[key])\n    return out\n  }\n  // Same rule as the inbound path: an encoder-owned value is handed back as it is. Rebuilding a\n  // `Date` or `Map` from `Object.keys` here would show the model `{}` for a value the plan really\n  // holds — a plan that reads back differently from what it contains.\n  return value\n}\n\n// ─── op identity ─────────────────────────────────────────────────────────────\n/** Distributive `Omit` over a union. A non-distributive `Omit<PlanOp, …>` collapses the union and\n *  loses every per-variant payload field (`node`/`edge`/`nodeId`/…); this form distributes because\n *  its conditional is over a naked type parameter `T`, which TS distributes over a union when the\n *  alias is instantiated with one. */\ntype DistributiveOmit<T, K extends keyof T> = T extends any ? Omit<T, K> : never\n/** The payload of a `PlanOp` minus its identity keys — a union with one member per op variant. */\ntype OpBody = DistributiveOmit<PlanOp, 'opId' | 'actorId' | 'lamport' | 'at'>\n\n/**\n * Mint a single authoring op under the forge's actor identity, with a monotonic lamport and a\n * unique op id.\n *\n * @remarks\n * The fold orders ops by `(lamport, actorId, opId)` and applies them last-writer-wins, so each\n * op needs a unique `opId` even at the same lamport. The lamport is seeded from the plan's\n * current revision (`revision + 1`) so a fresh op always sorts after every folded op for this\n * actor — a single-author forge tool is the common case, and the multi-writer CRDT case is the\n * store's concern, not the forge's.\n *\n * The `body` parameter is typed as a generic `T extends PlanOp` so the call site's literal\n * (`{ op: 'add_node', node }`, `{ op: 'remove_edge', edgeId }`, …) is checked against the\n * matching `PlanOp` union member directly. A non-generic `Omit<PlanOp, 'opId'|…>` parameter would\n * collapse the union and reject every payload field (`node`/`edge`/`nodeId`/…), so the op body\n * could not be expressed as a literal at all.\n *\n * @param store - The plan store holding the plan (unused at the mint site; kept for symmetry\n *   with the read helpers and so a subclass could override).\n * @param planId - The plan to append to.\n * @param actorId - The identity under which the op is authored.\n * @param revision - The plan's current revision, used to seed the lamport.\n * @param body - The op payload (everything except `opId`/`actorId`/`lamport`/`at`).\n * @returns The minted op.\n */\nconst mintOp = (\n  store: PlanStore,\n  planId: PlanId,\n  actorId: string,\n  revision: number,\n  body: OpBody\n): PlanOp => {\n  void store\n  void planId\n  const lamport = revision + 1\n  const opId = `${actorId}:${planId}:${lamport}:${crypto.randomUUID()}`\n  return {\n    opId,\n    actorId,\n    lamport,\n    at: new Date().toISOString(),\n    ...body,\n  } as unknown as PlanOp\n}\n\n/**\n * Read the plan's current revision (the number of folded ops), seeding op lamports from it.\n *\n * @remarks\n * A fresh plan is at revision 0; the first authoring op makes revision 1. Used so each minted op\n * sorts after every folded op for this actor.\n */\nconst currentRevision = async (store: PlanStore, planId: PlanId): Promise<number> => {\n  const state = await store.readState(planId)\n  return state.revision\n}\n\n// ─── prose helpers ───────────────────────────────────────────────────────────\n/** Render a plan as model-audience, as-planned prose. */\nconst renderModel = (view: RawPlanView): string =>\n  renderPlan(view, { audience: 'model', view: 'as_planned' })\n\n/** Render a plan as operator-audience, as-planned prose — the approval-gate view. */\nconst renderOperator = (view: RawPlanView): string =>\n  renderPlan(view, { audience: 'operator', view: 'as_planned' })\n\n/** Format a non-empty issue list as prose; an empty list yields a clean confirmation line. */\nconst renderIssues = (issues: readonly PlanIssue[]): string => {\n  if (issues.length === 0) return 'No issues.'\n  const lines = issues.map((i) => {\n    const where = i.nodeId ? ` [node ${i.nodeId}]` : i.edgeId ? ` [edge ${i.edgeId}]` : ''\n    return `  · (${i.severity}) ${i.code}${where}: ${i.message}`\n  })\n  return `Issues (${issues.length}):\\n${lines.join('\\n')}`\n}\n\n/**\n * Render a BOUNDED slice of a plan around a focal node id, plus its immediate neighbours and any\n * new issues — the scoped-prose return shape every mutation tool uses.\n *\n * @remarks\n * The prior art returned the whole projected plan on every edit so the model always re-read\n * current state; that was written for a large window and is precisely the context problem here.\n * This returns the focal node's slice (via the outline reader's self-locating slice), its\n * immediate predecessors and successors, and the plan's issues — BOUNDED regardless of plan size.\n *\n * @param store - The plan store holding the plan.\n * @param planId - The plan to read.\n * @param focal - The node id the edit touched, if any. Omitted renders the outline plus issues.\n * @returns The scoped prose.\n */\nconst renderScoped = async (store: PlanStore, planId: PlanId, focal?: NodeId): Promise<string> => {\n  if (focal !== undefined) {\n    try {\n      const slice = await planRead(store, planId, { node: focal })\n      const view = await rawPlan(store, planId)\n      const head = `Plan ${planId} (rev ${view.revision}) — changed node ${focal}.`\n      const neighbours =\n        `Predecessors: ${slice.boundary.incoming.join(', ') || '(none)'}. ` +\n        `Successors: ${slice.boundary.outgoing.join(', ') || '(none)'}.`\n      const body = renderModel({ ...view, nodes: slice.nodes })\n      return [head, neighbours, body, renderIssues(slice.issues)].join('\\n\\n')\n    } catch {\n      // The focal node is no longer present (a removal, or a rename in the same op batch) — fall\n      // through to the outline view, which is always well-defined.\n    }\n  }\n  const outline = await planOutline(store, planId)\n  const view = await rawPlan(store, planId)\n  const head = `Plan ${planId} (rev ${view.revision}, ${outline.nodeCount} node(s)).`\n  const phases = outline.phases\n    .concat(outline.unphased ? [outline.unphased] : [])\n    .map((p) => `  · ${p.phase || '(unphased)'}: ${p.summary} [${p.nodeIds.join(', ')}]`)\n    .join('\\n')\n  return [head, phases, renderIssues(view.digest ? [] : [])].join('\\n\\n')\n}\n\n// ─── schemas ─────────────────────────────────────────────────────────────────\n/** A declared-field schema (the entry/call/transform `output` and entry `input` element shape). */\nconst declaredFieldSchema = validator.alternatives(\n  validator\n    .object({\n      path: validator.string().required(),\n      type: validator.string().valid('string').required(),\n      maxBytes: validator.number().integer().min(1).optional(),\n    })\n    .unknown(false),\n  validator\n    .object({\n      path: validator.string().required(),\n      type: validator.string().valid('number').required(),\n    })\n    .unknown(false),\n  validator\n    .object({\n      path: validator.string().required(),\n      type: validator.string().valid('boolean').required(),\n    })\n    .unknown(false),\n  validator\n    .object({\n      path: validator.string().required(),\n      type: validator.string().valid('enum').required(),\n      values: validator.array().items(validator.string().required()).min(1).required(),\n    })\n    .unknown(false)\n)\n\n/**\n * A schema for an open staged-value field — `args`, `predicate`, a transform step's `args`, or a\n * prompt part's value — where the value may hold a `NodeRef`/`ParamRef` (on the wire, a\n * `{$ref}`/`{$param}` wrapper) and the closed-shape check is freeze's job, not the schema's.\n *\n * @remarks\n * The `adk/require-validator-any-required` rule is satisfied by `.required()`: a staged value must\n * be present, and its internal shape is validated at freeze against the node kind's contract.\n */\n\nconst openValueSchema = validator.any().required()\n\n/** A `PromptPart[]` schema: each item is `{text}` or a `{$ref}` wrapper (the wire form of a `NodeRef`). */\nconst promptPartsSchema = validator\n  .array()\n  .items(\n    validator.alternatives(\n      validator.object({ text: validator.string().required() }).unknown(false).required(),\n\n      validator\n        .object()\n        .pattern(new RegExp(`^${REF_KEY}$`), validator.object().unknown(true).required())\n        .unknown(false)\n        .required()\n    )\n  )\n  .required()\n\n/** The seven exact node-definition schemas, keyed by kind, composed into the closed alternatives. */\nconst nodeDefinitionSchemas: Record<PlanNodeKind, ReturnType<typeof validator.any>> = {\n  entry: validator\n    .object({ input: validator.array().items(declaredFieldSchema).required() })\n    .unknown(false)\n    .required(),\n  call: validator\n    .object({\n      tool: validator.string().required(),\n      args: validator.object().unknown(true).required(),\n      output: validator.array().items(declaredFieldSchema).required(),\n      onMissingValue: validator.string().valid('fail', 'omit').required(),\n      authority: validator\n        .array()\n        .items(\n          validator\n            .object({\n              capability: validator.string().required(),\n              scope: validator.string().required(),\n              verb: validator\n                .string()\n                .valid('list', 'read', 'create', 'update', 'delete')\n                .required(),\n            })\n            .unknown(false)\n            .required()\n        )\n        .required(),\n      replaySafe: validator.boolean().required(),\n      onIndeterminate: validator.string().valid('retry', 'halt', 'skip').required(),\n      declassifies: validator.array().items(validator.string().required()).optional(),\n    })\n    .unknown(false)\n    .required(),\n  reason: validator\n    .object({\n      prompt: promptPartsSchema,\n      outputSchema: validator.string().required(),\n      maxAttempts: validator.number().integer().min(1).required(),\n    })\n    .unknown(false)\n    .required(),\n  transform: validator\n    .object({\n      source: validator\n        .object()\n        .pattern(new RegExp(`^${REF_KEY}$`), validator.object().unknown(true).required())\n        .unknown(false)\n        .required(),\n      steps: validator\n        .array()\n        .items(\n          validator\n            .object({\n              name: validator.string().required(),\n              args: validator.object().unknown(true).optional(),\n            })\n            .unknown(false)\n            .required()\n        )\n        .required(),\n      emit: validator\n        .alternatives(\n          validator\n            .object({\n              as: validator.string().valid('value').required(),\n              field: validator.string().required(),\n            })\n            .unknown(false)\n            .required(),\n          validator\n            .object({ as: validator.string().valid('rows').required() })\n            .unknown(false)\n            .required()\n        )\n        .required(),\n      output: validator.array().items(declaredFieldSchema).required(),\n    })\n    .unknown(false)\n    .required(),\n  branch: validator\n    .object({\n      evaluator: validator.string().required(),\n      predicate: openValueSchema,\n    })\n    .unknown(false)\n    .required(),\n  select: validator\n    .object({\n      evaluator: validator.string().required(),\n      predicate: openValueSchema,\n      cases: validator.array().items(validator.string().required()).required(),\n    })\n    .unknown(false)\n    .required(),\n  join: validator\n    .object({ kind: validator.string().valid('diamond').optional() })\n    .unknown(false)\n    .required(),\n}\n\n/**\n * The CLOSED ALTERNATIVES schema for `set_node_config`'s `definition`: a node definition can only\n * be one of the seven exact node shapes, and unknown keys per kind are rejected (`.unknown(false)`\n * on every branch). The `kind` discriminator is required and closed over `NODE_KINDS`.\n */\nconst nodeDefinitionAlternatives = validator.alternatives(\n  ...NODE_KINDS.map((kind) =>\n    validator\n      .object({\n        kind: validator.string().valid(kind).required(),\n        definition: nodeDefinitionSchemas[kind],\n      })\n      .unknown(false)\n  )\n)\n\n/** A whole `PlanNode` schema: id, optional phase, and the closed kind/definition alternatives. */\nconst planNodeSchema = validator\n  .object({\n    id: validator\n      .string()\n      .pattern(/^[a-z0-9_]+$/)\n      .required(),\n    phase: validator.string().optional(),\n    kind: validator\n      .string()\n      .valid(...NODE_KINDS)\n      .required(),\n    definition: validator.any().required(),\n  })\n  .unknown(false)\n\n/** A `PlanEdge` schema with the edge-id charset rule freeze enforces. */\nconst planEdgeSchema = validator.object({\n  id: validator\n    .string()\n    .pattern(/^[A-Za-z0-9_-]{1,64}$/)\n    .required(),\n  from: validator.string().required(),\n  to: validator.string().required(),\n  handle: validator.string().required(),\n})\n\n// ─── the forge ───────────────────────────────────────────────────────────────\n/** The runtime a forge call is handed: the store, the tier-C allowlist, the wired predicate cells, and any registered templates. */\nexport interface ForgeOrchestrationRuntime {\n  /** The plan store all tools read and mutate. */\n  store: PlanStore\n  /** The tier-C allowlist a staged `call` may invoke — the SAME object the tool registry is, never a second list. */\n  invocable: InvocableTools\n  /** The wired predicate cells; a needed-but-absent cell refuses at freeze. */\n  evaluators: PredicateEvaluator[]\n  /** Consumer-defined plan shapes a model can instantiate. */\n  templates?: PlanTemplate[]\n  /** The identity under which minted ops are authored. */\n  actorId: string\n}\n\n/** Tier selection and optional per-tool overrides + a mutating-tool gate. */\nexport interface ForgeOrchestrationOptions {\n  /** `'front'` for the conversational surface, `'authoring'` for the graph-mechanics surface. */\n  tier: 'front' | 'authoring'\n  /** Optional names and descriptions keyed by their default tool name. */\n  overrides?: Record<string, { name?: string; description?: string }>\n  /** Optional gate run before any MUTATING tool executes. Throwing aborts the call. */\n  gate?: ToolGateFn\n}\n\n/**\n * Forge the model-facing orchestration tools for a configured runtime and tier.\n *\n * @remarks\n * Returns a `Record<string, Tool>` keyed by the (post-override) tool name. Tier A (`'front'`)\n * yields the three conversational tools; tier B (`'authoring'`) yields the graph-mechanics tools.\n * Tier C is `runtime.invocable`, not a tool tier, and is the SAME object the tool registry is.\n *\n * Where a `gate` is supplied it is run via {@link runToolGate} before any MUTATING tool executes;\n * read-only tools are not gated. The wire↔IR conversion ({@link hydrateRefs}/\n * {@link dehydrateRefs}) happens inside this function and nowhere else.\n *\n * @param runtime - The store, tier-C allowlist, predicate cells, templates, and actor identity.\n * @param options - Tier, per-tool overrides, and an optional mutating-tool gate.\n * @returns The forged tools, keyed by name.\n */\nexport function forgeOrchestrationTools(\n  runtime: ForgeOrchestrationRuntime,\n  options: ForgeOrchestrationOptions\n): Record<string, Tool> {\n  const { store, invocable, evaluators, templates, actorId } = runtime\n  const { tier, overrides, gate } = options\n  const tools: Record<string, Tool> = {}\n\n  /**\n   * Register a tool under its default name, applying any override and appending the\n   * {@link NODE_VOCABULARY} to the description so the graph grammar is never guessed.\n   */\n  const make = (\n    defaultName: string,\n    description: string,\n    schema: ReturnType<typeof validator.object> | ReturnType<typeof validator.any>,\n    handler: (args: Record<string, unknown>, context: DispatchContext) => Promise<string>,\n    mutating: boolean\n  ): void => {\n    const override = overrides?.[defaultName]\n    const name = override?.name ?? defaultName\n    const doc = `${description}${NODE_VOCABULARY}`\n    const tool = new Tool({\n      name,\n      description: override?.description ?? doc,\n      inputSchema: schema,\n      artifactConstructor: () => SpooledJsonArtifact,\n      handler: async (args, context) => {\n        if (mutating && gate) {\n          await runToolGate(gate, context, name, args)\n        }\n        return handler(args as Record<string, unknown>, context as DispatchContext)\n      },\n    })\n    tools[name] = tool\n  }\n\n  // ─── Tier A: front ────────────────────────────────────────────────────────\n  if (tier === 'front') {\n    make(\n      'list_templates',\n      'List the registered plan templates — id, one-line summary, and declared params for each. ' +\n        'Cheap and always safe; the natural first move for \"is there already a shape for this?\".',\n      validator.object({}).unknown(false),\n      async () => {\n        const list = templates ?? []\n        if (list.length === 0) {\n          return 'No plan templates are registered. Use author_plan to build a plan from scratch.'\n        }\n        const lines = list.map((tpl) => {\n          const params = tpl.params\n            .map(\n              (p) => `${p.path}: ${p.type}${p.type === 'enum' ? ` (${p.values.join('|')})` : ''}`\n            )\n            .join(', ')\n          return `  · ${tpl.id} — ${tpl.summary}\\n    params: ${params || '(none)'}`\n        })\n        return `Templates (${list.length}):\\n${lines.join('\\n')}`\n      },\n      false\n    )\n\n    make(\n      'instantiate_plan',\n      'Mint an editable plan from a registered template by filling its declared params. ' +\n        'Returns the RENDERED PROSE of what it created plus any non-fatal issues; never raw JSON.',\n      validator\n        .object({\n          template: validator.string().required(),\n          args: validator.object().unknown(true).required(),\n        })\n        .unknown(false),\n      async (args) => {\n        const tplId = args.template as string\n        const list = templates ?? []\n        const tpl = list.find((t) => t.id === tplId)\n        if (!tpl) {\n          const available = list.map((t) => t.id).join(', ')\n          return `Unknown template ${JSON.stringify(tplId)}. Registered templates: ${\n            available || '(none)'\n          }.`\n        }\n        // Validate the template against the live tier-C allowlist before instantiating, so an\n        // unknown-tool refusal surfaces here rather than at freeze.\n        const templateIssues = validateTemplate(tpl, invocable)\n        if (templateIssues.some((i) => i.severity === 'blocking')) {\n          return `Template ${JSON.stringify(tplId)} is not valid against the current tool allowlist:\\n${renderIssues(\n            templateIssues\n          )}`\n        }\n        // The args map's values may hold wire references; hydrate them to IR before substitution.\n        const hydratedArgs = hydrateRefs(args.args) as Record<string, EncodableValue>\n        const result = await instantiateTemplate(store, tpl, hydratedArgs, actorId)\n        if (!result.ok) {\n          return `Could not instantiate template ${JSON.stringify(tplId)}: ${result.reason} — ${result.detail}`\n        }\n        const view = await rawPlan(store, result.planId)\n        const head = `Instantiated plan ${result.planId} from template ${JSON.stringify(tplId)}.`\n        return [head, renderModel(view), renderIssues(result.issues)].join('\\n\\n')\n      },\n      true\n    )\n\n    make(\n      'author_plan',\n      'Author a new plan from scratch from a natural-language request. Pass `request` VERBATIM and ' +\n        'UNPARSED — do not pre-categorise the owner’s words; the authoring layer parses them. Returns ' +\n        'rendered prose of what was created, never raw JSON.',\n      validator\n        .object({\n          request: validator.string().required(),\n          detail: validator.string().optional(),\n        })\n        .unknown(false),\n      async (args) => {\n        // The request is passed VERBATIM and UNPARSED. Pre-parsing the owner's words into\n        // categories is what discarded \"at the Holly Springs Walgreens\" in the prior art, so this\n        // tool does not parse them — it mints an empty editable plan and hands the request to the\n        // authoring layer (tier B), which a sub-dispatch drives. The plan id is returned so the\n        // caller can continue with the tier-B tools.\n        const request = args.request as string\n        const planId = `plan-${crypto.randomUUID()}`\n        const created = await store.createPlan(planId, { label: request.slice(0, 80) })\n        if (!created.ok) {\n          return `Could not create a plan (${created.reason}).`\n        }\n        const view = await rawPlan(store, planId)\n        const head =\n          `Created empty plan ${planId} (editable). Hand the request to the authoring tools ` +\n          `(create_plan/add_node/…/set_node_config) to build it out. Request, verbatim:\\n\"${request}\"`\n        return [head, renderModel(view)].join('\\n\\n')\n      },\n      true\n    )\n    return tools\n  }\n\n  // ─── Tier B: authoring ────────────────────────────────────────────────────\n  // The graph-mechanics surface, exposed only inside an authoring sub-dispatch. Each mutation\n  // returns SCOPED PROSE (what changed, what it now connects to, any new issues), BOUNDED\n  // regardless of plan size — never the whole projected plan.\n\n  make(\n    'create_plan',\n    'Mint a fresh empty editable plan. Returns rendered prose of the (empty) plan and its id.',\n    validator\n      .object({\n        planId: validator\n          .string()\n          .pattern(/^plan-[A-Za-z0-9_-]+$/)\n          .optional(),\n        label: validator.string().optional(),\n      })\n      .unknown(false),\n    async (args) => {\n      const id = (args.planId as string | undefined) ?? `plan-${crypto.randomUUID()}`\n      const created = await store.createPlan(id, { label: args.label as string | undefined })\n      if (!created.ok) {\n        return `Could not create plan ${JSON.stringify(id)} (${created.reason}).`\n      }\n      const view = await rawPlan(store, id)\n      return [`Created plan ${id} (editable, rev 0).`, renderModel(view)].join('\\n\\n')\n    },\n    true\n  )\n\n  make(\n    'add_node',\n    'Add a node to an editable plan. The node kind must be one of the seven exact shapes; unknown ' +\n      'keys per kind are rejected. Returns scoped prose around the new node.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        node: planNodeSchema.required(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const rawNode = args.node as PlanNode\n      // Rebuild the node with hydrated references and a closed kind/definition pair.\n      const kind = rawNode.kind as PlanNodeKind\n      if (!NODE_KINDS.includes(kind)) {\n        return `Unknown node kind ${JSON.stringify(kind)}; valid kinds are ${NODE_KINDS.join(', ')}.`\n      }\n      const node = {\n        id: rawNode.id,\n        ...(rawNode.phase !== undefined ? { phase: rawNode.phase } : {}),\n        kind,\n        definition: hydrateRefs(rawNode.definition) as PlanNode['definition'],\n      } as PlanNode\n      const rev = await currentRevision(store, planId)\n      const op = mintOp(store, planId, actorId, rev, { op: 'add_node', node })\n      const appended = await store.appendOps(planId, [op])\n      if (!appended.ok) {\n        return `Could not add node ${JSON.stringify(node.id)} to ${planId} (${appended.reason}; actual state ${appended.actual.state} rev ${appended.actual.revision}).`\n      }\n      return renderScoped(store, planId, node.id)\n    },\n    true\n  )\n\n  make(\n    'set_node_config',\n    'Replace a node’s whole definition. Takes a CLOSED ALTERNATIVES schema: a definition can only ' +\n      'be one of the seven exact node shapes, unknown keys per kind rejected. Returns scoped prose ' +\n      'around the changed node.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        nodeId: validator.string().required(),\n        definition: nodeDefinitionAlternatives.required(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const nodeId = args.nodeId as NodeId\n      const def = args.definition as { kind: PlanNodeKind; definition: PlanNode['definition'] }\n      const definition = hydrateRefs(def.definition) as PlanNode['definition']\n      const rev = await currentRevision(store, planId)\n      const op = mintOp(store, planId, actorId, rev, {\n        op: 'set_node_definition',\n        nodeId,\n        definition,\n      })\n      const appended = await store.appendOps(planId, [op])\n      if (!appended.ok) {\n        return `Could not set config for node ${JSON.stringify(nodeId)} on ${planId} (${appended.reason}; actual state ${appended.actual.state} rev ${appended.actual.revision}).`\n      }\n      return renderScoped(store, planId, nodeId)\n    },\n    true\n  )\n\n  make(\n    'set_node_field',\n    'Set a single dot-path field within a node’s definition. The value may hold references on the ' +\n      'wire as {\"$ref\":…}/{\"$param\":…}. Returns scoped prose around the changed node.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        nodeId: validator.string().required(),\n        path: validator.string().required(),\n        value: openValueSchema,\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const nodeId = args.nodeId as NodeId\n      const path = args.path as string\n      const value = hydrateRefs(args.value) as ArgValue\n      const rev = await currentRevision(store, planId)\n      const op = mintOp(store, planId, actorId, rev, { op: 'set_node_field', nodeId, path, value })\n      const appended = await store.appendOps(planId, [op])\n      if (!appended.ok) {\n        return `Could not set field ${JSON.stringify(path)} on node ${JSON.stringify(nodeId)} (${appended.reason}; actual state ${appended.actual.state} rev ${appended.actual.revision}).`\n      }\n      return renderScoped(store, planId, nodeId)\n    },\n    true\n  )\n\n  make(\n    'set_node_phase',\n    'Set, change, or clear a node’s phase label. `phase: null` clears it. Phases group nodes for ' +\n      'reading and rendering only; they have no execution meaning. Returns scoped prose.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        nodeId: validator.string().required(),\n        phase: validator\n          .alternatives(validator.string(), validator.any().valid(null).required())\n          .required(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const nodeId = args.nodeId as NodeId\n      const phase = (args.phase ?? null) as string | null\n      const rev = await currentRevision(store, planId)\n      const op = mintOp(store, planId, actorId, rev, { op: 'set_node_phase', nodeId, phase })\n      const appended = await store.appendOps(planId, [op])\n      if (!appended.ok) {\n        return `Could not set phase for node ${JSON.stringify(nodeId)} (${appended.reason}; actual state ${appended.actual.state} rev ${appended.actual.revision}).`\n      }\n      return renderScoped(store, planId, nodeId)\n    },\n    true\n  )\n\n  make(\n    'connect_nodes',\n    'Add an edge between two nodes. The handle must apply to the source node’s kind. Returns scoped ' +\n      'prose around the source node.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        edge: planEdgeSchema.required(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const edge = args.edge as PlanEdge\n      const rev = await currentRevision(store, planId)\n      const op = mintOp(store, planId, actorId, rev, { op: 'add_edge', edge })\n      const appended = await store.appendOps(planId, [op])\n      if (!appended.ok) {\n        return `Could not add edge ${JSON.stringify(edge.id)} (${appended.reason}; actual state ${appended.actual.state} rev ${appended.actual.revision}).`\n      }\n      return renderScoped(store, planId, edge.from)\n    },\n    true\n  )\n\n  make(\n    'remove_node',\n    'Remove a node and its incident edges from an editable plan. Returns scoped prose (the outline, ' +\n      'since the focal node is gone).',\n    validator\n      .object({\n        planId: validator.string().required(),\n        nodeId: validator.string().required(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const nodeId = args.nodeId as NodeId\n      // Compute the incident edge ids BEFORE removal so the op is order-independent (the fold\n      // uses them to cascade removal without a second read).\n      const view = await rawPlan(store, planId)\n      const incident = view.edges\n        .filter((e) => e.from === nodeId || e.to === nodeId)\n        .map((e) => e.id)\n      const rev = await currentRevision(store, planId)\n      const op = mintOp(store, planId, actorId, rev, {\n        op: 'remove_node',\n        nodeId,\n        incidentEdgeIds: incident,\n      })\n      const appended = await store.appendOps(planId, [op])\n      if (!appended.ok) {\n        return `Could not remove node ${JSON.stringify(nodeId)} (${appended.reason}; actual state ${appended.actual.state} rev ${appended.actual.revision}).`\n      }\n      return renderScoped(store, planId)\n    },\n    true\n  )\n\n  make(\n    'disconnect_edge',\n    'Remove a single edge from an editable plan. Returns scoped prose around the edge’s source node.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        edgeId: validator.string().required(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const edgeId = args.edgeId as string\n      const view = await rawPlan(store, planId)\n      const edge = view.edges.find((e) => e.id === edgeId)\n      const rev = await currentRevision(store, planId)\n      const op = mintOp(store, planId, actorId, rev, { op: 'remove_edge', edgeId })\n      const appended = await store.appendOps(planId, [op])\n      if (!appended.ok) {\n        return `Could not remove edge ${JSON.stringify(edgeId)} (${appended.reason}; actual state ${appended.actual.state} rev ${appended.actual.revision}).`\n      }\n      return renderScoped(store, planId, edge?.from)\n    },\n    true\n  )\n\n  make(\n    'set_bounds',\n    'Override the plan’s bounds (the fold seed is DEFAULT_PLAN_BOUNDS; this op overrides it by LWW). ' +\n      'All members are required so an override is total and cannot half-specify. Returns scoped prose.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        bounds: validator\n          .object({\n            maxNodes: validator.number().integer().min(1).required(),\n            maxEdges: validator.number().integer().min(1).required(),\n            maxSteps: validator.number().integer().min(1).required(),\n            maxConcurrentFrames: validator.number().integer().min(1).required(),\n            maxEncodedBytes: validator.number().integer().min(1).required(),\n          })\n          .unknown(false)\n          .required(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const bounds = args.bounds as PlanBounds\n      const rev = await currentRevision(store, planId)\n      const op = mintOp(store, planId, actorId, rev, { op: 'set_bounds', bounds })\n      const appended = await store.appendOps(planId, [op])\n      if (!appended.ok) {\n        return `Could not set bounds on ${planId} (${appended.reason}; actual state ${appended.actual.state} rev ${appended.actual.revision}).`\n      }\n      return renderScoped(store, planId)\n    },\n    true\n  )\n\n  make(\n    'clone_plan',\n    'Clone a plan into a fresh editable id, seeded with the source’s folded state at a revision. ' +\n      'Inherits no approval and no run. Returns scoped prose of the clone.',\n    validator\n      .object({\n        sourcePlanId: validator.string().required(),\n        newPlanId: validator\n          .string()\n          .pattern(/^plan-[A-Za-z0-9_-]+$/)\n          .required(),\n        atRevision: validator.number().integer().min(0).optional(),\n      })\n      .unknown(false),\n    async (args) => {\n      const sourcePlanId = args.sourcePlanId as string\n      const newPlanId = args.newPlanId as string\n      const atRevision = args.atRevision as number | undefined\n      const cloned = await store.clonePlan(sourcePlanId, newPlanId, atRevision)\n      if (!cloned.ok) {\n        return `Could not clone ${sourcePlanId} → ${newPlanId} (${cloned.reason}).`\n      }\n      return renderScoped(store, newPlanId)\n    },\n    true\n  )\n\n  make(\n    'get_plan',\n    'Read a plan’s full rendered prose. With no argument, returns everything — scoped reading is ' +\n      'available via plan_outline/plan_read, not mandatory.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        audience: validator.string().valid('model', 'operator').optional(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const audience = (args.audience as 'model' | 'operator' | undefined) ?? 'model'\n      const view = await rawPlan(store, planId)\n      const body = audience === 'operator' ? renderOperator(view) : renderModel(view)\n      return [`Plan ${planId} (rev ${view.revision}, ${view.nodes.length} node(s)).`, body].join(\n        '\\n\\n'\n      )\n    },\n    false\n  )\n\n  make(\n    'validate_plan',\n    'Run the freeze-time checks against a plan WITHOUT freezing it. Surfaces every issue the graph ' +\n      'raises, blocking and advisory. No dry run exists; reachability and placeholder checks carry ' +\n      'the weight a dry run used to.',\n    validator.object({ planId: validator.string().required() }).unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const view = await rawPlan(store, planId)\n      const issues = await collectIssues(view, { invocable, evaluators })\n      return [`Validation of ${planId} (rev ${view.revision}).`, renderIssues(issues)].join('\\n\\n')\n    },\n    false\n  )\n\n  make(\n    'freeze_plan',\n    'Freeze an editable plan into reviewable. Runs the freeze checks and, only on a clean pass, ' +\n      'commits the editable→reviewable transition. Each refusal is surfaced with its model-addressed ' +\n      'message. There is no dry run.',\n    validator.object({ planId: validator.string().required() }).unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const result = await freezePlan(store, planId, { invocable, evaluators })\n      const head = result.ok\n        ? `Plan ${planId} is now reviewable.`\n        : `Plan ${planId} could not be frozen.`\n      return [head, renderIssues(result.issues)].join('\\n\\n')\n    },\n    true\n  )\n\n  make(\n    'unfreeze_plan',\n    'Return a reviewable plan to editable. Free re-entry; no approval is carried. Returns scoped prose.',\n    validator.object({ planId: validator.string().required() }).unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const state = await store.readState(planId)\n      if (state.state !== 'reviewable') {\n        return `Plan ${planId} is in state ${state.state}, not reviewable; only reviewable plans can be unfrozen.`\n      }\n      const transition = await store.transition(planId, {\n        from: 'reviewable',\n        to: 'editable',\n        expectedDigest: state.digest,\n      })\n      if (!transition.ok) {\n        const detail =\n          transition.reason === 'illegal_transition'\n            ? `${transition.from}→${transition.to}`\n            : `${transition.actual.state}`\n        return `Could not unfreeze ${planId} (${transition.reason}; ${detail}).`\n      }\n      return renderScoped(store, planId)\n    },\n    true\n  )\n\n  make(\n    'submit_plan',\n    'Freeze a plan and then approve it, moving it all the way to executable. The authority set is ' +\n      'recomputed over the reachable workflow and must match the supplied decision exactly. Each ' +\n      'refusal is surfaced with its model-addressed message. No dry run.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        decidedBy: validator.string().required(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const decidedBy = args.decidedBy as string\n      // 1. Freeze.\n      const frozen = await freezePlan(store, planId, { invocable, evaluators })\n      if (!frozen.ok) {\n        return [`Could not freeze ${planId} for submission.`, renderIssues(frozen.issues)].join(\n          '\\n\\n'\n        )\n      }\n      // 2. Recompute the reachable authority set and approve against it.\n      const view = await rawPlan(store, planId)\n      const authoritySet = computeAuthoritySet(view) as AuthorityClaim[]\n      const record: ApprovalRecord = {\n        planId,\n        digest: view.digest,\n        authoritySet,\n        decidedBy,\n        decidedAt: new Date().toISOString(),\n        disposition: 'approved',\n      }\n      const approved = await approvePlan(store, planId, record)\n      if (!approved.ok) {\n        const detail =\n          approved.reason === 'illegal_transition'\n            ? `${approved.from}→${approved.to}`\n            : `${approved.actual.state}`\n        return `Plan ${planId} was frozen but could not be approved (${approved.reason}; ${detail}).`\n      }\n      return [\n        `Plan ${planId} is now executable.`,\n        `Authority set (${authoritySet.length} claim(s)):`,\n        ...authoritySet.map((c) => `  · ${c.capability} / ${c.scope} / ${c.verb}`),\n      ].join('\\n')\n    },\n    true\n  )\n\n  make(\n    'plan_status',\n    'Read a plan’s lifecycle state, digest, and revision NOW. Lifecycle state is not an op and cannot ' +\n      'be folded from the log, so it is read from the store directly.',\n    validator.object({ planId: validator.string().required() }).unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const state = await store.readState(planId)\n      return `Plan ${planId}: state=${state.state}, rev=${state.revision}, digest=${state.digest}.`\n    },\n    false\n  )\n\n  make(\n    'raw_plan',\n    'Read the machine-readable folded content of a plan, optionally at a historical revision. This ' +\n      'is the data view (no narrative, no trust framing), for a UI or a model that wants exact state. ' +\n      'References are emitted in their wire form ($ref/$param).',\n    validator\n      .object({\n        planId: validator.string().required(),\n        revision: validator.number().integer().min(0).optional(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const view = await rawPlan(store, planId, {\n        revision: args.revision as number | undefined,\n      })\n      return JSON.stringify(dehydrateRefs(view), null, 2)\n    },\n    false\n  )\n\n  make(\n    'raw_diff',\n    'A STRUCTURAL delta between two folded states of a plan (`a` and `b`, each a revision number or ' +\n      '“current”). A node edited and then reverted across the span produces no row. References are ' +\n      'emitted in their wire form ($ref/$param).',\n    validator\n      .object({\n        planId: validator.string().required(),\n        a: validator\n          .alternatives(validator.number().integer().min(0), validator.string().valid('current'))\n          .required(),\n        b: validator\n          .alternatives(validator.number().integer().min(0), validator.string().valid('current'))\n          .required(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const a = args.a as number | 'current'\n      const b = args.b as number | 'current'\n      const diff = await rawDiff(store, planId, a, b)\n      return JSON.stringify(dehydrateRefs(diff), null, 2)\n    },\n    false\n  )\n\n  make(\n    'raw_ops',\n    'Read the plan’s raw op log, optionally filtered by Lamport clock or a revision prefix. The op ' +\n      'log is the source of truth the fold reads.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        sinceLamport: validator.number().integer().min(0).optional(),\n        throughRevision: validator.number().integer().min(0).optional(),\n      })\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const ops = await rawOps(store, planId, {\n        sinceLamport: args.sinceLamport as number | undefined,\n        throughRevision: args.throughRevision as number | undefined,\n      })\n      return JSON.stringify(dehydrateRefs(ops), null, 2)\n    },\n    false\n  )\n\n  // ─── scoped reading pair ──────────────────────────────────────────────────\n  // `plan_outline` takes no argument (no enum needed). `plan_read` takes a phase name or node id\n  // that must be present in the LIVE plan: the closed-enum check runs at call time against the\n  // live graph (the schema cannot close over a mutable graph, and the store is async), and a\n  // stale or invented id throws naming the valid set — a schema-shaped error, never an empty\n  // result a model might surface as an answer.\n  make(\n    'plan_outline',\n    'Build a flat outline of a plan: one entry per phase plus a single entry for unphased nodes. ' +\n      'Each entry carries the EXACT node ids and tool names a model cites back. ONE flat level, never two.',\n    validator.object({ planId: validator.string().required() }).unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const outline = await planOutline(store, planId)\n      const phases = outline.phases\n        .concat(outline.unphased ? [outline.unphased] : [])\n        .map((p) => {\n          const toolList = p.tools.length > 0 ? ` tools: ${p.tools.join(', ')}` : ''\n          return `  · ${p.phase || '(unphased)'} [${p.nodeIds.join(', ')}]${toolList} — ${p.summary} (${p.issueCount} issue(s))`\n        })\n        .join('\\n')\n      return [\n        `Outline of ${planId} (state ${outline.state}, ${outline.nodeCount} node(s), digest ${outline.digest}).`,\n        phases || '(no nodes)',\n      ].join('\\n')\n    },\n    false\n  )\n\n  make(\n    'plan_read',\n    'Read a self-locating slice of a plan by the exact identifier the outline printed: `{phase}` for a ' +\n      'whole phase or `{node}` for the slice around a single node. A stale or invented id is rejected ' +\n      'naming the valid set, never returned as an empty slice.',\n    validator\n      .object({\n        planId: validator.string().required(),\n        phase: validator.string().optional(),\n        node: validator.string().optional(),\n      })\n      .xor('phase', 'node')\n      .unknown(false),\n    async (args) => {\n      const planId = args.planId as string\n      const sel =\n        args.phase !== undefined ? { phase: args.phase as string } : { node: args.node as NodeId }\n      // planRead throws naming the valid set when the id is unknown — the closed-enum check\n      // against the live plan, surfaced as a tool error rather than an empty result.\n      const slice = await planRead(store, planId, sel)\n      const view = await rawPlan(store, planId)\n      const where = slice.phase\n        ? `phase ${JSON.stringify(slice.phase)}`\n        : `node ${JSON.stringify((slice.nodes[0] ?? { id: '?' }).id)}`\n      const head = `Slice of ${planId} around ${where}. Predecessors: ${\n        slice.boundary.incoming.join(', ') || '(none)'\n      }; successors: ${slice.boundary.outgoing.join(', ') || '(none)'}.`\n      return [head, renderModel({ ...view, nodes: slice.nodes }), renderIssues(slice.issues)].join(\n        '\\n\\n'\n      )\n    },\n    false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