@orkestrel/brief 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["#emitter","#records","#stage","#commit","#refuseDestroyed","#discard","#destroyed","#version","#emitter","#interpret","#reason","#ownInterpret","#ownReason","#actions","#domains","#refuseDestroyed","#snapshot","#refuse","#read","#draft","#unresolved","#blockage","#own","#destroyed"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/shapers.ts","../../../src/core/validators.ts","../../../src/core/cloners.ts","../../../src/core/helpers.ts","../../../src/core/parsers.ts","../../../src/core/BriefManager.ts","../../../src/core/BriefCompiler.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Interpretation } from '@orkestrel/interpret'\nimport type { OutputFormat, RiskSeverity, TaskDomain, TaskOperation } from './types.js'\n\n/** Lists the `TaskOperation` values, frozen. */\nexport const TASK_OPERATIONS: readonly TaskOperation[] = Object.freeze([\n\t'create',\n\t'refactor',\n\t'debug',\n\t'extract',\n\t'migrate',\n\t'explain',\n\t'review',\n\t'optimize',\n\t'audit',\n\t'test',\n\t'document',\n\t'plan',\n])\n\n/** Lists the `TaskDomain` values, frozen. */\nexport const TASK_DOMAINS: readonly TaskDomain[] = Object.freeze([\n\t'code',\n\t'writing',\n\t'research',\n\t'analysis',\n\t'design',\n\t'data',\n\t'ops',\n\t'other',\n])\n\n/** Lists the `OutputFormat` values, frozen. */\nexport const OUTPUT_FORMATS: readonly OutputFormat[] = Object.freeze([\n\t'markdown',\n\t'json',\n\t'code',\n\t'diff',\n\t'prose',\n])\n\n/** Lists the `RiskSeverity` values, frozen. */\nexport const RISK_SEVERITIES: readonly RiskSeverity[] = Object.freeze(['low', 'medium', 'high'])\n\n/**\n * Lists every published `Interpretation` member name, frozen.\n *\n * @remarks\n * The capture list `BriefCompiler` hands `captureValue` at each interpret door — the borrowed\n * engine's return, and the caller's supplied interpretation. A class instance carries its\n * contract on the prototype, so the captured view materializes exactly the members named here,\n * and a name missing from the list is a member the view drops.\n *\n * The `satisfies` clause refuses a name `Interpretation` does not declare, and it holds the\n * element type at the listed names rather than widening it to `string`. That is what lets the\n * equality assertion beside the capture cases refuse a list that has fallen short of the\n * published shape.\n */\nexport const INTERPRETATION_MEMBERS = Object.freeze([\n\t'text',\n\t'normalized',\n\t'intent',\n\t'entities',\n\t'subject',\n\t'definition',\n\t'mappings',\n\t'ambiguities',\n\t'prompt',\n\t'stages',\n\t'failures',\n\t'confidence',\n\t'digest',\n] satisfies ReadonlyArray<keyof Interpretation>)\n\n/**\n * Holds `16` — the default turn cap `briefToGoal` renders.\n *\n * @remarks\n * Domain-qualified so the barrel stays collision-free as sibling modules add their own\n * turn defaults.\n */\nexport const DEFAULT_BRIEF_TURNS = 16\n\n/** Holds `'gate'` — the id of the `buildGateDefinition()` logical definition. */\nexport const GATE_ID = 'gate'\n\n/**\n * Matches every line terminator a brief field refuses.\n *\n * @remarks\n * Every ECMAScript line terminator, not just `\\n`: a renderer that splits on any of them\n * would let the others forge a markdown row. CRLF leads the alternation so a Windows\n * exemplar splits as ONE break rather than two, which would insert a blank line the caller\n * never wrote. Kept unanchored and stateless — no `g` flag — so `test` never carries\n * `lastIndex` between calls.\n */\nexport const LINE_BREAK_PATTERN = /\\r\\n|[\\n\\r\\u2028\\u2029]/\n\n/**\n * Holds the positive form of {@link LINE_BREAK_PATTERN}, for the shape DSL.\n *\n * @remarks\n * `stringShape`'s `pattern` must MATCH an accepted value, so the guard's refusal regex\n * cannot be reused directly. Both are derived from one character class, which is what\n * keeps the hand-composed guards and the compiled shapes refusing the same strings.\n */\nexport const SINGLE_LINE_PATTERN = /^[^\\n\\r\\u2028\\u2029]*$/\n\n/**\n * Matches a string of one or more spaces and nothing else.\n *\n * @remarks\n * The one exemplar side `exampleToLines` must NOT pad. CommonMark strips a fully-blank code\n * span to nothing rather than one space from each end, so padding inflates an all-space value\n * while every other value needs the pad to keep its own boundary spaces.\n *\n * `+` rather than `*`, because the EMPTY string is not that case: it has no spaces to\n * preserve, and withholding the pad emitted an empty backtick run that does not close.\n */\nexport const BLANK_PATTERN = /^ +$/\n","import type { BriefErrorCode } from './types.js'\n\n/**\n * Represents the one error class this package throws.\n *\n * @remarks\n * Throws are reserved for caller misuse: `assertBrief`, `snapshotBrief`, and `pinBrief` on\n * off-contract data throw `INVALID`; any method after `destroy()` throws `DESTROYED`; and `BriefCompiler.gate` throws\n * `GATE_FAILED` when a borrowed reasoner returns a non-logical result. A stage that fails\n * inside `compile` is CONTAINED as a `BriefStageFailure` on the `Briefing` instead.\n *\n * @example\n * ```ts\n * import { BriefError } from '@orkestrel/brief'\n *\n * const error = new BriefError('INVALID', 'Brief failed the exact-record contract', {\n * \tfield: 'proofs',\n * })\n * error.code // 'INVALID'\n * error.context // { field: 'proofs' }\n * ```\n */\nexport class BriefError extends Error {\n\treadonly code: BriefErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(code: BriefErrorCode, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tthis.name = 'BriefError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows a caught value to a {@link BriefError}.\n *\n * @param value - The caught value to inspect.\n * @returns True if `value` is a `BriefError`; false otherwise.\n *\n * @example\n * ```ts\n * import { BriefError, isBriefError } from '@orkestrel/brief'\n *\n * try {\n * \tthrow new BriefError('DESTROYED', 'BriefCompiler has been destroyed')\n * } catch (error) {\n * \tif (isBriefError(error)) error.code // 'DESTROYED'\n * }\n * ```\n */\nexport function isBriefError(value: unknown): value is BriefError {\n\treturn value instanceof BriefError\n}\n","import type { StringShape } from '@orkestrel/contract'\nimport {\n\tarrayShape,\n\tbooleanShape,\n\tintegerShape,\n\tliteralShape,\n\tobjectShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\nimport {\n\tOUTPUT_FORMATS,\n\tRISK_SEVERITIES,\n\tTASK_DOMAINS,\n\tTASK_OPERATIONS,\n\tSINGLE_LINE_PATTERN,\n} from './constants.js'\n\n/** Describes a single-line string of any length, including empty. */\nexport const textShape: StringShape = stringShape({ pattern: SINGLE_LINE_PATTERN })\n\n/** Describes a non-empty single-line string — the shape mirror of `isLine`. */\nexport const lineShape: StringShape = stringShape({ min: 1, pattern: SINGLE_LINE_PATTERN })\n\n/** Describes the `Task` shape — closed operation and domain vocabularies plus a non-empty statement. */\nexport const taskShape = objectShape(\n\t{\n\t\toperation: literalShape(TASK_OPERATIONS),\n\t\tdomain: literalShape(TASK_DOMAINS),\n\t\tstatement: lineShape,\n\t},\n\t{ description: 'What the brief asks for, in one imperative sentence.' },\n)\n\n/** Describes the `Reference` shape — a path and the note that justifies listing it. */\nexport const referenceShape = objectShape(\n\t{\n\t\tpath: lineShape,\n\t\tnote: lineShape,\n\t},\n\t{ description: 'One referenced path and why it is listed.' },\n)\n\n/** Describes the `Manifest` shape — disjoint reference partitions. */\nexport const manifestShape = objectShape(\n\t{\n\t\tread: arrayShape(referenceShape),\n\t\tedit: arrayShape(referenceShape),\n\t\tlocked: arrayShape(referenceShape),\n\t\tforbidden: arrayShape(referenceShape),\n\t},\n\t{ description: 'The disjoint file partitions of a brief.' },\n)\n\n/** Describes the `Outcome` shape — a one-based rank, the result text, and whether it gates done. */\nexport const outcomeShape = objectShape(\n\t{\n\t\trank: integerShape({ min: 1 }),\n\t\ttext: lineShape,\n\t\trequired: booleanShape(),\n\t},\n\t{ description: 'One ranked outcome — a result, never a step.' },\n)\n\n/** Describes the `Given` shape — one categorized context fact. */\nexport const givenShape = objectShape(\n\t{\n\t\tcategory: lineShape,\n\t\tname: lineShape,\n\t\tvalue: textShape,\n\t},\n\t{ description: 'One context fact handed to the executor.' },\n)\n\n/** Describes the `Example` shape — one input to output exemplar. */\nexport const exampleShape = objectShape(\n\t{\n\t\tinput: stringShape({ min: 1 }),\n\t\toutput: stringShape({ min: 1 }),\n\t\tnote: optionalShape(lineShape),\n\t},\n\t{ description: 'One input to output exemplar.' },\n)\n\n/** Describes the `Citation` shape — a name, a locator, and why the source is cited. */\nexport const citationShape = objectShape(\n\t{\n\t\tname: lineShape,\n\t\turl: lineShape,\n\t\tnote: lineShape,\n\t},\n\t{ description: 'One external source; list order is the trust order.' },\n)\n\n/** Describes the `Gap` shape — an unknown, whether it blocks, and the candidates that would close it. */\nexport const gapShape = objectShape(\n\t{\n\t\tfield: lineShape,\n\t\tquestion: lineShape,\n\t\tblocking: booleanShape(),\n\t\tcandidates: optionalShape(arrayShape(lineShape)),\n\t},\n\t{ description: 'One unresolved decision; blocking means the gate fails closed.' },\n)\n\n/** Describes the `Risk` shape — a closed severity, the risk, and its mitigation. */\nexport const riskShape = objectShape(\n\t{\n\t\tseverity: literalShape(RISK_SEVERITIES),\n\t\ttext: lineShape,\n\t\tmitigation: lineShape,\n\t},\n\t{ description: 'One pre-empted risk and the mitigation that answers it.' },\n)\n\n/** Describes the `Output` shape — a closed format plus its optional refinements. */\nexport const outputShape = objectShape(\n\t{\n\t\tformat: literalShape(OUTPUT_FORMATS),\n\t\tsections: optionalShape(arrayShape(lineShape)),\n\t\tinclude: optionalShape(arrayShape(lineShape)),\n\t\texclude: optionalShape(arrayShape(lineShape)),\n\t},\n\t{ description: 'The closed shape of the deliverable.' },\n)\n\n/** Describes the `Proof` shape — the claim and the command that settles it. */\nexport const proofShape = objectShape(\n\t{\n\t\ttext: lineShape,\n\t\tcommand: lineShape,\n\t},\n\t{ description: 'One mechanical, transcript-provable check.' },\n)\n\n/**\n * Describes the whole `Brief` shape, section shapes composed.\n *\n * @remarks\n * `trace` and `hash` are optional because `pinBrief` fills them; an unpinned draft is\n * on-contract without them.\n */\nexport const briefShape = objectShape(\n\t{\n\t\ttask: taskShape,\n\t\tauthority: arrayShape(referenceShape),\n\t\tmanifest: manifestShape,\n\t\toutcomes: arrayShape(outcomeShape),\n\t\trules: arrayShape(lineShape),\n\t\tinvariants: arrayShape(lineShape),\n\t\tgivens: arrayShape(givenShape),\n\t\texamples: arrayShape(exampleShape),\n\t\tassumptions: arrayShape(lineShape),\n\t\tcitations: arrayShape(citationShape),\n\t\tgaps: arrayShape(gapShape),\n\t\trisks: arrayShape(riskShape),\n\t\toutput: outputShape,\n\t\tproofs: arrayShape(proofShape),\n\t\ttrace: optionalShape(lineShape),\n\t\thash: optionalShape(lineShape),\n\t},\n\t{ description: 'The closed execution contract one agent can run with no interpretation left.' },\n)\n","import type { Guard } from '@orkestrel/contract'\nimport type {\n\tBrief,\n\tCitation,\n\tExample,\n\tGap,\n\tGiven,\n\tManifest,\n\tOutcome,\n\tOutput,\n\tOutputFormat,\n\tProof,\n\tReference,\n\tRisk,\n\tRiskSeverity,\n\tTask,\n\tTaskDomain,\n\tTaskOperation,\n} from './types.js'\nimport {\n\tandOf,\n\tarrayOf,\n\tboundsOf,\n\tisBoolean,\n\tisInteger,\n\tisNonEmptyString,\n\tisString,\n\tliteralOf,\n\trecordOf,\n} from '@orkestrel/contract'\nimport {\n\tLINE_BREAK_PATTERN,\n\tOUTPUT_FORMATS,\n\tRISK_SEVERITIES,\n\tTASK_DOMAINS,\n\tTASK_OPERATIONS,\n} from './constants.js'\n\n/**\n * Checks whether the value is a string holding no line terminator, empty included.\n *\n * @remarks\n * `briefToMarkdown` renders each brief field as ONE markdown row, so a field carrying a\n * line break would forge a heading or an extra manifest row — which is how a rendered\n * prompt and `briefToDispatch`'s path sets could disagree about the same brief.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a string holding no line terminator, empty included; false\n * otherwise.\n */\nexport const isText: Guard<string> = (value: unknown): value is string =>\n\tisString(value) && !LINE_BREAK_PATTERN.test(value)\n\n/**\n * Checks whether the value is a non-empty string holding no line terminator.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a non-empty string holding no line terminator; false otherwise.\n */\nexport const isLine: Guard<string> = andOf(isNonEmptyString, isText)\n\n/**\n * Checks whether the value is one of the `TaskOperation` literals.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is one of the `TaskOperation` literals; false otherwise.\n */\nexport const isTaskOperation: Guard<TaskOperation> = literalOf(TASK_OPERATIONS)\n\n/**\n * Checks whether the value is one of the `TaskDomain` literals.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is one of the `TaskDomain` literals; false otherwise.\n */\nexport const isTaskDomain: Guard<TaskDomain> = literalOf(TASK_DOMAINS)\n\n/**\n * Checks whether the value is one of the `OutputFormat` literals.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is one of the `OutputFormat` literals; false otherwise.\n */\nexport const isOutputFormat: Guard<OutputFormat> = literalOf(OUTPUT_FORMATS)\n\n/**\n * Checks whether the value is one of the `RiskSeverity` literals.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is one of the `RiskSeverity` literals; false otherwise.\n */\nexport const isRiskSeverity: Guard<RiskSeverity> = literalOf(RISK_SEVERITIES)\n\n/**\n * Checks whether the value is a well-formed `Task` — both vocabularies closed, statement one line.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Task`; false otherwise.\n */\nexport const isTask: Guard<Task> = recordOf({\n\toperation: isTaskOperation,\n\tdomain: isTaskDomain,\n\tstatement: isLine,\n})\n\n/**\n * Checks whether the value is a well-formed `Reference` — both members required, both single-line.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Reference`; false otherwise.\n */\nexport const isReference: Guard<Reference> = recordOf({\n\tpath: isLine,\n\tnote: isLine,\n})\n\n/**\n * Checks whether the value is a well-formed `Manifest`.\n *\n * @remarks\n * Partition presence only — disjointness is `validateBrief`'s semantic pass.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Manifest`; false otherwise.\n */\nexport const isManifest: Guard<Manifest> = recordOf({\n\tread: arrayOf(isReference),\n\tedit: arrayOf(isReference),\n\tlocked: arrayOf(isReference),\n\tforbidden: arrayOf(isReference),\n})\n\n/**\n * Checks whether the value is a well-formed `Outcome` — `rank` a positive integer.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Outcome`; false otherwise.\n */\nexport const isOutcome: Guard<Outcome> = recordOf({\n\trank: andOf(isInteger, boundsOf(1)),\n\ttext: isLine,\n\trequired: isBoolean,\n})\n\n/**\n * Checks whether the value is a well-formed `Given` — its `value` may be empty but stays one line.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Given`; false otherwise.\n */\nexport const isGiven: Guard<Given> = recordOf({\n\tcategory: isLine,\n\tname: isLine,\n\tvalue: isText,\n})\n\n/**\n * Checks whether the value is a well-formed `Example`.\n *\n * @remarks\n * An exemplar's two sides are the ONLY members a brief lets span lines, because they\n * carry code. `briefToMarkdown` fences them rather than rendering them as a row.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Example`; false otherwise.\n */\nexport const isExample: Guard<Example> = recordOf(\n\t{\n\t\tinput: isNonEmptyString,\n\t\toutput: isNonEmptyString,\n\t\tnote: isLine,\n\t},\n\t['note'],\n)\n\n/**\n * Checks whether the value is a well-formed `Citation` — every member single-line.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Citation`; false otherwise.\n */\nexport const isCitation: Guard<Citation> = recordOf({\n\tname: isLine,\n\turl: isLine,\n\tnote: isLine,\n})\n\n/**\n * Checks whether the value is a well-formed `Gap`.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Gap`; false otherwise.\n */\nexport const isGap: Guard<Gap> = recordOf(\n\t{\n\t\tfield: isLine,\n\t\tquestion: isLine,\n\t\tblocking: isBoolean,\n\t\tcandidates: arrayOf(isLine),\n\t},\n\t['candidates'],\n)\n\n/**\n * Checks whether the value is a well-formed `Risk` — `severity` on the closed vocabulary.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Risk`; false otherwise.\n */\nexport const isRisk: Guard<Risk> = recordOf({\n\tseverity: isRiskSeverity,\n\ttext: isLine,\n\tmitigation: isLine,\n})\n\n/**\n * Checks whether the value is a well-formed `Output` — `format` on the closed vocabulary.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Output`; false otherwise.\n */\nexport const isOutput: Guard<Output> = recordOf(\n\t{\n\t\tformat: isOutputFormat,\n\t\tsections: arrayOf(isLine),\n\t\tinclude: arrayOf(isLine),\n\t\texclude: arrayOf(isLine),\n\t},\n\t['sections', 'include', 'exclude'],\n)\n\n/**\n * Checks whether the value is a well-formed `Proof`.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Proof`; false otherwise.\n */\nexport const isProof: Guard<Proof> = recordOf({\n\ttext: isLine,\n\tcommand: isLine,\n})\n\n/**\n * Checks whether the value satisfies the whole exact-record `Brief` contract.\n *\n * @remarks\n * Every section must be present; an extra key fails. `trace` and `hash` are the only\n * optional members, because `pinBrief` rather than the author fills them.\n *\n * @param value - The value to inspect.\n * @returns True if `value` satisfies the whole exact-record `Brief` contract; false otherwise.\n */\nexport const isBrief: Guard<Brief> = recordOf(\n\t{\n\t\ttask: isTask,\n\t\tauthority: arrayOf(isReference),\n\t\tmanifest: isManifest,\n\t\toutcomes: arrayOf(isOutcome),\n\t\trules: arrayOf(isLine),\n\t\tinvariants: arrayOf(isLine),\n\t\tgivens: arrayOf(isGiven),\n\t\texamples: arrayOf(isExample),\n\t\tassumptions: arrayOf(isLine),\n\t\tcitations: arrayOf(isCitation),\n\t\tgaps: arrayOf(isGap),\n\t\trisks: arrayOf(isRisk),\n\t\toutput: isOutput,\n\t\tproofs: arrayOf(isProof),\n\t\ttrace: isLine,\n\t\thash: isLine,\n\t},\n\t['trace', 'hash'],\n)\n","import type { Brief } from './types.js'\nimport { attempt, cloneJSONRecord } from '@orkestrel/contract'\nimport { BriefError } from './errors.js'\nimport { isBrief } from './validators.js'\n\n/**\n * Captures one stable, frozen view of a foreign contract value.\n *\n * @remarks\n * Rebuilds the root and every reachable plain container from its own enumerable members.\n * Unknown own members survive. Each published member absent from that copied own set is read\n * once and materialized, which admits a class that supplies its contract through prototype\n * accessors without leaving later reads attached to the live instance. Non-container leaves\n * retain their identity, including functions that `structuredClone` cannot carry.\n *\n * @param source - The foreign value to capture.\n * @param members - The published root member names to materialize when absent from its own set.\n * @returns A deeply frozen plain view, or `source` itself when it is a primitive.\n *\n * @example\n * ```ts\n * import { captureValue } from '@orkestrel/brief'\n *\n * const leaf = () => 'ready'\n * const owned = captureValue({ leaf }, ['leaf'])\n * Reflect.get(owned, 'leaf') === leaf // true — an uncloneable leaf keeps its identity\n * Object.isFrozen(owned) // true\n * ```\n */\nexport function captureValue(source: unknown, members: readonly string[]): unknown {\n\tif (source === null || (typeof source !== 'object' && typeof source !== 'function')) {\n\t\treturn source\n\t}\n\n\tconst target: object = Array.isArray(source) ? [] : Object.create(null)\n\tconst seen = new WeakMap<object, object>([[source, target]])\n\tconst captured: object[] = [target]\n\tconst pending: Array<\n\t\treadonly [source: object, target: object, members: readonly string[] | undefined]\n\t> = [[source, target, members]]\n\n\twhile (pending.length > 0) {\n\t\tconst frame = pending.pop()\n\t\tif (frame === undefined) continue\n\t\tconst [current, view, expected] = frame\n\t\tconst entries: Array<readonly [key: PropertyKey, value: unknown]> = []\n\t\tconst copied = new Set<PropertyKey>()\n\n\t\tfor (const key of Reflect.ownKeys(current)) {\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(current, key)\n\t\t\tif (descriptor === undefined || !descriptor.enumerable) continue\n\t\t\tcopied.add(key)\n\t\t\tentries.push([key, 'value' in descriptor ? descriptor.value : Reflect.get(current, key)])\n\t\t}\n\t\tfor (const key of expected ?? []) {\n\t\t\tif (!copied.has(key)) entries.push([key, Reflect.get(current, key)])\n\t\t}\n\n\t\tfor (const [key, value] of entries) {\n\t\t\tlet owned = value\n\t\t\tif (value !== null && typeof value === 'object') {\n\t\t\t\tconst existing = seen.get(value)\n\t\t\t\tif (existing !== undefined) {\n\t\t\t\t\towned = existing\n\t\t\t\t} else {\n\t\t\t\t\tconst prototype = Reflect.getPrototypeOf(value)\n\t\t\t\t\tif (Array.isArray(value) || prototype === null || prototype === Object.prototype) {\n\t\t\t\t\t\tconst branch: object = Array.isArray(value) ? [] : Object.create(null)\n\t\t\t\t\t\tseen.set(value, branch)\n\t\t\t\t\t\tcaptured.push(branch)\n\t\t\t\t\t\tpending.push([value, branch, undefined])\n\t\t\t\t\t\towned = branch\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tReflect.defineProperty(view, key, {\n\t\t\t\tvalue: owned,\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: false,\n\t\t\t\twritable: false,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor (const view of captured) Object.freeze(view)\n\treturn target\n}\n\n/**\n * Returns a deeply owned, deeply frozen copy of a brief, refusing anything off-contract.\n *\n * @remarks\n * The one reading boundary this package has, used by the pin, the registry, and every\n * projection. It matters twice over. A brief built from caller collections ADOPTS those\n * arrays, so a later `outcomes.push` would change content a hash already described. And a\n * caller's object may answer differently on each read, so validating one reading and\n * rendering from a second let a brief that passed the contract render a row it does not\n * contain — this takes ONE reading, validates that, and freezes it.\n *\n * `cloneJSONRecord` is `@orkestrel/contract`'s primitive rather than the ambient\n * `structuredClone`: it deep-freezes, it refuses a value JSON cannot express, and it is a\n * captured import rather than a mutable global. The result is a null-prototype record, so\n * compare it structurally rather than by prototype.\n *\n * This file imports no sibling helper, which is what lets `helpers.ts` consume it without a\n * module cycle.\n *\n * @param source - The brief to snapshot.\n * @returns A deeply frozen `Brief` sharing no reference with `source`.\n * @throws {@link BriefError} `INVALID` when the value is off-contract or JSON cannot express it.\n *\n * @example\n * ```ts\n * import { buildBrief, buildOutcome, buildTask, snapshotBrief } from '@orkestrel/brief'\n *\n * const outcomes = [buildOutcome(1, 'shipped')]\n * const owned = snapshotBrief(buildBrief(buildTask('plan', 'ops', 'Plan the release.'), { outcomes }))\n * owned.outcomes === outcomes // false — the alias is broken\n * Object.isFrozen(owned.outcomes) // true\n * ```\n */\nexport function snapshotBrief(source: Brief): Brief {\n\tconst owned = attempt(() => cloneJSONRecord(source))\n\tif (!owned.success || !isBrief(owned.value)) {\n\t\tthrow new BriefError('INVALID', 'Brief carries data that cannot be read as one value', {\n\t\t\tfield: 'brief',\n\t\t})\n\t}\n\treturn owned.value\n}\n","import type { Ambiguity, Entity, Intent } from '@orkestrel/interpret'\nimport type { LogicalDefinition, ReasonValidationResult, Rule, Subject } from '@orkestrel/reason'\nimport type {\n\tBrief,\n\tCitation,\n\tDispatch,\n\tExample,\n\tGap,\n\tGiven,\n\tManifest,\n\tOutcome,\n\tOutput,\n\tOutputFormat,\n\tProof,\n\tReference,\n\tRisk,\n\tRiskSeverity,\n\tTask,\n\tTaskDomain,\n\tTaskOperation,\n} from './types.js'\nimport { attempt } from '@orkestrel/contract'\nimport { canonicalize, collapseWhitespace, digestValue } from '@orkestrel/interpret'\nimport {\n\tcreateAtom,\n\tcreateCompound,\n\tcreateLogicalDefinition,\n\tcreateRule,\n\tformatField,\n} from '@orkestrel/reason'\nimport { snapshotBrief } from './cloners.js'\nimport { BriefError } from './errors.js'\nimport { BLANK_PATTERN, DEFAULT_BRIEF_TURNS, GATE_ID, LINE_BREAK_PATTERN } from './constants.js'\nimport { isBrief, isTaskDomain, isTaskOperation } from './validators.js'\n\n/**\n * Assembles a `Task` from an operation, a domain, and a statement.\n *\n * @param operation - What the brief asks for, from the closed operation vocabulary.\n * @param domain - The subject matter, from the closed domain vocabulary.\n * @param statement - One imperative sentence naming the object of the work.\n * @returns A fresh `Task`.\n *\n * @example\n * ```ts\n * import { buildTask } from '@orkestrel/brief'\n *\n * buildTask('refactor', 'code', 'Refactor useForm to native browser form APIs.')\n * ```\n */\nexport function buildTask(operation: TaskOperation, domain: TaskDomain, statement: string): Task {\n\treturn { operation, domain, statement }\n}\n\n/**\n * Assembles a `Reference` from a path and the note that justifies listing it.\n *\n * @param path - The referenced path or glob.\n * @param note - Why the path is listed.\n * @returns A fresh `Reference`.\n *\n * @example\n * ```ts\n * import { buildReference } from '@orkestrel/brief'\n *\n * buildReference('AGENTS.md', 'project law') // { path: 'AGENTS.md', note: 'project law' }\n * ```\n */\nexport function buildReference(path: string, note: string): Reference {\n\treturn { path, note }\n}\n\n/**\n * Assembles a `Manifest`, defaulting every absent partition to an empty list.\n *\n * @param partitions - The partitions to fill; a partial literal is enough.\n * @returns A fresh `Manifest` with every partition present.\n *\n * @example\n * ```ts\n * import { buildManifest, buildReference } from '@orkestrel/brief'\n *\n * buildManifest({ edit: [buildReference('src/core/helpers.ts', 'implementation')] })\n * ```\n */\nexport function buildManifest(partitions?: Partial<Manifest>): Manifest {\n\treturn {\n\t\tread: partitions?.read ?? [],\n\t\tedit: partitions?.edit ?? [],\n\t\tlocked: partitions?.locked ?? [],\n\t\tforbidden: partitions?.forbidden ?? [],\n\t}\n}\n\n/**\n * Assembles an `Outcome` from a rank and its result text.\n *\n * @param rank - The one-based rank; lower ranks matter more.\n * @param text - The result, never a step.\n * @param required - If `true`, the outcome gates \"done\"; if `false`, it is desirable but not\n * blocking. Default: `true`.\n * @returns A fresh `Outcome`.\n *\n * @example\n * ```ts\n * import { buildOutcome } from '@orkestrel/brief'\n *\n * buildOutcome(1, 'useForm uses native FormData with no behavior change') // required: true\n * buildOutcome(2, 'the diff stays under 200 lines', false)\n * ```\n */\nexport function buildOutcome(rank: number, text: string, required = true): Outcome {\n\treturn { rank, text, required }\n}\n\n/**\n * Assembles a `Given` from a category, a name, and a value.\n *\n * @param category - The kind of fact — a convention, a version, a constraint.\n * @param name - The fact's name.\n * @param value - The fact's value, already rendered as text.\n * @returns A fresh `Given`.\n *\n * @example\n * ```ts\n * import { buildGiven } from '@orkestrel/brief'\n *\n * buildGiven('convention', 'indentation', 'tabs')\n * ```\n */\nexport function buildGiven(category: string, name: string, value: string): Given {\n\treturn { category, name, value }\n}\n\n/**\n * Assembles an `Example` from an exemplar input and its expected output.\n *\n * @param input - The exemplar input.\n * @param output - The expected output for that input.\n * @param note - Optional detail; the key is OMITTED when absent.\n * @returns A fresh `Example`.\n *\n * @example\n * ```ts\n * import { buildExample } from '@orkestrel/brief'\n *\n * buildExample('<input required>', 'validity read from el.validity')\n * ```\n */\nexport function buildExample(input: string, output: string, note?: string): Example {\n\treturn note === undefined ? { input, output } : { input, output, note }\n}\n\n/**\n * Assembles a `Citation` from a name, a URL, and the note that justifies citing it.\n *\n * @param name - The source's display name.\n * @param url - Where the source lives.\n * @param note - Why the source is cited.\n * @returns A fresh `Citation`.\n *\n * @example\n * ```ts\n * import { buildCitation } from '@orkestrel/brief'\n *\n * buildCitation(\n * \t'MDN Constraint Validation',\n * \t'https://developer.mozilla.org/',\n * \t'the native validity behavior being adopted',\n * )\n * ```\n */\nexport function buildCitation(name: string, url: string, note: string): Citation {\n\treturn { name, url, note }\n}\n\n/**\n * Assembles a `Gap` from the section it belongs to and the question that would close it.\n *\n * @param field - The brief section the unknown belongs to.\n * @param question - The question that would close it.\n * @param overrides - Optional `blocking` and `candidates`; an absent `candidates` key is\n * OMITTED entirely. Default: `blocking: false`.\n * @returns A fresh `Gap`.\n *\n * @example\n * ```ts\n * import { buildGap } from '@orkestrel/brief'\n *\n * buildGap('rules', 'Does validation message wording need to change?') // blocking: false\n * buildGap('output', 'Diff or full files?', { blocking: true, candidates: ['diff', 'code'] })\n * ```\n */\nexport function buildGap(\n\tfield: string,\n\tquestion: string,\n\toverrides?: Partial<Omit<Gap, 'field' | 'question'>>,\n): Gap {\n\tconst blocking = overrides?.blocking ?? false\n\treturn overrides?.candidates === undefined\n\t\t? { field, question, blocking }\n\t\t: { field, question, blocking, candidates: overrides.candidates }\n}\n\n/**\n * Assembles a `Risk` from a severity, what could go wrong, and the mitigation that answers it.\n *\n * @param severity - The closed severity.\n * @param text - What could go wrong.\n * @param mitigation - What answers it.\n * @returns A fresh `Risk`.\n *\n * @example\n * ```ts\n * import { buildRisk } from '@orkestrel/brief'\n *\n * buildRisk('medium', 'native validation differs subtly', 'assert message and state in tests')\n * ```\n */\nexport function buildRisk(severity: RiskSeverity, text: string, mitigation: string): Risk {\n\treturn { severity, text, mitigation }\n}\n\n/**\n * Assembles an `Output` from a format plus its optional refinements.\n *\n * @param format - The closed deliverable format.\n * @param overrides - Optional `sections` / `include` / `exclude`; absent keys are OMITTED.\n * @returns A fresh `Output`.\n *\n * @example\n * ```ts\n * import { buildOutput } from '@orkestrel/brief'\n *\n * buildOutput('markdown') // { format: 'markdown' }\n * buildOutput('diff', { include: ['updated useForm.ts'] })\n * ```\n */\nexport function buildOutput(\n\tformat: OutputFormat,\n\toverrides?: Partial<Omit<Output, 'format'>>,\n): Output {\n\treturn {\n\t\tformat,\n\t\t...(overrides?.sections === undefined ? {} : { sections: overrides.sections }),\n\t\t...(overrides?.include === undefined ? {} : { include: overrides.include }),\n\t\t...(overrides?.exclude === undefined ? {} : { exclude: overrides.exclude }),\n\t}\n}\n\n/**\n * Assembles a `Proof` from what the check settles and the command that settles it.\n *\n * @param text - What the check settles.\n * @param command - The command whose exit signal settles it.\n * @returns A fresh `Proof`.\n *\n * @example\n * ```ts\n * import { buildProof } from '@orkestrel/brief'\n *\n * buildProof('type-check and lint pass', 'npm run check')\n * ```\n */\nexport function buildProof(text: string, command: string): Proof {\n\treturn { text, command }\n}\n\n/**\n * Assembles a `Brief` from a `Task` plus section overrides.\n *\n * @param subject - The task the brief is about.\n * @param overrides - Any sections to fill; `trace` / `hash` stay OMITTED so `pinBrief` can\n * fill them. Default: `[]` for every absent collection and `buildOutput('markdown')` for\n * `output`.\n * @returns A fresh, unpinned `Brief`.\n *\n * @example\n * ```ts\n * import { buildBrief, buildOutcome, buildProof, buildTask } from '@orkestrel/brief'\n *\n * buildBrief(buildTask('audit', 'code', 'Audit the barrel for undocumented exports.'), {\n * \toutcomes: [buildOutcome(1, 'every export appears in the guide')],\n * \tproofs: [buildProof('parity passes', 'npm run test:guides')],\n * })\n * ```\n */\nexport function buildBrief(\n\tsubject: Task,\n\toverrides?: Partial<Omit<Brief, 'task' | 'trace' | 'hash'>>,\n): Brief {\n\treturn {\n\t\ttask: subject,\n\t\tauthority: overrides?.authority ?? [],\n\t\tmanifest: overrides?.manifest ?? buildManifest(),\n\t\toutcomes: overrides?.outcomes ?? [],\n\t\trules: overrides?.rules ?? [],\n\t\tinvariants: overrides?.invariants ?? [],\n\t\tgivens: overrides?.givens ?? [],\n\t\texamples: overrides?.examples ?? [],\n\t\tassumptions: overrides?.assumptions ?? [],\n\t\tcitations: overrides?.citations ?? [],\n\t\tgaps: overrides?.gaps ?? [],\n\t\trisks: overrides?.risks ?? [],\n\t\toutput: overrides?.output ?? buildOutput('markdown'),\n\t\tproofs: overrides?.proofs ?? [],\n\t}\n}\n\n/**\n * Assembles the fail-closed readiness gate as a reasons `LogicalDefinition`.\n *\n * @remarks\n * Each readiness rule derives one named fact from `briefToSubject`'s measures, and a final\n * `ready` rule conjoins them all. Forward chaining reports the LAST rule's conclusion, so\n * `LogicalResult.conclusion` is exactly `ready`.\n *\n * The gate takes NO parameters, and that is deliberate rather than unfinished. The\n * reasoner overlays every derived fact into one flat namespace, so a caller rule named\n * for a readiness fact overwrites it and `ready` then conjoins a fact no base rule\n * proved — a refusal silently becomes a pass. Readiness is this package's contract, not\n * a caller setting. A caller who needs different readiness composes their own\n * `LogicalDefinition` over `briefToSubject` and evaluates it on their own reasoner; both\n * are exported for exactly that, and neither can reach this definition.\n *\n * @returns A fresh `LogicalDefinition` with id `GATE_ID`.\n *\n * @example\n * ```ts\n * import { briefToSubject, buildGateDefinition } from '@orkestrel/brief'\n * import { createLogicalReasoner, createReason } from '@orkestrel/reason'\n *\n * const reason = createReason({ reasoners: [createLogicalReasoner()] })\n * const verdict = reason.reason(briefToSubject(pinned), buildGateDefinition())\n * reason.destroy()\n * ```\n */\nexport function buildGateDefinition(): LogicalDefinition {\n\tconst readiness: readonly Rule[] = [\n\t\tcreateRule(\n\t\t\t'specified',\n\t\t\t[createAtom('blocking', 'equals', 0)],\n\t\t\tcreateAtom('specified', 'equals', true),\n\t\t),\n\t\tcreateRule(\n\t\t\t'aimed',\n\t\t\t[\n\t\t\t\tcreateCompound('and', [\n\t\t\t\t\tcreateAtom('outcomes', 'above', 0),\n\t\t\t\t\tcreateAtom('required', 'above', 0),\n\t\t\t\t]),\n\t\t\t],\n\t\t\tcreateAtom('aimed', 'equals', true),\n\t\t),\n\t\tcreateRule('proven', [createAtom('proofs', 'above', 0)], createAtom('proven', 'equals', true)),\n\t\tcreateRule(\n\t\t\t'disjoint',\n\t\t\t[createAtom('overlaps', 'equals', 0)],\n\t\t\tcreateAtom('disjoint', 'equals', true),\n\t\t),\n\t\tcreateRule(\n\t\t\t'granted',\n\t\t\t[createAtom('ungranted', 'equals', 0)],\n\t\t\tcreateAtom('granted', 'equals', true),\n\t\t),\n\t\tcreateRule(\n\t\t\t'single',\n\t\t\t[createAtom('sentences', 'equals', 1)],\n\t\t\tcreateAtom('single', 'equals', true),\n\t\t),\n\t]\n\treturn createLogicalDefinition(GATE_ID, 'Brief readiness', [\n\t\t...readiness,\n\t\tcreateRule(\n\t\t\t'ready',\n\t\t\t[\n\t\t\t\tcreateCompound(\n\t\t\t\t\t'and',\n\t\t\t\t\treadiness.map((entry) => createAtom(entry.id, 'equals', true)),\n\t\t\t\t),\n\t\t\t],\n\t\t\tcreateAtom('ready', 'equals', true),\n\t\t),\n\t])\n}\n\n/**\n * Lists the readiness rules a brief fails, computed directly from its own measures.\n *\n * @remarks\n * The gate's decision, in code. `buildGateDefinition()` states the same rules as data for a\n * reasoner to narrate, and a narration is not a decision: `BriefCompilerOptions.reason` lets a\n * caller supply the engine, and an engine that answers \"met\" to everything would otherwise\n * emit a brief with no proofs. `compile` refuses on THIS and keeps the verdict for its\n * trace, so a supplied engine can add detail and never remove a refusal.\n *\n * The data and the code must agree. `tests/src/core/helpers.test.ts` drives both over one\n * value set, which is what stops them from drifting apart.\n *\n * @param source - The brief to measure.\n * @returns The unmet rule ids, in gate order; empty when the brief is ready.\n *\n * @example\n * ```ts\n * import { buildBrief, buildOutcome, buildProof, buildTask, findUnmetRules } from '@orkestrel/brief'\n *\n * findUnmetRules(buildBrief(buildTask('plan', 'ops', 'Plan the release.'))) // ['aimed', 'proven']\n * findUnmetRules(\n * \tbuildBrief(buildTask('plan', 'ops', 'Plan the release.'), {\n * \t\toutcomes: [buildOutcome(1, 'shipped')],\n * \t\tproofs: [buildProof('x', 'npm test')],\n * \t}),\n * ) // []\n * ```\n */\nexport function findUnmetRules(source: Brief): readonly string[] {\n\tconst unready: string[] = []\n\tif (findBlockingGaps(source).length !== 0) unready.push('specified')\n\tif (\n\t\tsource.outcomes.length === 0 ||\n\t\tsource.outcomes.filter((entry) => entry.required).length === 0\n\t)\n\t\tunready.push('aimed')\n\tif (source.proofs.length === 0) unready.push('proven')\n\tif (findManifestOverlaps(source).length !== 0) unready.push('disjoint')\n\tif (findUngrantedAuthority(source).length !== 0) unready.push('granted')\n\tif (countSentences(source.task.statement) !== 1) unready.push('single')\n\treturn unready\n}\n\n/**\n * Counts the sentences a statement holds.\n *\n * @remarks\n * A terminator run (`.`, `!`, `?`) followed by whitespace or the end of the text closes one\n * sentence, and a trailing run with no terminator closes one more.\n *\n * LIMIT, stated because it decides a gate: an embedded abbreviation reads as a boundary, so\n * `'Ask Dr. Smith'` and `'Compare React vs. Vue'` count TWO and the `single` rule refuses\n * them. Rewrite the statement without the abbreviation — a brief's statement is one\n * imperative sentence naming the object of the work, and it rarely needs one.\n *\n * This is inherent rather than unfinished. Separating `'Dr.'` from a real boundary needs a\n * lexicon or a heuristic over capitalisation and word length, and a heuristic gets a\n * different set of statements wrong — quietly, in the direction of letting a genuinely\n * compound statement through, which is the failure this rule exists to prevent. `validateBrief`\n * therefore reports the count and lets the author judge, rather than guessing at intent.\n *\n * @param statement - The statement to measure.\n * @returns The sentence count; `0` for empty or whitespace-only text.\n *\n * @example\n * ```ts\n * import { countSentences } from '@orkestrel/brief'\n *\n * countSentences('Refactor useForm to native APIs.') // 1\n * countSentences('Refactor useForm. Then update the tests') // 2 — the tail counts\n * countSentences('Ask Dr. Smith') // 2 — an abbreviation reads as a boundary\n * countSentences('') // 0\n * ```\n */\nexport function countSentences(statement: string): number {\n\tconst text = collapseWhitespace(statement)\n\tif (text.length === 0) return 0\n\tconst matches = text.match(/[.!?]+(?=\\s|$)/gu)\n\tif (matches === null) return 1\n\t// A trailing run with no terminator is a sentence too. Counting terminators alone made\n\t// \"Do one thing. Then another\" read as ONE, so a genuinely compound statement passed the\n\t// `single` gate rule whenever its last sentence was unterminated — which is most of the\n\t// time, because people drop the final period.\n\treturn /[.!?]$/u.test(text) ? matches.length : matches.length + 1\n}\n\n/**\n * Lists the gaps that block emission.\n *\n * @param source - The brief to inspect.\n * @returns Every gap carrying `blocking: true`, in declaration order.\n *\n * @example\n * ```ts\n * import { buildBrief, buildGap, buildTask, findBlockingGaps } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('plan', 'ops', 'Plan the release.'), {\n * \tgaps: [buildGap('output', 'Diff or files?', { blocking: true })],\n * })\n * findBlockingGaps(draft).length // 1\n * ```\n */\nexport function findBlockingGaps(source: Brief): readonly Gap[] {\n\treturn source.gaps.filter((entry) => entry.blocking)\n}\n\n/**\n * Lists the authority paths the manifest never grants access to.\n *\n * @remarks\n * An authority the executor cannot open is an instruction it cannot follow, so every ranked\n * path must appear in `read`, `edit`, or `locked`. Those are the grants: `locked` is a\n * grant, because read-only is exactly what obeying a file requires.\n *\n * This subsumes the narrower question of an authority sitting in `forbidden`. The partitions\n * are disjoint — `findManifestOverlaps` and the `disjoint` rule enforce it — so a forbidden\n * path is in none of the grants and is reported here. An authority named in NO partition at\n * all is reported for the same reason, and that is the case a forbidden-only check misses\n * entirely: the brief simply never says the executor may open what it must obey.\n *\n * Paths are compared as EXACT strings, matching `findManifestOverlaps`. A glob is never\n * expanded, so `read: 'guides/**'` does not grant `authority: 'guides/brief.md'`. State a\n * grant as the same literal path the authority carries.\n *\n * @param source - The brief to inspect.\n * @returns Each ungranted authority path once, in authority order; empty when all are granted.\n *\n * @example\n * ```ts\n * import {\n * \tbuildBrief,\n * \tbuildManifest,\n * \tbuildReference,\n * \tbuildTask,\n * \tfindUngrantedAuthority,\n * } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('debug', 'code', 'Fix the leak.'), {\n * \tauthority: [buildReference('AGENTS.md', 'project law')],\n * \tmanifest: buildManifest(),\n * })\n * findUngrantedAuthority(draft) // ['AGENTS.md'] — ranked, but no partition opens it\n * ```\n */\nexport function findUngrantedAuthority(source: Brief): readonly string[] {\n\tconst granted = new Set(\n\t\t[...source.manifest.read, ...source.manifest.edit, ...source.manifest.locked].map(\n\t\t\t(entry) => entry.path,\n\t\t),\n\t)\n\tconst ungranted: string[] = []\n\tfor (const path of new Set(source.authority.map((entry) => entry.path))) {\n\t\tif (!granted.has(path)) ungranted.push(path)\n\t}\n\treturn ungranted\n}\n\n/**\n * Lists the paths appearing in more than one manifest partition.\n *\n * @remarks\n * Duplicates WITHIN one partition are not an overlap; the partitions must be\n * mutually disjoint, which is what `validateBrief` errors on.\n *\n * Paths are compared as EXACT strings. A glob is never expanded, so `edit: 'app/file.ts'`\n * and `forbidden: 'app/**'` are not reported as an overlap even though a walker would place\n * one inside the other. Disjointness here is a property of the written paths.\n *\n * @param source - The brief to inspect.\n * @returns Each overlapping path once, in first-seen partition order.\n *\n * @example\n * ```ts\n * import {\n * \tbuildBrief,\n * \tbuildManifest,\n * \tbuildReference,\n * \tbuildTask,\n * \tfindManifestOverlaps,\n * } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('debug', 'code', 'Fix the leak.'), {\n * \tmanifest: buildManifest({\n * \t\tedit: [buildReference('src/core/BriefCompiler.ts', 'the leaking pipeline')],\n * \t\tlocked: [buildReference('src/core/BriefCompiler.ts', 'the published contract')],\n * \t}),\n * })\n * findManifestOverlaps(draft) // ['src/core/BriefCompiler.ts']\n * ```\n */\nexport function findManifestOverlaps(source: Brief): readonly string[] {\n\tconst counts = new Map<string, number>()\n\tconst partitions: ReadonlyArray<readonly Reference[]> = [\n\t\tsource.manifest.read,\n\t\tsource.manifest.edit,\n\t\tsource.manifest.locked,\n\t\tsource.manifest.forbidden,\n\t]\n\tfor (const partition of partitions) {\n\t\tfor (const path of new Set(partition.map((entry) => entry.path))) {\n\t\t\tcounts.set(path, (counts.get(path) ?? 0) + 1)\n\t\t}\n\t}\n\tconst overlaps: string[] = []\n\tfor (const [path, count] of counts) {\n\t\tif (count > 1) overlaps.push(path)\n\t}\n\treturn overlaps\n}\n\n/**\n * Lists the open gaps with no assumption to stand on.\n *\n * @remarks\n * The discipline is exactly one recorded assumption per open gap, so the open gaps past\n * the assumption count are the unpaired ones. A blocking gap is never unpaired — it is\n * a question, not something to assume around.\n *\n * @param source - The brief to inspect.\n * @returns The surplus open gaps, in declaration order.\n *\n * @example\n * ```ts\n * import { buildBrief, buildGap, buildTask, findUnpairedGaps } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('plan', 'ops', 'Plan the release.'), {\n * \tgaps: [buildGap('rules', 'Keep the wording?'), buildGap('output', 'Diff or files?')],\n * \tassumptions: ['Wording is preserved.'],\n * })\n * findUnpairedGaps(draft).length // 1\n * ```\n */\nexport function findUnpairedGaps(source: Brief): readonly Gap[] {\n\treturn source.gaps.filter((entry) => !entry.blocking).slice(source.assumptions.length)\n}\n\n/**\n * Projects a brief into the reasons `Subject` of readiness measures the gate reads.\n *\n * @param source - The brief to measure.\n * @returns A flat record of counts plus the task's vocabulary values.\n *\n * @example\n * ```ts\n * import { briefToSubject, buildBrief, buildProof, buildTask } from '@orkestrel/brief'\n *\n * briefToSubject(buildBrief(buildTask('test', 'code', 'Cover the gate.'), { proofs: [buildProof('x', 'y')] }))\n * // { operation: 'test', domain: 'code', sentences: 1, proofs: 1, … }\n * ```\n */\nexport function briefToSubject(source: Brief): Subject {\n\treturn {\n\t\toperation: source.task.operation,\n\t\tdomain: source.task.domain,\n\t\tsentences: countSentences(source.task.statement),\n\t\tauthority: source.authority.length,\n\t\tgaps: source.gaps.length,\n\t\tblocking: findBlockingGaps(source).length,\n\t\tunpaired: findUnpairedGaps(source).length,\n\t\toutcomes: source.outcomes.length,\n\t\trequired: source.outcomes.filter((entry) => entry.required).length,\n\t\tproofs: source.proofs.length,\n\t\treads: source.manifest.read.length,\n\t\tedits: source.manifest.edit.length,\n\t\tlocks: source.manifest.locked.length,\n\t\tbans: source.manifest.forbidden.length,\n\t\toverlaps: findManifestOverlaps(source).length,\n\t\tungranted: findUngrantedAuthority(source).length,\n\t\trisks: source.risks.length,\n\t\texamples: source.examples.length,\n\t}\n}\n\n/**\n * Runs the semantic pass over an already-shape-valid brief.\n *\n * @remarks\n * ERRORS are the structural violations no assumption can paper over: a manifest\n * overlap, an authority no partition grants access to, an empty `proofs` list, and a\n * statement that is not exactly one sentence.\n * WARNINGS are runnable but suspicious: duplicate outcome ranks, an unpaired open gap,\n * and an optional outcome ranked above a required one. Never throws.\n *\n * @param source - The brief to inspect.\n * @returns A reasons `ReasonValidationResult`; `valid` exactly when `errors` is empty.\n *\n * @example\n * ```ts\n * import { buildBrief, buildProof, buildTask, validateBrief } from '@orkestrel/brief'\n *\n * validateBrief(buildBrief(buildTask('plan', 'ops', 'Plan the release.'))) // valid: false — no proofs\n * validateBrief(\n * \tbuildBrief(buildTask('plan', 'ops', 'Plan the release.'), { proofs: [buildProof('ok', 'npm test')] }),\n * ) // valid: true\n * ```\n */\nexport function validateBrief(source: Brief): ReasonValidationResult {\n\tconst errors: string[] = []\n\tconst warnings: string[] = []\n\n\tfor (const path of findManifestOverlaps(source)) {\n\t\terrors.push(`Path \"${path}\" appears in more than one manifest partition`)\n\t}\n\tfor (const path of findUngrantedAuthority(source)) {\n\t\terrors.push(\n\t\t\t`Authority \"${path}\" is in no manifest partition that grants access — the executor cannot obey what it cannot open`,\n\t\t)\n\t}\n\tif (source.proofs.length === 0) {\n\t\terrors.push('Brief records no proof — nothing can settle \"done\"')\n\t}\n\tconst sentences = countSentences(source.task.statement)\n\tif (sentences !== 1) {\n\t\terrors.push(\n\t\t\t`Statement holds ${String(sentences)} sentences — a compound statement is two briefs`,\n\t\t)\n\t}\n\n\tconst ranks = new Map<number, number>()\n\tfor (const entry of source.outcomes) ranks.set(entry.rank, (ranks.get(entry.rank) ?? 0) + 1)\n\tfor (const [rank, count] of ranks) {\n\t\tif (count > 1) warnings.push(`Outcome rank ${String(rank)} is used ${String(count)} times`)\n\t}\n\tfor (const entry of findUnpairedGaps(source)) {\n\t\twarnings.push(`Open gap \"${entry.field}\" has no paired assumption`)\n\t}\n\tconst required = source.outcomes.filter((entry) => entry.required).map((entry) => entry.rank)\n\tif (required.length > 0) {\n\t\tconst floor = Math.min(...required)\n\t\tfor (const entry of source.outcomes) {\n\t\t\tif (!entry.required && entry.rank < floor) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Outcome ${String(entry.rank)} is optional but outranks every required outcome`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors, warnings }\n}\n\n/**\n * Computes the canonical structural digest of a brief's content.\n *\n * @remarks\n * `trace` and `hash` are stripped before digesting, so the value is the identity of what\n * the brief SAYS rather than of a particular pinning. Deterministic across runs — the\n * same interprets `digestValue` the fleet uses everywhere else.\n *\n * @param source - The brief to digest.\n * @returns An eight-hex-digit digest.\n *\n * @example\n * ```ts\n * import { briefToHash, buildBrief, buildTask, pinBrief } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('plan', 'ops', 'Plan the release.'))\n * briefToHash(draft) === briefToHash(pinBrief(draft)) // true — pinning does not move it\n * ```\n */\nexport function briefToHash(source: Brief): string {\n\treturn digestValue(briefToContent(source))\n}\n\n/**\n * Renders the canonical text of exactly what a brief's hash describes.\n *\n * @remarks\n * `trace` and `hash` are stripped, then interprets `canonicalize` renders the rest in a\n * key-order-stable form. Two briefs with the same hash are the same brief only when this\n * text matches — the digest is eight hex digits, so hash equality alone is not identity.\n *\n * @param source - The brief to render.\n * @returns The canonical content text.\n *\n * @example\n * ```ts\n * import { briefToContent, buildBrief, buildTask, pinBrief } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('plan', 'ops', 'Plan the release.'))\n * briefToContent(draft) === briefToContent(pinBrief(draft)) // true — pinning adds no content\n * ```\n */\nexport function briefToContent(source: Brief): string {\n\tconst { trace: _trace, hash: _hash, ...content } = source\n\treturn canonicalize(content)\n}\n\n/**\n * Freezes a value and everything reachable from it.\n *\n * @remarks\n * `Object.freeze` is SHALLOW, so freezing a record leaves every nested array and object\n * writable. A `Briefing` is documented as a replayable record, and a shallow freeze let a\n * consumer rewrite the recorded stage input after the digest describing it was already\n * sealed — the replay and its hash could disagree.\n *\n * Cycles terminate: `structuredClone` preserves them, so a naive walk would not return.\n * Delegates each branch to `freezeBranch` with the shared visited set.\n *\n * Reaches PLAIN objects and arrays, which is the whole of a `Brief` — it is JSON-serializable\n * by contract. A `Map`, `Set`, or typed array is frozen as an object and its CONTENTS are left\n * writable, and `Object.isFrozen` reports `true` for it either way. Nothing this package\n * produces contains one; the limit lands on a caller freezing their own value.\n *\n * @param value - The value to freeze in place; returned for convenience.\n * @returns The same value, now deeply frozen.\n *\n * @example\n * ```ts\n * import { freezeDeep } from '@orkestrel/brief'\n *\n * const owned = freezeDeep({ outcomes: [{ rank: 1 }] })\n * Object.isFrozen(owned.outcomes) // true — the nested array too\n * ```\n */\nexport function freezeDeep<T>(value: T): T {\n\treturn freezeBranch(value, new WeakSet())\n}\n\n/**\n * Freezes one branch of a value graph, skipping what the visited set already holds.\n *\n * @param value - The branch to freeze.\n * @param seen - The objects already frozen on this walk; what makes a cycle terminate.\n * @returns The same branch, now frozen.\n *\n * @example\n * ```ts\n * import { freezeBranch } from '@orkestrel/brief'\n *\n * freezeBranch({ a: [1] }, new WeakSet()) // frozen, one level of nesting included\n * ```\n */\nexport function freezeBranch<T>(value: T, seen: WeakSet<object>): T {\n\tif (value === null || typeof value !== 'object') return value\n\tif (seen.has(value)) return value\n\tseen.add(value)\n\tObject.freeze(value)\n\tfor (const nested of Object.values(value)) freezeBranch(nested, seen)\n\treturn value\n}\n\n/**\n * Renders a value thrown by a stage into a message.\n *\n * @remarks\n * TOTAL: it never throws, for any input. That is load-bearing rather than tidy, because this\n * is the containment code itself — `compile` calls it inside the `catch` that turns a thrown\n * stage into a recorded `BriefStageFailure`. A throw here escapes `compile` uncontained and\n * falsifies the package's central promise that a failing stage yields an incomplete\n * `Briefing` rather than an exception.\n *\n * Real inputs used to throw: an `Error` subclass whose `message` getter throws, a value\n * whose string conversion throws, and a null-prototype object, which has no inherited\n * conversion for String() to reach. Each is wrapped, and an unreadable value degrades to its\n * type rather than propagating.\n *\n * @param error - The caught value, of any shape.\n * @returns The `Error` message when there is one, otherwise the value stringified; a fixed\n * description when the value cannot be read at all.\n *\n * @example\n * ```ts\n * import { errorToMessage } from '@orkestrel/brief'\n *\n * errorToMessage(new Error('boom')) // 'boom'\n * errorToMessage('boom') // 'boom'\n * errorToMessage(Object.create(null)) // 'an unreadable object was thrown'\n * ```\n */\nexport function errorToMessage(error: unknown): string {\n\tconst read = attempt(() => (error instanceof Error ? error.message : String(error)))\n\tif (read.success && typeof read.value === 'string') return read.value\n\treturn `an unreadable ${typeof error} was thrown`\n}\n\n/**\n * Narrows unknown data to a `Brief`, throwing when it is off-contract.\n *\n * @remarks\n * The throwing half of the intake pair: this returns its argument by IDENTITY after the\n * guard passes, while `parseBrief` returns `undefined` for bad input. It constructs\n * nothing, so it is an assertion rather than a factory. Reserve it for programmer-error\n * contexts where invalidity is a bug.\n *\n * Intake NARROWS, and transfers no ownership. What comes back is the caller's own object,\n * so a member carried on an accessor can answer this guard one way and a later reader\n * another. The division is deliberate: the borrowed-engine law governs values this package\n * pulls across a seam it called, and a value handed in at the door stays the caller's.\n * `snapshotBrief` is the ownership door, and `pinBrief`, `BriefManager`, `briefToMarkdown`,\n * `briefToGoal`, and `briefToDispatch` take it. `briefToSubject`, `briefToContent`, and\n * `briefToTrace` read the value they are handed instead, so a caller reaching one of those\n * directly owns that reading. Pass `assertBrief` a value you already own.\n *\n * @param value - The candidate brief value.\n * @returns The same value, now known to satisfy {@link Brief}.\n * @throws {@link BriefError} `INVALID` when `value` fails `isBrief`.\n *\n * @example\n * ```ts\n * import { assertBrief, buildBrief, buildProof, buildTask } from '@orkestrel/brief'\n *\n * assertBrief(buildBrief(buildTask('plan', 'ops', 'Plan the release.'), { proofs: [buildProof('x', 'y')] }))\n * assertBrief({ task: { operation: 'plan', domain: 'ops', statement: 'x.' } }) // throws INVALID\n * ```\n */\nexport function assertBrief(value: unknown): Brief {\n\tif (!isBrief(value)) {\n\t\tthrow new BriefError('INVALID', 'Brief failed the exact-record contract', { field: 'brief' })\n\t}\n\treturn value\n}\n\n/**\n * Returns a fresh brief with `trace` and `hash` derived from its own content.\n *\n * @remarks\n * Deterministic: no clock, no randomness, no run-specific data. Any existing `trace` /\n * `hash` is stripped before the digest, so pinning is idempotent and a re-pin of unchanged\n * content produces the same hash.\n *\n * The snapshot is taken FIRST, before any member is read, so a hostile input whose getters\n * throw surfaces as this package's coded error rather than as whatever it threw.\n *\n * @param source - The brief to pin.\n * @returns A fresh, pinned, deeply frozen `Brief`.\n * @throws {@link BriefError} `INVALID` when the brief carries data JSON cannot express.\n *\n * @example\n * ```ts\n * import { buildBrief, buildTask, pinBrief } from '@orkestrel/brief'\n *\n * const pinned = pinBrief(buildBrief(buildTask('document', 'writing', 'Write the brief guide.')))\n * pinned.hash // an 8-hex-digit structural digest\n * pinned.trace // 'document/writing · outcomes:0 · gaps:0/0 · proofs:0'\n * ```\n */\nexport function pinBrief(source: Brief): Brief {\n\tconst owned = snapshotBrief(source)\n\tconst { trace: _trace, hash: _hash, ...content } = owned\n\treturn snapshotBrief({ ...content, trace: briefToTrace(owned), hash: briefToHash(owned) })\n}\n\n/**\n * Renders the one-line census `pinBrief` stamps onto a brief.\n *\n * @remarks\n * Extracted so it has ONE implementation. `pinBrief` derives it and `BriefManager` re-derives\n * it to reconcile an inbound brief's own `trace` against its content — an inbound `trace` is\n * shape-checked rather than verified, and it is the line `briefToMarkdown` prints at the top\n * of the executor's prompt, so a stale one misdescribes the brief where it is most read.\n *\n * @param source - The brief to describe.\n * @returns The census line: operation/domain, outcomes, blocking-over-total gaps, proofs.\n *\n * @example\n * ```ts\n * import { briefToTrace, buildBrief, buildTask } from '@orkestrel/brief'\n *\n * briefToTrace(buildBrief(buildTask('document', 'writing', 'Write the guide.')))\n * // 'document/writing · outcomes:0 · gaps:0/0 · proofs:0'\n * ```\n */\nexport function briefToTrace(source: Brief): string {\n\treturn [\n\t\t`${source.task.operation}/${source.task.domain}`,\n\t\t`outcomes:${String(source.outcomes.length)}`,\n\t\t`gaps:${String(findBlockingGaps(source).length)}/${String(source.gaps.length)}`,\n\t\t`proofs:${String(source.proofs.length)}`,\n\t].join(' · ')\n}\n\n/**\n * Renders one exemplar as markdown lines.\n *\n * @remarks\n * An `Example`'s two sides are the only brief members permitted to span lines, so a\n * single-line pair renders as one row and a multi-line pair renders as a fenced block.\n * Fencing is what stops the one permissive field from forging a heading.\n *\n * @param entry - The exemplar to render.\n * @returns The markdown lines, without a trailing blank.\n *\n * @example\n * ```ts\n * import { buildExample, exampleToLines } from '@orkestrel/brief'\n *\n * exampleToLines(buildExample('<input required>', 'el.validity')) // ['- ` <input required> ` → ` el.validity `']\n * ```\n */\nexport function exampleToLines(entry: Example): readonly string[] {\n\tconst note = entry.note === undefined ? '' : ` (${entry.note})`\n\t// The longest unbroken backtick run across both sides, so the delimiter can outrun it.\n\tlet runs = 0\n\tlet current = 0\n\tfor (const character of `${entry.input} ${entry.output}`) {\n\t\tcurrent = character === '`' ? current + 1 : 0\n\t\tif (current > runs) runs = current\n\t}\n\tif (!LINE_BREAK_PATTERN.test(entry.input) && !LINE_BREAK_PATTERN.test(entry.output)) {\n\t\t// The inline delimiter outruns the content too. A fixed single backtick is closed by an\n\t\t// exemplar containing one, which puts the rest of the value outside the code span.\n\t\t// CommonMark strips one leading and trailing space, so a padded span survives content\n\t\t// that begins or ends with a backtick.\n\t\t//\n\t\t// Padded, because CommonMark strips exactly one space from each end of a code span, so a\n\t\t// padded span returns the exemplar's own boundary spaces — withholding the pad deleted\n\t\t// them and silently changed the value the executor reads.\n\t\t//\n\t\t// The one exception is a side that is ENTIRELY spaces: CommonMark strips a fully-blank\n\t\t// span to nothing rather than one space from each end, so padding inflates it while\n\t\t// withholding the pad renders it exactly. Decided per side, since one side being blank\n\t\t// says nothing about the other.\n\t\tconst tick = '`'.repeat(runs + 1)\n\t\tconst inputPad = BLANK_PATTERN.test(entry.input) ? '' : ' '\n\t\tconst outputPad = BLANK_PATTERN.test(entry.output) ? '' : ' '\n\t\treturn [\n\t\t\t`- ${tick}${inputPad}${entry.input}${inputPad}${tick} → ${tick}${outputPad}${entry.output}${outputPad}${tick}${note}`,\n\t\t]\n\t}\n\t// The fence must outrun the content. A fixed three-backtick fence is closed by an\n\t// exemplar that contains one, which puts the rest of the example back into the\n\t// document as structure.\n\tconst fence = '`'.repeat(Math.max(3, runs) + 1)\n\treturn [\n\t\t`- exemplar${note}`,\n\t\t'',\n\t\t` ${fence}text`,\n\t\t...entry.input.split(LINE_BREAK_PATTERN).map((line) => ` ${line}`),\n\t\t` ${fence}`,\n\t\t'',\n\t\t` ${fence}text`,\n\t\t...entry.output.split(LINE_BREAK_PATTERN).map((line) => ` ${line}`),\n\t\t` ${fence}`,\n\t]\n}\n\n/**\n * Projects a brief into the copy-ready agent prompt.\n *\n * @remarks\n * Paths are REFERENCED, never inlined — the executor retrieves them. An empty section is\n * omitted entirely, so the rendering carries no filler an executor must read past.\n *\n * @param input - The brief to render.\n * @returns The markdown prompt.\n *\n * @example\n * ```ts\n * import { briefToMarkdown, buildBrief, buildTask } from '@orkestrel/brief'\n *\n * briefToMarkdown(buildBrief(buildTask('review', 'code', 'Review the gate rules.')))\n * // '# Brief: Review the gate rules.\\n\\nreview · code\\n\\n## Output\\n\\n- format: markdown\\n'\n * ```\n */\nexport function briefToMarkdown(input: Brief): string {\n\tconst source = snapshotBrief(input)\n\tconst lines: string[] = [`# Brief: ${source.task.statement}`, '']\n\tlines.push(`${source.task.operation} · ${source.task.domain}`, '')\n\tif (source.trace !== undefined) lines.push(`Trace: ${source.trace}`, '')\n\tif (source.hash !== undefined) lines.push(`Hash: ${source.hash}`, '')\n\n\tif (source.authority.length > 0) {\n\t\tlines.push('## Authority (ranked)', '')\n\t\tlines.push(\n\t\t\t...source.authority.map(\n\t\t\t\t(entry, index) => `${String(index + 1)}. ${entry.path} — ${entry.note}`,\n\t\t\t),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tconst partitions: ReadonlyArray<readonly [string, readonly Reference[]]> = [\n\t\t['Read', source.manifest.read],\n\t\t['Edit', source.manifest.edit],\n\t\t['Locked', source.manifest.locked],\n\t\t['Forbidden', source.manifest.forbidden],\n\t]\n\tif (partitions.some((partition) => partition[1].length > 0)) {\n\t\tlines.push('## Manifest', '')\n\t\tfor (const [heading, entries] of partitions) {\n\t\t\tif (entries.length === 0) continue\n\t\t\tlines.push(`### ${heading}`, '')\n\t\t\tlines.push(...entries.map((entry) => `- ${entry.path} — ${entry.note}`))\n\t\t\tlines.push('')\n\t\t}\n\t}\n\n\tif (source.outcomes.length > 0) {\n\t\tlines.push('## Outcomes', '')\n\t\tlines.push(\n\t\t\t...source.outcomes.map(\n\t\t\t\t(entry) =>\n\t\t\t\t\t`${String(entry.rank)}. ${entry.text}${entry.required ? ' (required)' : ' (optional)'}`,\n\t\t\t),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tconst prose: ReadonlyArray<readonly [string, readonly string[]]> = [\n\t\t['Rules', source.rules],\n\t\t['Invariants', source.invariants],\n\t\t['Assumptions', source.assumptions],\n\t]\n\tfor (const [heading, entries] of prose) {\n\t\tif (entries.length === 0) continue\n\t\tlines.push(`## ${heading}`, '')\n\t\tlines.push(...entries.map((entry) => `- ${entry}`))\n\t\tlines.push('')\n\t}\n\n\tif (source.givens.length > 0) {\n\t\tlines.push('## Givens', '')\n\t\tlines.push(\n\t\t\t...source.givens.map((entry) => `- ${entry.category} · ${entry.name}: ${entry.value}`),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tif (source.examples.length > 0) {\n\t\tlines.push('## Examples', '')\n\t\tfor (const entry of source.examples) {\n\t\t\tlines.push(...exampleToLines(entry))\n\t\t}\n\t\tlines.push('')\n\t}\n\n\tif (source.citations.length > 0) {\n\t\tlines.push('## Citations (trust order)', '')\n\t\tlines.push(\n\t\t\t...source.citations.map(\n\t\t\t\t(entry, index) => `${String(index + 1)}. ${entry.name} — ${entry.note} — ${entry.url}`,\n\t\t\t),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tif (source.gaps.length > 0) {\n\t\tlines.push('## Gaps', '')\n\t\tlines.push(\n\t\t\t...source.gaps.map((entry) => {\n\t\t\t\tconst mark = entry.blocking ? 'blocking' : 'open'\n\t\t\t\tconst candidates =\n\t\t\t\t\tentry.candidates === undefined ? '' : ` (candidates: ${entry.candidates.join(', ')})`\n\t\t\t\treturn `- [${mark}] ${entry.field}: ${entry.question}${candidates}`\n\t\t\t}),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tif (source.risks.length > 0) {\n\t\tlines.push('## Risks', '')\n\t\tlines.push(\n\t\t\t...source.risks.map((entry) => `- ${entry.severity}: ${entry.text} — ${entry.mitigation}`),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tlines.push('## Output', '', `- format: ${source.output.format}`)\n\tconst refinements: ReadonlyArray<readonly [string, readonly string[] | undefined]> = [\n\t\t['sections', source.output.sections],\n\t\t['include', source.output.include],\n\t\t['exclude', source.output.exclude],\n\t]\n\tfor (const [label, entries] of refinements) {\n\t\tif (entries === undefined || entries.length === 0) continue\n\t\tlines.push(`- ${label}: ${entries.join(', ')}`)\n\t}\n\tlines.push('')\n\n\tif (source.proofs.length > 0) {\n\t\tlines.push('## Proofs', '')\n\t\tlines.push(...source.proofs.map((entry) => `- ${entry.text} — \\`${entry.command}\\``))\n\t\tlines.push('')\n\t}\n\n\treturn lines.join('\\n')\n}\n\n/**\n * Projects a brief into a `/goal` completion condition.\n *\n * @remarks\n * The proofs' commands VERBATIM plus a turn cap — the goal never adds a condition the\n * brief does not carry.\n *\n * @param input - The brief to render.\n * @param turns - The turn cap. Default: `DEFAULT_BRIEF_TURNS`.\n * @returns The one-line completion condition.\n *\n * @example\n * ```ts\n * import { briefToGoal, buildBrief, buildProof, buildTask } from '@orkestrel/brief'\n *\n * briefToGoal(buildBrief(buildTask('test', 'code', 'Cover the gate.'), { proofs: [buildProof('x', 'npm test')] }))\n * // 'Done when every proof passes: npm test exits 0. Cap: 16 turns.'\n * ```\n */\nexport function briefToGoal(input: Brief, turns: number = DEFAULT_BRIEF_TURNS): string {\n\t// Every projection takes ONE owned reading. A shifting `proofs` getter would otherwise let\n\t// this emit a command that was not in the reading the contract validated.\n\tconst source = snapshotBrief(input)\n\tconst conditions =\n\t\tsource.proofs.length === 0\n\t\t\t? 'no proofs recorded'\n\t\t\t: source.proofs.map((entry) => `${entry.command} exits 0`).join('; ')\n\treturn `Done when every proof passes: ${conditions}. Cap: ${String(turns)} turns.`\n}\n\n/**\n * Projects a brief into a subagent `Dispatch`.\n *\n * @remarks\n * `edit` is exactly `manifest.edit`, so two dispatches whose `edit` sets do not intersect\n * can run concurrently under the same brief without conflict.\n *\n * `authority` is exactly `brief.authority` in rank order, and it is a SEPARATE axis from the\n * permission sets rather than a further partition — a ranked path normally also appears in\n * `read` or `locked`, because the executor has to open what it obeys. It is projected as\n * paths so a machine consumer never has to parse `prompt`, which is written for a model.\n *\n * @param input - The brief to project.\n * @returns The dispatch — the rendered prompt, the ranked authority, and the path sets.\n *\n * @example\n * ```ts\n * import {\n * \tbriefToDispatch,\n * \tbuildBrief,\n * \tbuildManifest,\n * \tbuildReference,\n * \tbuildTask,\n * } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('migrate', 'code', 'Migrate the stores.'), {\n * \tauthority: [buildReference('AGENTS.md', 'project law')],\n * \tmanifest: buildManifest({ edit: [buildReference('src/core/stores/**', 'the legacy stores')] }),\n * })\n * briefToDispatch(draft).edit // ['src/core/stores/**']\n * briefToDispatch(draft).authority // ['AGENTS.md']\n * ```\n */\nexport function briefToDispatch(input: Brief): Dispatch {\n\t// Both halves derive from ONE owned reading of the caller's value. `briefToMarkdown`\n\t// snapshots again, but of `source` rather than of `input`, and re-snapshotting an owned\n\t// frozen record is idempotent — so the prompt and the path arrays cannot disagree. Reading\n\t// the CALLER's value twice is what let a shifting getter put a row in the prompt that the\n\t// path arrays do not contain.\n\tconst source = snapshotBrief(input)\n\treturn {\n\t\tprompt: briefToMarkdown(source),\n\t\tauthority: source.authority.map((entry) => entry.path),\n\t\tread: source.manifest.read.map((entry) => entry.path),\n\t\tedit: source.manifest.edit.map((entry) => entry.path),\n\t\tlocked: source.manifest.locked.map((entry) => entry.path),\n\t\tforbidden: source.manifest.forbidden.map((entry) => entry.path),\n\t}\n}\n\n/**\n * Derives one imperative statement from free text.\n *\n * @remarks\n * Whitespace collapses, the first character uppercases, and a terminator is appended\n * when the text carries none. Nothing else is invented.\n *\n * @param text - The raw request text.\n * @returns The statement, or `undefined` for empty or whitespace-only text.\n *\n * @example\n * ```ts\n * import { deriveStatement } from '@orkestrel/brief'\n *\n * deriveStatement(' clean up useForm ') // 'Clean up useForm.'\n * deriveStatement('') // undefined\n * ```\n */\nexport function deriveStatement(text: string): string | undefined {\n\tconst collapsed = collapseWhitespace(text)\n\tif (collapsed.length === 0) return undefined\n\tconst capitalized = collapsed.charAt(0).toUpperCase() + collapsed.slice(1)\n\treturn /[.!?]$/u.test(capitalized) ? capitalized : `${capitalized}.`\n}\n\n/**\n * Derives a `Task` from an interprets `Intent` through the caller's vocabularies.\n *\n * @remarks\n * The vocabularies are the CALLER's policy: this maps and never guesses. An action or\n * domain the caller did not map — or mapped to an off-vocabulary value — yields\n * `undefined` rather than an invented task. Inherited keys never resolve. `Intent.action`\n * and `Intent.domain` are optional, because `classifyIntent` leaves an unmatched axis\n * absent, and an absent axis is unmapped by definition: it yields `undefined` before\n * either vocabulary is read.\n *\n * @param intent - The classified intent from an interpret pipeline.\n * @param text - The text the statement derives from.\n * @param actions - Maps an intent action onto a closed `TaskOperation`.\n * @param domains - Maps an intent domain onto a closed `TaskDomain`.\n * @returns The derived `Task`, or `undefined` when either side is unmapped.\n *\n * @example\n * ```ts\n * import { deriveTask } from '@orkestrel/brief'\n *\n * const intent = { action: 'migrate', domain: 'code', confidence: 1 }\n * deriveTask(intent, 'migrate the stores', { migrate: 'migrate' }, { code: 'code' })\n * // { operation: 'migrate', domain: 'code', statement: 'Migrate the stores.' }\n * deriveTask(intent, 'migrate the stores', {}, { code: 'code' }) // undefined\n * ```\n */\nexport function deriveTask(\n\tintent: Intent,\n\ttext: string,\n\tactions: Readonly<Record<string, TaskOperation>>,\n\tdomains: Readonly<Record<string, TaskDomain>>,\n): Task | undefined {\n\tif (intent.action === undefined || intent.domain === undefined) return undefined\n\tconst operationDescriptor = Object.getOwnPropertyDescriptor(actions, intent.action)\n\tconst domainDescriptor = Object.getOwnPropertyDescriptor(domains, intent.domain)\n\tconst operation: unknown =\n\t\toperationDescriptor === undefined\n\t\t\t? undefined\n\t\t\t: 'value' in operationDescriptor\n\t\t\t\t? operationDescriptor.value\n\t\t\t\t: operationDescriptor.get === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: Reflect.apply(operationDescriptor.get, actions, [])\n\tconst domain: unknown =\n\t\tdomainDescriptor === undefined\n\t\t\t? undefined\n\t\t\t: 'value' in domainDescriptor\n\t\t\t\t? domainDescriptor.value\n\t\t\t\t: domainDescriptor.get === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: Reflect.apply(domainDescriptor.get, domains, [])\n\tif (!isTaskOperation(operation) || !isTaskDomain(domain)) return undefined\n\tconst statement = deriveStatement(text)\n\treturn statement === undefined ? undefined : buildTask(operation, domain, statement)\n}\n\n/**\n * Derives `Given[]` from an interprets `Entity[]`.\n *\n * @remarks\n * Every extracted entity becomes one `extracted` fact. A nameless entity is dropped; an\n * object value renders through interprets `canonicalize`, so the text is key-order stable.\n *\n * @param entities - The entities an interpret pipeline extracted.\n * @returns One `Given` per named entity, in extraction order.\n *\n * @example\n * ```ts\n * import { deriveGivens } from '@orkestrel/brief'\n *\n * deriveGivens([\n * \t{ name: 'value', value: 3, provenance: { category: 'extracted' }, confidence: 1 },\n * ]) // [{ category: 'extracted', name: 'value', value: '3' }]\n * ```\n */\nexport function deriveGivens(entities: readonly Entity[]): readonly Given[] {\n\treturn entities\n\t\t.filter((entity) => entity.name.length > 0)\n\t\t.map((entity) =>\n\t\t\tbuildGiven(\n\t\t\t\t'extracted',\n\t\t\t\tentity.name,\n\t\t\t\ttypeof entity.value === 'string'\n\t\t\t\t\t? entity.value\n\t\t\t\t\t: typeof entity.value === 'object' && entity.value !== null\n\t\t\t\t\t\t? canonicalize(entity.value)\n\t\t\t\t\t\t: String(entity.value),\n\t\t\t),\n\t\t)\n}\n\n/**\n * Derives `Gap[]` from an interprets `Ambiguity[]`.\n *\n * @remarks\n * A REQUIRED ambiguity becomes a BLOCKING gap — the gate must fail closed on it. The\n * rest stay open, to be answered with a recorded assumption. An array field path flattens\n * through reasons `formatField`.\n *\n * @param ambiguities - The ambiguities an interpret pipeline surfaced.\n * @returns One `Gap` per ambiguity, in surfacing order.\n *\n * @example\n * ```ts\n * import { deriveGaps } from '@orkestrel/brief'\n *\n * deriveGaps([{ field: 'output', question: 'Diff or files?', candidates: [], required: true }])\n * // [{ field: 'output', question: 'Diff or files?', blocking: true }]\n * ```\n */\nexport function deriveGaps(ambiguities: readonly Ambiguity[]): readonly Gap[] {\n\treturn ambiguities.map((ambiguity) => {\n\t\tconst candidates = ambiguity.candidates.filter((candidate) => candidate.length > 0)\n\t\treturn buildGap(formatField(ambiguity.field), ambiguity.question, {\n\t\t\tblocking: ambiguity.required,\n\t\t\t...(candidates.length === 0 ? {} : { candidates }),\n\t\t})\n\t})\n}\n","import type { Brief } from './types.js'\nimport { parseJSONAs } from '@orkestrel/contract'\nimport { isBrief } from './validators.js'\n\n/**\n * Parses a JSON string into a `Brief`.\n *\n * @remarks\n * The parse-then-trust boundary for a stored brief, a tool argument, or an agent's\n * emission. Invalid JSON, an extra key, an off-vocabulary literal, and a missing section\n * all fail the same way — `undefined`, never a throw. Coerce a bare vocabulary value with\n * `parseEnum` from `@orkestrel/contract` against the exported tuple instead.\n *\n * The half of the intake pair that is OWNED BY CONSTRUCTION, which is what separates it from\n * `assertBrief`. The argument is text, so the graph the guard reads is one `JSON.parse` built\n * inside this call: it carries no caller identity, no accessor, and no alias back into anything\n * the caller still holds, and the parse-and-guard primitive this file imports from\n * `@orkestrel/contract` returns that same parsed graph rather than a second reading of it.\n * Every member `isBrief` checked therefore answers a later reader identically. The value is\n * fresh rather than frozen, so the caller owns it outright — reach for `snapshotBrief` when the\n * value came from code instead of from text.\n *\n * @param value - The JSON text to parse.\n * @returns The `Brief` when the parsed value satisfies `isBrief`, otherwise `undefined`.\n *\n * @example\n * ```ts\n * import { parseBrief } from '@orkestrel/brief'\n *\n * parseBrief('not json') // undefined\n * parseBrief('{\"task\":{\"operation\":\"plan\",\"domain\":\"ops\",\"statement\":\"x.\"}}') // undefined\n * ```\n */\nexport function parseBrief(value: string): Brief | undefined {\n\treturn parseJSONAs(value, isBrief)\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { RecordOptions } from '@orkestrel/interpret'\nimport type {\n\tBrief,\n\tBriefManagerEventMap,\n\tBriefManagerInterface,\n\tBriefManagerOptions,\n\tBriefRecord,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { snapshotBrief } from './cloners.js'\nimport { BriefError } from './errors.js'\nimport { briefToContent, briefToHash, briefToTrace } from './helpers.js'\n\n/**\n * Implements the self-owning, versioned and content-hashed brief registry.\n *\n * @remarks\n * Record ids are MINTED from each brief's own content hash unless the caller names one,\n * so registering unchanged content twice is a version no-op and two callers who compiled\n * the same request land on the same id with no coordination. A call after `destroy()`\n * throws `BriefError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { BriefManager, buildBrief, buildTask } from '@orkestrel/brief'\n *\n * const briefs = new BriefManager()\n * const record = briefs.add(buildBrief(buildTask('document', 'writing', 'Write the brief guide.')))\n * record.id === record.hash // true\n * briefs.destroy()\n * ```\n */\nexport class BriefManager implements BriefManagerInterface {\n\treadonly #emitter: Emitter<BriefManagerEventMap>\n\treadonly #records = new Map<string, BriefRecord>()\n\t#destroyed = false\n\n\tconstructor(options?: BriefManagerOptions) {\n\t\t// One read per option; a second read lets a getter answer differently.\n\t\tconst hooks = options?.on\n\t\tconst failed = options?.error\n\t\tconst seeds = options?.briefs ?? []\n\t\t// Seeding is ALL-OR-NOTHING. `add` throws INVALID for an off-contract or colliding\n\t\t// entry, so seeding straight into the registry emitted `add` for earlier entries and\n\t\t// then abandoned a constructor that never returns — hooks observing ids for an instance\n\t\t// the caller does not have, and an emitter nothing can destroy. Validate every seed\n\t\t// first, then build the emitter, then commit.\n\t\tconst staged = new Map<string, BriefRecord>()\n\t\tfor (const entry of seeds) {\n\t\t\tconst record = this.#stage(entry, staged)\n\t\t\tstaged.set(record.id, record)\n\t\t}\n\t\tthis.#emitter = new Emitter<BriefManagerEventMap>({\n\t\t\t...(hooks === undefined ? {} : { on: hooks }),\n\t\t\t...(failed === undefined ? {} : { error: failed }),\n\t\t})\n\t\tfor (const record of staged.values()) this.#commit(record)\n\t}\n\n\tget emitter(): EmitterInterface<BriefManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#records.size\n\t}\n\n\thas(id: string): boolean {\n\t\tthis.#refuseDestroyed()\n\t\treturn this.#records.has(id)\n\t}\n\n\tbrief(id: string): BriefRecord | undefined {\n\t\tthis.#refuseDestroyed()\n\t\treturn this.#records.get(id)\n\t}\n\n\tbriefs(): readonly BriefRecord[] {\n\t\tthis.#refuseDestroyed()\n\t\treturn [...this.#records.values()]\n\t}\n\n\tadd(brief: Brief, options?: RecordOptions): BriefRecord {\n\t\tthis.#refuseDestroyed()\n\t\tconst record = this.#stage(brief, this.#records, options)\n\t\tthis.#commit(record)\n\t\treturn record\n\t}\n\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tthis.#refuseDestroyed()\n\t\tif (target === undefined) {\n\t\t\tfor (const id of [...this.#records.keys()]) this.#discard(id)\n\t\t\treturn\n\t\t}\n\t\tif (typeof target === 'string') return this.#discard(target)\n\t\t// Deduplicated, because the contract is about the listed SET. A repeated id was removed\n\t\t// on its first pass and then reported missing on its second, so `remove(['a', 'a'])`\n\t\t// returned false for a record it had just removed.\n\t\tlet removed = true\n\t\tfor (const id of new Set(target)) {\n\t\t\tif (!this.#discard(id)) removed = false\n\t\t}\n\t\treturn removed\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#records.clear()\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// Build the record without registering or announcing it. Split out of `add` so the\n\t// constructor can validate every seed before committing any: `snapshotBrief` and `#version`\n\t// both throw INVALID, and seeding straight into the registry left earlier entries announced\n\t// on an instance that never returned. `against` is the registry to version against — the\n\t// live one for `add`, the in-progress staging map while seeding, so two colliding seeds are\n\t// caught the same way two colliding adds are.\n\t#stage(\n\t\tsource: Brief,\n\t\tagainst: ReadonlyMap<string, BriefRecord>,\n\t\toptions?: RecordOptions,\n\t): BriefRecord {\n\t\t// Snapshot first: a record whose brief still aliases the caller's arrays would let a\n\t\t// later push change content this hash already described.\n\t\tconst owned = snapshotBrief(source)\n\t\tconst hash = briefToHash(owned)\n\t\t// An inbound brief's own `hash` is shape-checked, not verified — that is what lets a\n\t\t// pinned brief round-trip through JSON. So a record arriving with a hash that\n\t\t// contradicts its content is refused HERE, at the identity boundary, rather than\n\t\t// stored and later projected into an executor's prompt as if it were pinned.\n\t\tif (owned.hash !== undefined && owned.hash !== hash) {\n\t\t\tthrow new BriefError('INVALID', 'Brief carries a hash that does not describe it', {\n\t\t\t\tfield: 'hash',\n\t\t\t\thash: owned.hash,\n\t\t\t})\n\t\t}\n\t\t// `trace` gets the same reconciliation, and needs it more: `hash` is an opaque digest a\n\t\t// reader cannot check, while `trace` is the census line `briefToMarkdown` prints at the\n\t\t// top of the executor's prompt. A stale one misdescribes the brief exactly where it is\n\t\t// most read.\n\t\tconst trace = briefToTrace(owned)\n\t\tif (owned.trace !== undefined && owned.trace !== trace) {\n\t\t\tthrow new BriefError('INVALID', 'Brief carries a trace that does not describe it', {\n\t\t\t\tfield: 'trace',\n\t\t\t\ttrace: owned.trace,\n\t\t\t})\n\t\t}\n\t\tconst id = options?.id ?? hash\n\t\tconst previous = against.get(id)\n\t\treturn Object.freeze({\n\t\t\tid,\n\t\t\tbrief: owned,\n\t\t\tversion: previous === undefined ? 1 : this.#version(previous, owned, hash),\n\t\t\thash,\n\t\t})\n\t}\n\n\t// Register a staged record and announce it. Nothing here can throw, which is what makes\n\t// seeding all-or-nothing after every entry has been staged.\n\t#commit(record: BriefRecord): void {\n\t\tthis.#records.set(record.id, record)\n\t\tthis.#emitter.emit('add', record.id)\n\t}\n\n\t// The version a re-add earns, and the one place a digest collision is caught. The hash is\n\t// eight hex digits, so two DIFFERENT briefs can land on one id; treating that as\n\t// \"unchanged content\" would silently replace the first and report version 1. Content is\n\t// compared canonically, and only equal content is a version no-op.\n\t#version(previous: BriefRecord, incoming: Brief, hash: string): number {\n\t\tif (previous.hash !== hash) return previous.version + 1\n\t\t// Compare exactly what the hash describes. `briefToHash` strips `trace` and `hash`\n\t\t// first, so a draft and its own pinned form share a hash while their whole records\n\t\t// differ — comparing whole records would report that as a collision.\n\t\tif (briefToContent(previous.brief) === briefToContent(incoming)) return previous.version\n\t\tthrow new BriefError(\n\t\t\t'INVALID',\n\t\t\t'Two different briefs share one content hash — name them with distinct ids',\n\t\t\t{ field: 'hash', hash },\n\t\t)\n\t}\n\n\t// Deletes one record and emits only when a record was actually there.\n\t#discard(id: string): boolean {\n\t\tif (!this.#records.delete(id)) return false\n\t\tthis.#emitter.emit('remove', id)\n\t\treturn true\n\t}\n\n\t// Every method except the getters and `destroy` refuses a destroyed manager.\n\t#refuseDestroyed(): void {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new BriefError('DESTROYED', 'BriefManager has been destroyed')\n\t\t}\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { Interpretation, InterpretInterface } from '@orkestrel/interpret'\nimport type { LogicalResult, ReasonInterface } from '@orkestrel/reason'\nimport type {\n\tBrief,\n\tBriefInput,\n\tBriefing,\n\tBriefStageFailure,\n\tBriefStageRecord,\n\tBriefCompilerEventMap,\n\tBriefCompilerInterface,\n\tBriefCompilerOptions,\n\tGap,\n\tTaskDomain,\n\tTaskOperation,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { createInterpret, digestValue, isInterpretation } from '@orkestrel/interpret'\nimport { attempt } from '@orkestrel/contract'\nimport { createLogicalReasoner, createReason, isLogicalResult } from '@orkestrel/reason'\nimport { captureValue, snapshotBrief } from './cloners.js'\nimport { INTERPRETATION_MEMBERS } from './constants.js'\nimport { BriefError } from './errors.js'\nimport {\n\tbriefToSubject,\n\tbuildBrief,\n\tbuildGap,\n\tbuildGateDefinition,\n\tbuildManifest,\n\tbuildOutput,\n\tderiveGaps,\n\tderiveGivens,\n\tderiveTask,\n\terrorToMessage,\n\tfindBlockingGaps,\n\tfindUnmetRules,\n\tfreezeDeep,\n\tpinBrief,\n} from './helpers.js'\n\n/**\n * Implements the compilation orchestrator — the `[interpret, draft, gate, pin]` pipeline.\n *\n * @remarks\n * `compile` is genuinely SYNCHRONOUS and never throws for a brief it cannot emit: a\n * blocking gap, a refused gate, and a thrown stage all yield a visible INCOMPLETE\n * `Briefing`. It owns the engines it created and BORROWS the ones passed in, so\n * `destroy()` releases only what it made.\n *\n * @example\n * ```ts\n * import { BriefCompiler, buildProof, buildTask } from '@orkestrel/brief'\n *\n * const compiler = new BriefCompiler()\n * const briefing = compiler.compile({\n * \ttask: buildTask('audit', 'code', 'Audit the barrel for undocumented exports.'),\n * \toutcomes: [{ rank: 1, text: 'every export appears in the guide', required: true }],\n * \tproofs: [buildProof('parity passes', 'npm run test:guides')],\n * })\n * briefing.brief !== undefined // true — the presence of the brief IS the completeness test\n * compiler.destroy()\n * ```\n */\nexport class BriefCompiler implements BriefCompilerInterface {\n\treadonly #emitter: Emitter<BriefCompilerEventMap>\n\treadonly #interpret: InterpretInterface\n\treadonly #reason: ReasonInterface\n\treadonly #ownInterpret: boolean\n\treadonly #ownReason: boolean\n\treadonly #actions: Readonly<Record<string, TaskOperation>>\n\treadonly #domains: Readonly<Record<string, TaskDomain>>\n\t#destroyed = false\n\n\tconstructor(options?: BriefCompilerOptions) {\n\t\t// ONE read per option, for the reason `compile` takes one reading of its input: a second\n\t\t// read lets a getter answer differently. Reading `interpret` twice decided ownership from\n\t\t// the first answer and stored the second, so a borrowed engine could be destroyed and a\n\t\t// self-made one leaked — the exact inversion of the documented contract.\n\t\tconst hooks = options?.on\n\t\tconst failed = options?.error\n\t\tconst borrowedInterpret = options?.interpret\n\t\tconst borrowedReason = options?.reason\n\t\tthis.#emitter = new Emitter<BriefCompilerEventMap>({\n\t\t\t...(hooks === undefined ? {} : { on: hooks }),\n\t\t\t...(failed === undefined ? {} : { error: failed }),\n\t\t})\n\t\tthis.#ownInterpret = borrowedInterpret === undefined\n\t\tthis.#ownReason = borrowedReason === undefined\n\t\tthis.#interpret = borrowedInterpret ?? createInterpret()\n\t\tthis.#reason = borrowedReason ?? createReason({ reasoners: [createLogicalReasoner()] })\n\t\tthis.#actions = options?.actions ?? {}\n\t\tthis.#domains = options?.domains ?? {}\n\t}\n\n\tget emitter(): EmitterInterface<BriefCompilerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget interpret(): InterpretInterface {\n\t\treturn this.#interpret\n\t}\n\n\tget reason(): ReasonInterface {\n\t\treturn this.#reason\n\t}\n\n\tcompile(input: BriefInput): Briefing {\n\t\tthis.#refuseDestroyed()\n\t\tconst stages: BriefStageRecord[] = []\n\t\tconst failures: BriefStageFailure[] = []\n\n\t\t// ONE reading of the caller's object, taken first and used by every following stage. Reading\n\t\t// it again per stage let a getter answer differently each time, so the replay could\n\t\t// describe a compilation that did not happen — and a getter that THREW escaped `compile`\n\t\t// as a foreign error, which this contains into the same visible refusal as any other\n\t\t// stage failure.\n\t\tconst taken = attempt(() => this.#snapshot(input))\n\t\tif (!taken.success) {\n\t\t\tconst message = errorToMessage(taken.error)\n\t\t\tstages.push(Object.freeze({ stage: 'draft', input: {}, error: message }))\n\t\t\tfailures.push(Object.freeze({ stage: 'draft', code: 'DRAFT_FAILED', message }))\n\t\t\tthis.#emitter.emit('error', taken.error)\n\t\t\treturn this.#refuse(undefined, undefined, [], undefined, stages, failures)\n\t\t}\n\t\tconst owned = taken.value\n\n\t\tconst interpretation = this.#read(owned, input, stages, failures)\n\n\t\tconst drafted = attempt(() =>\n\t\t\tthis.#draft(owned, interpretation, this.#unresolved(interpretation, failures)),\n\t\t)\n\t\tif (!drafted.success) {\n\t\t\tconst message = errorToMessage(drafted.error)\n\t\t\tstages.push(Object.freeze({ stage: 'draft', input: owned, error: message }))\n\t\t\tfailures.push(Object.freeze({ stage: 'draft', code: 'DRAFT_FAILED', message }))\n\t\t\tthis.#emitter.emit('error', drafted.error)\n\t\t\treturn this.#refuse(interpretation, undefined, [], undefined, stages, failures)\n\t\t}\n\t\tconst draft = drafted.value\n\t\tstages.push(Object.freeze({ stage: 'draft', input: owned, output: draft }))\n\n\t\tconst questions = findBlockingGaps(draft)\n\t\tconst subject = Object.freeze(briefToSubject(draft))\n\t\t// `gate` owns the verdict at arrival, so it is already this compiler's own frozen value —\n\t\t// no second reading here. Contained, because a borrowed engine's throw must not escape.\n\t\tconst ruled = attempt(() => this.gate(draft))\n\t\tif (ruled.success) {\n\t\t\tstages.push(Object.freeze({ stage: 'gate', input: subject, output: ruled.value }))\n\t\t} else {\n\t\t\tconst message = errorToMessage(ruled.error)\n\t\t\tstages.push(Object.freeze({ stage: 'gate', input: subject, error: message }))\n\t\t\tfailures.push(Object.freeze({ stage: 'gate', code: 'GATE_FAILED', message }))\n\t\t\tthis.#emitter.emit('error', ruled.error)\n\t\t}\n\t\tconst verdict = ruled.success ? ruled.value : undefined\n\n\t\t// Readiness is decided HERE, from the measures, before the verdict is consulted. The\n\t\t// reasoner is borrowed — `BriefCompilerOptions.reason` is a documented seam — so its verdict\n\t\t// narrates and never decides: a supplied engine can add detail to a refusal and can\n\t\t// never turn one into a pass.\n\t\tconst unready = findUnmetRules(draft)\n\t\tif (unready.length > 0 || verdict === undefined || !verdict.conclusion) {\n\t\t\tconst refusal = this.#blockage(questions, unready, verdict)\n\t\t\tif (refusal !== undefined) failures.push(Object.freeze(refusal))\n\t\t\treturn this.#refuse(interpretation, draft, questions, verdict, stages, failures)\n\t\t}\n\n\t\tconst stamped = attempt(() => pinBrief(draft))\n\t\tif (!stamped.success) {\n\t\t\tconst message = errorToMessage(stamped.error)\n\t\t\tstages.push(Object.freeze({ stage: 'pin', input: draft, error: message }))\n\t\t\tfailures.push(Object.freeze({ stage: 'pin', code: 'PIN_FAILED', message }))\n\t\t\tthis.#emitter.emit('error', stamped.error)\n\t\t\treturn this.#refuse(interpretation, draft, questions, verdict, stages, failures)\n\t\t}\n\t\tconst pinned = stamped.value\n\t\tstages.push(Object.freeze({ stage: 'pin', input: draft, output: pinned }))\n\n\t\tconst briefing: Briefing = Object.freeze({\n\t\t\t...(interpretation === undefined ? {} : { interpretation }),\n\t\t\tbrief: pinned,\n\t\t\tquestions: Object.freeze([]),\n\t\t\tverdict,\n\t\t\tstages: Object.freeze([...stages]),\n\t\t\tfailures: Object.freeze([...failures]),\n\t\t\tdigest: digestValue({ brief: pinned, questions: [], failures }),\n\t\t})\n\t\tthis.#emitter.emit('compile', briefing)\n\t\treturn briefing\n\t}\n\n\tgate(brief: Brief): LogicalResult {\n\t\tthis.#refuseDestroyed()\n\t\t// The reasoner is BORROWED, so it can throw its own foreign error — a `ReasonError` from\n\t\t// an engine the caller already destroyed, for one. Every throw out of this module is a\n\t\t// `BriefError` that `isBriefError` narrows, so a foreign throw is translated rather than\n\t\t// leaked.\n\t\t// OWNED at arrival, then validated on the owned copy — one reading of the foreign value,\n\t\t// the law `compile` already applies to the caller's input. Validating one reading and\n\t\t// recording another let a getter bless a shape the pipeline never saw.\n\t\tconst ruled = attempt(() =>\n\t\t\tthis.#own(this.#reason.reason(briefToSubject(brief), buildGateDefinition()), [\n\t\t\t\t'reasoning',\n\t\t\t\t'conclusion',\n\t\t\t\t'rules',\n\t\t\t\t'count',\n\t\t\t\t'success',\n\t\t\t\t'trace',\n\t\t\t\t'errors',\n\t\t\t]),\n\t\t)\n\t\tif (!ruled.success) {\n\t\t\tthrow new BriefError('GATE_FAILED', errorToMessage(ruled.error), {\n\t\t\t\tstage: 'gate',\n\t\t\t\tfield: 'reason',\n\t\t\t})\n\t\t}\n\t\tconst verdict = ruled.value\n\t\t// Guard the WHOLE value, not one field. The reasoner is borrowed, so its return is\n\t\t// foreign data however well-typed the interface is: reading `.reasoning` off `undefined`\n\t\t// threw a raw TypeError where the contract promises `GATE_FAILED`, and a result that\n\t\t// claimed `reasoning: 'logical'` without a `rules` array crashed the caller of this\n\t\t// method instead. reason's published `isLogicalResult` is total, so every malformed\n\t\t// shape lands here.\n\t\tif (!isLogicalResult(verdict)) {\n\t\t\tthrow new BriefError('GATE_FAILED', 'The gate reasoner returned a non-logical result', {\n\t\t\t\tstage: 'gate',\n\t\t\t\tfield: 'reasoning',\n\t\t\t})\n\t\t}\n\t\treturn verdict\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tif (this.#ownInterpret) this.#interpret.destroy()\n\t\tif (this.#ownReason) this.#reason.destroy()\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// THE reading of the caller's input — taken once, deep, and shared by every stage. A\n\t// per-field copy left the members aliased, and a second reading let a getter answer\n\t// differently, so there is exactly one and no fallback that re-reads. The freeze is DEEP\n\t// because `Object.freeze` alone left every nested array writable, so a consumer could\n\t// rewrite the recorded stage input after the digest describing it was sealed. Throws for\n\t// an input that cannot be cloned; `compile` contains that into a visible refusal.\n\t#snapshot(input: BriefInput): BriefInput {\n\t\treturn freezeDeep(structuredClone(input))\n\t}\n\n\t// THE ownership boundary for every value a BORROWED engine returns. `Briefing` is documented\n\t// as replayable, and a foreign object is neither ours nor stable — it may be pooled, mutated\n\t// later, or handed to another caller.\n\t//\n\t// It NEVER narrows past the foreign contract, which is the law the verdict guards already\n\t// follow. `structuredClone` accepts JSON and a little more; the contracts here are wider —\n\t// `Entity.value` is declared `unknown`, and `LogicalResult` is an interface a class instance\n\t// satisfies. Cloning unconditionally therefore FAILED a stage for a type-conforming engine\n\t// result, and for the interpret stage that failure deleted the derived blocking gaps and let\n\t// an under-specified brief through the gate.\n\t//\n\t// So: clone when the value permits it, which also breaks the alias, and otherwise capture a\n\t// plain view that materializes the published members once while retaining uncloneable leaves.\n\t// Every later read is of that frozen view. What is never acceptable is refusing the value.\n\t#own(value: unknown, members: readonly string[]): unknown {\n\t\tconst cloned = attempt(() => structuredClone(value))\n\t\treturn cloned.success ? freezeDeep(cloned.value) : captureValue(value, members)\n\t}\n\n\t// The interpret stage. Skipped entirely when the input carries no text, in which case\n\t// a caller-supplied interpretation still reaches the draft. Both doors are guarded with\n\t// interpret's published `isInterpretation` before anything dereferences `intent`,\n\t// `entities`, or `ambiguities`: the engine is borrowed, and a malformed return threw a\n\t// raw TypeError out of `compile` where the contract promises INTERPRET_FAILED. The\n\t// supplied-interpretation door shares the guard for the caller a type system cannot\n\t// see — a JS consumer or a replayed value — at the cost of one total check.\n\t#read(\n\t\tinput: BriefInput,\n\t\traw: BriefInput,\n\t\tstages: BriefStageRecord[],\n\t\tfailures: BriefStageFailure[],\n\t): Interpretation | undefined {\n\t\tconst text = input.text\n\t\tif (text !== undefined) {\n\t\t\t// Owned for the same reason the verdict is: the engine is borrowed and its\n\t\t\t// `Interpretation` is foreign data the briefing then carries as a replay.\n\t\t\tconst read = attempt(() => this.#own(this.#interpret.interpret(text), INTERPRETATION_MEMBERS))\n\t\t\tif (read.success && isInterpretation(read.value)) {\n\t\t\t\tstages.push(Object.freeze({ stage: 'interpret', input: text, output: read.value }))\n\t\t\t\treturn read.value\n\t\t\t}\n\t\t\tconst message = read.success\n\t\t\t\t? 'The interpret engine returned a non-interpretation result'\n\t\t\t\t: errorToMessage(read.error)\n\t\t\tstages.push(Object.freeze({ stage: 'interpret', input: text, error: message }))\n\t\t\tfailures.push(Object.freeze({ stage: 'interpret', code: 'INTERPRET_FAILED', message }))\n\t\t\tthis.#emitter.emit(\n\t\t\t\t'error',\n\t\t\t\tread.success\n\t\t\t\t\t? new BriefError('INTERPRET_FAILED', message, { stage: 'interpret' })\n\t\t\t\t\t: read.error,\n\t\t\t)\n\t\t}\n\t\tconst supplied = input.interpretation\n\t\tif (supplied === undefined || isInterpretation(supplied)) return supplied\n\t\t// The snapshot's clone keeps own members only, so a conforming interpretation carried\n\t\t// by prototype accessors arrives here empty. Capture the live value into a plain view;\n\t\t// no later read remains attached to the caller's accessors.\n\t\tconst live = raw.interpretation\n\t\tconst captured = attempt(() => captureValue(live, INTERPRETATION_MEMBERS))\n\t\tif (captured.success && isInterpretation(captured.value)) return captured.value\n\t\tconst message = 'The supplied interpretation does not satisfy the published shape'\n\t\tstages.push(Object.freeze({ stage: 'interpret', input: 'interpretation', error: message }))\n\t\tfailures.push(Object.freeze({ stage: 'interpret', code: 'INTERPRET_FAILED', message }))\n\t\treturn undefined\n\t}\n\n\t// The one place a refusal is coded. Blocking gaps ALWAYS produce `BLOCKED`, including\n\t// when the gate itself threw and left no verdict to report rules from.\n\t#blockage(\n\t\tquestions: readonly Gap[],\n\t\tunready: readonly string[],\n\t\tverdict: LogicalResult | undefined,\n\t): BriefStageFailure | undefined {\n\t\tif (questions.length > 0) {\n\t\t\treturn {\n\t\t\t\tstage: 'gate',\n\t\t\t\tcode: 'BLOCKED',\n\t\t\t\tmessage: `${String(questions.length)} blocking gap(s)`,\n\t\t\t}\n\t\t}\n\t\t// The measured refusal is named first, because it is the one that decided.\n\t\tif (unready.length > 0) {\n\t\t\treturn { stage: 'gate', code: 'BLOCKED', message: `Gate refused: ${unready.join(', ')}` }\n\t\t}\n\t\tif (verdict === undefined) return undefined\n\t\tconst refused = verdict.rules\n\t\t\t.filter((entry) => !entry.applied)\n\t\t\t.map((entry) => entry.id)\n\t\t\t.join(', ')\n\t\t// A borrowed engine may refuse through `conclusion` alone and name no failing rule, which\n\t\t// rendered as `Gate refused: ` — a refusal with the cause cut off. The refusal is correct\n\t\t// and this is the one case where the supplied engine is the sole decider, so say so.\n\t\tif (refused.length === 0) {\n\t\t\treturn {\n\t\t\t\tstage: 'gate',\n\t\t\t\tcode: 'BLOCKED',\n\t\t\t\tmessage: 'Gate refused: the supplied reasoner named no failing rule',\n\t\t\t}\n\t\t}\n\t\treturn { stage: 'gate', code: 'BLOCKED', message: `Gate refused: ${refused}` }\n\t}\n\n\t// The blocking gap a CONTAINED interpret failure owes the brief.\n\t//\n\t// Containing that failure is right, but it silently deleted what the stage would have\n\t// produced: `deriveGaps(interpretation.ambiguities)`. With the ambiguities gone,\n\t// `findBlockingGaps` was empty, `findUnmetRules` dropped `specified`, the gate passed, and\n\t// `compile` emitted a pinned brief for a request it had correctly refused a moment earlier.\n\t// A failure that removes evidence must never read as evidence of readiness.\n\t//\n\t// Empty when an interpretation survived — a caller-supplied `BriefInput.interpretation`\n\t// carries its own ambiguities, so nothing was lost.\n\t#unresolved(\n\t\tinterpretation: Interpretation | undefined,\n\t\tfailures: readonly BriefStageFailure[],\n\t): readonly Gap[] {\n\t\tif (interpretation !== undefined) return []\n\t\tif (!failures.some((entry) => entry.stage === 'interpret')) return []\n\t\treturn [\n\t\t\tbuildGap(\n\t\t\t\t'gaps',\n\t\t\t\t'The interpret stage failed, so the request is unread and its unknowns are unknown',\n\t\t\t\t{\n\t\t\t\t\tblocking: true,\n\t\t\t\t},\n\t\t\t),\n\t\t]\n\t}\n\n\t// The draft stage. Derived sections come first and caller sections merge OVER them,\n\t// so the user is never overridden; derived and caller gaps and givens accumulate.\n\t#draft(\n\t\tinput: BriefInput,\n\t\tinterpretation: Interpretation | undefined,\n\t\tunresolved: readonly Gap[],\n\t): Brief {\n\t\tconst derived =\n\t\t\tinterpretation === undefined\n\t\t\t\t? undefined\n\t\t\t\t: deriveTask(interpretation.intent, interpretation.text, this.#actions, this.#domains)\n\t\tconst subject = input.task ?? derived\n\t\tif (subject === undefined) {\n\t\t\tthrow new BriefError(\n\t\t\t\t'DRAFT_FAILED',\n\t\t\t\t'No task: supply BriefInput.task, or map the intent through the actions and domains vocabularies',\n\t\t\t\t{ stage: 'draft', field: 'task' },\n\t\t\t)\n\t\t}\n\t\t// Snapshot at the draft, not only at the pin. A drafted brief adopts the caller's\n\t\t// arrays, and it is what `Briefing.stages` records — a replay that changes when the\n\t\t// caller mutates their own input afterwards is not a replay.\n\t\treturn snapshotBrief(\n\t\t\tbuildBrief(subject, {\n\t\t\t\tauthority: input.authority ?? [],\n\t\t\t\tmanifest: input.manifest ?? buildManifest(),\n\t\t\t\toutcomes: input.outcomes ?? [],\n\t\t\t\trules: input.rules ?? [],\n\t\t\t\tinvariants: input.invariants ?? [],\n\t\t\t\tgivens: [\n\t\t\t\t\t...(interpretation === undefined ? [] : deriveGivens(interpretation.entities)),\n\t\t\t\t\t...(input.givens ?? []),\n\t\t\t\t],\n\t\t\t\texamples: input.examples ?? [],\n\t\t\t\tassumptions: input.assumptions ?? [],\n\t\t\t\tcitations: input.citations ?? [],\n\t\t\t\tgaps: [\n\t\t\t\t\t...(interpretation === undefined ? [] : deriveGaps(interpretation.ambiguities)),\n\t\t\t\t\t...unresolved,\n\t\t\t\t\t...(input.gaps ?? []),\n\t\t\t\t],\n\t\t\t\trisks: input.risks ?? [],\n\t\t\t\toutput: input.output ?? buildOutput('markdown'),\n\t\t\t\tproofs: input.proofs ?? [],\n\t\t\t}),\n\t\t)\n\t}\n\n\t// The one incomplete result shape: no brief, the questions visible, `block` emitted.\n\t#refuse(\n\t\tinterpretation: Interpretation | undefined,\n\t\tdraft: Brief | undefined,\n\t\tquestions: readonly Gap[],\n\t\tverdict: LogicalResult | undefined,\n\t\tstages: readonly BriefStageRecord[],\n\t\tfailures: readonly BriefStageFailure[],\n\t): Briefing {\n\t\t// Frozen exactly as the complete path is. The incomplete briefing is this package's\n\t\t// headline artifact — the visible refusal — so it must not be the mutable one: a\n\t\t// `failures.pop()` would drop the `BLOCKED` marker the `digest` already attests to.\n\t\t// ONE frozen array, carried by the briefing AND handed to every listener. Emitting the\n\t\t// caller-reachable `questions` instead gave observers a mutable array that was not the\n\t\t// briefing's: one listener could rewrite what the next was handed, and neither reached\n\t\t// the record the digest attests to. Observation is a side-channel, so it reads exactly\n\t\t// what the briefing carries and can change nothing.\n\t\tconst asked = Object.freeze([...questions])\n\t\tconst briefing: Briefing = Object.freeze({\n\t\t\t...(interpretation === undefined ? {} : { interpretation }),\n\t\t\tquestions: asked,\n\t\t\t...(verdict === undefined ? {} : { verdict }),\n\t\t\tstages: Object.freeze([...stages]),\n\t\t\tfailures: Object.freeze([...failures]),\n\t\t\t// The DRAFT is digested, for the reason the pinned brief is on the complete path.\n\t\t\t// Digesting only `questions` and `failures` gave every ordinary refusal one digest —\n\t\t\t// two entirely different requests refused for \"no proofs\" were indistinguishable, in\n\t\t\t// the member documented as identifying the outcome and offered as a cache key.\n\t\t\tdigest: digestValue({\n\t\t\t\t...(draft === undefined ? {} : { brief: draft }),\n\t\t\t\tquestions,\n\t\t\t\tfailures,\n\t\t\t}),\n\t\t})\n\t\tthis.#emitter.emit('block', asked)\n\t\treturn briefing\n\t}\n\n\t// Every method except the getters and `destroy` refuses a destroyed compiler.\n\t#refuseDestroyed(): void {\n\t\tif (this.#destroyed) throw new BriefError('DESTROYED', 'BriefCompiler has been destroyed')\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tBrief,\n\tBriefManagerInterface,\n\tBriefManagerOptions,\n\tBriefCompilerInterface,\n\tBriefCompilerOptions,\n} from './types.js'\nimport { createContract } from '@orkestrel/contract'\nimport { BriefManager } from './BriefManager.js'\nimport { BriefCompiler } from './BriefCompiler.js'\nimport { briefShape } from './shapers.js'\n\n/**\n * Creates a compilation orchestrator.\n *\n * @remarks\n * With no engines supplied the compiler wires its own: a default `createInterpret()`\n * (empty vocabularies, so `options.actions` / `options.domains` drive `deriveTask`) and a\n * `createReason` carrying one `LogicalReasoner` for the gate. Pass your own to share\n * instances or observe their emitters — the compiler destroys ONLY what it created.\n *\n * @param options - Engines to borrow, the `actions` and `domains` intent vocabularies, and\n * emitter hooks.\n * @returns A working {@link BriefCompilerInterface}.\n *\n * @example\n * ```ts\n * import { createBriefCompiler } from '@orkestrel/brief'\n *\n * const compiler = createBriefCompiler({ actions: { refactor: 'refactor' }, domains: { code: 'code' } })\n * compiler.destroy()\n * ```\n */\nexport function createBriefCompiler(options?: BriefCompilerOptions): BriefCompilerInterface {\n\treturn new BriefCompiler(options)\n}\n\n/**\n * Creates a brief registry.\n *\n * @param options - An optional seed collection plus emitter hooks.\n * @returns A working {@link BriefManagerInterface}.\n *\n * @example\n * ```ts\n * import { createBriefManager } from '@orkestrel/brief'\n *\n * const briefs = createBriefManager()\n * briefs.count // 0\n * briefs.destroy()\n * ```\n */\nexport function createBriefManager(options?: BriefManagerOptions): BriefManagerInterface {\n\treturn new BriefManager(options)\n}\n\n/**\n * Compiles `briefShape` into a guard, parser, JSON Schema, and seeded generator bundle.\n *\n * @remarks\n * The schema is what a tool boundary needs — hand it to `schemaToParameters` — and\n * `generate(seededRandom(n))` yields a reproducible on-contract brief for tests. This\n * bundle and the hand-composed `isBrief` are two independent mechanisms over one\n * vocabulary; `tests/src/core/shapers.test.ts` is what holds them in lockstep.\n *\n * @returns A `ContractInterface` over `Brief`.\n *\n * @example\n * ```ts\n * import { createBriefContract } from '@orkestrel/brief'\n * import { schemaToParameters, seededRandom } from '@orkestrel/contract'\n *\n * const contract = createBriefContract()\n * schemaToParameters(contract.schema) // the open tool-parameters record, no `as` anywhere\n * contract.generate(seededRandom(42)) // a reproducible on-contract brief\n * ```\n */\nexport function createBriefContract(): ContractInterface<Brief> {\n\treturn createContract(briefShape)\n}\n"],"mappings":";;;;;;;AAIA,IAAa,kBAA4C,OAAO,OAAO;CACtE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,eAAsC,OAAO,OAAO;CAChE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,iBAA0C,OAAO,OAAO;CACpE;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,kBAA2C,OAAO,OAAO;CAAC;CAAO;CAAU;AAAM,CAAC;;;;;;;;;;;;;;;AAgB/F,IAAa,yBAAyB,OAAO,OAAO;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAA+C;;;;;;;;AAS/C,IAAa,sBAAsB;;AAGnC,IAAa,UAAU;;;;;;;;;;;AAYvB,IAAa,qBAAqB;;;;;;;;;AAUlC,IAAa,sBAAsB;;;;;;;;;;;;AAanC,IAAa,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;AChG7B,IAAa,aAAb,cAAgC,MAAM;CACrC;CACA;CAEA,YAAY,MAAsB,SAAiB,SAA6C;EAC/F,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,aAAa,OAAqC;CACjE,OAAO,iBAAiB;AACzB;;;;AClCA,IAAa,aAAA,GAAyB,oBAAA,YAAA,CAAY,EAAE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AM,UAAU,CAAC;EAC1B,CAAC,CACF;CACD;CAGA,QACC,gBACA,OACA,WACA,SACA,QACA,UACW;EASX,MAAM,QAAQ,OAAO,OAAO,CAAC,GAAG,SAAS,CAAC;EAC1C,MAAM,WAAqB,OAAO,OAAO;GACxC,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe;GACzD,WAAW;GACX,GAAI,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ;GAC3C,QAAQ,OAAO,OAAO,CAAC,GAAG,MAAM,CAAC;GACjC,UAAU,OAAO,OAAO,CAAC,GAAG,QAAQ,CAAC;GAKrC,SAAA,GAAQ,qBAAA,YAAA,CAAY;IACnB,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM;IAC9C;IACA;GACD,CAAC;EACF,CAAC;EACD,KAAKN,SAAS,KAAK,SAAS,KAAK;EACjC,OAAO;CACR;CAGA,mBAAyB;EACxB,IAAI,KAAKe,YAAY,MAAM,IAAI,WAAW,aAAa,kCAAkC;CAC1F;AACD;;;;;;;;;;;;;;;;;;;;;;;;ACtbA,SAAgB,oBAAoB,SAAwD;CAC3F,OAAO,IAAI,cAAc,OAAO;AACjC;;;;;;;;;;;;;;;;AAiBA,SAAgB,mBAAmB,SAAsD;CACxF,OAAO,IAAI,aAAa,OAAO;AAChC;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,sBAAgD;CAC/D,QAAA,GAAO,oBAAA,eAAA,CAAe,UAAU;AACjC"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/shapers.ts","../../../src/core/validators.ts","../../../src/core/cloners.ts","../../../src/core/helpers.ts","../../../src/core/parsers.ts","../../../src/core/BriefManager.ts","../../../src/core/BriefCompiler.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Interpretation } from '@orkestrel/interpret'\nimport type { OutputFormat, RiskSeverity, TaskDomain, TaskOperation } from './types.js'\n\n/**\n * Lists the `TaskOperation` values, frozen.\n *\n * @remarks\n * Compose the tuple rather than restating its members: `literalOf(TASK_OPERATIONS)` builds the\n * guard and `parseEnum(value, TASK_OPERATIONS)` coerces a bare value against it.\n */\nexport const TASK_OPERATIONS: readonly TaskOperation[] = Object.freeze([\n\t'create',\n\t'refactor',\n\t'debug',\n\t'extract',\n\t'migrate',\n\t'explain',\n\t'review',\n\t'optimize',\n\t'audit',\n\t'test',\n\t'document',\n\t'plan',\n])\n\n/** Lists the `TaskDomain` values, frozen. */\nexport const TASK_DOMAINS: readonly TaskDomain[] = Object.freeze([\n\t'code',\n\t'writing',\n\t'research',\n\t'analysis',\n\t'design',\n\t'data',\n\t'ops',\n\t'other',\n])\n\n/** Lists the `OutputFormat` values, frozen. */\nexport const OUTPUT_FORMATS: readonly OutputFormat[] = Object.freeze([\n\t'markdown',\n\t'json',\n\t'code',\n\t'diff',\n\t'prose',\n])\n\n/** Lists the `RiskSeverity` values, frozen. */\nexport const RISK_SEVERITIES: readonly RiskSeverity[] = Object.freeze(['low', 'medium', 'high'])\n\n/**\n * Lists every published `Interpretation` member name, frozen.\n *\n * @remarks\n * The capture list `BriefCompiler` hands `captureValue` at each interpret door — the borrowed\n * engine's return, and the caller's supplied interpretation. A class instance carries its\n * contract on the prototype, so the captured view materializes exactly the members named here,\n * and a name missing from the list is a member the view drops.\n *\n * The `satisfies` clause refuses a name `Interpretation` does not declare, and it holds the\n * element type at the listed names rather than widening it to `string`. That is what lets the\n * equality assertion beside the capture cases refuse a list that has fallen short of the\n * published shape.\n */\nexport const INTERPRETATION_MEMBERS = Object.freeze([\n\t'text',\n\t'normalized',\n\t'intent',\n\t'entities',\n\t'subject',\n\t'definition',\n\t'mappings',\n\t'ambiguities',\n\t'prompt',\n\t'stages',\n\t'failures',\n\t'confidence',\n\t'digest',\n] satisfies ReadonlyArray<keyof Interpretation>)\n\n/**\n * Holds `16` — the default turn cap `briefToGoal` renders.\n *\n * @remarks\n * Domain-qualified so the barrel stays collision-free as sibling modules add their own\n * turn defaults.\n */\nexport const DEFAULT_BRIEF_TURNS = 16\n\n/** Holds `'gate'` — the id of the `buildGateDefinition()` logical definition. */\nexport const GATE_ID = 'gate'\n\n/**\n * Matches every line terminator a brief field refuses.\n *\n * @remarks\n * Every ECMAScript line terminator, not only `\\n`: a renderer that splits on any of them\n * would let the others forge a markdown row. CRLF leads the alternation so a Windows\n * exemplar splits as ONE break rather than two, which would insert a blank line the caller\n * never wrote. Kept unanchored and stateless — no `g` flag — so `test` never carries\n * `lastIndex` between calls.\n */\nexport const LINE_BREAK_PATTERN = /\\r\\n|[\\n\\r\\u2028\\u2029]/\n\n/**\n * Holds the positive form of {@link LINE_BREAK_PATTERN}, for a `stringShape` `pattern`.\n *\n * @remarks\n * `stringShape`'s `pattern` must MATCH an accepted value, so the guard's refusal regex\n * cannot be reused directly. Both are derived from one character class, which is what\n * keeps the hand-composed guards and the compiled shapes refusing the same strings.\n */\nexport const SINGLE_LINE_PATTERN = /^[^\\n\\r\\u2028\\u2029]*$/\n\n/**\n * Matches a string of one or more spaces and nothing else.\n *\n * @remarks\n * The one exemplar side `exampleToLines` must NOT pad. CommonMark strips a fully-blank code\n * span to nothing rather than one space from each end, so padding inflates an all-space value\n * while every other value needs the pad to keep its own boundary spaces.\n *\n * `+` rather than `*`, because the EMPTY string is not that case: it has no spaces to\n * preserve, and withholding the pad emitted an empty backtick run that does not close.\n */\nexport const BLANK_PATTERN = /^ +$/\n","import type { BriefErrorCode } from './types.js'\n\n/**\n * Represents the one error class this package throws.\n *\n * @remarks\n * Extends `Error` with a readonly `code` on the `BriefErrorCode` vocabulary and an optional\n * readonly `context` record carrying whatever the raising site can supply.\n *\n * Throws are reserved for caller misuse: `assertBrief`, `snapshotBrief`, and `pinBrief` on\n * off-contract data throw `INVALID`; any method after `destroy()` throws `DESTROYED`; and `BriefCompiler.gate` throws\n * `GATE_FAILED` when a borrowed reasoner returns a non-logical result. A stage that fails\n * inside `compile` is CONTAINED as a `BriefStageFailure` on the `Briefing` instead.\n *\n * @example\n * ```ts\n * import { BriefError } from '@orkestrel/brief'\n *\n * const error = new BriefError('INVALID', 'Brief failed the exact-record contract', {\n * \tfield: 'proofs',\n * })\n * error.code // 'INVALID'\n * error.context // { field: 'proofs' }\n * ```\n */\nexport class BriefError extends Error {\n\treadonly code: BriefErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(code: BriefErrorCode, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tthis.name = 'BriefError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows a caught value to a {@link BriefError}.\n *\n * @param value - The caught value to inspect.\n * @returns True if `value` is a `BriefError`; false otherwise.\n *\n * @example\n * ```ts\n * import { BriefError, isBriefError } from '@orkestrel/brief'\n *\n * try {\n * \tthrow new BriefError('DESTROYED', 'BriefCompiler has been destroyed')\n * } catch (error) {\n * \tif (isBriefError(error)) error.code // 'DESTROYED'\n * }\n * ```\n */\nexport function isBriefError(value: unknown): value is BriefError {\n\treturn value instanceof BriefError\n}\n","import type { StringShape } from '@orkestrel/contract'\nimport {\n\tarrayShape,\n\tbooleanShape,\n\tintegerShape,\n\tliteralShape,\n\tobjectShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\nimport {\n\tOUTPUT_FORMATS,\n\tRISK_SEVERITIES,\n\tTASK_DOMAINS,\n\tTASK_OPERATIONS,\n\tSINGLE_LINE_PATTERN,\n} from './constants.js'\n\n/** Describes a single-line string of any length, including empty — the shape mirror of `isText`. */\nexport const textShape: StringShape = stringShape({ pattern: SINGLE_LINE_PATTERN })\n\n/** Describes a non-empty single-line string — the shape mirror of `isLine`. */\nexport const lineShape: StringShape = stringShape({ min: 1, pattern: SINGLE_LINE_PATTERN })\n\n/**\n * Describes the `Task` shape — closed operation and domain vocabularies plus a non-empty\n * statement.\n *\n * @remarks\n * `literalShape(TASK_OPERATIONS)` and `literalShape(TASK_DOMAINS)` compile the same tuples the\n * guards read, and `statement` carries `min: 1`.\n */\nexport const taskShape = objectShape(\n\t{\n\t\toperation: literalShape(TASK_OPERATIONS),\n\t\tdomain: literalShape(TASK_DOMAINS),\n\t\tstatement: lineShape,\n\t},\n\t{ description: 'What the brief asks for, in one imperative sentence.' },\n)\n\n/** Describes the `Reference` shape — a path and the note that justifies listing it. */\nexport const referenceShape = objectShape(\n\t{\n\t\tpath: lineShape,\n\t\tnote: lineShape,\n\t},\n\t{ description: 'One referenced path and why it is listed.' },\n)\n\n/**\n * Describes the `Manifest` shape — disjoint reference partitions.\n *\n * @remarks\n * Each partition is an `arrayShape(referenceShape)`; disjointness is `validateBrief`'s pass\n * rather than the shape's.\n */\nexport const manifestShape = objectShape(\n\t{\n\t\tread: arrayShape(referenceShape),\n\t\tedit: arrayShape(referenceShape),\n\t\tlocked: arrayShape(referenceShape),\n\t\tforbidden: arrayShape(referenceShape),\n\t},\n\t{ description: 'The disjoint file partitions of a brief.' },\n)\n\n/**\n * Describes the `Outcome` shape — a one-based rank, the result text, and whether it gates done.\n *\n * @remarks\n * `rank` is an `integerShape({ min: 1 })`, so a zero or fractional rank is off-contract.\n */\nexport const outcomeShape = objectShape(\n\t{\n\t\trank: integerShape({ min: 1 }),\n\t\ttext: lineShape,\n\t\trequired: booleanShape(),\n\t},\n\t{ description: 'One ranked outcome — a result, never a step.' },\n)\n\n/** Describes the `Given` shape — one categorized context fact. */\nexport const givenShape = objectShape(\n\t{\n\t\tcategory: lineShape,\n\t\tname: lineShape,\n\t\tvalue: textShape,\n\t},\n\t{ description: 'One context fact handed to the executor.' },\n)\n\n/** Describes the `Example` shape — one input to output exemplar. */\nexport const exampleShape = objectShape(\n\t{\n\t\tinput: stringShape({ min: 1 }),\n\t\toutput: stringShape({ min: 1 }),\n\t\tnote: optionalShape(lineShape),\n\t},\n\t{ description: 'One input to output exemplar.' },\n)\n\n/** Describes the `Citation` shape — a name, a locator, and why the source is cited. */\nexport const citationShape = objectShape(\n\t{\n\t\tname: lineShape,\n\t\turl: lineShape,\n\t\tnote: lineShape,\n\t},\n\t{ description: 'One external source; list order is the trust order.' },\n)\n\n/** Describes the `Gap` shape — an unknown, whether it blocks, and the candidates that would close it. */\nexport const gapShape = objectShape(\n\t{\n\t\tfield: lineShape,\n\t\tquestion: lineShape,\n\t\tblocking: booleanShape(),\n\t\tcandidates: optionalShape(arrayShape(lineShape)),\n\t},\n\t{ description: 'One unresolved decision; blocking means the gate fails closed.' },\n)\n\n/** Describes the `Risk` shape — a closed severity, the risk, and its mitigation. */\nexport const riskShape = objectShape(\n\t{\n\t\tseverity: literalShape(RISK_SEVERITIES),\n\t\ttext: lineShape,\n\t\tmitigation: lineShape,\n\t},\n\t{ description: 'One pre-empted risk and the mitigation that answers it.' },\n)\n\n/** Describes the `Output` shape — a closed format plus its optional refinements. */\nexport const outputShape = objectShape(\n\t{\n\t\tformat: literalShape(OUTPUT_FORMATS),\n\t\tsections: optionalShape(arrayShape(lineShape)),\n\t\tinclude: optionalShape(arrayShape(lineShape)),\n\t\texclude: optionalShape(arrayShape(lineShape)),\n\t},\n\t{ description: 'The closed shape of the deliverable.' },\n)\n\n/** Describes the `Proof` shape — the claim and the command that settles it. */\nexport const proofShape = objectShape(\n\t{\n\t\ttext: lineShape,\n\t\tcommand: lineShape,\n\t},\n\t{ description: 'One mechanical, transcript-provable check.' },\n)\n\n/**\n * Describes the whole `Brief` shape, section shapes composed.\n *\n * @remarks\n * `trace` and `hash` are optional because `pinBrief` fills them; an unpinned draft is\n * on-contract without them.\n */\nexport const briefShape = objectShape(\n\t{\n\t\ttask: taskShape,\n\t\tauthority: arrayShape(referenceShape),\n\t\tmanifest: manifestShape,\n\t\toutcomes: arrayShape(outcomeShape),\n\t\trules: arrayShape(lineShape),\n\t\tinvariants: arrayShape(lineShape),\n\t\tgivens: arrayShape(givenShape),\n\t\texamples: arrayShape(exampleShape),\n\t\tassumptions: arrayShape(lineShape),\n\t\tcitations: arrayShape(citationShape),\n\t\tgaps: arrayShape(gapShape),\n\t\trisks: arrayShape(riskShape),\n\t\toutput: outputShape,\n\t\tproofs: arrayShape(proofShape),\n\t\ttrace: optionalShape(lineShape),\n\t\thash: optionalShape(lineShape),\n\t},\n\t{ description: 'The closed execution contract one agent can run with no interpretation left.' },\n)\n","import type { Guard } from '@orkestrel/contract'\nimport type {\n\tBrief,\n\tCitation,\n\tExample,\n\tGap,\n\tGiven,\n\tManifest,\n\tOutcome,\n\tOutput,\n\tOutputFormat,\n\tProof,\n\tReference,\n\tRisk,\n\tRiskSeverity,\n\tTask,\n\tTaskDomain,\n\tTaskOperation,\n} from './types.js'\nimport {\n\tandOf,\n\tarrayOf,\n\tboundsOf,\n\tisBoolean,\n\tisInteger,\n\tisNonEmptyString,\n\tisString,\n\tliteralOf,\n\trecordOf,\n} from '@orkestrel/contract'\nimport {\n\tLINE_BREAK_PATTERN,\n\tOUTPUT_FORMATS,\n\tRISK_SEVERITIES,\n\tTASK_DOMAINS,\n\tTASK_OPERATIONS,\n} from './constants.js'\n\n/**\n * Checks whether the value is a string holding no line terminator, empty included.\n *\n * @remarks\n * `briefToMarkdown` renders each brief field as ONE markdown row, so a field carrying a\n * line break would forge a heading or an extra manifest row — which is how a rendered\n * prompt and `briefToDispatch`'s path sets could disagree about the same brief.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a string holding no line terminator, empty included; false\n * otherwise.\n */\nexport const isText: Guard<string> = (value: unknown): value is string =>\n\tisString(value) && !LINE_BREAK_PATTERN.test(value)\n\n/**\n * Checks whether the value is a non-empty string holding no line terminator.\n *\n * @remarks\n * The shape of nearly every brief field: a path, a note, a statement, a rule, and a command\n * all narrow through it.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a non-empty string holding no line terminator; false otherwise.\n */\nexport const isLine: Guard<string> = andOf(isNonEmptyString, isText)\n\n/**\n * Checks whether the value is one of the `TaskOperation` literals.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is one of the `TaskOperation` literals; false otherwise.\n */\nexport const isTaskOperation: Guard<TaskOperation> = literalOf(TASK_OPERATIONS)\n\n/**\n * Checks whether the value is one of the `TaskDomain` literals.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is one of the `TaskDomain` literals; false otherwise.\n */\nexport const isTaskDomain: Guard<TaskDomain> = literalOf(TASK_DOMAINS)\n\n/**\n * Checks whether the value is one of the `OutputFormat` literals.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is one of the `OutputFormat` literals; false otherwise.\n */\nexport const isOutputFormat: Guard<OutputFormat> = literalOf(OUTPUT_FORMATS)\n\n/**\n * Checks whether the value is one of the `RiskSeverity` literals.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is one of the `RiskSeverity` literals; false otherwise.\n */\nexport const isRiskSeverity: Guard<RiskSeverity> = literalOf(RISK_SEVERITIES)\n\n/**\n * Checks whether the value is a well-formed `Task` — both vocabularies closed, statement one line.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Task`; false otherwise.\n */\nexport const isTask: Guard<Task> = recordOf({\n\toperation: isTaskOperation,\n\tdomain: isTaskDomain,\n\tstatement: isLine,\n})\n\n/**\n * Checks whether the value is a well-formed `Reference` — both members required, both single-line.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Reference`; false otherwise.\n */\nexport const isReference: Guard<Reference> = recordOf({\n\tpath: isLine,\n\tnote: isLine,\n})\n\n/**\n * Checks whether the value is a well-formed `Manifest`.\n *\n * @remarks\n * Partition presence only — disjointness is `validateBrief`'s semantic pass.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Manifest`; false otherwise.\n */\nexport const isManifest: Guard<Manifest> = recordOf({\n\tread: arrayOf(isReference),\n\tedit: arrayOf(isReference),\n\tlocked: arrayOf(isReference),\n\tforbidden: arrayOf(isReference),\n})\n\n/**\n * Checks whether the value is a well-formed `Outcome` — `rank` a positive integer.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Outcome`; false otherwise.\n */\nexport const isOutcome: Guard<Outcome> = recordOf({\n\trank: andOf(isInteger, boundsOf(1)),\n\ttext: isLine,\n\trequired: isBoolean,\n})\n\n/**\n * Checks whether the value is a well-formed `Given` — its `value` may be empty but stays one line.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Given`; false otherwise.\n */\nexport const isGiven: Guard<Given> = recordOf({\n\tcategory: isLine,\n\tname: isLine,\n\tvalue: isText,\n})\n\n/**\n * Checks whether the value is a well-formed `Example`.\n *\n * @remarks\n * An exemplar's two sides are the ONLY members a brief lets span lines, because they\n * carry code. `briefToMarkdown` fences them rather than rendering them as a row.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Example`; false otherwise.\n */\nexport const isExample: Guard<Example> = recordOf(\n\t{\n\t\tinput: isNonEmptyString,\n\t\toutput: isNonEmptyString,\n\t\tnote: isLine,\n\t},\n\t['note'],\n)\n\n/**\n * Checks whether the value is a well-formed `Citation` — every member single-line.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Citation`; false otherwise.\n */\nexport const isCitation: Guard<Citation> = recordOf({\n\tname: isLine,\n\turl: isLine,\n\tnote: isLine,\n})\n\n/**\n * Checks whether the value is a well-formed `Gap`.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Gap`; false otherwise.\n */\nexport const isGap: Guard<Gap> = recordOf(\n\t{\n\t\tfield: isLine,\n\t\tquestion: isLine,\n\t\tblocking: isBoolean,\n\t\tcandidates: arrayOf(isLine),\n\t},\n\t['candidates'],\n)\n\n/**\n * Checks whether the value is a well-formed `Risk` — `severity` on the closed vocabulary.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Risk`; false otherwise.\n */\nexport const isRisk: Guard<Risk> = recordOf({\n\tseverity: isRiskSeverity,\n\ttext: isLine,\n\tmitigation: isLine,\n})\n\n/**\n * Checks whether the value is a well-formed `Output` — `format` on the closed vocabulary.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Output`; false otherwise.\n */\nexport const isOutput: Guard<Output> = recordOf(\n\t{\n\t\tformat: isOutputFormat,\n\t\tsections: arrayOf(isLine),\n\t\tinclude: arrayOf(isLine),\n\t\texclude: arrayOf(isLine),\n\t},\n\t['sections', 'include', 'exclude'],\n)\n\n/**\n * Checks whether the value is a well-formed `Proof`.\n *\n * @param value - The value to inspect.\n * @returns True if `value` is a well-formed `Proof`; false otherwise.\n */\nexport const isProof: Guard<Proof> = recordOf({\n\ttext: isLine,\n\tcommand: isLine,\n})\n\n/**\n * Checks whether the value satisfies the whole exact-record `Brief` contract.\n *\n * @remarks\n * Every section must be present; an extra key fails. `trace` and `hash` are the only\n * optional members, because `pinBrief` rather than the author fills them.\n *\n * @param value - The value to inspect.\n * @returns True if `value` satisfies the whole exact-record `Brief` contract; false otherwise.\n */\nexport const isBrief: Guard<Brief> = recordOf(\n\t{\n\t\ttask: isTask,\n\t\tauthority: arrayOf(isReference),\n\t\tmanifest: isManifest,\n\t\toutcomes: arrayOf(isOutcome),\n\t\trules: arrayOf(isLine),\n\t\tinvariants: arrayOf(isLine),\n\t\tgivens: arrayOf(isGiven),\n\t\texamples: arrayOf(isExample),\n\t\tassumptions: arrayOf(isLine),\n\t\tcitations: arrayOf(isCitation),\n\t\tgaps: arrayOf(isGap),\n\t\trisks: arrayOf(isRisk),\n\t\toutput: isOutput,\n\t\tproofs: arrayOf(isProof),\n\t\ttrace: isLine,\n\t\thash: isLine,\n\t},\n\t['trace', 'hash'],\n)\n","import type { Brief } from './types.js'\nimport { attempt, cloneJSONRecord } from '@orkestrel/contract'\nimport { BriefError } from './errors.js'\nimport { isBrief } from './validators.js'\n\n/**\n * Captures one stable, frozen view of a foreign contract value.\n *\n * @remarks\n * Rebuilds the root and every reachable plain container from its own enumerable members.\n * Unknown own members survive. Each published member absent from that copied own set is read\n * once and materialized, which admits a class that supplies its contract through prototype\n * accessors without leaving later reads attached to the live instance. Non-container leaves\n * retain their identity, including functions that `structuredClone` cannot carry.\n *\n * @param source - The foreign value to capture.\n * @param members - The published root member names to materialize when absent from its own set.\n * @returns A deeply frozen plain view, or `source` itself when it is a primitive.\n *\n * @example\n * ```ts\n * import { captureValue } from '@orkestrel/brief'\n *\n * const leaf = () => 'ready'\n * const owned = captureValue({ leaf }, ['leaf'])\n * Reflect.get(owned, 'leaf') === leaf // true — an uncloneable leaf keeps its identity\n * Object.isFrozen(owned) // true\n * ```\n */\nexport function captureValue(source: unknown, members: readonly string[]): unknown {\n\tif (source === null || (typeof source !== 'object' && typeof source !== 'function')) {\n\t\treturn source\n\t}\n\n\tconst target: object = Array.isArray(source) ? [] : Object.create(null)\n\tconst seen = new WeakMap<object, object>([[source, target]])\n\tconst captured: object[] = [target]\n\tconst pending: Array<\n\t\treadonly [source: object, target: object, members: readonly string[] | undefined]\n\t> = [[source, target, members]]\n\n\twhile (pending.length > 0) {\n\t\tconst frame = pending.pop()\n\t\tif (frame === undefined) continue\n\t\tconst [current, view, expected] = frame\n\t\tconst entries: Array<readonly [key: PropertyKey, value: unknown]> = []\n\t\tconst copied = new Set<PropertyKey>()\n\n\t\tfor (const key of Reflect.ownKeys(current)) {\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(current, key)\n\t\t\tif (descriptor === undefined || !descriptor.enumerable) continue\n\t\t\tcopied.add(key)\n\t\t\tentries.push([key, 'value' in descriptor ? descriptor.value : Reflect.get(current, key)])\n\t\t}\n\t\tfor (const key of expected ?? []) {\n\t\t\tif (!copied.has(key)) entries.push([key, Reflect.get(current, key)])\n\t\t}\n\n\t\tfor (const [key, value] of entries) {\n\t\t\tlet owned = value\n\t\t\tif (value !== null && typeof value === 'object') {\n\t\t\t\tconst existing = seen.get(value)\n\t\t\t\tif (existing !== undefined) {\n\t\t\t\t\towned = existing\n\t\t\t\t} else {\n\t\t\t\t\tconst prototype = Reflect.getPrototypeOf(value)\n\t\t\t\t\tif (Array.isArray(value) || prototype === null || prototype === Object.prototype) {\n\t\t\t\t\t\tconst branch: object = Array.isArray(value) ? [] : Object.create(null)\n\t\t\t\t\t\tseen.set(value, branch)\n\t\t\t\t\t\tcaptured.push(branch)\n\t\t\t\t\t\tpending.push([value, branch, undefined])\n\t\t\t\t\t\towned = branch\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tReflect.defineProperty(view, key, {\n\t\t\t\tvalue: owned,\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: false,\n\t\t\t\twritable: false,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor (const view of captured) Object.freeze(view)\n\treturn target\n}\n\n/**\n * Returns a deeply owned, deeply frozen copy of a brief, refusing anything off-contract.\n *\n * @remarks\n * The one reading boundary this package has, used by the pin, the registry, and every\n * projection. It matters twice over. A brief built from caller collections ADOPTS those\n * arrays, so a later `outcomes.push` would change content a hash already described. And a\n * caller's object may answer differently on each read, so validating one reading and\n * rendering from a second let a brief that passed the contract render a row it does not\n * contain — this takes ONE reading, validates that, and freezes it.\n *\n * `cloneJSONRecord` is `@orkestrel/contract`'s primitive rather than the ambient\n * `structuredClone`: it deep-freezes, it refuses a value JSON cannot express, and it is a\n * captured import rather than a mutable global. The result is a null-prototype record, so\n * compare it structurally rather than by prototype.\n *\n * This file imports no sibling helper, which is what lets `helpers.ts` consume it without a\n * module cycle.\n *\n * @param source - The brief to snapshot.\n * @returns A deeply frozen `Brief` sharing no reference with `source`.\n * @throws {@link BriefError} `INVALID` when the value is off-contract or JSON cannot express it.\n *\n * @example\n * ```ts\n * import { buildBrief, buildOutcome, buildTask, snapshotBrief } from '@orkestrel/brief'\n *\n * const outcomes = [buildOutcome(1, 'shipped')]\n * const owned = snapshotBrief(buildBrief(buildTask('plan', 'ops', 'Plan the release.'), { outcomes }))\n * owned.outcomes === outcomes // false — the alias is broken\n * Object.isFrozen(owned.outcomes) // true\n * ```\n */\nexport function snapshotBrief(source: Brief): Brief {\n\tconst owned = attempt(() => cloneJSONRecord(source))\n\tif (!owned.success || !isBrief(owned.value)) {\n\t\tthrow new BriefError('INVALID', 'Brief carries data that cannot be read as one value', {\n\t\t\tfield: 'brief',\n\t\t})\n\t}\n\treturn owned.value\n}\n","import type { Ambiguity, Entity, Intent } from '@orkestrel/interpret'\nimport type { LogicalDefinition, ReasonValidationResult, Rule, Subject } from '@orkestrel/reason'\nimport type {\n\tBrief,\n\tCitation,\n\tDispatch,\n\tExample,\n\tGap,\n\tGiven,\n\tManifest,\n\tOutcome,\n\tOutput,\n\tOutputFormat,\n\tProof,\n\tReference,\n\tRisk,\n\tRiskSeverity,\n\tTask,\n\tTaskDomain,\n\tTaskOperation,\n} from './types.js'\nimport { attempt } from '@orkestrel/contract'\nimport { canonicalize, collapseWhitespace, digestValue } from '@orkestrel/interpret'\nimport {\n\tcreateAtom,\n\tcreateCompound,\n\tcreateLogicalDefinition,\n\tcreateRule,\n\tformatField,\n} from '@orkestrel/reason'\nimport { snapshotBrief } from './cloners.js'\nimport { BriefError } from './errors.js'\nimport { BLANK_PATTERN, DEFAULT_BRIEF_TURNS, GATE_ID, LINE_BREAK_PATTERN } from './constants.js'\nimport { isBrief, isTaskDomain, isTaskOperation } from './validators.js'\n\n/**\n * Assembles a `Task` from an operation, a domain, and a statement.\n *\n * @param operation - What the brief asks for, from the closed operation vocabulary.\n * @param domain - The subject matter, from the closed domain vocabulary.\n * @param statement - One imperative sentence naming the object of the work.\n * @returns A fresh `Task`.\n *\n * @example\n * ```ts\n * import { buildTask } from '@orkestrel/brief'\n *\n * buildTask('refactor', 'code', 'Refactor useForm to native browser form APIs.')\n * ```\n */\nexport function buildTask(operation: TaskOperation, domain: TaskDomain, statement: string): Task {\n\treturn { operation, domain, statement }\n}\n\n/**\n * Assembles a `Reference` from a path and the note that justifies listing it.\n *\n * @remarks\n * The one builder for an authority entry and a manifest entry alike: the container the record\n * lands in is what says whether the path is ranked or permitted.\n *\n * @param path - The referenced path or glob.\n * @param note - Why the path is listed.\n * @returns A fresh `Reference`.\n *\n * @example\n * ```ts\n * import { buildReference } from '@orkestrel/brief'\n *\n * buildReference('AGENTS.md', 'project law') // { path: 'AGENTS.md', note: 'project law' }\n * ```\n */\nexport function buildReference(path: string, note: string): Reference {\n\treturn { path, note }\n}\n\n/**\n * Assembles a `Manifest`, defaulting every absent partition to an empty list.\n *\n * @param partitions - The partitions to fill; a partial literal is enough.\n * @returns A fresh `Manifest` with every partition present.\n *\n * @example\n * ```ts\n * import { buildManifest, buildReference } from '@orkestrel/brief'\n *\n * buildManifest({ edit: [buildReference('src/core/helpers.ts', 'implementation')] })\n * ```\n */\nexport function buildManifest(partitions?: Partial<Manifest>): Manifest {\n\treturn {\n\t\tread: partitions?.read ?? [],\n\t\tedit: partitions?.edit ?? [],\n\t\tlocked: partitions?.locked ?? [],\n\t\tforbidden: partitions?.forbidden ?? [],\n\t}\n}\n\n/**\n * Assembles an `Outcome` from a rank and its result text.\n *\n * @param rank - The one-based rank; lower ranks matter more.\n * @param text - The result, never a step.\n * @param required - If `true`, the outcome gates \"done\"; if `false`, it is desirable but not\n * blocking. Default: `true`.\n * @returns A fresh `Outcome`.\n *\n * @example\n * ```ts\n * import { buildOutcome } from '@orkestrel/brief'\n *\n * buildOutcome(1, 'useForm uses native FormData with no behavior change') // required: true\n * buildOutcome(2, 'the diff stays under 200 lines', false)\n * ```\n */\nexport function buildOutcome(rank: number, text: string, required = true): Outcome {\n\treturn { rank, text, required }\n}\n\n/**\n * Assembles a `Given` from a category, a name, and a value.\n *\n * @param category - The kind of fact — a convention, a version, a constraint.\n * @param name - The fact's name.\n * @param value - The fact's value, already rendered as text.\n * @returns A fresh `Given`.\n *\n * @example\n * ```ts\n * import { buildGiven } from '@orkestrel/brief'\n *\n * buildGiven('convention', 'indentation', 'tabs')\n * ```\n */\nexport function buildGiven(category: string, name: string, value: string): Given {\n\treturn { category, name, value }\n}\n\n/**\n * Assembles an `Example` from an exemplar input and its expected output.\n *\n * @param input - The exemplar input.\n * @param output - The expected output for that input.\n * @param note - Optional detail; the key is OMITTED when absent.\n * @returns A fresh `Example`.\n *\n * @example\n * ```ts\n * import { buildExample } from '@orkestrel/brief'\n *\n * buildExample('<input required>', 'validity read from el.validity')\n * ```\n */\nexport function buildExample(input: string, output: string, note?: string): Example {\n\treturn note === undefined ? { input, output } : { input, output, note }\n}\n\n/**\n * Assembles a `Citation` from a name, a URL, and the note that justifies citing it.\n *\n * @param name - The source's display name.\n * @param url - Where the source lives.\n * @param note - Why the source is cited.\n * @returns A fresh `Citation`.\n *\n * @example\n * ```ts\n * import { buildCitation } from '@orkestrel/brief'\n *\n * buildCitation(\n * \t'MDN Constraint Validation',\n * \t'https://developer.mozilla.org/',\n * \t'the native validity behavior being adopted',\n * )\n * ```\n */\nexport function buildCitation(name: string, url: string, note: string): Citation {\n\treturn { name, url, note }\n}\n\n/**\n * Assembles a `Gap` from the section it belongs to and the question that would close it.\n *\n * @param field - The brief section the unknown belongs to.\n * @param question - The question that would close it.\n * @param overrides - Optional `blocking` and `candidates`; an absent `candidates` key is\n * OMITTED entirely. Default: `blocking: false`.\n * @returns A fresh `Gap`.\n *\n * @example\n * ```ts\n * import { buildGap } from '@orkestrel/brief'\n *\n * buildGap('rules', 'Does validation message wording need to change?') // blocking: false\n * buildGap('output', 'Diff or full files?', { blocking: true, candidates: ['diff', 'code'] })\n * ```\n */\nexport function buildGap(\n\tfield: string,\n\tquestion: string,\n\toverrides?: Partial<Omit<Gap, 'field' | 'question'>>,\n): Gap {\n\tconst blocking = overrides?.blocking ?? false\n\treturn overrides?.candidates === undefined\n\t\t? { field, question, blocking }\n\t\t: { field, question, blocking, candidates: overrides.candidates }\n}\n\n/**\n * Assembles a `Risk` from a severity, what could go wrong, and the mitigation that answers it.\n *\n * @param severity - The closed severity.\n * @param text - What could go wrong.\n * @param mitigation - What answers it.\n * @returns A fresh `Risk`.\n *\n * @example\n * ```ts\n * import { buildRisk } from '@orkestrel/brief'\n *\n * buildRisk('medium', 'native validation differs subtly', 'assert message and state in tests')\n * ```\n */\nexport function buildRisk(severity: RiskSeverity, text: string, mitigation: string): Risk {\n\treturn { severity, text, mitigation }\n}\n\n/**\n * Assembles an `Output` from a format plus its optional refinements.\n *\n * @param format - The closed deliverable format.\n * @param overrides - Optional `sections` / `include` / `exclude`; absent keys are OMITTED.\n * @returns A fresh `Output`.\n *\n * @example\n * ```ts\n * import { buildOutput } from '@orkestrel/brief'\n *\n * buildOutput('markdown') // { format: 'markdown' }\n * buildOutput('diff', { include: ['updated useForm.ts'] })\n * ```\n */\nexport function buildOutput(\n\tformat: OutputFormat,\n\toverrides?: Partial<Omit<Output, 'format'>>,\n): Output {\n\treturn {\n\t\tformat,\n\t\t...(overrides?.sections === undefined ? {} : { sections: overrides.sections }),\n\t\t...(overrides?.include === undefined ? {} : { include: overrides.include }),\n\t\t...(overrides?.exclude === undefined ? {} : { exclude: overrides.exclude }),\n\t}\n}\n\n/**\n * Assembles a `Proof` from what the check settles and the command that settles it.\n *\n * @param text - What the check settles.\n * @param command - The command whose exit signal settles it.\n * @returns A fresh `Proof`.\n *\n * @example\n * ```ts\n * import { buildProof } from '@orkestrel/brief'\n *\n * buildProof('type-check and lint pass', 'npm run check')\n * ```\n */\nexport function buildProof(text: string, command: string): Proof {\n\treturn { text, command }\n}\n\n/**\n * Assembles a `Brief` from a `Task` plus section overrides.\n *\n * @param subject - The task the brief is about.\n * @param overrides - Any sections to fill; `trace` / `hash` stay OMITTED so `pinBrief` can\n * fill them. Default: `[]` for every absent collection and `buildOutput('markdown')` for\n * `output`.\n * @returns A fresh, unpinned `Brief`.\n *\n * @example\n * ```ts\n * import { buildBrief, buildOutcome, buildProof, buildTask } from '@orkestrel/brief'\n *\n * buildBrief(buildTask('audit', 'code', 'Audit the barrel for undocumented exports.'), {\n * \toutcomes: [buildOutcome(1, 'every export appears in the guide')],\n * \tproofs: [buildProof('parity passes', 'npm run test:guides')],\n * })\n * ```\n */\nexport function buildBrief(\n\tsubject: Task,\n\toverrides?: Partial<Omit<Brief, 'task' | 'trace' | 'hash'>>,\n): Brief {\n\treturn {\n\t\ttask: subject,\n\t\tauthority: overrides?.authority ?? [],\n\t\tmanifest: overrides?.manifest ?? buildManifest(),\n\t\toutcomes: overrides?.outcomes ?? [],\n\t\trules: overrides?.rules ?? [],\n\t\tinvariants: overrides?.invariants ?? [],\n\t\tgivens: overrides?.givens ?? [],\n\t\texamples: overrides?.examples ?? [],\n\t\tassumptions: overrides?.assumptions ?? [],\n\t\tcitations: overrides?.citations ?? [],\n\t\tgaps: overrides?.gaps ?? [],\n\t\trisks: overrides?.risks ?? [],\n\t\toutput: overrides?.output ?? buildOutput('markdown'),\n\t\tproofs: overrides?.proofs ?? [],\n\t}\n}\n\n/**\n * Assembles the fail-closed readiness gate as a reasons `LogicalDefinition`.\n *\n * @remarks\n * Each readiness rule derives one named fact from `briefToSubject`'s measures, and a final\n * `ready` rule conjoins them all. Forward chaining reports the LAST rule's conclusion, so\n * `LogicalResult.conclusion` is exactly `ready`.\n *\n * The gate takes NO parameters, and that is deliberate rather than unfinished. The\n * reasoner overlays every derived fact into one flat namespace, so a caller rule named\n * for a readiness fact overwrites it and `ready` then conjoins a fact no base rule\n * proved — a refusal silently becomes a pass. Readiness is this package's contract, not\n * a caller setting. A caller who needs different readiness composes their own\n * `LogicalDefinition` over `briefToSubject` and evaluates it on their own reasoner; both\n * are exported for exactly that, and neither can reach this definition.\n *\n * @returns A fresh `LogicalDefinition` with id `GATE_ID`.\n *\n * @example\n * ```ts\n * import { briefToSubject, buildGateDefinition } from '@orkestrel/brief'\n * import { createLogicalReasoner, createReason } from '@orkestrel/reason'\n *\n * const reason = createReason({ reasoners: [createLogicalReasoner()] })\n * const verdict = reason.reason(briefToSubject(pinned), buildGateDefinition())\n * reason.destroy()\n * ```\n */\nexport function buildGateDefinition(): LogicalDefinition {\n\tconst readiness: readonly Rule[] = [\n\t\tcreateRule(\n\t\t\t'specified',\n\t\t\t[createAtom('blocking', 'equals', 0)],\n\t\t\tcreateAtom('specified', 'equals', true),\n\t\t),\n\t\tcreateRule(\n\t\t\t'aimed',\n\t\t\t[\n\t\t\t\tcreateCompound('and', [\n\t\t\t\t\tcreateAtom('outcomes', 'above', 0),\n\t\t\t\t\tcreateAtom('required', 'above', 0),\n\t\t\t\t]),\n\t\t\t],\n\t\t\tcreateAtom('aimed', 'equals', true),\n\t\t),\n\t\tcreateRule('proven', [createAtom('proofs', 'above', 0)], createAtom('proven', 'equals', true)),\n\t\tcreateRule(\n\t\t\t'disjoint',\n\t\t\t[createAtom('overlaps', 'equals', 0)],\n\t\t\tcreateAtom('disjoint', 'equals', true),\n\t\t),\n\t\tcreateRule(\n\t\t\t'granted',\n\t\t\t[createAtom('ungranted', 'equals', 0)],\n\t\t\tcreateAtom('granted', 'equals', true),\n\t\t),\n\t\tcreateRule(\n\t\t\t'single',\n\t\t\t[createAtom('sentences', 'equals', 1)],\n\t\t\tcreateAtom('single', 'equals', true),\n\t\t),\n\t]\n\treturn createLogicalDefinition(GATE_ID, 'Brief readiness', [\n\t\t...readiness,\n\t\tcreateRule(\n\t\t\t'ready',\n\t\t\t[\n\t\t\t\tcreateCompound(\n\t\t\t\t\t'and',\n\t\t\t\t\treadiness.map((entry) => createAtom(entry.id, 'equals', true)),\n\t\t\t\t),\n\t\t\t],\n\t\t\tcreateAtom('ready', 'equals', true),\n\t\t),\n\t])\n}\n\n/**\n * Lists the readiness rules a brief fails, computed directly from its own measures.\n *\n * @remarks\n * The gate's decision, in code. `buildGateDefinition()` states the same rules as data for a\n * reasoner to narrate, and a narration is not a decision: `BriefCompilerOptions.reason` lets a\n * caller supply the engine, and an engine that answers \"met\" to everything would otherwise\n * emit a brief with no proofs. `compile` refuses on THIS and keeps the verdict for its\n * trace, so a supplied engine can add detail and never remove a refusal.\n *\n * The data and the code must agree. `tests/src/core/helpers.test.ts` drives both over one\n * value set, which is what stops them from drifting apart.\n *\n * @param source - The brief to measure.\n * @returns The unmet rule ids, in gate order; empty when the brief is ready.\n *\n * @example\n * ```ts\n * import { buildBrief, buildOutcome, buildProof, buildTask, findUnmetRules } from '@orkestrel/brief'\n *\n * findUnmetRules(buildBrief(buildTask('plan', 'ops', 'Plan the release.'))) // ['aimed', 'proven']\n * findUnmetRules(\n * \tbuildBrief(buildTask('plan', 'ops', 'Plan the release.'), {\n * \t\toutcomes: [buildOutcome(1, 'shipped')],\n * \t\tproofs: [buildProof('x', 'npm test')],\n * \t}),\n * ) // []\n * ```\n */\nexport function findUnmetRules(source: Brief): readonly string[] {\n\tconst unready: string[] = []\n\tif (findBlockingGaps(source).length !== 0) unready.push('specified')\n\tif (\n\t\tsource.outcomes.length === 0 ||\n\t\tsource.outcomes.filter((entry) => entry.required).length === 0\n\t)\n\t\tunready.push('aimed')\n\tif (source.proofs.length === 0) unready.push('proven')\n\tif (findManifestOverlaps(source).length !== 0) unready.push('disjoint')\n\tif (findUngrantedAuthority(source).length !== 0) unready.push('granted')\n\tif (countSentences(source.task.statement) !== 1) unready.push('single')\n\treturn unready\n}\n\n/**\n * Counts the sentences a statement holds.\n *\n * @remarks\n * A terminator run (`.`, `!`, `?`) followed by whitespace or the end of the text closes one\n * sentence, and a trailing run with no terminator closes one more.\n *\n * LIMIT, stated because it decides a gate: an embedded abbreviation reads as a boundary, so\n * `'Ask Dr. Smith'` and `'Compare React vs. Vue'` count TWO and the `single` rule refuses\n * them. Rewrite the statement without the abbreviation — a brief's statement is one\n * imperative sentence naming the object of the work, and it rarely needs one.\n *\n * This is inherent rather than unfinished. Separating `'Dr.'` from a real boundary needs a\n * lexicon or a heuristic over capitalisation and word length, and a heuristic gets a\n * different set of statements wrong — quietly, in the direction of letting a genuinely\n * compound statement through, which is the failure this rule exists to prevent. `validateBrief`\n * therefore reports the count and lets the author judge, rather than guessing at intent.\n *\n * @param statement - The statement to measure.\n * @returns The sentence count; `0` for empty or whitespace-only text.\n *\n * @example\n * ```ts\n * import { countSentences } from '@orkestrel/brief'\n *\n * countSentences('Refactor useForm to native APIs.') // 1\n * countSentences('Refactor useForm. Then update the tests') // 2 — the tail counts\n * countSentences('Ask Dr. Smith') // 2 — an abbreviation reads as a boundary\n * countSentences('') // 0\n * ```\n */\nexport function countSentences(statement: string): number {\n\tconst text = collapseWhitespace(statement)\n\tif (text.length === 0) return 0\n\tconst matches = text.match(/[.!?]+(?=\\s|$)/gu)\n\tif (matches === null) return 1\n\t// A trailing run with no terminator is a sentence too. Counting terminators alone made\n\t// \"Do one thing. Then another\" read as ONE, so a genuinely compound statement passed the\n\t// `single` gate rule whenever its last sentence was unterminated — which is most of the\n\t// time, because people drop the final period.\n\treturn /[.!?]$/u.test(text) ? matches.length : matches.length + 1\n}\n\n/**\n * Lists the gaps that block emission.\n *\n * @remarks\n * A non-empty result means the gate must fail closed: a blocking gap has no safe default, so\n * the compile yields a visible incomplete `Briefing` carrying the questions instead of a brief.\n *\n * @param source - The brief to inspect.\n * @returns Every gap carrying `blocking: true`, in declaration order.\n *\n * @example\n * ```ts\n * import { buildBrief, buildGap, buildTask, findBlockingGaps } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('plan', 'ops', 'Plan the release.'), {\n * \tgaps: [buildGap('output', 'Diff or files?', { blocking: true })],\n * })\n * findBlockingGaps(draft).length // 1\n * ```\n */\nexport function findBlockingGaps(source: Brief): readonly Gap[] {\n\treturn source.gaps.filter((entry) => entry.blocking)\n}\n\n/**\n * Lists the authority paths the manifest never grants access to.\n *\n * @remarks\n * An authority the executor cannot open is an instruction it cannot follow, so every ranked\n * path must appear in `read`, `edit`, or `locked`. Those are the grants: `locked` is a\n * grant, because read-only is exactly what obeying a file requires.\n *\n * This subsumes the narrower question of an authority sitting in `forbidden`. The partitions\n * are disjoint — `findManifestOverlaps` and the `disjoint` rule enforce it — so a forbidden\n * path is in none of the grants and is reported here. An authority named in NO partition at\n * all is reported for the same reason, and that is the case a forbidden-only check misses\n * entirely: the brief never says the executor may open what it must obey.\n *\n * Paths are compared as EXACT strings, matching `findManifestOverlaps`. A glob is never\n * expanded, so `read: 'guides/**'` does not grant `authority: 'guides/brief.md'`. State a\n * grant as the same literal path the authority carries.\n *\n * @param source - The brief to inspect.\n * @returns Each ungranted authority path once, in authority order; empty when all are granted.\n *\n * @example\n * ```ts\n * import {\n * \tbuildBrief,\n * \tbuildManifest,\n * \tbuildReference,\n * \tbuildTask,\n * \tfindUngrantedAuthority,\n * } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('debug', 'code', 'Fix the leak.'), {\n * \tauthority: [buildReference('AGENTS.md', 'project law')],\n * \tmanifest: buildManifest(),\n * })\n * findUngrantedAuthority(draft) // ['AGENTS.md'] — ranked, but no partition opens it\n * ```\n */\nexport function findUngrantedAuthority(source: Brief): readonly string[] {\n\tconst granted = new Set(\n\t\t[...source.manifest.read, ...source.manifest.edit, ...source.manifest.locked].map(\n\t\t\t(entry) => entry.path,\n\t\t),\n\t)\n\tconst ungranted: string[] = []\n\tfor (const path of new Set(source.authority.map((entry) => entry.path))) {\n\t\tif (!granted.has(path)) ungranted.push(path)\n\t}\n\treturn ungranted\n}\n\n/**\n * Lists the paths appearing in more than one manifest partition.\n *\n * @remarks\n * Duplicates WITHIN one partition are not an overlap; the partitions must be\n * mutually disjoint, which is what `validateBrief` errors on.\n *\n * Paths are compared as EXACT strings. A glob is never expanded, so `edit: 'app/file.ts'`\n * and `forbidden: 'app/**'` are not reported as an overlap even though a walker would place\n * one inside the other. Disjointness here is a property of the written paths.\n *\n * @param source - The brief to inspect.\n * @returns Each overlapping path once, in first-seen partition order.\n *\n * @example\n * ```ts\n * import {\n * \tbuildBrief,\n * \tbuildManifest,\n * \tbuildReference,\n * \tbuildTask,\n * \tfindManifestOverlaps,\n * } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('debug', 'code', 'Fix the leak.'), {\n * \tmanifest: buildManifest({\n * \t\tedit: [buildReference('src/core/BriefCompiler.ts', 'the leaking pipeline')],\n * \t\tlocked: [buildReference('src/core/BriefCompiler.ts', 'the published contract')],\n * \t}),\n * })\n * findManifestOverlaps(draft) // ['src/core/BriefCompiler.ts']\n * ```\n */\nexport function findManifestOverlaps(source: Brief): readonly string[] {\n\tconst counts = new Map<string, number>()\n\tconst partitions: ReadonlyArray<readonly Reference[]> = [\n\t\tsource.manifest.read,\n\t\tsource.manifest.edit,\n\t\tsource.manifest.locked,\n\t\tsource.manifest.forbidden,\n\t]\n\tfor (const partition of partitions) {\n\t\tfor (const path of new Set(partition.map((entry) => entry.path))) {\n\t\t\tcounts.set(path, (counts.get(path) ?? 0) + 1)\n\t\t}\n\t}\n\tconst overlaps: string[] = []\n\tfor (const [path, count] of counts) {\n\t\tif (count > 1) overlaps.push(path)\n\t}\n\treturn overlaps\n}\n\n/**\n * Lists the open gaps with no assumption to stand on.\n *\n * @remarks\n * The discipline is exactly one recorded assumption per open gap, so the open gaps past\n * the assumption count are the unpaired ones. A blocking gap is never unpaired — it is\n * a question, not something to assume around.\n *\n * @param source - The brief to inspect.\n * @returns The surplus open gaps, in declaration order.\n *\n * @example\n * ```ts\n * import { buildBrief, buildGap, buildTask, findUnpairedGaps } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('plan', 'ops', 'Plan the release.'), {\n * \tgaps: [buildGap('rules', 'Keep the wording?'), buildGap('output', 'Diff or files?')],\n * \tassumptions: ['Wording is preserved.'],\n * })\n * findUnpairedGaps(draft).length // 1\n * ```\n */\nexport function findUnpairedGaps(source: Brief): readonly Gap[] {\n\treturn source.gaps.filter((entry) => !entry.blocking).slice(source.assumptions.length)\n}\n\n/**\n * Projects a brief into the reasons `Subject` of readiness measures the gate reads.\n *\n * @param source - The brief to measure.\n * @returns A flat record of counts plus the task's vocabulary values.\n *\n * @example\n * ```ts\n * import { briefToSubject, buildBrief, buildProof, buildTask } from '@orkestrel/brief'\n *\n * briefToSubject(buildBrief(buildTask('test', 'code', 'Cover the gate.'), { proofs: [buildProof('x', 'y')] }))\n * // { operation: 'test', domain: 'code', sentences: 1, proofs: 1, … }\n * ```\n */\nexport function briefToSubject(source: Brief): Subject {\n\treturn {\n\t\toperation: source.task.operation,\n\t\tdomain: source.task.domain,\n\t\tsentences: countSentences(source.task.statement),\n\t\tauthority: source.authority.length,\n\t\tgaps: source.gaps.length,\n\t\tblocking: findBlockingGaps(source).length,\n\t\tunpaired: findUnpairedGaps(source).length,\n\t\toutcomes: source.outcomes.length,\n\t\trequired: source.outcomes.filter((entry) => entry.required).length,\n\t\tproofs: source.proofs.length,\n\t\treads: source.manifest.read.length,\n\t\tedits: source.manifest.edit.length,\n\t\tlocks: source.manifest.locked.length,\n\t\tbans: source.manifest.forbidden.length,\n\t\toverlaps: findManifestOverlaps(source).length,\n\t\tungranted: findUngrantedAuthority(source).length,\n\t\trisks: source.risks.length,\n\t\texamples: source.examples.length,\n\t}\n}\n\n/**\n * Runs the semantic pass over an already-shape-valid brief.\n *\n * @remarks\n * ERRORS are the structural violations no assumption can paper over: a manifest\n * overlap, an authority no partition grants access to, an empty `proofs` list, and a\n * statement that is not exactly one sentence.\n * WARNINGS are runnable but suspicious: duplicate outcome ranks, an unpaired open gap,\n * and an optional outcome ranked above a required one. Never throws.\n *\n * @param source - The brief to inspect.\n * @returns A reasons `ReasonValidationResult`; `valid` exactly when `errors` is empty.\n *\n * @example\n * ```ts\n * import { buildBrief, buildProof, buildTask, validateBrief } from '@orkestrel/brief'\n *\n * validateBrief(buildBrief(buildTask('plan', 'ops', 'Plan the release.'))) // valid: false — no proofs\n * validateBrief(\n * \tbuildBrief(buildTask('plan', 'ops', 'Plan the release.'), { proofs: [buildProof('ok', 'npm test')] }),\n * ) // valid: true\n * ```\n */\nexport function validateBrief(source: Brief): ReasonValidationResult {\n\tconst errors: string[] = []\n\tconst warnings: string[] = []\n\n\tfor (const path of findManifestOverlaps(source)) {\n\t\terrors.push(`Path \"${path}\" appears in more than one manifest partition`)\n\t}\n\tfor (const path of findUngrantedAuthority(source)) {\n\t\terrors.push(\n\t\t\t`Authority \"${path}\" is in no manifest partition that grants access — the executor cannot obey what it cannot open`,\n\t\t)\n\t}\n\tif (source.proofs.length === 0) {\n\t\terrors.push('Brief records no proof — nothing can settle \"done\"')\n\t}\n\tconst sentences = countSentences(source.task.statement)\n\tif (sentences !== 1) {\n\t\terrors.push(\n\t\t\t`Statement holds ${String(sentences)} sentences — a compound statement is two briefs`,\n\t\t)\n\t}\n\n\tconst ranks = new Map<number, number>()\n\tfor (const entry of source.outcomes) ranks.set(entry.rank, (ranks.get(entry.rank) ?? 0) + 1)\n\tfor (const [rank, count] of ranks) {\n\t\tif (count > 1) warnings.push(`Outcome rank ${String(rank)} is used ${String(count)} times`)\n\t}\n\tfor (const entry of findUnpairedGaps(source)) {\n\t\twarnings.push(`Open gap \"${entry.field}\" has no paired assumption`)\n\t}\n\tconst required = source.outcomes.filter((entry) => entry.required).map((entry) => entry.rank)\n\tif (required.length > 0) {\n\t\tconst floor = Math.min(...required)\n\t\tfor (const entry of source.outcomes) {\n\t\t\tif (!entry.required && entry.rank < floor) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Outcome ${String(entry.rank)} is optional but outranks every required outcome`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors, warnings }\n}\n\n/**\n * Computes the canonical structural digest of a brief's content.\n *\n * @remarks\n * `trace` and `hash` are stripped before digesting, so the value is the identity of what\n * the brief SAYS rather than of a particular pinning. Deterministic across runs — the\n * same interprets `digestValue` the fleet uses everywhere else.\n *\n * @param source - The brief to digest.\n * @returns An eight-hex-digit digest.\n *\n * @example\n * ```ts\n * import { briefToHash, buildBrief, buildTask, pinBrief } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('plan', 'ops', 'Plan the release.'))\n * briefToHash(draft) === briefToHash(pinBrief(draft)) // true — pinning does not move it\n * ```\n */\nexport function briefToHash(source: Brief): string {\n\treturn digestValue(briefToContent(source))\n}\n\n/**\n * Renders the canonical text of exactly what a brief's hash describes.\n *\n * @remarks\n * `trace` and `hash` are stripped, then interprets `canonicalize` renders the rest in a\n * key-order-stable form. Two briefs with the same hash are the same brief only when this\n * text matches — the digest is eight hex digits, so hash equality alone is not identity.\n *\n * @param source - The brief to render.\n * @returns The canonical content text.\n *\n * @example\n * ```ts\n * import { briefToContent, buildBrief, buildTask, pinBrief } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('plan', 'ops', 'Plan the release.'))\n * briefToContent(draft) === briefToContent(pinBrief(draft)) // true — pinning adds no content\n * ```\n */\nexport function briefToContent(source: Brief): string {\n\tconst { trace: _trace, hash: _hash, ...content } = source\n\treturn canonicalize(content)\n}\n\n/**\n * Freezes a value and everything reachable from it.\n *\n * @remarks\n * `Object.freeze` is SHALLOW, so freezing a record leaves every nested array and object\n * writable. A `Briefing` is documented as a replayable record, and a shallow freeze let a\n * consumer rewrite the recorded stage input after the digest describing it was already\n * sealed — the replay and its hash could disagree.\n *\n * Cycles terminate: `structuredClone` preserves them, so a naive walk would not return.\n * Delegates each branch to `freezeBranch` with the shared visited set.\n *\n * Reaches PLAIN objects and arrays, which is the whole of a `Brief` — it is JSON-serializable\n * by contract. A `Map`, `Set`, or typed array is frozen as an object and its CONTENTS are left\n * writable, and `Object.isFrozen` reports `true` for it either way. Nothing this package\n * produces contains one; the limit lands on a caller freezing their own value.\n *\n * @param value - The value to freeze in place; returned for convenience.\n * @returns The same value, now deeply frozen.\n *\n * @example\n * ```ts\n * import { freezeDeep } from '@orkestrel/brief'\n *\n * const owned = freezeDeep({ outcomes: [{ rank: 1 }] })\n * Object.isFrozen(owned.outcomes) // true — the nested array too\n * ```\n */\nexport function freezeDeep<T>(value: T): T {\n\treturn freezeBranch(value, new WeakSet())\n}\n\n/**\n * Freezes one branch of a value graph, skipping what the visited set already holds.\n *\n * @param value - The branch to freeze.\n * @param seen - The objects already frozen on this walk; what makes a cycle terminate.\n * @returns The same branch, now frozen.\n *\n * @example\n * ```ts\n * import { freezeBranch } from '@orkestrel/brief'\n *\n * freezeBranch({ a: [1] }, new WeakSet()) // frozen, one level of nesting included\n * ```\n */\nexport function freezeBranch<T>(value: T, seen: WeakSet<object>): T {\n\tif (value === null || typeof value !== 'object') return value\n\tif (seen.has(value)) return value\n\tseen.add(value)\n\tObject.freeze(value)\n\tfor (const nested of Object.values(value)) freezeBranch(nested, seen)\n\treturn value\n}\n\n/**\n * Renders a value thrown by a stage into a message.\n *\n * @remarks\n * TOTAL: it never throws, for any input. That is load-bearing rather than tidy, because this\n * is the containment code itself — `compile` calls it inside the `catch` that turns a thrown\n * stage into a recorded `BriefStageFailure`. A throw here escapes `compile` uncontained and\n * falsifies the package's central promise that a failing stage yields an incomplete\n * `Briefing` rather than an exception.\n *\n * Real inputs used to throw: an `Error` subclass whose `message` getter throws, a value\n * whose string conversion throws, and a null-prototype object, which has no inherited\n * conversion for String() to reach. Each is wrapped, and an unreadable value degrades to its\n * type rather than propagating.\n *\n * @param error - The caught value, of any shape.\n * @returns The `Error` message when there is one, otherwise the value stringified; a fixed\n * description when the value cannot be read at all.\n *\n * @example\n * ```ts\n * import { errorToMessage } from '@orkestrel/brief'\n *\n * errorToMessage(new Error('boom')) // 'boom'\n * errorToMessage('boom') // 'boom'\n * errorToMessage(Object.create(null)) // 'an unreadable object was thrown'\n * ```\n */\nexport function errorToMessage(error: unknown): string {\n\tconst read = attempt(() => (error instanceof Error ? error.message : String(error)))\n\tif (read.success && typeof read.value === 'string') return read.value\n\treturn `an unreadable ${typeof error} was thrown`\n}\n\n/**\n * Narrows unknown data to a `Brief`, throwing when it is off-contract.\n *\n * @remarks\n * The throwing half of the intake pair: this returns its argument by IDENTITY after the\n * guard passes, while `parseBrief` returns `undefined` for bad input. It constructs\n * nothing, so it is an assertion rather than a factory. Reserve it for programmer-error\n * contexts where invalidity is a bug.\n *\n * Intake NARROWS, and transfers no ownership. What comes back is the caller's own object,\n * so a member carried on an accessor can answer this guard one way and a later reader\n * another. The division is deliberate: the borrowed-engine law governs values this package\n * pulls across a seam it called, and a value handed in at the door stays the caller's.\n * `snapshotBrief` is the ownership door, and `pinBrief`, `BriefManager`, `briefToMarkdown`,\n * `briefToGoal`, and `briefToDispatch` take it. `briefToSubject`, `briefToContent`, and\n * `briefToTrace` read the value they are handed instead, so a caller reaching one of those\n * directly owns that reading. Pass `assertBrief` a value you already own.\n *\n * @param value - The candidate brief value.\n * @returns The same value, now known to satisfy {@link Brief}.\n * @throws {@link BriefError} `INVALID` when `value` fails `isBrief`.\n *\n * @example\n * ```ts\n * import { assertBrief, buildBrief, buildProof, buildTask } from '@orkestrel/brief'\n *\n * assertBrief(buildBrief(buildTask('plan', 'ops', 'Plan the release.'), { proofs: [buildProof('x', 'y')] }))\n * assertBrief({ task: { operation: 'plan', domain: 'ops', statement: 'x.' } }) // throws INVALID\n * ```\n */\nexport function assertBrief(value: unknown): Brief {\n\tif (!isBrief(value)) {\n\t\tthrow new BriefError('INVALID', 'Brief failed the exact-record contract', { field: 'brief' })\n\t}\n\treturn value\n}\n\n/**\n * Returns a fresh brief with `trace` and `hash` derived from its own content.\n *\n * @remarks\n * Deterministic: no clock, no randomness, no run-specific data. Any existing `trace` /\n * `hash` is stripped before the digest, so pinning is idempotent and a re-pin of unchanged\n * content produces the same hash.\n *\n * The snapshot is taken FIRST, before any member is read, so a hostile input whose getters\n * throw surfaces as this package's coded error rather than as whatever it threw.\n *\n * @param source - The brief to pin.\n * @returns A fresh, pinned, deeply frozen `Brief`.\n * @throws {@link BriefError} `INVALID` when the brief carries data JSON cannot express.\n *\n * @example\n * ```ts\n * import { buildBrief, buildTask, pinBrief } from '@orkestrel/brief'\n *\n * const pinned = pinBrief(buildBrief(buildTask('document', 'writing', 'Write the brief guide.')))\n * pinned.hash // an 8-hex-digit structural digest\n * pinned.trace // 'document/writing · outcomes:0 · gaps:0/0 · proofs:0'\n * ```\n */\nexport function pinBrief(source: Brief): Brief {\n\tconst owned = snapshotBrief(source)\n\tconst { trace: _trace, hash: _hash, ...content } = owned\n\treturn snapshotBrief({ ...content, trace: briefToTrace(owned), hash: briefToHash(owned) })\n}\n\n/**\n * Renders the one-line census `pinBrief` stamps onto a brief.\n *\n * @remarks\n * Extracted so it has ONE implementation. `pinBrief` derives it and `BriefManager` re-derives\n * it to reconcile an inbound brief's own `trace` against its content — an inbound `trace` is\n * shape-checked rather than verified, and it is the line `briefToMarkdown` prints at the top\n * of the executor's prompt, so a stale one misdescribes the brief where it is most read.\n *\n * @param source - The brief to describe.\n * @returns The census line: operation/domain, outcomes, blocking-over-total gaps, proofs.\n *\n * @example\n * ```ts\n * import { briefToTrace, buildBrief, buildTask } from '@orkestrel/brief'\n *\n * briefToTrace(buildBrief(buildTask('document', 'writing', 'Write the guide.')))\n * // 'document/writing · outcomes:0 · gaps:0/0 · proofs:0'\n * ```\n */\nexport function briefToTrace(source: Brief): string {\n\treturn [\n\t\t`${source.task.operation}/${source.task.domain}`,\n\t\t`outcomes:${String(source.outcomes.length)}`,\n\t\t`gaps:${String(findBlockingGaps(source).length)}/${String(source.gaps.length)}`,\n\t\t`proofs:${String(source.proofs.length)}`,\n\t].join(' · ')\n}\n\n/**\n * Renders one exemplar as markdown lines.\n *\n * @remarks\n * An `Example`'s two sides are the only brief members permitted to span lines, so a\n * single-line pair renders as one row and a multi-line pair renders as a fenced block.\n * Fencing is what stops the one permissive field from forging a heading.\n *\n * @param entry - The exemplar to render.\n * @returns The markdown lines, without a trailing blank.\n *\n * @example\n * ```ts\n * import { buildExample, exampleToLines } from '@orkestrel/brief'\n *\n * exampleToLines(buildExample('<input required>', 'el.validity')) // ['- ` <input required> ` → ` el.validity `']\n * ```\n */\nexport function exampleToLines(entry: Example): readonly string[] {\n\tconst note = entry.note === undefined ? '' : ` (${entry.note})`\n\t// The longest unbroken backtick run across both sides, so the delimiter can outrun it.\n\tlet runs = 0\n\tlet current = 0\n\tfor (const character of `${entry.input} ${entry.output}`) {\n\t\tcurrent = character === '`' ? current + 1 : 0\n\t\tif (current > runs) runs = current\n\t}\n\tif (!LINE_BREAK_PATTERN.test(entry.input) && !LINE_BREAK_PATTERN.test(entry.output)) {\n\t\t// The inline delimiter outruns the content too. A fixed single backtick is closed by an\n\t\t// exemplar containing one, which puts the rest of the value outside the code span.\n\t\t// CommonMark strips one leading and trailing space, so a padded span survives content\n\t\t// that begins or ends with a backtick.\n\t\t//\n\t\t// Padded, because CommonMark strips exactly one space from each end of a code span, so a\n\t\t// padded span returns the exemplar's own boundary spaces — withholding the pad deleted\n\t\t// them and silently changed the value the executor reads.\n\t\t//\n\t\t// The one exception is a side that is ENTIRELY spaces: CommonMark strips a fully-blank\n\t\t// span to nothing rather than one space from each end, so padding inflates it while\n\t\t// withholding the pad renders it exactly. Decided per side, since one side being blank\n\t\t// says nothing about the other.\n\t\tconst tick = '`'.repeat(runs + 1)\n\t\tconst inputPad = BLANK_PATTERN.test(entry.input) ? '' : ' '\n\t\tconst outputPad = BLANK_PATTERN.test(entry.output) ? '' : ' '\n\t\treturn [\n\t\t\t`- ${tick}${inputPad}${entry.input}${inputPad}${tick} → ${tick}${outputPad}${entry.output}${outputPad}${tick}${note}`,\n\t\t]\n\t}\n\t// The fence must outrun the content. A fixed three-backtick fence is closed by an\n\t// exemplar that contains one, which puts the rest of the example back into the\n\t// document as structure.\n\tconst fence = '`'.repeat(Math.max(3, runs) + 1)\n\treturn [\n\t\t`- exemplar${note}`,\n\t\t'',\n\t\t` ${fence}text`,\n\t\t...entry.input.split(LINE_BREAK_PATTERN).map((line) => ` ${line}`),\n\t\t` ${fence}`,\n\t\t'',\n\t\t` ${fence}text`,\n\t\t...entry.output.split(LINE_BREAK_PATTERN).map((line) => ` ${line}`),\n\t\t` ${fence}`,\n\t]\n}\n\n/**\n * Projects a brief into the copy-ready agent prompt.\n *\n * @remarks\n * Sections render in authority order, so the executor meets what wins a conflict before what\n * it may touch. Paths are referenced, never inlined — the executor retrieves them. An empty\n * section is omitted entirely, so the rendering carries no filler an executor must read past.\n *\n * @param input - The brief to render.\n * @returns The markdown prompt.\n *\n * @example\n * ```ts\n * import { briefToMarkdown, buildBrief, buildTask } from '@orkestrel/brief'\n *\n * briefToMarkdown(buildBrief(buildTask('review', 'code', 'Review the gate rules.')))\n * // '# Brief: Review the gate rules.\\n\\nreview · code\\n\\n## Output\\n\\n- format: markdown\\n'\n * ```\n */\nexport function briefToMarkdown(input: Brief): string {\n\tconst source = snapshotBrief(input)\n\tconst lines: string[] = [`# Brief: ${source.task.statement}`, '']\n\tlines.push(`${source.task.operation} · ${source.task.domain}`, '')\n\tif (source.trace !== undefined) lines.push(`Trace: ${source.trace}`, '')\n\tif (source.hash !== undefined) lines.push(`Hash: ${source.hash}`, '')\n\n\tif (source.authority.length > 0) {\n\t\tlines.push('## Authority (ranked)', '')\n\t\tlines.push(\n\t\t\t...source.authority.map(\n\t\t\t\t(entry, index) => `${String(index + 1)}. ${entry.path} — ${entry.note}`,\n\t\t\t),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tconst partitions: ReadonlyArray<readonly [string, readonly Reference[]]> = [\n\t\t['Read', source.manifest.read],\n\t\t['Edit', source.manifest.edit],\n\t\t['Locked', source.manifest.locked],\n\t\t['Forbidden', source.manifest.forbidden],\n\t]\n\tif (partitions.some((partition) => partition[1].length > 0)) {\n\t\tlines.push('## Manifest', '')\n\t\tfor (const [heading, entries] of partitions) {\n\t\t\tif (entries.length === 0) continue\n\t\t\tlines.push(`### ${heading}`, '')\n\t\t\tlines.push(...entries.map((entry) => `- ${entry.path} — ${entry.note}`))\n\t\t\tlines.push('')\n\t\t}\n\t}\n\n\tif (source.outcomes.length > 0) {\n\t\tlines.push('## Outcomes', '')\n\t\tlines.push(\n\t\t\t...source.outcomes.map(\n\t\t\t\t(entry) =>\n\t\t\t\t\t`${String(entry.rank)}. ${entry.text}${entry.required ? ' (required)' : ' (optional)'}`,\n\t\t\t),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tconst prose: ReadonlyArray<readonly [string, readonly string[]]> = [\n\t\t['Rules', source.rules],\n\t\t['Invariants', source.invariants],\n\t\t['Assumptions', source.assumptions],\n\t]\n\tfor (const [heading, entries] of prose) {\n\t\tif (entries.length === 0) continue\n\t\tlines.push(`## ${heading}`, '')\n\t\tlines.push(...entries.map((entry) => `- ${entry}`))\n\t\tlines.push('')\n\t}\n\n\tif (source.givens.length > 0) {\n\t\tlines.push('## Givens', '')\n\t\tlines.push(\n\t\t\t...source.givens.map((entry) => `- ${entry.category} · ${entry.name}: ${entry.value}`),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tif (source.examples.length > 0) {\n\t\tlines.push('## Examples', '')\n\t\tfor (const entry of source.examples) {\n\t\t\tlines.push(...exampleToLines(entry))\n\t\t}\n\t\tlines.push('')\n\t}\n\n\tif (source.citations.length > 0) {\n\t\tlines.push('## Citations (trust order)', '')\n\t\tlines.push(\n\t\t\t...source.citations.map(\n\t\t\t\t(entry, index) => `${String(index + 1)}. ${entry.name} — ${entry.note} — ${entry.url}`,\n\t\t\t),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tif (source.gaps.length > 0) {\n\t\tlines.push('## Gaps', '')\n\t\tlines.push(\n\t\t\t...source.gaps.map((entry) => {\n\t\t\t\tconst mark = entry.blocking ? 'blocking' : 'open'\n\t\t\t\tconst candidates =\n\t\t\t\t\tentry.candidates === undefined ? '' : ` (candidates: ${entry.candidates.join(', ')})`\n\t\t\t\treturn `- [${mark}] ${entry.field}: ${entry.question}${candidates}`\n\t\t\t}),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tif (source.risks.length > 0) {\n\t\tlines.push('## Risks', '')\n\t\tlines.push(\n\t\t\t...source.risks.map((entry) => `- ${entry.severity}: ${entry.text} — ${entry.mitigation}`),\n\t\t)\n\t\tlines.push('')\n\t}\n\n\tlines.push('## Output', '', `- format: ${source.output.format}`)\n\tconst refinements: ReadonlyArray<readonly [string, readonly string[] | undefined]> = [\n\t\t['sections', source.output.sections],\n\t\t['include', source.output.include],\n\t\t['exclude', source.output.exclude],\n\t]\n\tfor (const [label, entries] of refinements) {\n\t\tif (entries === undefined || entries.length === 0) continue\n\t\tlines.push(`- ${label}: ${entries.join(', ')}`)\n\t}\n\tlines.push('')\n\n\tif (source.proofs.length > 0) {\n\t\tlines.push('## Proofs', '')\n\t\tlines.push(...source.proofs.map((entry) => `- ${entry.text} — \\`${entry.command}\\``))\n\t\tlines.push('')\n\t}\n\n\treturn lines.join('\\n')\n}\n\n/**\n * Projects a brief into a `/goal` completion condition.\n *\n * @remarks\n * The proofs' commands VERBATIM plus a turn cap — the goal never adds a condition the\n * brief does not carry.\n *\n * @param input - The brief to render.\n * @param turns - The turn cap. Default: `DEFAULT_BRIEF_TURNS`.\n * @returns The one-line completion condition.\n *\n * @example\n * ```ts\n * import { briefToGoal, buildBrief, buildProof, buildTask } from '@orkestrel/brief'\n *\n * briefToGoal(buildBrief(buildTask('test', 'code', 'Cover the gate.'), { proofs: [buildProof('x', 'npm test')] }))\n * // 'Done when every proof passes: npm test exits 0. Cap: 16 turns.'\n * ```\n */\nexport function briefToGoal(input: Brief, turns: number = DEFAULT_BRIEF_TURNS): string {\n\t// Every projection takes ONE owned reading. A shifting `proofs` getter would otherwise let\n\t// this emit a command that was not in the reading the contract validated.\n\tconst source = snapshotBrief(input)\n\tconst conditions =\n\t\tsource.proofs.length === 0\n\t\t\t? 'no proofs recorded'\n\t\t\t: source.proofs.map((entry) => `${entry.command} exits 0`).join('; ')\n\treturn `Done when every proof passes: ${conditions}. Cap: ${String(turns)} turns.`\n}\n\n/**\n * Projects a brief into a subagent `Dispatch`.\n *\n * @remarks\n * `edit` is exactly `manifest.edit` — the owned set — so two dispatches whose `edit` sets do\n * not intersect can run concurrently under the same brief without conflict. `locked` and\n * `forbidden` cross unchanged as the do-not-touch sets.\n *\n * `authority` is exactly `brief.authority` in rank order, and it is a separate axis from the\n * permission sets rather than a further partition — a ranked path normally also appears in\n * `read` or `locked`, because the executor has to open what it obeys. It is projected as\n * paths so a machine consumer never has to parse `prompt`, which is written for a model.\n *\n * @param input - The brief to project.\n * @returns The dispatch — the rendered prompt, the ranked authority, and the path sets.\n *\n * @example\n * ```ts\n * import {\n * \tbriefToDispatch,\n * \tbuildBrief,\n * \tbuildManifest,\n * \tbuildReference,\n * \tbuildTask,\n * } from '@orkestrel/brief'\n *\n * const draft = buildBrief(buildTask('migrate', 'code', 'Migrate the stores.'), {\n * \tauthority: [buildReference('AGENTS.md', 'project law')],\n * \tmanifest: buildManifest({ edit: [buildReference('src/core/stores/**', 'the legacy stores')] }),\n * })\n * briefToDispatch(draft).edit // ['src/core/stores/**']\n * briefToDispatch(draft).authority // ['AGENTS.md']\n * ```\n */\nexport function briefToDispatch(input: Brief): Dispatch {\n\t// Both halves derive from ONE owned reading of the caller's value. `briefToMarkdown`\n\t// snapshots again, but of `source` rather than of `input`, and re-snapshotting an owned\n\t// frozen record is idempotent — so the prompt and the path arrays cannot disagree. Reading\n\t// the CALLER's value twice is what let a shifting getter put a row in the prompt that the\n\t// path arrays do not contain.\n\tconst source = snapshotBrief(input)\n\treturn {\n\t\tprompt: briefToMarkdown(source),\n\t\tauthority: source.authority.map((entry) => entry.path),\n\t\tread: source.manifest.read.map((entry) => entry.path),\n\t\tedit: source.manifest.edit.map((entry) => entry.path),\n\t\tlocked: source.manifest.locked.map((entry) => entry.path),\n\t\tforbidden: source.manifest.forbidden.map((entry) => entry.path),\n\t}\n}\n\n/**\n * Derives one imperative statement from free text.\n *\n * @remarks\n * Whitespace collapses, the first character uppercases, and a terminator is appended\n * when the text carries none. Nothing else is invented.\n *\n * @param text - The raw request text.\n * @returns The statement, or `undefined` for empty or whitespace-only text.\n *\n * @example\n * ```ts\n * import { deriveStatement } from '@orkestrel/brief'\n *\n * deriveStatement(' clean up useForm ') // 'Clean up useForm.'\n * deriveStatement('') // undefined\n * ```\n */\nexport function deriveStatement(text: string): string | undefined {\n\tconst collapsed = collapseWhitespace(text)\n\tif (collapsed.length === 0) return undefined\n\tconst capitalized = collapsed.charAt(0).toUpperCase() + collapsed.slice(1)\n\treturn /[.!?]$/u.test(capitalized) ? capitalized : `${capitalized}.`\n}\n\n/**\n * Derives a `Task` from an interprets `Intent` through the caller's vocabularies.\n *\n * @remarks\n * The vocabularies are the CALLER's policy: this maps and never guesses. An action or\n * domain the caller did not map — or mapped to an off-vocabulary value — yields\n * `undefined` rather than an invented task. Inherited keys never resolve. `Intent.action`\n * and `Intent.domain` are optional, because `classifyIntent` leaves an unmatched axis\n * absent, and an absent axis is unmapped by definition: it yields `undefined` before\n * either vocabulary is read.\n *\n * @param intent - The classified intent from an interpret pipeline.\n * @param text - The text the statement derives from.\n * @param actions - Maps an intent action onto a closed `TaskOperation`.\n * @param domains - Maps an intent domain onto a closed `TaskDomain`.\n * @returns The derived `Task`, or `undefined` when either side is unmapped.\n *\n * @example\n * ```ts\n * import { deriveTask } from '@orkestrel/brief'\n *\n * const intent = { action: 'migrate', domain: 'code', confidence: 1 }\n * deriveTask(intent, 'migrate the stores', { migrate: 'migrate' }, { code: 'code' })\n * // { operation: 'migrate', domain: 'code', statement: 'Migrate the stores.' }\n * deriveTask(intent, 'migrate the stores', {}, { code: 'code' }) // undefined\n * ```\n */\nexport function deriveTask(\n\tintent: Intent,\n\ttext: string,\n\tactions: Readonly<Record<string, TaskOperation>>,\n\tdomains: Readonly<Record<string, TaskDomain>>,\n): Task | undefined {\n\tif (intent.action === undefined || intent.domain === undefined) return undefined\n\tconst operationDescriptor = Object.getOwnPropertyDescriptor(actions, intent.action)\n\tconst domainDescriptor = Object.getOwnPropertyDescriptor(domains, intent.domain)\n\tconst operation: unknown =\n\t\toperationDescriptor === undefined\n\t\t\t? undefined\n\t\t\t: 'value' in operationDescriptor\n\t\t\t\t? operationDescriptor.value\n\t\t\t\t: operationDescriptor.get === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: Reflect.apply(operationDescriptor.get, actions, [])\n\tconst domain: unknown =\n\t\tdomainDescriptor === undefined\n\t\t\t? undefined\n\t\t\t: 'value' in domainDescriptor\n\t\t\t\t? domainDescriptor.value\n\t\t\t\t: domainDescriptor.get === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: Reflect.apply(domainDescriptor.get, domains, [])\n\tif (!isTaskOperation(operation) || !isTaskDomain(domain)) return undefined\n\tconst statement = deriveStatement(text)\n\treturn statement === undefined ? undefined : buildTask(operation, domain, statement)\n}\n\n/**\n * Derives `Given[]` from an interprets `Entity[]`.\n *\n * @remarks\n * Every extracted entity becomes one `extracted` fact. A nameless entity is dropped; an\n * object value renders through interprets `canonicalize`, so the text is key-order stable.\n *\n * @param entities - The entities an interpret pipeline extracted.\n * @returns One `Given` per named entity, in extraction order.\n *\n * @example\n * ```ts\n * import { deriveGivens } from '@orkestrel/brief'\n *\n * deriveGivens([\n * \t{ name: 'value', value: 3, provenance: { category: 'extracted' }, confidence: 1 },\n * ]) // [{ category: 'extracted', name: 'value', value: '3' }]\n * ```\n */\nexport function deriveGivens(entities: readonly Entity[]): readonly Given[] {\n\treturn entities\n\t\t.filter((entity) => entity.name.length > 0)\n\t\t.map((entity) =>\n\t\t\tbuildGiven(\n\t\t\t\t'extracted',\n\t\t\t\tentity.name,\n\t\t\t\ttypeof entity.value === 'string'\n\t\t\t\t\t? entity.value\n\t\t\t\t\t: typeof entity.value === 'object' && entity.value !== null\n\t\t\t\t\t\t? canonicalize(entity.value)\n\t\t\t\t\t\t: String(entity.value),\n\t\t\t),\n\t\t)\n}\n\n/**\n * Derives `Gap[]` from an interprets `Ambiguity[]`.\n *\n * @remarks\n * A REQUIRED ambiguity becomes a BLOCKING gap — the gate must fail closed on it. The\n * rest stay open, to be answered with a recorded assumption. An array field path flattens\n * through reasons `formatField`.\n *\n * @param ambiguities - The ambiguities an interpret pipeline surfaced.\n * @returns One `Gap` per ambiguity, in surfacing order.\n *\n * @example\n * ```ts\n * import { deriveGaps } from '@orkestrel/brief'\n *\n * deriveGaps([{ field: 'output', question: 'Diff or files?', candidates: [], required: true }])\n * // [{ field: 'output', question: 'Diff or files?', blocking: true }]\n * ```\n */\nexport function deriveGaps(ambiguities: readonly Ambiguity[]): readonly Gap[] {\n\treturn ambiguities.map((ambiguity) => {\n\t\tconst candidates = ambiguity.candidates.filter((candidate) => candidate.length > 0)\n\t\treturn buildGap(formatField(ambiguity.field), ambiguity.question, {\n\t\t\tblocking: ambiguity.required,\n\t\t\t...(candidates.length === 0 ? {} : { candidates }),\n\t\t})\n\t})\n}\n","import type { Brief } from './types.js'\nimport { parseJSONAs } from '@orkestrel/contract'\nimport { isBrief } from './validators.js'\n\n/**\n * Parses a JSON string into a `Brief`.\n *\n * @remarks\n * The parse-then-trust boundary for a stored brief, a tool argument, or an agent's\n * emission. Invalid JSON, an extra key, an off-vocabulary literal, and a missing section\n * all fail the same way — `undefined`, never a throw. Coerce a bare vocabulary value with\n * `parseEnum` from `@orkestrel/contract` against the exported tuple instead.\n *\n * The half of the intake pair that is OWNED BY CONSTRUCTION, which is what separates it from\n * `assertBrief`. The argument is text, so the graph the guard reads is one `JSON.parse` built\n * inside this call: it carries no caller identity, no accessor, and no alias back into anything\n * the caller still holds, and the parse-and-guard primitive this file imports from\n * `@orkestrel/contract` returns that same parsed graph rather than a second reading of it.\n * Every member `isBrief` checked therefore answers a later reader identically. The value is\n * fresh rather than frozen, so the caller owns it outright — reach for `snapshotBrief` when the\n * value came from code instead of from text.\n *\n * @param value - The JSON text to parse.\n * @returns The `Brief` when the parsed value satisfies `isBrief`, otherwise `undefined`.\n *\n * @example\n * ```ts\n * import { parseBrief } from '@orkestrel/brief'\n *\n * parseBrief('not json') // undefined\n * parseBrief('{\"task\":{\"operation\":\"plan\",\"domain\":\"ops\",\"statement\":\"x.\"}}') // undefined\n * ```\n */\nexport function parseBrief(value: string): Brief | undefined {\n\treturn parseJSONAs(value, isBrief)\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { RecordOptions } from '@orkestrel/interpret'\nimport type {\n\tBrief,\n\tBriefManagerEventMap,\n\tBriefManagerInterface,\n\tBriefManagerOptions,\n\tBriefRecord,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { snapshotBrief } from './cloners.js'\nimport { BriefError } from './errors.js'\nimport { briefToContent, briefToHash, briefToTrace } from './helpers.js'\n\n/**\n * Implements the self-owning, versioned and content-hashed brief registry.\n *\n * @remarks\n * Record ids are MINTED from each brief's own content hash unless the caller names one,\n * so registering unchanged content twice is a version no-op and two callers who compiled\n * the same request land on the same id with no coordination. A call after `destroy()`\n * throws `BriefError('DESTROYED', …)`.\n *\n * @example\n * ```ts\n * import { BriefManager, buildBrief, buildTask } from '@orkestrel/brief'\n *\n * const briefs = new BriefManager()\n * const record = briefs.add(buildBrief(buildTask('document', 'writing', 'Write the brief guide.')))\n * record.id === record.hash // true\n * briefs.destroy()\n * ```\n */\nexport class BriefManager implements BriefManagerInterface {\n\treadonly #emitter: Emitter<BriefManagerEventMap>\n\treadonly #records = new Map<string, BriefRecord>()\n\t#destroyed = false\n\n\tconstructor(options?: BriefManagerOptions) {\n\t\t// One read per option; a second read lets a getter answer differently.\n\t\tconst hooks = options?.on\n\t\tconst failed = options?.error\n\t\tconst seeds = options?.briefs ?? []\n\t\t// Seeding is ALL-OR-NOTHING. `add` throws INVALID for an off-contract or colliding\n\t\t// entry, so seeding straight into the registry emitted `add` for earlier entries and\n\t\t// then abandoned a constructor that never returns — hooks observing ids for an instance\n\t\t// the caller does not have, and an emitter nothing can destroy. Validate every seed\n\t\t// first, then build the emitter, then commit.\n\t\tconst staged = new Map<string, BriefRecord>()\n\t\tfor (const entry of seeds) {\n\t\t\tconst record = this.#stage(entry, staged)\n\t\t\tstaged.set(record.id, record)\n\t\t}\n\t\tthis.#emitter = new Emitter<BriefManagerEventMap>({\n\t\t\t...(hooks === undefined ? {} : { on: hooks }),\n\t\t\t...(failed === undefined ? {} : { error: failed }),\n\t\t})\n\t\tfor (const record of staged.values()) this.#commit(record)\n\t}\n\n\tget emitter(): EmitterInterface<BriefManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#records.size\n\t}\n\n\thas(id: string): boolean {\n\t\tthis.#refuseDestroyed()\n\t\treturn this.#records.has(id)\n\t}\n\n\tbrief(id: string): BriefRecord | undefined {\n\t\tthis.#refuseDestroyed()\n\t\treturn this.#records.get(id)\n\t}\n\n\tbriefs(): readonly BriefRecord[] {\n\t\tthis.#refuseDestroyed()\n\t\treturn [...this.#records.values()]\n\t}\n\n\tadd(brief: Brief, options?: RecordOptions): BriefRecord {\n\t\tthis.#refuseDestroyed()\n\t\tconst record = this.#stage(brief, this.#records, options)\n\t\tthis.#commit(record)\n\t\treturn record\n\t}\n\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tthis.#refuseDestroyed()\n\t\tif (target === undefined) {\n\t\t\tfor (const id of [...this.#records.keys()]) this.#discard(id)\n\t\t\treturn\n\t\t}\n\t\tif (typeof target === 'string') return this.#discard(target)\n\t\t// Deduplicated, because the contract is about the listed SET. A repeated id was removed\n\t\t// on its first pass and then reported missing on its second, so `remove(['a', 'a'])`\n\t\t// returned false for a record it had already removed.\n\t\tlet removed = true\n\t\tfor (const id of new Set(target)) {\n\t\t\tif (!this.#discard(id)) removed = false\n\t\t}\n\t\treturn removed\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#records.clear()\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// Build the record without registering or announcing it. Split out of `add` so the\n\t// constructor can validate every seed before committing any: `snapshotBrief` and `#version`\n\t// both throw INVALID, and seeding straight into the registry left earlier entries announced\n\t// on an instance that never returned. `against` is the registry to version against — the\n\t// live one for `add`, the in-progress staging map while seeding, so two colliding seeds are\n\t// caught the same way two colliding adds are.\n\t#stage(\n\t\tsource: Brief,\n\t\tagainst: ReadonlyMap<string, BriefRecord>,\n\t\toptions?: RecordOptions,\n\t): BriefRecord {\n\t\t// Snapshot first: a record whose brief still aliases the caller's arrays would let a\n\t\t// later push change content this hash already described.\n\t\tconst owned = snapshotBrief(source)\n\t\tconst hash = briefToHash(owned)\n\t\t// An inbound brief's own `hash` is shape-checked, not verified — that is what lets a\n\t\t// pinned brief round-trip through JSON. So a record arriving with a hash that\n\t\t// contradicts its content is refused HERE, at the identity boundary, rather than\n\t\t// stored and later projected into an executor's prompt as if it were pinned.\n\t\tif (owned.hash !== undefined && owned.hash !== hash) {\n\t\t\tthrow new BriefError('INVALID', 'Brief carries a hash that does not describe it', {\n\t\t\t\tfield: 'hash',\n\t\t\t\thash: owned.hash,\n\t\t\t})\n\t\t}\n\t\t// `trace` gets the same reconciliation, and needs it more: `hash` is an opaque digest a\n\t\t// reader cannot check, while `trace` is the census line `briefToMarkdown` prints at the\n\t\t// top of the executor's prompt. A stale one misdescribes the brief exactly where it is\n\t\t// most read.\n\t\tconst trace = briefToTrace(owned)\n\t\tif (owned.trace !== undefined && owned.trace !== trace) {\n\t\t\tthrow new BriefError('INVALID', 'Brief carries a trace that does not describe it', {\n\t\t\t\tfield: 'trace',\n\t\t\t\ttrace: owned.trace,\n\t\t\t})\n\t\t}\n\t\tconst id = options?.id ?? hash\n\t\tconst previous = against.get(id)\n\t\treturn Object.freeze({\n\t\t\tid,\n\t\t\tbrief: owned,\n\t\t\tversion: previous === undefined ? 1 : this.#version(previous, owned, hash),\n\t\t\thash,\n\t\t})\n\t}\n\n\t// Register a staged record and announce it. Nothing here can throw, which is what makes\n\t// seeding all-or-nothing after every entry has been staged.\n\t#commit(record: BriefRecord): void {\n\t\tthis.#records.set(record.id, record)\n\t\tthis.#emitter.emit('add', record.id)\n\t}\n\n\t// The version a re-add earns, and the one place a digest collision is caught. The hash is\n\t// eight hex digits, so two DIFFERENT briefs can land on one id; treating that as\n\t// \"unchanged content\" would silently replace the first and report version 1. Content is\n\t// compared canonically, and only equal content is a version no-op.\n\t#version(previous: BriefRecord, incoming: Brief, hash: string): number {\n\t\tif (previous.hash !== hash) return previous.version + 1\n\t\t// Compare exactly what the hash describes. `briefToHash` strips `trace` and `hash`\n\t\t// first, so a draft and its own pinned form share a hash while their whole records\n\t\t// differ — comparing whole records would report that as a collision.\n\t\tif (briefToContent(previous.brief) === briefToContent(incoming)) return previous.version\n\t\tthrow new BriefError(\n\t\t\t'INVALID',\n\t\t\t'Two different briefs share one content hash — name them with distinct ids',\n\t\t\t{ field: 'hash', hash },\n\t\t)\n\t}\n\n\t// Deletes one record and emits only when a record was actually there.\n\t#discard(id: string): boolean {\n\t\tif (!this.#records.delete(id)) return false\n\t\tthis.#emitter.emit('remove', id)\n\t\treturn true\n\t}\n\n\t// Every method except the getters and `destroy` refuses a destroyed manager.\n\t#refuseDestroyed(): void {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new BriefError('DESTROYED', 'BriefManager has been destroyed')\n\t\t}\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type { Interpretation, InterpretInterface } from '@orkestrel/interpret'\nimport type { LogicalResult, ReasonInterface } from '@orkestrel/reason'\nimport type {\n\tBrief,\n\tBriefInput,\n\tBriefing,\n\tBriefStageFailure,\n\tBriefStageRecord,\n\tBriefCompilerEventMap,\n\tBriefCompilerInterface,\n\tBriefCompilerOptions,\n\tGap,\n\tTaskDomain,\n\tTaskOperation,\n} from './types.js'\nimport { Emitter } from '@orkestrel/emitter'\nimport { createInterpret, digestValue, isInterpretation } from '@orkestrel/interpret'\nimport { attempt } from '@orkestrel/contract'\nimport { createLogicalReasoner, createReason, isLogicalResult } from '@orkestrel/reason'\nimport { captureValue, snapshotBrief } from './cloners.js'\nimport { INTERPRETATION_MEMBERS } from './constants.js'\nimport { BriefError } from './errors.js'\nimport {\n\tbriefToSubject,\n\tbuildBrief,\n\tbuildGap,\n\tbuildGateDefinition,\n\tbuildManifest,\n\tbuildOutput,\n\tderiveGaps,\n\tderiveGivens,\n\tderiveTask,\n\terrorToMessage,\n\tfindBlockingGaps,\n\tfindUnmetRules,\n\tfreezeDeep,\n\tpinBrief,\n} from './helpers.js'\n\n/**\n * Implements the compilation orchestrator — the `[interpret, draft, gate, pin]` pipeline.\n *\n * @remarks\n * `compile` is genuinely SYNCHRONOUS and never throws for a brief it cannot emit: a\n * blocking gap, a refused gate, and a thrown stage all yield a visible INCOMPLETE\n * `Briefing`. It owns the engines it created and BORROWS the ones passed in, so\n * `destroy()` releases only what it made.\n *\n * @example\n * ```ts\n * import { BriefCompiler, buildProof, buildTask } from '@orkestrel/brief'\n *\n * const compiler = new BriefCompiler()\n * const briefing = compiler.compile({\n * \ttask: buildTask('audit', 'code', 'Audit the barrel for undocumented exports.'),\n * \toutcomes: [{ rank: 1, text: 'every export appears in the guide', required: true }],\n * \tproofs: [buildProof('parity passes', 'npm run test:guides')],\n * })\n * briefing.brief !== undefined // true — the presence of the brief IS the completeness test\n * compiler.destroy()\n * ```\n */\nexport class BriefCompiler implements BriefCompilerInterface {\n\treadonly #emitter: Emitter<BriefCompilerEventMap>\n\treadonly #interpret: InterpretInterface\n\treadonly #reason: ReasonInterface\n\treadonly #ownInterpret: boolean\n\treadonly #ownReason: boolean\n\treadonly #actions: Readonly<Record<string, TaskOperation>>\n\treadonly #domains: Readonly<Record<string, TaskDomain>>\n\t#destroyed = false\n\n\tconstructor(options?: BriefCompilerOptions) {\n\t\t// ONE read per option, for the reason `compile` takes one reading of its input: a second\n\t\t// read lets a getter answer differently. Reading `interpret` twice decided ownership from\n\t\t// the first answer and stored the second, so a borrowed engine could be destroyed and a\n\t\t// self-made one leaked — the exact inversion of the documented contract.\n\t\tconst hooks = options?.on\n\t\tconst failed = options?.error\n\t\tconst borrowedInterpret = options?.interpret\n\t\tconst borrowedReason = options?.reason\n\t\tthis.#emitter = new Emitter<BriefCompilerEventMap>({\n\t\t\t...(hooks === undefined ? {} : { on: hooks }),\n\t\t\t...(failed === undefined ? {} : { error: failed }),\n\t\t})\n\t\tthis.#ownInterpret = borrowedInterpret === undefined\n\t\tthis.#ownReason = borrowedReason === undefined\n\t\tthis.#interpret = borrowedInterpret ?? createInterpret()\n\t\tthis.#reason = borrowedReason ?? createReason({ reasoners: [createLogicalReasoner()] })\n\t\tthis.#actions = options?.actions ?? {}\n\t\tthis.#domains = options?.domains ?? {}\n\t}\n\n\tget emitter(): EmitterInterface<BriefCompilerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget interpret(): InterpretInterface {\n\t\treturn this.#interpret\n\t}\n\n\tget reason(): ReasonInterface {\n\t\treturn this.#reason\n\t}\n\n\tcompile(input: BriefInput): Briefing {\n\t\tthis.#refuseDestroyed()\n\t\tconst stages: BriefStageRecord[] = []\n\t\tconst failures: BriefStageFailure[] = []\n\n\t\t// ONE reading of the caller's object, taken first and used by every following stage. Reading\n\t\t// it again per stage let a getter answer differently each time, so the replay could\n\t\t// describe a compilation that did not happen — and a getter that THREW escaped `compile`\n\t\t// as a foreign error, which this contains into the same visible refusal as any other\n\t\t// stage failure.\n\t\tconst taken = attempt(() => this.#snapshot(input))\n\t\tif (!taken.success) {\n\t\t\tconst message = errorToMessage(taken.error)\n\t\t\tstages.push(Object.freeze({ stage: 'draft', input: {}, error: message }))\n\t\t\tfailures.push(Object.freeze({ stage: 'draft', code: 'DRAFT_FAILED', message }))\n\t\t\tthis.#emitter.emit('error', taken.error)\n\t\t\treturn this.#refuse(undefined, undefined, [], undefined, stages, failures)\n\t\t}\n\t\tconst owned = taken.value\n\n\t\tconst interpretation = this.#read(owned, input, stages, failures)\n\n\t\tconst drafted = attempt(() =>\n\t\t\tthis.#draft(owned, interpretation, this.#unresolved(interpretation, failures)),\n\t\t)\n\t\tif (!drafted.success) {\n\t\t\tconst message = errorToMessage(drafted.error)\n\t\t\tstages.push(Object.freeze({ stage: 'draft', input: owned, error: message }))\n\t\t\tfailures.push(Object.freeze({ stage: 'draft', code: 'DRAFT_FAILED', message }))\n\t\t\tthis.#emitter.emit('error', drafted.error)\n\t\t\treturn this.#refuse(interpretation, undefined, [], undefined, stages, failures)\n\t\t}\n\t\tconst draft = drafted.value\n\t\tstages.push(Object.freeze({ stage: 'draft', input: owned, output: draft }))\n\n\t\tconst questions = findBlockingGaps(draft)\n\t\tconst subject = Object.freeze(briefToSubject(draft))\n\t\t// `gate` owns the verdict at arrival, so it is already this compiler's own frozen value —\n\t\t// no second reading here. Contained, because a borrowed engine's throw must not escape.\n\t\tconst ruled = attempt(() => this.gate(draft))\n\t\tif (ruled.success) {\n\t\t\tstages.push(Object.freeze({ stage: 'gate', input: subject, output: ruled.value }))\n\t\t} else {\n\t\t\tconst message = errorToMessage(ruled.error)\n\t\t\tstages.push(Object.freeze({ stage: 'gate', input: subject, error: message }))\n\t\t\tfailures.push(Object.freeze({ stage: 'gate', code: 'GATE_FAILED', message }))\n\t\t\tthis.#emitter.emit('error', ruled.error)\n\t\t}\n\t\tconst verdict = ruled.success ? ruled.value : undefined\n\n\t\t// Readiness is decided HERE, from the measures, before the verdict is consulted. The\n\t\t// reasoner is borrowed — `BriefCompilerOptions.reason` is a documented seam — so its verdict\n\t\t// narrates and never decides: a supplied engine can add detail to a refusal and can\n\t\t// never turn one into a pass.\n\t\tconst unready = findUnmetRules(draft)\n\t\tif (unready.length > 0 || verdict === undefined || !verdict.conclusion) {\n\t\t\tconst refusal = this.#blockage(questions, unready, verdict)\n\t\t\tif (refusal !== undefined) failures.push(Object.freeze(refusal))\n\t\t\treturn this.#refuse(interpretation, draft, questions, verdict, stages, failures)\n\t\t}\n\n\t\tconst stamped = attempt(() => pinBrief(draft))\n\t\tif (!stamped.success) {\n\t\t\tconst message = errorToMessage(stamped.error)\n\t\t\tstages.push(Object.freeze({ stage: 'pin', input: draft, error: message }))\n\t\t\tfailures.push(Object.freeze({ stage: 'pin', code: 'PIN_FAILED', message }))\n\t\t\tthis.#emitter.emit('error', stamped.error)\n\t\t\treturn this.#refuse(interpretation, draft, questions, verdict, stages, failures)\n\t\t}\n\t\tconst pinned = stamped.value\n\t\tstages.push(Object.freeze({ stage: 'pin', input: draft, output: pinned }))\n\n\t\tconst briefing: Briefing = Object.freeze({\n\t\t\t...(interpretation === undefined ? {} : { interpretation }),\n\t\t\tbrief: pinned,\n\t\t\tquestions: Object.freeze([]),\n\t\t\tverdict,\n\t\t\tstages: Object.freeze([...stages]),\n\t\t\tfailures: Object.freeze([...failures]),\n\t\t\tdigest: digestValue({ brief: pinned, questions: [], failures }),\n\t\t})\n\t\tthis.#emitter.emit('compile', briefing)\n\t\treturn briefing\n\t}\n\n\tgate(brief: Brief): LogicalResult {\n\t\tthis.#refuseDestroyed()\n\t\t// The reasoner is BORROWED, so it can throw its own foreign error — a `ReasonError` from\n\t\t// an engine the caller already destroyed, for one. Every throw out of this module is a\n\t\t// `BriefError` that `isBriefError` narrows, so a foreign throw is translated rather than\n\t\t// leaked.\n\t\t// OWNED at arrival, then validated on the owned copy — one reading of the foreign value,\n\t\t// the law `compile` already applies to the caller's input. Validating one reading and\n\t\t// recording another let a getter bless a shape the pipeline never saw.\n\t\tconst ruled = attempt(() =>\n\t\t\tthis.#own(this.#reason.reason(briefToSubject(brief), buildGateDefinition()), [\n\t\t\t\t'reasoning',\n\t\t\t\t'conclusion',\n\t\t\t\t'rules',\n\t\t\t\t'count',\n\t\t\t\t'success',\n\t\t\t\t'trace',\n\t\t\t\t'errors',\n\t\t\t]),\n\t\t)\n\t\tif (!ruled.success) {\n\t\t\tthrow new BriefError('GATE_FAILED', errorToMessage(ruled.error), {\n\t\t\t\tstage: 'gate',\n\t\t\t\tfield: 'reason',\n\t\t\t})\n\t\t}\n\t\tconst verdict = ruled.value\n\t\t// Guard the WHOLE value, not one field. The reasoner is borrowed, so its return is\n\t\t// foreign data however well-typed the interface is: reading `.reasoning` off `undefined`\n\t\t// threw a raw TypeError where the contract promises `GATE_FAILED`, and a result that\n\t\t// claimed `reasoning: 'logical'` without a `rules` array crashed the caller of this\n\t\t// method instead. reason's published `isLogicalResult` is total, so every malformed\n\t\t// shape lands here.\n\t\tif (!isLogicalResult(verdict)) {\n\t\t\tthrow new BriefError('GATE_FAILED', 'The gate reasoner returned a non-logical result', {\n\t\t\t\tstage: 'gate',\n\t\t\t\tfield: 'reasoning',\n\t\t\t})\n\t\t}\n\t\treturn verdict\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tif (this.#ownInterpret) this.#interpret.destroy()\n\t\tif (this.#ownReason) this.#reason.destroy()\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// THE reading of the caller's input — taken once, deep, and shared by every stage. A\n\t// per-field copy left the members aliased, and a second reading let a getter answer\n\t// differently, so there is exactly one and no fallback that re-reads. The freeze is DEEP\n\t// because `Object.freeze` alone left every nested array writable, so a consumer could\n\t// rewrite the recorded stage input after the digest describing it was sealed. Throws for\n\t// an input that cannot be cloned; `compile` contains that into a visible refusal.\n\t#snapshot(input: BriefInput): BriefInput {\n\t\treturn freezeDeep(structuredClone(input))\n\t}\n\n\t// THE ownership boundary for every value a BORROWED engine returns. `Briefing` is documented\n\t// as replayable, and a foreign object is neither ours nor stable — it may be pooled, mutated\n\t// later, or handed to another caller.\n\t//\n\t// It NEVER narrows past the foreign contract, which is the law the verdict guards already\n\t// follow. `structuredClone` accepts JSON and a little more; the contracts here are wider —\n\t// `Entity.value` is declared `unknown`, and `LogicalResult` is an interface a class instance\n\t// satisfies. Cloning unconditionally therefore FAILED a stage for a type-conforming engine\n\t// result, and for the interpret stage that failure deleted the derived blocking gaps and let\n\t// an under-specified brief through the gate.\n\t//\n\t// So: clone when the value permits it, which also breaks the alias, and otherwise capture a\n\t// plain view that materializes the published members once while retaining uncloneable leaves.\n\t// Every later read is of that frozen view. What is never acceptable is refusing the value.\n\t#own(value: unknown, members: readonly string[]): unknown {\n\t\tconst cloned = attempt(() => structuredClone(value))\n\t\treturn cloned.success ? freezeDeep(cloned.value) : captureValue(value, members)\n\t}\n\n\t// The interpret stage. Skipped entirely when the input carries no text, in which case\n\t// a caller-supplied interpretation still reaches the draft. Both doors are guarded with\n\t// interpret's published `isInterpretation` before anything dereferences `intent`,\n\t// `entities`, or `ambiguities`: the engine is borrowed, and a malformed return threw a\n\t// raw TypeError out of `compile` where the contract promises INTERPRET_FAILED. The\n\t// supplied-interpretation door shares the guard for the caller a type system cannot\n\t// see — a JS consumer or a replayed value — at the cost of one total check.\n\t#read(\n\t\tinput: BriefInput,\n\t\traw: BriefInput,\n\t\tstages: BriefStageRecord[],\n\t\tfailures: BriefStageFailure[],\n\t): Interpretation | undefined {\n\t\tconst text = input.text\n\t\tif (text !== undefined) {\n\t\t\t// Owned for the same reason the verdict is: the engine is borrowed and its\n\t\t\t// `Interpretation` is foreign data the briefing then carries as a replay.\n\t\t\tconst read = attempt(() => this.#own(this.#interpret.interpret(text), INTERPRETATION_MEMBERS))\n\t\t\tif (read.success && isInterpretation(read.value)) {\n\t\t\t\tstages.push(Object.freeze({ stage: 'interpret', input: text, output: read.value }))\n\t\t\t\treturn read.value\n\t\t\t}\n\t\t\tconst message = read.success\n\t\t\t\t? 'The interpret engine returned a non-interpretation result'\n\t\t\t\t: errorToMessage(read.error)\n\t\t\tstages.push(Object.freeze({ stage: 'interpret', input: text, error: message }))\n\t\t\tfailures.push(Object.freeze({ stage: 'interpret', code: 'INTERPRET_FAILED', message }))\n\t\t\tthis.#emitter.emit(\n\t\t\t\t'error',\n\t\t\t\tread.success\n\t\t\t\t\t? new BriefError('INTERPRET_FAILED', message, { stage: 'interpret' })\n\t\t\t\t\t: read.error,\n\t\t\t)\n\t\t}\n\t\tconst supplied = input.interpretation\n\t\tif (supplied === undefined || isInterpretation(supplied)) return supplied\n\t\t// The snapshot's clone keeps own members only, so a conforming interpretation carried\n\t\t// by prototype accessors arrives here empty. Capture the live value into a plain view;\n\t\t// no later read remains attached to the caller's accessors.\n\t\tconst live = raw.interpretation\n\t\tconst captured = attempt(() => captureValue(live, INTERPRETATION_MEMBERS))\n\t\tif (captured.success && isInterpretation(captured.value)) return captured.value\n\t\tconst message = 'The supplied interpretation does not satisfy the published shape'\n\t\tstages.push(Object.freeze({ stage: 'interpret', input: 'interpretation', error: message }))\n\t\tfailures.push(Object.freeze({ stage: 'interpret', code: 'INTERPRET_FAILED', message }))\n\t\treturn undefined\n\t}\n\n\t// The one place a refusal is coded. Blocking gaps ALWAYS produce `BLOCKED`, including\n\t// when the gate itself threw and left no verdict to report rules from.\n\t#blockage(\n\t\tquestions: readonly Gap[],\n\t\tunready: readonly string[],\n\t\tverdict: LogicalResult | undefined,\n\t): BriefStageFailure | undefined {\n\t\tif (questions.length > 0) {\n\t\t\treturn {\n\t\t\t\tstage: 'gate',\n\t\t\t\tcode: 'BLOCKED',\n\t\t\t\tmessage: `${String(questions.length)} blocking gap(s)`,\n\t\t\t}\n\t\t}\n\t\t// The measured refusal is named first, because it is the one that decided.\n\t\tif (unready.length > 0) {\n\t\t\treturn { stage: 'gate', code: 'BLOCKED', message: `Gate refused: ${unready.join(', ')}` }\n\t\t}\n\t\tif (verdict === undefined) return undefined\n\t\tconst refused = verdict.rules\n\t\t\t.filter((entry) => !entry.applied)\n\t\t\t.map((entry) => entry.id)\n\t\t\t.join(', ')\n\t\t// A borrowed engine may refuse through `conclusion` alone and name no failing rule, which\n\t\t// rendered as `Gate refused: ` — a refusal with the cause cut off. The refusal is correct\n\t\t// and this is the one case where the supplied engine is the sole decider, so say so.\n\t\tif (refused.length === 0) {\n\t\t\treturn {\n\t\t\t\tstage: 'gate',\n\t\t\t\tcode: 'BLOCKED',\n\t\t\t\tmessage: 'Gate refused: the supplied reasoner named no failing rule',\n\t\t\t}\n\t\t}\n\t\treturn { stage: 'gate', code: 'BLOCKED', message: `Gate refused: ${refused}` }\n\t}\n\n\t// The blocking gap a CONTAINED interpret failure owes the brief.\n\t//\n\t// Containing that failure is right, but it silently deleted what the stage would have\n\t// produced: `deriveGaps(interpretation.ambiguities)`. With the ambiguities gone,\n\t// `findBlockingGaps` was empty, `findUnmetRules` dropped `specified`, the gate passed, and\n\t// `compile` emitted a pinned brief for a request it had correctly refused a moment earlier.\n\t// A failure that removes evidence must never read as evidence of readiness.\n\t//\n\t// Empty when an interpretation survived — a caller-supplied `BriefInput.interpretation`\n\t// carries its own ambiguities, so nothing was lost.\n\t#unresolved(\n\t\tinterpretation: Interpretation | undefined,\n\t\tfailures: readonly BriefStageFailure[],\n\t): readonly Gap[] {\n\t\tif (interpretation !== undefined) return []\n\t\tif (!failures.some((entry) => entry.stage === 'interpret')) return []\n\t\treturn [\n\t\t\tbuildGap(\n\t\t\t\t'gaps',\n\t\t\t\t'The interpret stage failed, so the request is unread and its unknowns are unknown',\n\t\t\t\t{\n\t\t\t\t\tblocking: true,\n\t\t\t\t},\n\t\t\t),\n\t\t]\n\t}\n\n\t// The draft stage. Derived sections come first and caller sections merge OVER them,\n\t// so the user is never overridden; derived and caller gaps and givens accumulate.\n\t#draft(\n\t\tinput: BriefInput,\n\t\tinterpretation: Interpretation | undefined,\n\t\tunresolved: readonly Gap[],\n\t): Brief {\n\t\tconst derived =\n\t\t\tinterpretation === undefined\n\t\t\t\t? undefined\n\t\t\t\t: deriveTask(interpretation.intent, interpretation.text, this.#actions, this.#domains)\n\t\tconst subject = input.task ?? derived\n\t\tif (subject === undefined) {\n\t\t\tthrow new BriefError(\n\t\t\t\t'DRAFT_FAILED',\n\t\t\t\t'No task: supply BriefInput.task, or map the intent through the actions and domains vocabularies',\n\t\t\t\t{ stage: 'draft', field: 'task' },\n\t\t\t)\n\t\t}\n\t\t// Snapshot at the draft, not only at the pin. A drafted brief adopts the caller's\n\t\t// arrays, and it is what `Briefing.stages` records — a replay that changes when the\n\t\t// caller mutates their own input afterwards is not a replay.\n\t\treturn snapshotBrief(\n\t\t\tbuildBrief(subject, {\n\t\t\t\tauthority: input.authority ?? [],\n\t\t\t\tmanifest: input.manifest ?? buildManifest(),\n\t\t\t\toutcomes: input.outcomes ?? [],\n\t\t\t\trules: input.rules ?? [],\n\t\t\t\tinvariants: input.invariants ?? [],\n\t\t\t\tgivens: [\n\t\t\t\t\t...(interpretation === undefined ? [] : deriveGivens(interpretation.entities)),\n\t\t\t\t\t...(input.givens ?? []),\n\t\t\t\t],\n\t\t\t\texamples: input.examples ?? [],\n\t\t\t\tassumptions: input.assumptions ?? [],\n\t\t\t\tcitations: input.citations ?? [],\n\t\t\t\tgaps: [\n\t\t\t\t\t...(interpretation === undefined ? [] : deriveGaps(interpretation.ambiguities)),\n\t\t\t\t\t...unresolved,\n\t\t\t\t\t...(input.gaps ?? []),\n\t\t\t\t],\n\t\t\t\trisks: input.risks ?? [],\n\t\t\t\toutput: input.output ?? buildOutput('markdown'),\n\t\t\t\tproofs: input.proofs ?? [],\n\t\t\t}),\n\t\t)\n\t}\n\n\t// The one incomplete result shape: no brief, the questions visible, `block` emitted.\n\t#refuse(\n\t\tinterpretation: Interpretation | undefined,\n\t\tdraft: Brief | undefined,\n\t\tquestions: readonly Gap[],\n\t\tverdict: LogicalResult | undefined,\n\t\tstages: readonly BriefStageRecord[],\n\t\tfailures: readonly BriefStageFailure[],\n\t): Briefing {\n\t\t// Frozen exactly as the complete path is. The incomplete briefing is this package's\n\t\t// headline artifact — the visible refusal — so it must not be the mutable one: a\n\t\t// `failures.pop()` would drop the `BLOCKED` marker the `digest` already attests to.\n\t\t// ONE frozen array, carried by the briefing AND handed to every listener. Emitting the\n\t\t// caller-reachable `questions` instead gave observers a mutable array that was not the\n\t\t// briefing's: one listener could rewrite what the next was handed, and neither reached\n\t\t// the record the digest attests to. Observation is a side-channel, so it reads exactly\n\t\t// what the briefing carries and can change nothing.\n\t\tconst asked = Object.freeze([...questions])\n\t\tconst briefing: Briefing = Object.freeze({\n\t\t\t...(interpretation === undefined ? {} : { interpretation }),\n\t\t\tquestions: asked,\n\t\t\t...(verdict === undefined ? {} : { verdict }),\n\t\t\tstages: Object.freeze([...stages]),\n\t\t\tfailures: Object.freeze([...failures]),\n\t\t\t// The DRAFT is digested, for the reason the pinned brief is on the complete path.\n\t\t\t// Digesting only `questions` and `failures` gave every ordinary refusal one digest —\n\t\t\t// two entirely different requests refused for \"no proofs\" were indistinguishable, in\n\t\t\t// the member documented as identifying the outcome and offered as a cache key.\n\t\t\tdigest: digestValue({\n\t\t\t\t...(draft === undefined ? {} : { brief: draft }),\n\t\t\t\tquestions,\n\t\t\t\tfailures,\n\t\t\t}),\n\t\t})\n\t\tthis.#emitter.emit('block', asked)\n\t\treturn briefing\n\t}\n\n\t// Every method except the getters and `destroy` refuses a destroyed compiler.\n\t#refuseDestroyed(): void {\n\t\tif (this.#destroyed) throw new BriefError('DESTROYED', 'BriefCompiler has been destroyed')\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tBrief,\n\tBriefManagerInterface,\n\tBriefManagerOptions,\n\tBriefCompilerInterface,\n\tBriefCompilerOptions,\n} from './types.js'\nimport { createContract } from '@orkestrel/contract'\nimport { BriefManager } from './BriefManager.js'\nimport { BriefCompiler } from './BriefCompiler.js'\nimport { briefShape } from './shapers.js'\n\n/**\n * Creates a compilation orchestrator.\n *\n * @remarks\n * With no engines supplied the compiler wires its own: a default `createInterpret()`\n * (empty vocabularies, so `options.actions` / `options.domains` drive `deriveTask`) and a\n * `createReason` carrying one `LogicalReasoner` for the gate. Pass your own to share\n * instances or observe their emitters — the compiler destroys ONLY what it created.\n *\n * @param options - Engines to borrow, the `actions` and `domains` intent vocabularies, and\n * emitter hooks.\n * @returns A working {@link BriefCompilerInterface}.\n *\n * @example Compile and project a brief\n * ```ts\n * import {\n * \tbriefToGoal,\n * \tbriefToMarkdown,\n * \tbuildOutcome,\n * \tbuildProof,\n * \tbuildTask,\n * \tcreateBriefCompiler,\n * } from '@orkestrel/brief'\n *\n * const compiler = createBriefCompiler()\n *\n * const briefing = compiler.compile({\n * \ttask: buildTask('refactor', 'code', 'Refactor useForm to native browser form APIs.'),\n * \tauthority: [{ path: 'AGENTS.md', note: 'project law; wins every conflict' }],\n * \tmanifest: {\n * \t\tread: [\n * \t\t\t{ path: 'AGENTS.md', note: 'project law; wins every conflict' },\n * \t\t\t{ path: 'guides/browser.md', note: 'the composable contract' },\n * \t\t],\n * \t\tedit: [{ path: 'src/browser/composables/useForm.ts', note: 'the composable being refactored' }],\n * \t\tlocked: [{ path: 'src/browser/types.ts', note: 'the published contract' }],\n * \t\tforbidden: [{ path: 'app/**', note: 'out of scope' }],\n * \t},\n * \toutcomes: [buildOutcome(1, 'useForm uses native FormData with no behavior change')],\n * \tproofs: [buildProof('type-check and lint pass', 'npm run check')],\n * })\n *\n * briefing.brief !== undefined // true — the brief is present exactly when the gate passed\n * if (briefing.brief !== undefined) {\n * \tbriefToMarkdown(briefing.brief) // the copy-ready agent prompt\n * \tbriefToGoal(briefing.brief) // the /goal completion condition\n * }\n *\n * compiler.emitter.on('block', (questions) => questions.length)\n * compiler.destroy()\n * ```\n *\n * @example\n * ```ts\n * import { createBriefCompiler } from '@orkestrel/brief'\n *\n * const compiler = createBriefCompiler({ actions: { refactor: 'refactor' }, domains: { code: 'code' } })\n * compiler.destroy()\n * ```\n */\nexport function createBriefCompiler(options?: BriefCompilerOptions): BriefCompilerInterface {\n\treturn new BriefCompiler(options)\n}\n\n/**\n * Creates a brief registry.\n *\n * @param options - An optional seed collection plus emitter hooks.\n * @returns A working {@link BriefManagerInterface}.\n *\n * @example\n * ```ts\n * import { createBriefManager } from '@orkestrel/brief'\n *\n * const briefs = createBriefManager()\n * briefs.count // 0\n * briefs.destroy()\n * ```\n */\nexport function createBriefManager(options?: BriefManagerOptions): BriefManagerInterface {\n\treturn new BriefManager(options)\n}\n\n/**\n * Compiles `briefShape` into a guard, parser, JSON Schema, and seeded generator bundle.\n *\n * @remarks\n * The schema is what a tool boundary needs — hand it to `schemaToParameters` — and\n * `generate(seededRandom(n))` yields a reproducible on-contract brief for tests. This\n * bundle and the hand-composed `isBrief` are two independent mechanisms over one\n * vocabulary; `tests/src/core/shapers.test.ts` is what holds them in lockstep.\n *\n * @returns A `ContractInterface` over `Brief`.\n *\n * @example\n * ```ts\n * import { createBriefContract } from '@orkestrel/brief'\n * import { schemaToParameters, seededRandom } from '@orkestrel/contract'\n *\n * const contract = createBriefContract()\n * schemaToParameters(contract.schema) // the open tool-parameters record, no `as` anywhere\n * contract.generate(seededRandom(42)) // a reproducible on-contract brief\n * ```\n */\nexport function createBriefContract(): ContractInterface<Brief> {\n\treturn createContract(briefShape)\n}\n"],"mappings":";;;;;;;;;;;;;AAUA,IAAa,kBAA4C,OAAO,OAAO;CACtE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,eAAsC,OAAO,OAAO;CAChE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,iBAA0C,OAAO,OAAO;CACpE;CACA;CACA;CACA;CACA;AACD,CAAC;;AAGD,IAAa,kBAA2C,OAAO,OAAO;CAAC;CAAO;CAAU;AAAM,CAAC;;;;;;;;;;;;;;;AAgB/F,IAAa,yBAAyB,OAAO,OAAO;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAA+C;;;;;;;;AAS/C,IAAa,sBAAsB;;AAGnC,IAAa,UAAU;;;;;;;;;;;AAYvB,IAAa,qBAAqB;;;;;;;;;AAUlC,IAAa,sBAAsB;;;;;;;;;;;;AAanC,IAAa,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;ACnG7B,IAAa,aAAb,cAAgC,MAAM;CACrC;CACA;CAEA,YAAY,MAAsB,SAAiB,SAA6C;EAC/F,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,aAAa,OAAqC;CACjE,OAAO,iBAAiB;AACzB;;;;ACrCA,IAAa,aAAA,GAAyB,oBAAA,YAAA,CAAY,EAAE,SAAS,oBAAoB,CAAC;;AAGlF,IAAa,aAAA,GAAyB,oBAAA,YAAA,CAAY;CAAE,KAAK;CAAG,SAAS;AAAoB,CAAC;;;;;;;;;AAU1F,IAAa,aAAA,GAAY,oBAAA,YAAA,CACxB;CACC,YAAA,GAA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