@orkestrel/brief 0.0.2 → 0.0.3
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.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orkestrel/brief",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.3",
|
|
4
4
|
"description": "A synchronous, deterministic specification compiler: a rough request becomes a closed, content-hashed execution contract another agent can run, gated by a traceable reasoner and projected into every downstream artifact.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|
|
@@ -69,14 +69,14 @@
|
|
|
69
69
|
},
|
|
70
70
|
"dependencies": {
|
|
71
71
|
"@orkestrel/contract": "^0.0.12",
|
|
72
|
-
"@orkestrel/emitter": "^0.0.
|
|
73
|
-
"@orkestrel/interpret": "^0.0.
|
|
74
|
-
"@orkestrel/reason": "^0.0.
|
|
72
|
+
"@orkestrel/emitter": "^0.0.7",
|
|
73
|
+
"@orkestrel/interpret": "^0.0.10",
|
|
74
|
+
"@orkestrel/reason": "^0.0.7"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
77
|
"@microsoft/api-extractor": "^7.58.12",
|
|
78
|
-
"@orkestrel/guide": "^0.0.
|
|
79
|
-
"@orkestrel/scaffold": "^0.0.
|
|
78
|
+
"@orkestrel/guide": "^0.0.12",
|
|
79
|
+
"@orkestrel/scaffold": "^0.0.39",
|
|
80
80
|
"@orkestrel/test": "^0.0.6",
|
|
81
81
|
"@types/node": "^26.2.0",
|
|
82
82
|
"oxfmt": "^0.63.0",
|
|
@@ -1 +0,0 @@
|
|
|
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 { OutputFormat, RiskSeverity, TaskDomain, TaskOperation } from './types.js'\n\n/** The twelve `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/** The eight `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/** The five `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/** The three `RiskSeverity` values, frozen. */\nexport const RISK_SEVERITIES: readonly RiskSeverity[] = Object.freeze(['low', 'medium', 'high'])\n\n/**\n * `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/** `'gate'` — the id of the `gateDefinition()` logical definition. */\nexport const GATE_ID = 'gate'\n\n/**\n * Every line terminator a brief field refuses.\n *\n * @remarks\n * The four ECMAScript line terminators, not just `\\n`: a renderer that splits on any of\n * them would let the other three forge a markdown row. CRLF leads the alternation so a\n * Windows exemplar splits as ONE break rather than two, which would insert a blank line the\n * caller 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 * 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 * 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 * 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 * Narrow a caught value to a {@link BriefError}.\n *\n * @param value - The caught value to inspect.\n * @returns `true` when `value` is a `BriefError`.\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/** A single-line string of any length, including empty. */\nexport const textShape: StringShape = stringShape({ pattern: SINGLE_LINE_PATTERN })\n\n/** A non-empty single-line string — the shape mirror of `isLine`. */\nexport const lineShape: StringShape = stringShape({ min: 1, pattern: SINGLE_LINE_PATTERN })\n\n/** 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/** 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/** The `Manifest` shape — four 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 four disjoint file partitions of a brief.' },\n)\n\n/** 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/** 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/** 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/** 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/** 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/** 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/** 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/** 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 * 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 {\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'\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'\n\n/**\n * `true` when 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 */\nexport const isText: Guard<string> = (value: unknown): value is string =>\n\tisString(value) && !LINE_BREAK_PATTERN.test(value)\n\n/** `true` when the value is a non-empty string holding no line terminator. */\nexport const isLine: Guard<string> = andOf(isNonEmptyString, isText)\n\n/** `true` when the value is one of the twelve `TaskOperation` literals. */\nexport const isTaskOperation: Guard<TaskOperation> = literalOf(TASK_OPERATIONS)\n\n/** `true` when the value is one of the eight `TaskDomain` literals. */\nexport const isTaskDomain: Guard<TaskDomain> = literalOf(TASK_DOMAINS)\n\n/** `true` when the value is one of the five `OutputFormat` literals. */\nexport const isOutputFormat: Guard<OutputFormat> = literalOf(OUTPUT_FORMATS)\n\n/** `true` when the value is one of the three `RiskSeverity` literals. */\nexport const isRiskSeverity: Guard<RiskSeverity> = literalOf(RISK_SEVERITIES)\n\n/** `true` when the value is a well-formed `Task` — both vocabularies closed, statement one line. */\nexport const isTask: Guard<Task> = recordOf({\n\toperation: isTaskOperation,\n\tdomain: isTaskDomain,\n\tstatement: isLine,\n})\n\n/** `true` when the value is a well-formed `Reference` — both members required, both single-line. */\nexport const isReference: Guard<Reference> = recordOf({\n\tpath: isLine,\n\tnote: isLine,\n})\n\n/**\n * `true` when the value is a well-formed `Manifest`.\n *\n * @remarks\n * Partition presence only — disjointness is `validateBrief`'s semantic pass.\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/** `true` when the value is a well-formed `Outcome` — `rank` a positive integer. */\nexport const isOutcome: Guard<Outcome> = recordOf({\n\trank: andOf(isInteger, boundsOf(1)),\n\ttext: isLine,\n\trequired: isBoolean,\n})\n\n/** `true` when the value is a well-formed `Given` — `value` may be empty but stays one line. */\nexport const isGiven: Guard<Given> = recordOf({\n\tcategory: isLine,\n\tname: isLine,\n\tvalue: isText,\n})\n\n/**\n * `true` when 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 */\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/** `true` when the value is a well-formed `Citation` — all three members single-line. */\nexport const isCitation: Guard<Citation> = recordOf({\n\tname: isLine,\n\turl: isLine,\n\tnote: isLine,\n})\n\n/** `true` when the value is a well-formed `Gap`. */\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/** `true` when the value is a well-formed `Risk` — `severity` on the closed vocabulary. */\nexport const isRisk: Guard<Risk> = recordOf({\n\tseverity: isRiskSeverity,\n\ttext: isLine,\n\tmitigation: isLine,\n})\n\n/** `true` when the value is a well-formed `Output` — `format` on the closed vocabulary. */\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/** `true` when the value is a well-formed `Proof`. */\nexport const isProof: Guard<Proof> = recordOf({\n\ttext: isLine,\n\tcommand: isLine,\n})\n\n/**\n * `true` when 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 */\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 { attempt, cloneJSONRecord } from '@orkestrel/contract'\nimport { BriefError } from './errors.js'\nimport type { Brief } from './types.js'\nimport { isBrief } from './validators.js'\n\n/**\n * Return 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 { brief, outcome, snapshotBrief, task } from '@orkestrel/brief'\n *\n * const outcomes = [outcome(1, 'shipped')]\n * const owned = snapshotBrief(brief(task('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 { attempt } from '@orkestrel/contract'\nimport type { Ambiguity, Entity, Intent } from '@orkestrel/interpret'\nimport { canonicalize, collapseWhitespace, digestValue } from '@orkestrel/interpret'\nimport type { LogicalDefinition, ReasonValidationResult, Rule, Subject } from '@orkestrel/reason'\nimport { atom, compound, formatField, logicalDefinition, rule } 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 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 { isBrief, isTaskDomain, isTaskOperation } from './validators.js'\n\n/**\n * Build a `Task`.\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 { task } from '@orkestrel/brief'\n *\n * task('refactor', 'code', 'Refactor useForm to native browser form APIs.')\n * ```\n */\nexport function task(operation: TaskOperation, domain: TaskDomain, statement: string): Task {\n\treturn { operation, domain, statement }\n}\n\n/**\n * Build a `Reference`.\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 { reference } from '@orkestrel/brief'\n *\n * reference('AGENTS.md', 'project law') // { path: 'AGENTS.md', note: 'project law' }\n * ```\n */\nexport function reference(path: string, note: string): Reference {\n\treturn { path, note }\n}\n\n/**\n * Build 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 all four partitions present.\n *\n * @example\n * ```ts\n * import { manifest, reference } from '@orkestrel/brief'\n *\n * manifest({ edit: [reference('src/core/helpers.ts', 'implementation')] })\n * ```\n */\nexport function manifest(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 * Build an `Outcome`.\n *\n * @param rank - The one-based rank; lower ranks matter more.\n * @param text - The result, never a step.\n * @param required - Whether the outcome gates \"done\"; defaults to `true`.\n * @returns A fresh `Outcome`.\n *\n * @example\n * ```ts\n * import { outcome } from '@orkestrel/brief'\n *\n * outcome(1, 'useForm uses native FormData with no behavior change') // required: true\n * outcome(2, 'the diff stays under 200 lines', false)\n * ```\n */\nexport function outcome(rank: number, text: string, required = true): Outcome {\n\treturn { rank, text, required }\n}\n\n/**\n * Build a `Given`.\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 { given } from '@orkestrel/brief'\n *\n * given('convention', 'indentation', 'tabs')\n * ```\n */\nexport function given(category: string, name: string, value: string): Given {\n\treturn { category, name, value }\n}\n\n/**\n * Build an `Example`.\n *\n * @param input - The exemplar input.\n * @param result - 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 { example } from '@orkestrel/brief'\n *\n * example('<input required>', 'validity read from el.validity')\n * ```\n */\nexport function example(input: string, result: string, note?: string): Example {\n\treturn note === undefined ? { input, output: result } : { input, output: result, note }\n}\n\n/**\n * Build a `Citation`.\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 { citation } from '@orkestrel/brief'\n *\n * citation(\n * \t'MDN Constraint Validation',\n * \t'https://developer.mozilla.org/',\n * \t'the native validity behavior being adopted',\n * )\n * ```\n */\nexport function citation(name: string, url: string, note: string): Citation {\n\treturn { name, url, note }\n}\n\n/**\n * Build a `Gap`.\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` (defaults `false`) and `candidates`; an absent\n * `candidates` key is OMITTED entirely.\n * @returns A fresh `Gap`.\n *\n * @example\n * ```ts\n * import { gap } from '@orkestrel/brief'\n *\n * gap('rules', 'Should validation message wording change?') // blocking: false\n * gap('output', 'Diff or full files?', { blocking: true, candidates: ['diff', 'code'] })\n * ```\n */\nexport function gap(\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 * Build a `Risk`.\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 { risk } from '@orkestrel/brief'\n *\n * risk('medium', 'native validation differs subtly', 'assert message and state in tests')\n * ```\n */\nexport function risk(severity: RiskSeverity, text: string, mitigation: string): Risk {\n\treturn { severity, text, mitigation }\n}\n\n/**\n * Build an `Output`.\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 { output } from '@orkestrel/brief'\n *\n * output('markdown') // { format: 'markdown' }\n * output('diff', { include: ['updated useForm.ts'] })\n * ```\n */\nexport function output(format: OutputFormat, overrides?: Partial<Omit<Output, 'format'>>): 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 * Build a `Proof`.\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 { proof } from '@orkestrel/brief'\n *\n * proof('type-check and lint pass', 'npm run check')\n * ```\n */\nexport function proof(text: string, command: string): Proof {\n\treturn { text, command }\n}\n\n/**\n * Build 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; every absent collection defaults to `[]`,\n * `output` defaults to `output('markdown')`, and `trace` / `hash` stay OMITTED so\n * `pinBrief` can fill them.\n * @returns A fresh, unpinned `Brief`.\n *\n * @example\n * ```ts\n * import { brief, outcome, proof, task } from '@orkestrel/brief'\n *\n * brief(task('audit', 'code', 'Audit the barrel for undocumented exports.'), {\n * \toutcomes: [outcome(1, 'every export appears in the guide')],\n * \tproofs: [proof('parity passes', 'npm run test:guides')],\n * })\n * ```\n */\nexport function brief(\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 ?? manifest(),\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 ?? output('markdown'),\n\t\tproofs: overrides?.proofs ?? [],\n\t}\n}\n\n/**\n * Build the fail-closed readiness gate as a reasons `LogicalDefinition`.\n *\n * @remarks\n * Six readiness rules each derive one named fact from `briefToSubject`'s measures, and a\n * final `ready` rule conjoins all six. Forward chaining reports the LAST rule's\n * conclusion, so `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, gateDefinition } from '@orkestrel/brief'\n * import { createLogicalReasoner, createReason } from '@orkestrel/reason'\n *\n * const reason = createReason({ reasoners: [createLogicalReasoner()] })\n * const verdict = reason.reason(briefToSubject(pinned), gateDefinition())\n * reason.destroy()\n * ```\n */\nexport function gateDefinition(): LogicalDefinition {\n\tconst readiness: readonly Rule[] = [\n\t\trule('specified', [atom('blocking', 'equals', 0)], atom('specified', 'equals', true)),\n\t\trule(\n\t\t\t'aimed',\n\t\t\t[compound('and', [atom('outcomes', 'above', 0), atom('required', 'above', 0)])],\n\t\t\tatom('aimed', 'equals', true),\n\t\t),\n\t\trule('proven', [atom('proofs', 'above', 0)], atom('proven', 'equals', true)),\n\t\trule('disjoint', [atom('overlaps', 'equals', 0)], atom('disjoint', 'equals', true)),\n\t\trule('granted', [atom('ungranted', 'equals', 0)], atom('granted', 'equals', true)),\n\t\trule('single', [atom('sentences', 'equals', 1)], atom('single', 'equals', true)),\n\t]\n\treturn logicalDefinition(GATE_ID, 'Brief readiness', [\n\t\t...readiness,\n\t\trule(\n\t\t\t'ready',\n\t\t\t[\n\t\t\t\tcompound(\n\t\t\t\t\t'and',\n\t\t\t\t\treadiness.map((entry) => atom(entry.id, 'equals', true)),\n\t\t\t\t),\n\t\t\t],\n\t\t\tatom('ready', 'equals', true),\n\t\t),\n\t])\n}\n\n/**\n * The readiness rules a brief fails, computed directly from its own measures.\n *\n * @remarks\n * The gate's decision, in code. `gateDefinition()` states the same six 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 two must agree. `tests/src/core/helpers.test.ts` drives both over one value set, which\n * is what stops the data and the code 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 { brief, findUnmetRules, outcome, proof, task } from '@orkestrel/brief'\n *\n * findUnmetRules(brief(task('plan', 'ops', 'Plan the release.'))) // ['aimed', 'proven']\n * findUnmetRules(\n * \tbrief(task('plan', 'ops', 'Plan the release.'), {\n * \t\toutcomes: [outcome(1, 'shipped')],\n * \t\tproofs: [proof('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 * Count 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 * 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 { brief, findBlockingGaps, gap, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('plan', 'ops', 'Plan the release.'), {\n * \tgaps: [gap('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 * 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 three 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 four\n * partitions are disjoint — `findManifestOverlaps` and the `disjoint` rule enforce it — so a\n * forbidden path is in none of the three grants and is reported here. An authority named in\n * NO partition at all is reported for the same reason, and that is the case a forbidden-only\n * check misses 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 { brief, findUngrantedAuthority, manifest, reference, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('debug', 'code', 'Fix the leak.'), {\n * \tauthority: [reference('AGENTS.md', 'project law')],\n * \tmanifest: manifest(),\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 * The paths appearing in more than one manifest partition.\n *\n * @remarks\n * Duplicates WITHIN one partition are not an overlap; the four 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 { brief, findManifestOverlaps, manifest, reference, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('debug', 'code', 'Fix the leak.'), {\n * \tmanifest: manifest({\n * \t\tedit: [reference('src/core/BriefCompiler.ts', 'the leaking pipeline')],\n * \t\tlocked: [reference('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 * 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 { brief, findUnpairedGaps, gap, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('plan', 'ops', 'Plan the release.'), {\n * \tgaps: [gap('rules', 'Keep the wording?'), gap('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 * Project 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 two vocabulary values.\n *\n * @example\n * ```ts\n * import { brief, briefToSubject, proof, task } from '@orkestrel/brief'\n *\n * briefToSubject(brief(task('test', 'code', 'Cover the gate.'), { proofs: [proof('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 * 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 { brief, proof, task, validateBrief } from '@orkestrel/brief'\n *\n * validateBrief(brief(task('plan', 'ops', 'Plan the release.'))) // valid: false — no proofs\n * validateBrief(\n * \tbrief(task('plan', 'ops', 'Plan the release.'), { proofs: [proof('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 * 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 { brief, briefToHash, pinBrief, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('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 * 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 { brief, briefToContent, pinBrief, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('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 * Freeze 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; a caller freezing their own value should know the limit.\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 * Freeze 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 * Render 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 * Three 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 * Narrow 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 once 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 * @param data - The candidate brief data.\n * @returns The same value, now known to satisfy {@link Brief}.\n * @throws {@link BriefError} `INVALID` when `data` fails `isBrief`.\n *\n * @example\n * ```ts\n * import { assertBrief, brief, proof, task } from '@orkestrel/brief'\n *\n * assertBrief(brief(task('plan', 'ops', 'Plan the release.'), { proofs: [proof('x', 'y')] }))\n * assertBrief({ task: { operation: 'plan', domain: 'ops', statement: 'x.' } }) // throws INVALID\n * ```\n */\nexport function assertBrief(data: unknown): Brief {\n\tif (!isBrief(data)) {\n\t\tthrow new BriefError('INVALID', 'Brief failed the exact-record contract', { field: 'brief' })\n\t}\n\treturn data\n}\n\n/**\n * Return 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 { brief, pinBrief, task } from '@orkestrel/brief'\n *\n * const pinned = pinBrief(brief(task('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 * 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 { brief, briefToTrace, task } from '@orkestrel/brief'\n *\n * briefToTrace(brief(task('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 * Render 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 { example, exampleToLines } from '@orkestrel/brief'\n *\n * exampleToLines(example('<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 * Project 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 source - The brief to render.\n * @returns The markdown prompt.\n *\n * @example\n * ```ts\n * import { brief, briefToMarkdown, task } from '@orkestrel/brief'\n *\n * briefToMarkdown(brief(task('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 * Project 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 source - The brief to render.\n * @param turns - The turn cap; defaults to `DEFAULT_BRIEF_TURNS`.\n * @returns The one-line completion condition.\n *\n * @example\n * ```ts\n * import { brief, briefToGoal, proof, task } from '@orkestrel/brief'\n *\n * briefToGoal(brief(task('test', 'code', 'Cover the gate.'), { proofs: [proof('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 * Project 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 * four permission sets rather than a fifth 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 source - The brief to project.\n * @returns The dispatch — the rendered prompt, the ranked authority, and the four path sets.\n *\n * @example\n * ```ts\n * import { brief, briefToDispatch, manifest, reference, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('migrate', 'code', 'Migrate the stores.'), {\n * \tauthority: [reference('AGENTS.md', 'project law')],\n * \tmanifest: manifest({ edit: [reference('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 * Derive 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 `''` 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('') // ''\n * ```\n */\nexport function deriveStatement(text: string): string {\n\tconst collapsed = collapseWhitespace(text)\n\tif (collapsed.length === 0) return ''\n\tconst capitalized = collapsed.charAt(0).toUpperCase() + collapsed.slice(1)\n\treturn /[.!?]$/u.test(capitalized) ? capitalized : `${capitalized}.`\n}\n\n/**\n * Derive 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.\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\tconst operation = Object.hasOwn(actions, intent.action) ? actions[intent.action] : undefined\n\tconst domain = Object.hasOwn(domains, intent.domain) ? domains[intent.domain] : undefined\n\tif (!isTaskOperation(operation) || !isTaskDomain(domain)) return undefined\n\tconst statement = deriveStatement(text)\n\treturn statement.length === 0 ? undefined : task(operation, domain, statement)\n}\n\n/**\n * Derive `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\tgiven(\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 * Derive `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 gap(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 { parseJSONAs } from '@orkestrel/contract'\nimport type { Brief } from './types.js'\nimport { isBrief } from './validators.js'\n\n/**\n * Parse 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 * @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 { Emitter } from '@orkestrel/emitter'\nimport type { ManagerAddOptions } from '@orkestrel/interpret'\nimport { snapshotBrief } from './cloners.js'\nimport { BriefError } from './errors.js'\nimport { briefToContent, briefToHash, briefToTrace } from './helpers.js'\nimport type {\n\tBrief,\n\tBriefManagerEventMap,\n\tBriefManagerInterface,\n\tBriefManagerOptions,\n\tBriefRecord,\n} from './types.js'\n\n/**\n * 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, brief, task } from '@orkestrel/brief'\n *\n * const briefs = new BriefManager()\n * const record = briefs.add(brief(task('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 size(): 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(source: Brief, options?: ManagerAddOptions): BriefRecord {\n\t\tthis.#refuseDestroyed()\n\t\tconst record = this.#stage(source, 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?: ManagerAddOptions,\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 once 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 { Emitter } from '@orkestrel/emitter'\nimport type { Interpretation, InterpretInterface } from '@orkestrel/interpret'\nimport { createInterpret, digestValue, isInterpretation } from '@orkestrel/interpret'\nimport { attempt } from '@orkestrel/contract'\nimport type { LogicalResult, ReasonInterface } from '@orkestrel/reason'\nimport { createLogicalReasoner, createReason, isLogicalResult } from '@orkestrel/reason'\nimport { snapshotBrief } from './cloners.js'\nimport { BriefError } from './errors.js'\nimport {\n\tbrief,\n\tbriefToSubject,\n\tderiveGaps,\n\tderiveGivens,\n\tderiveTask,\n\terrorToMessage,\n\tfindBlockingGaps,\n\tfindUnmetRules,\n\tfreezeDeep,\n\tgap,\n\tpinBrief,\n\tgateDefinition,\n\tmanifest,\n\toutput,\n} from './helpers.js'\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'\n\n/**\n * The compilation orchestrator — the four-stage `[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, proof, task } from '@orkestrel/brief'\n *\n * const compiler = new BriefCompiler()\n * const briefing = compiler.compile({\n * \ttask: task('audit', 'code', 'Audit the barrel for undocumented exports.'),\n * \toutcomes: [{ rank: 1, text: 'every export appears in the guide', required: true }],\n * \tproofs: [proof('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 stage below. 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(source: 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(source), gateDefinition())),\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 seal in\n\t// place. Sealing alone is enough against the stated threat — a pooled engine rewriting a\n\t// returned briefing — because the write throws in the engine instead of corrupting the\n\t// record. What is never acceptable is refusing the value.\n\t#own<TValue>(value: TValue): TValue {\n\t\tconst cloned = attempt(() => structuredClone(value))\n\t\treturn freezeDeep(cloned.success ? cloned.value : value)\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)))\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. The published contract is wider than the\n\t\t// copy mechanism, and the sealing law says seal the live value in place rather than\n\t\t// refuse it.\n\t\tconst live = raw.interpretation\n\t\tif (live !== undefined && isInterpretation(live)) return freezeDeep(live)\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\t// The same total guard `gate` applies. A borrowed engine can hand back a value that\n\t\t// satisfies the compiler and not the contract, and reading `.rules.filter` off one threw\n\t\t// out of `compile` — from the code whose whole job is containing a failure.\n\t\tif (!isLogicalResult(verdict)) return undefined\n\t\tconst refused = verdict.rules\n\t\t\t.filter((entry) => !entry.conclusion)\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\tgap(\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\tbrief(subject, {\n\t\t\t\tauthority: input.authority ?? [],\n\t\t\t\tmanifest: input.manifest ?? manifest(),\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 ?? output('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 { createContract } from '@orkestrel/contract'\nimport { BriefManager } from './BriefManager.js'\nimport { BriefCompiler } from './BriefCompiler.js'\nimport { briefShape } from './shapers.js'\nimport type {\n\tBrief,\n\tBriefManagerInterface,\n\tBriefManagerOptions,\n\tBriefCompilerInterface,\n\tBriefCompilerOptions,\n} from './types.js'\n\n/**\n * Create 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 two intent vocabularies, and 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 * Create 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.size // 0\n * briefs.destroy()\n * ```\n */\nexport function createBriefManager(options?: BriefManagerOptions): BriefManagerInterface {\n\treturn new BriefManager(options)\n}\n\n/**\n * Compile `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":";;;;;;;AAGA,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;;;;;;;;AAS/F,IAAa,sBAAsB;;AAGnC,IAAa,UAAU;;;;;;;;;;;AAYvB,IAAa,qBAAqB;;;;;;;;;AAUlC,IAAa,sBAAsB;;;;;;;;;;;;AAanC,IAAa,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;ACjE7B,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,SAAS,oBAAoB,CAAC;;AAGlF,IAAa,aAAA,GAAyB,oBAAA,YAAA,CAAY;CAAE,KAAK;CAAG,SAAS;AAAoB,CAAC;;AAG1F,IAAa,aAAA,GAAY,oBAAA,YAAA,CACxB;CACC,YAAA,GAAW,oBAAA,aAAA,CAAa,eAAe;CACvC,SAAA,GAAQ,oBAAA,aAAA,CAAa,YAAY;CACjC,WAAW;AACZ,GACA,EAAE,aAAa,uDAAuD,CACvE;;AAGA,IAAa,kBAAA,GAAiB,oBAAA,YAAA,CAC7B;CACC,MAAM;CACN,MAAM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AAQ,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;;;;;;;;;;;;;;;;;;;;;;;AClbA,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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","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 { OutputFormat, RiskSeverity, TaskDomain, TaskOperation } from './types.js'\n\n/** The twelve `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/** The eight `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/** The five `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/** The three `RiskSeverity` values, frozen. */\nexport const RISK_SEVERITIES: readonly RiskSeverity[] = Object.freeze(['low', 'medium', 'high'])\n\n/**\n * `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/** `'gate'` — the id of the `gateDefinition()` logical definition. */\nexport const GATE_ID = 'gate'\n\n/**\n * Every line terminator a brief field refuses.\n *\n * @remarks\n * The four ECMAScript line terminators, not just `\\n`: a renderer that splits on any of\n * them would let the other three forge a markdown row. CRLF leads the alternation so a\n * Windows exemplar splits as ONE break rather than two, which would insert a blank line the\n * caller 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 * 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 * 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 * 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 * Narrow a caught value to a {@link BriefError}.\n *\n * @param value - The caught value to inspect.\n * @returns `true` when `value` is a `BriefError`.\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/** A single-line string of any length, including empty. */\nexport const textShape: StringShape = stringShape({ pattern: SINGLE_LINE_PATTERN })\n\n/** A non-empty single-line string — the shape mirror of `isLine`. */\nexport const lineShape: StringShape = stringShape({ min: 1, pattern: SINGLE_LINE_PATTERN })\n\n/** 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/** 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/** The `Manifest` shape — four 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 four disjoint file partitions of a brief.' },\n)\n\n/** 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/** 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/** 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/** 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/** 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/** 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/** 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/** 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 * 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 {\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'\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'\n\n/**\n * `true` when 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 */\nexport const isText: Guard<string> = (value: unknown): value is string =>\n\tisString(value) && !LINE_BREAK_PATTERN.test(value)\n\n/** `true` when the value is a non-empty string holding no line terminator. */\nexport const isLine: Guard<string> = andOf(isNonEmptyString, isText)\n\n/** `true` when the value is one of the twelve `TaskOperation` literals. */\nexport const isTaskOperation: Guard<TaskOperation> = literalOf(TASK_OPERATIONS)\n\n/** `true` when the value is one of the eight `TaskDomain` literals. */\nexport const isTaskDomain: Guard<TaskDomain> = literalOf(TASK_DOMAINS)\n\n/** `true` when the value is one of the five `OutputFormat` literals. */\nexport const isOutputFormat: Guard<OutputFormat> = literalOf(OUTPUT_FORMATS)\n\n/** `true` when the value is one of the three `RiskSeverity` literals. */\nexport const isRiskSeverity: Guard<RiskSeverity> = literalOf(RISK_SEVERITIES)\n\n/** `true` when the value is a well-formed `Task` — both vocabularies closed, statement one line. */\nexport const isTask: Guard<Task> = recordOf({\n\toperation: isTaskOperation,\n\tdomain: isTaskDomain,\n\tstatement: isLine,\n})\n\n/** `true` when the value is a well-formed `Reference` — both members required, both single-line. */\nexport const isReference: Guard<Reference> = recordOf({\n\tpath: isLine,\n\tnote: isLine,\n})\n\n/**\n * `true` when the value is a well-formed `Manifest`.\n *\n * @remarks\n * Partition presence only — disjointness is `validateBrief`'s semantic pass.\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/** `true` when the value is a well-formed `Outcome` — `rank` a positive integer. */\nexport const isOutcome: Guard<Outcome> = recordOf({\n\trank: andOf(isInteger, boundsOf(1)),\n\ttext: isLine,\n\trequired: isBoolean,\n})\n\n/** `true` when the value is a well-formed `Given` — `value` may be empty but stays one line. */\nexport const isGiven: Guard<Given> = recordOf({\n\tcategory: isLine,\n\tname: isLine,\n\tvalue: isText,\n})\n\n/**\n * `true` when 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 */\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/** `true` when the value is a well-formed `Citation` — all three members single-line. */\nexport const isCitation: Guard<Citation> = recordOf({\n\tname: isLine,\n\turl: isLine,\n\tnote: isLine,\n})\n\n/** `true` when the value is a well-formed `Gap`. */\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/** `true` when the value is a well-formed `Risk` — `severity` on the closed vocabulary. */\nexport const isRisk: Guard<Risk> = recordOf({\n\tseverity: isRiskSeverity,\n\ttext: isLine,\n\tmitigation: isLine,\n})\n\n/** `true` when the value is a well-formed `Output` — `format` on the closed vocabulary. */\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/** `true` when the value is a well-formed `Proof`. */\nexport const isProof: Guard<Proof> = recordOf({\n\ttext: isLine,\n\tcommand: isLine,\n})\n\n/**\n * `true` when 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 */\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 { attempt, cloneJSONRecord } from '@orkestrel/contract'\nimport { BriefError } from './errors.js'\nimport type { Brief } from './types.js'\nimport { isBrief } from './validators.js'\n\n/**\n * Return 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 { brief, outcome, snapshotBrief, task } from '@orkestrel/brief'\n *\n * const outcomes = [outcome(1, 'shipped')]\n * const owned = snapshotBrief(brief(task('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 { attempt } from '@orkestrel/contract'\nimport type { Ambiguity, Entity, Intent } from '@orkestrel/interpret'\nimport { canonicalize, collapseWhitespace, digestValue } from '@orkestrel/interpret'\nimport type { LogicalDefinition, ReasonValidationResult, Rule, Subject } from '@orkestrel/reason'\nimport { atom, compound, formatField, logicalDefinition, rule } 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 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 { isBrief, isTaskDomain, isTaskOperation } from './validators.js'\n\n/**\n * Build a `Task`.\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 { task } from '@orkestrel/brief'\n *\n * task('refactor', 'code', 'Refactor useForm to native browser form APIs.')\n * ```\n */\nexport function task(operation: TaskOperation, domain: TaskDomain, statement: string): Task {\n\treturn { operation, domain, statement }\n}\n\n/**\n * Build a `Reference`.\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 { reference } from '@orkestrel/brief'\n *\n * reference('AGENTS.md', 'project law') // { path: 'AGENTS.md', note: 'project law' }\n * ```\n */\nexport function reference(path: string, note: string): Reference {\n\treturn { path, note }\n}\n\n/**\n * Build 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 all four partitions present.\n *\n * @example\n * ```ts\n * import { manifest, reference } from '@orkestrel/brief'\n *\n * manifest({ edit: [reference('src/core/helpers.ts', 'implementation')] })\n * ```\n */\nexport function manifest(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 * Build an `Outcome`.\n *\n * @param rank - The one-based rank; lower ranks matter more.\n * @param text - The result, never a step.\n * @param required - Whether the outcome gates \"done\"; defaults to `true`.\n * @returns A fresh `Outcome`.\n *\n * @example\n * ```ts\n * import { outcome } from '@orkestrel/brief'\n *\n * outcome(1, 'useForm uses native FormData with no behavior change') // required: true\n * outcome(2, 'the diff stays under 200 lines', false)\n * ```\n */\nexport function outcome(rank: number, text: string, required = true): Outcome {\n\treturn { rank, text, required }\n}\n\n/**\n * Build a `Given`.\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 { given } from '@orkestrel/brief'\n *\n * given('convention', 'indentation', 'tabs')\n * ```\n */\nexport function given(category: string, name: string, value: string): Given {\n\treturn { category, name, value }\n}\n\n/**\n * Build an `Example`.\n *\n * @param input - The exemplar input.\n * @param result - 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 { example } from '@orkestrel/brief'\n *\n * example('<input required>', 'validity read from el.validity')\n * ```\n */\nexport function example(input: string, result: string, note?: string): Example {\n\treturn note === undefined ? { input, output: result } : { input, output: result, note }\n}\n\n/**\n * Build a `Citation`.\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 { citation } from '@orkestrel/brief'\n *\n * citation(\n * \t'MDN Constraint Validation',\n * \t'https://developer.mozilla.org/',\n * \t'the native validity behavior being adopted',\n * )\n * ```\n */\nexport function citation(name: string, url: string, note: string): Citation {\n\treturn { name, url, note }\n}\n\n/**\n * Build a `Gap`.\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` (defaults `false`) and `candidates`; an absent\n * `candidates` key is OMITTED entirely.\n * @returns A fresh `Gap`.\n *\n * @example\n * ```ts\n * import { gap } from '@orkestrel/brief'\n *\n * gap('rules', 'Should validation message wording change?') // blocking: false\n * gap('output', 'Diff or full files?', { blocking: true, candidates: ['diff', 'code'] })\n * ```\n */\nexport function gap(\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 * Build a `Risk`.\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 { risk } from '@orkestrel/brief'\n *\n * risk('medium', 'native validation differs subtly', 'assert message and state in tests')\n * ```\n */\nexport function risk(severity: RiskSeverity, text: string, mitigation: string): Risk {\n\treturn { severity, text, mitigation }\n}\n\n/**\n * Build an `Output`.\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 { output } from '@orkestrel/brief'\n *\n * output('markdown') // { format: 'markdown' }\n * output('diff', { include: ['updated useForm.ts'] })\n * ```\n */\nexport function output(format: OutputFormat, overrides?: Partial<Omit<Output, 'format'>>): 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 * Build a `Proof`.\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 { proof } from '@orkestrel/brief'\n *\n * proof('type-check and lint pass', 'npm run check')\n * ```\n */\nexport function proof(text: string, command: string): Proof {\n\treturn { text, command }\n}\n\n/**\n * Build 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; every absent collection defaults to `[]`,\n * `output` defaults to `output('markdown')`, and `trace` / `hash` stay OMITTED so\n * `pinBrief` can fill them.\n * @returns A fresh, unpinned `Brief`.\n *\n * @example\n * ```ts\n * import { brief, outcome, proof, task } from '@orkestrel/brief'\n *\n * brief(task('audit', 'code', 'Audit the barrel for undocumented exports.'), {\n * \toutcomes: [outcome(1, 'every export appears in the guide')],\n * \tproofs: [proof('parity passes', 'npm run test:guides')],\n * })\n * ```\n */\nexport function brief(\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 ?? manifest(),\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 ?? output('markdown'),\n\t\tproofs: overrides?.proofs ?? [],\n\t}\n}\n\n/**\n * Build the fail-closed readiness gate as a reasons `LogicalDefinition`.\n *\n * @remarks\n * Six readiness rules each derive one named fact from `briefToSubject`'s measures, and a\n * final `ready` rule conjoins all six. Forward chaining reports the LAST rule's\n * conclusion, so `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, gateDefinition } from '@orkestrel/brief'\n * import { createLogicalReasoner, createReason } from '@orkestrel/reason'\n *\n * const reason = createReason({ reasoners: [createLogicalReasoner()] })\n * const verdict = reason.reason(briefToSubject(pinned), gateDefinition())\n * reason.destroy()\n * ```\n */\nexport function gateDefinition(): LogicalDefinition {\n\tconst readiness: readonly Rule[] = [\n\t\trule('specified', [atom('blocking', 'equals', 0)], atom('specified', 'equals', true)),\n\t\trule(\n\t\t\t'aimed',\n\t\t\t[compound('and', [atom('outcomes', 'above', 0), atom('required', 'above', 0)])],\n\t\t\tatom('aimed', 'equals', true),\n\t\t),\n\t\trule('proven', [atom('proofs', 'above', 0)], atom('proven', 'equals', true)),\n\t\trule('disjoint', [atom('overlaps', 'equals', 0)], atom('disjoint', 'equals', true)),\n\t\trule('granted', [atom('ungranted', 'equals', 0)], atom('granted', 'equals', true)),\n\t\trule('single', [atom('sentences', 'equals', 1)], atom('single', 'equals', true)),\n\t]\n\treturn logicalDefinition(GATE_ID, 'Brief readiness', [\n\t\t...readiness,\n\t\trule(\n\t\t\t'ready',\n\t\t\t[\n\t\t\t\tcompound(\n\t\t\t\t\t'and',\n\t\t\t\t\treadiness.map((entry) => atom(entry.id, 'equals', true)),\n\t\t\t\t),\n\t\t\t],\n\t\t\tatom('ready', 'equals', true),\n\t\t),\n\t])\n}\n\n/**\n * The readiness rules a brief fails, computed directly from its own measures.\n *\n * @remarks\n * The gate's decision, in code. `gateDefinition()` states the same six 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 two must agree. `tests/src/core/helpers.test.ts` drives both over one value set, which\n * is what stops the data and the code 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 { brief, findUnmetRules, outcome, proof, task } from '@orkestrel/brief'\n *\n * findUnmetRules(brief(task('plan', 'ops', 'Plan the release.'))) // ['aimed', 'proven']\n * findUnmetRules(\n * \tbrief(task('plan', 'ops', 'Plan the release.'), {\n * \t\toutcomes: [outcome(1, 'shipped')],\n * \t\tproofs: [proof('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 * Count 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 * 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 { brief, findBlockingGaps, gap, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('plan', 'ops', 'Plan the release.'), {\n * \tgaps: [gap('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 * 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 three 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 four\n * partitions are disjoint — `findManifestOverlaps` and the `disjoint` rule enforce it — so a\n * forbidden path is in none of the three grants and is reported here. An authority named in\n * NO partition at all is reported for the same reason, and that is the case a forbidden-only\n * check misses 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 { brief, findUngrantedAuthority, manifest, reference, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('debug', 'code', 'Fix the leak.'), {\n * \tauthority: [reference('AGENTS.md', 'project law')],\n * \tmanifest: manifest(),\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 * The paths appearing in more than one manifest partition.\n *\n * @remarks\n * Duplicates WITHIN one partition are not an overlap; the four 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 { brief, findManifestOverlaps, manifest, reference, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('debug', 'code', 'Fix the leak.'), {\n * \tmanifest: manifest({\n * \t\tedit: [reference('src/core/BriefCompiler.ts', 'the leaking pipeline')],\n * \t\tlocked: [reference('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 * 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 { brief, findUnpairedGaps, gap, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('plan', 'ops', 'Plan the release.'), {\n * \tgaps: [gap('rules', 'Keep the wording?'), gap('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 * Project 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 two vocabulary values.\n *\n * @example\n * ```ts\n * import { brief, briefToSubject, proof, task } from '@orkestrel/brief'\n *\n * briefToSubject(brief(task('test', 'code', 'Cover the gate.'), { proofs: [proof('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 * 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 { brief, proof, task, validateBrief } from '@orkestrel/brief'\n *\n * validateBrief(brief(task('plan', 'ops', 'Plan the release.'))) // valid: false — no proofs\n * validateBrief(\n * \tbrief(task('plan', 'ops', 'Plan the release.'), { proofs: [proof('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 * 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 { brief, briefToHash, pinBrief, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('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 * 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 { brief, briefToContent, pinBrief, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('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 * Freeze 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; a caller freezing their own value should know the limit.\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 * Freeze 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 * Render 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 * Three 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 * Narrow 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 once 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 * @param data - The candidate brief data.\n * @returns The same value, now known to satisfy {@link Brief}.\n * @throws {@link BriefError} `INVALID` when `data` fails `isBrief`.\n *\n * @example\n * ```ts\n * import { assertBrief, brief, proof, task } from '@orkestrel/brief'\n *\n * assertBrief(brief(task('plan', 'ops', 'Plan the release.'), { proofs: [proof('x', 'y')] }))\n * assertBrief({ task: { operation: 'plan', domain: 'ops', statement: 'x.' } }) // throws INVALID\n * ```\n */\nexport function assertBrief(data: unknown): Brief {\n\tif (!isBrief(data)) {\n\t\tthrow new BriefError('INVALID', 'Brief failed the exact-record contract', { field: 'brief' })\n\t}\n\treturn data\n}\n\n/**\n * Return 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 { brief, pinBrief, task } from '@orkestrel/brief'\n *\n * const pinned = pinBrief(brief(task('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 * 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 { brief, briefToTrace, task } from '@orkestrel/brief'\n *\n * briefToTrace(brief(task('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 * Render 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 { example, exampleToLines } from '@orkestrel/brief'\n *\n * exampleToLines(example('<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 * Project 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 source - The brief to render.\n * @returns The markdown prompt.\n *\n * @example\n * ```ts\n * import { brief, briefToMarkdown, task } from '@orkestrel/brief'\n *\n * briefToMarkdown(brief(task('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 * Project 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 source - The brief to render.\n * @param turns - The turn cap; defaults to `DEFAULT_BRIEF_TURNS`.\n * @returns The one-line completion condition.\n *\n * @example\n * ```ts\n * import { brief, briefToGoal, proof, task } from '@orkestrel/brief'\n *\n * briefToGoal(brief(task('test', 'code', 'Cover the gate.'), { proofs: [proof('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 * Project 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 * four permission sets rather than a fifth 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 source - The brief to project.\n * @returns The dispatch — the rendered prompt, the ranked authority, and the four path sets.\n *\n * @example\n * ```ts\n * import { brief, briefToDispatch, manifest, reference, task } from '@orkestrel/brief'\n *\n * const draft = brief(task('migrate', 'code', 'Migrate the stores.'), {\n * \tauthority: [reference('AGENTS.md', 'project law')],\n * \tmanifest: manifest({ edit: [reference('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 * Derive 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 `''` 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('') // ''\n * ```\n */\nexport function deriveStatement(text: string): string {\n\tconst collapsed = collapseWhitespace(text)\n\tif (collapsed.length === 0) return ''\n\tconst capitalized = collapsed.charAt(0).toUpperCase() + collapsed.slice(1)\n\treturn /[.!?]$/u.test(capitalized) ? capitalized : `${capitalized}.`\n}\n\n/**\n * Derive 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.\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\tconst operation = Object.hasOwn(actions, intent.action) ? actions[intent.action] : undefined\n\tconst domain = Object.hasOwn(domains, intent.domain) ? domains[intent.domain] : undefined\n\tif (!isTaskOperation(operation) || !isTaskDomain(domain)) return undefined\n\tconst statement = deriveStatement(text)\n\treturn statement.length === 0 ? undefined : task(operation, domain, statement)\n}\n\n/**\n * Derive `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\tgiven(\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 * Derive `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 gap(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 { parseJSONAs } from '@orkestrel/contract'\nimport type { Brief } from './types.js'\nimport { isBrief } from './validators.js'\n\n/**\n * Parse 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 * @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 { Emitter } from '@orkestrel/emitter'\nimport type { ManagerAddOptions } from '@orkestrel/interpret'\nimport { snapshotBrief } from './cloners.js'\nimport { BriefError } from './errors.js'\nimport { briefToContent, briefToHash, briefToTrace } from './helpers.js'\nimport type {\n\tBrief,\n\tBriefManagerEventMap,\n\tBriefManagerInterface,\n\tBriefManagerOptions,\n\tBriefRecord,\n} from './types.js'\n\n/**\n * 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, brief, task } from '@orkestrel/brief'\n *\n * const briefs = new BriefManager()\n * const record = briefs.add(brief(task('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 size(): 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(source: Brief, options?: ManagerAddOptions): BriefRecord {\n\t\tthis.#refuseDestroyed()\n\t\tconst record = this.#stage(source, 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?: ManagerAddOptions,\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 once 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 { Emitter } from '@orkestrel/emitter'\nimport type { Interpretation, InterpretInterface } from '@orkestrel/interpret'\nimport { createInterpret, digestValue, isInterpretation } from '@orkestrel/interpret'\nimport { attempt } from '@orkestrel/contract'\nimport type { LogicalResult, ReasonInterface } from '@orkestrel/reason'\nimport { createLogicalReasoner, createReason, isLogicalResult } from '@orkestrel/reason'\nimport { snapshotBrief } from './cloners.js'\nimport { BriefError } from './errors.js'\nimport {\n\tbrief,\n\tbriefToSubject,\n\tderiveGaps,\n\tderiveGivens,\n\tderiveTask,\n\terrorToMessage,\n\tfindBlockingGaps,\n\tfindUnmetRules,\n\tfreezeDeep,\n\tgap,\n\tpinBrief,\n\tgateDefinition,\n\tmanifest,\n\toutput,\n} from './helpers.js'\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'\n\n/**\n * The compilation orchestrator — the four-stage `[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, proof, task } from '@orkestrel/brief'\n *\n * const compiler = new BriefCompiler()\n * const briefing = compiler.compile({\n * \ttask: task('audit', 'code', 'Audit the barrel for undocumented exports.'),\n * \toutcomes: [{ rank: 1, text: 'every export appears in the guide', required: true }],\n * \tproofs: [proof('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 stage below. 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(source: 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(source), gateDefinition())),\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 seal in\n\t// place. Sealing alone is enough against the stated threat — a pooled engine rewriting a\n\t// returned briefing — because the write throws in the engine instead of corrupting the\n\t// record. What is never acceptable is refusing the value.\n\t#own<TValue>(value: TValue): TValue {\n\t\tconst cloned = attempt(() => structuredClone(value))\n\t\treturn freezeDeep(cloned.success ? cloned.value : value)\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)))\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. The published contract is wider than the\n\t\t// copy mechanism, and the sealing law says seal the live value in place rather than\n\t\t// refuse it.\n\t\tconst live = raw.interpretation\n\t\tif (live !== undefined && isInterpretation(live)) return freezeDeep(live)\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\t// The same total guard `gate` applies. A borrowed engine can hand back a value that\n\t\t// satisfies the compiler and not the contract, and reading `.rules.filter` off one threw\n\t\t// out of `compile` — from the code whose whole job is containing a failure.\n\t\tif (!isLogicalResult(verdict)) return undefined\n\t\tconst refused = verdict.rules\n\t\t\t.filter((entry) => !entry.conclusion)\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\tgap(\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\tbrief(subject, {\n\t\t\t\tauthority: input.authority ?? [],\n\t\t\t\tmanifest: input.manifest ?? manifest(),\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 ?? output('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 { createContract } from '@orkestrel/contract'\nimport { BriefManager } from './BriefManager.js'\nimport { BriefCompiler } from './BriefCompiler.js'\nimport { briefShape } from './shapers.js'\nimport type {\n\tBrief,\n\tBriefManagerInterface,\n\tBriefManagerOptions,\n\tBriefCompilerInterface,\n\tBriefCompilerOptions,\n} from './types.js'\n\n/**\n * Create 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 two intent vocabularies, and 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 * Create 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.size // 0\n * briefs.destroy()\n * ```\n */\nexport function createBriefManager(options?: BriefManagerOptions): BriefManagerInterface {\n\treturn new BriefManager(options)\n}\n\n/**\n * Compile `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":";;;;;;AAGA,IAAa,kBAA4C,OAAO,OAAO;CACtE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CA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