cohorte 2.10.1 → 3.0.0-dev.0

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.
Files changed (211) hide show
  1. package/README.md +7 -0
  2. package/assets/manifest.json +193 -0
  3. package/assets/migrations/config/README.md +12 -0
  4. package/assets/migrations/state/0001_init.sql +154 -0
  5. package/assets/prompts/README.md +11 -0
  6. package/assets/prompts/agents/fixer.md +7 -0
  7. package/assets/prompts/agents/implementer.md +12 -0
  8. package/assets/prompts/agents/reviewer.md +8 -0
  9. package/assets/prompts/agents/security-reviewer.md +7 -0
  10. package/assets/prompts/phases/build.md +5 -0
  11. package/assets/prompts/phases/review.md +5 -0
  12. package/assets/prompts/phases/test.md +5 -0
  13. package/assets/prompts/system.md +11 -0
  14. package/assets/schemas/agent-output.schema.json +225 -0
  15. package/assets/schemas/auth-status.schema.json +87 -0
  16. package/assets/schemas/command-result.schema.json +192 -0
  17. package/assets/schemas/commands.schema.json +952 -0
  18. package/assets/schemas/config.schema.json +2259 -0
  19. package/assets/schemas/doctor-report.schema.json +104 -0
  20. package/assets/schemas/events.schema.json +8514 -0
  21. package/assets/schemas/fake-script.schema.json +549 -0
  22. package/assets/schemas/inspect.schema.json +3133 -0
  23. package/assets/schemas/manifest.schema.json +79 -0
  24. package/assets/schemas/ownership.schema.json +52 -0
  25. package/assets/schemas/policy-verdict.schema.json +282 -0
  26. package/assets/schemas/project-model.schema.json +783 -0
  27. package/assets/schemas/project-status.schema.json +217 -0
  28. package/assets/schemas/reconcile-plan.schema.json +155 -0
  29. package/assets/schemas/run-diff.schema.json +177 -0
  30. package/assets/schemas/run-snapshot-manifest.schema.json +2104 -0
  31. package/assets/schemas/run-state.schema.json +1755 -0
  32. package/assets/schemas/runtime-capabilities.schema.json +1545 -0
  33. package/assets/schemas/sandbox-capabilities.schema.json +116 -0
  34. package/assets/schemas/skill.schema.json +87 -0
  35. package/assets/schemas/spec.schema.json +202 -0
  36. package/assets/schemas/tool-catalogue.schema.json +655 -0
  37. package/assets/schemas/trust-record.schema.json +38 -0
  38. package/assets/skills/README.md +9 -0
  39. package/assets/skills/inspect-surface.md +4 -0
  40. package/dist/agent-host.mjs +50 -0
  41. package/dist/agent-host.mjs.map +1 -0
  42. package/dist/bundle-manifest.json +102 -0
  43. package/dist/chunks/__host-DgGPyco9.mjs +18 -0
  44. package/dist/chunks/__host-DgGPyco9.mjs.map +1 -0
  45. package/dist/chunks/approve-Cv135UqI.mjs +19 -0
  46. package/dist/chunks/approve-Cv135UqI.mjs.map +1 -0
  47. package/dist/chunks/auth-BT5oVp76.mjs +132 -0
  48. package/dist/chunks/auth-BT5oVp76.mjs.map +1 -0
  49. package/dist/chunks/auth-D8rCVY33.mjs +84 -0
  50. package/dist/chunks/auth-D8rCVY33.mjs.map +1 -0
  51. package/dist/chunks/brainstorm-CU10T1tm.mjs +7 -0
  52. package/dist/chunks/brainstorm-CU10T1tm.mjs.map +1 -0
  53. package/dist/chunks/cancel-KV_cpsqS.mjs +15 -0
  54. package/dist/chunks/cancel-KV_cpsqS.mjs.map +1 -0
  55. package/dist/chunks/canonical-C8UxeEmB.mjs +57 -0
  56. package/dist/chunks/canonical-C8UxeEmB.mjs.map +1 -0
  57. package/dist/chunks/catalogue-BvwSrM_j.mjs +1549 -0
  58. package/dist/chunks/catalogue-BvwSrM_j.mjs.map +1 -0
  59. package/dist/chunks/compose-Cr0hP0qm.mjs +7303 -0
  60. package/dist/chunks/compose-Cr0hP0qm.mjs.map +1 -0
  61. package/dist/chunks/config-DefHA2Lw.mjs +96 -0
  62. package/dist/chunks/config-DefHA2Lw.mjs.map +1 -0
  63. package/dist/chunks/contract-B0ra2-bm.mjs +295 -0
  64. package/dist/chunks/contract-B0ra2-bm.mjs.map +1 -0
  65. package/dist/chunks/contract-vYbwYr0Y.mjs +123 -0
  66. package/dist/chunks/contract-vYbwYr0Y.mjs.map +1 -0
  67. package/dist/chunks/deny-ClTxSvHJ.mjs +15 -0
  68. package/dist/chunks/deny-ClTxSvHJ.mjs.map +1 -0
  69. package/dist/chunks/diff-Qw0II0sj.mjs +101 -0
  70. package/dist/chunks/diff-Qw0II0sj.mjs.map +1 -0
  71. package/dist/chunks/discover-30Ciya_0.mjs +20 -0
  72. package/dist/chunks/discover-30Ciya_0.mjs.map +1 -0
  73. package/dist/chunks/doctor-DfCrKpfT.mjs +222 -0
  74. package/dist/chunks/doctor-DfCrKpfT.mjs.map +1 -0
  75. package/dist/chunks/fix-D4Tj8RVA.mjs +18 -0
  76. package/dist/chunks/fix-D4Tj8RVA.mjs.map +1 -0
  77. package/dist/chunks/gc-BBXlBF5w.mjs +161 -0
  78. package/dist/chunks/gc-BBXlBF5w.mjs.map +1 -0
  79. package/dist/chunks/init-Okz4mlhW.mjs +30 -0
  80. package/dist/chunks/init-Okz4mlhW.mjs.map +1 -0
  81. package/dist/chunks/inspect-Buby4cQD.mjs +22 -0
  82. package/dist/chunks/inspect-Buby4cQD.mjs.map +1 -0
  83. package/dist/chunks/logs-Giq5sUau.mjs +25 -0
  84. package/dist/chunks/logs-Giq5sUau.mjs.map +1 -0
  85. package/dist/chunks/migrate-DRoFUg53.mjs +19 -0
  86. package/dist/chunks/migrate-DRoFUg53.mjs.map +1 -0
  87. package/dist/chunks/models-Btp6X2YZ.mjs +24 -0
  88. package/dist/chunks/models-Btp6X2YZ.mjs.map +1 -0
  89. package/dist/chunks/pause-BASBfKLO.mjs +16 -0
  90. package/dist/chunks/pause-BASBfKLO.mjs.map +1 -0
  91. package/dist/chunks/policy-DUIgzF3W.mjs +139 -0
  92. package/dist/chunks/policy-DUIgzF3W.mjs.map +1 -0
  93. package/dist/chunks/providers-Dx78imKj.mjs +19 -0
  94. package/dist/chunks/providers-Dx78imKj.mjs.map +1 -0
  95. package/dist/chunks/reconcile-BfD785gd.mjs +26 -0
  96. package/dist/chunks/reconcile-BfD785gd.mjs.map +1 -0
  97. package/dist/chunks/render-DyZr5Lgi.mjs +53 -0
  98. package/dist/chunks/render-DyZr5Lgi.mjs.map +1 -0
  99. package/dist/chunks/resume-GJQRb2Eb.mjs +15 -0
  100. package/dist/chunks/resume-GJQRb2Eb.mjs.map +1 -0
  101. package/dist/chunks/retry-CLrUem1H.mjs +15 -0
  102. package/dist/chunks/retry-CLrUem1H.mjs.map +1 -0
  103. package/dist/chunks/review-BDdjb6kB.mjs +17 -0
  104. package/dist/chunks/review-BDdjb6kB.mjs.map +1 -0
  105. package/dist/chunks/run-CgTWYlcd.mjs +82 -0
  106. package/dist/chunks/run-CgTWYlcd.mjs.map +1 -0
  107. package/dist/chunks/run-tool-C3rAv4XF.mjs +26 -0
  108. package/dist/chunks/run-tool-C3rAv4XF.mjs.map +1 -0
  109. package/dist/chunks/schema-C9QbUW4H.mjs +578 -0
  110. package/dist/chunks/schema-C9QbUW4H.mjs.map +1 -0
  111. package/dist/chunks/send-BdnJ85Nz.mjs +19 -0
  112. package/dist/chunks/send-BdnJ85Nz.mjs.map +1 -0
  113. package/dist/chunks/ship-DTuLGoaJ.mjs +19 -0
  114. package/dist/chunks/ship-DTuLGoaJ.mjs.map +1 -0
  115. package/dist/chunks/shutdown-BM92Iyv2.mjs +15 -0
  116. package/dist/chunks/shutdown-BM92Iyv2.mjs.map +1 -0
  117. package/dist/chunks/skip-DZG5kpcH.mjs +18 -0
  118. package/dist/chunks/skip-DZG5kpcH.mjs.map +1 -0
  119. package/dist/chunks/spec-Bq0P3jVh.mjs +20 -0
  120. package/dist/chunks/spec-Bq0P3jVh.mjs.map +1 -0
  121. package/dist/chunks/src-CId6kMsY.mjs +1689 -0
  122. package/dist/chunks/src-CId6kMsY.mjs.map +1 -0
  123. package/dist/chunks/src-CfAOde7C.mjs +5403 -0
  124. package/dist/chunks/src-CfAOde7C.mjs.map +1 -0
  125. package/dist/chunks/src-Cu3TxNob.mjs +783 -0
  126. package/dist/chunks/src-Cu3TxNob.mjs.map +1 -0
  127. package/dist/chunks/src-DcU4IXMe.mjs +117 -0
  128. package/dist/chunks/src-DcU4IXMe.mjs.map +1 -0
  129. package/dist/chunks/src-JxawBQBn.mjs +446 -0
  130. package/dist/chunks/src-JxawBQBn.mjs.map +1 -0
  131. package/dist/chunks/src-s7YRvk0t.mjs +2116 -0
  132. package/dist/chunks/src-s7YRvk0t.mjs.map +1 -0
  133. package/dist/chunks/status-SMjiOMYy.mjs +29 -0
  134. package/dist/chunks/status-SMjiOMYy.mjs.map +1 -0
  135. package/dist/chunks/tail-BuhT-2PH.mjs +25 -0
  136. package/dist/chunks/tail-BuhT-2PH.mjs.map +1 -0
  137. package/dist/chunks/update-BXIppsbi.mjs +16 -0
  138. package/dist/chunks/update-BXIppsbi.mjs.map +1 -0
  139. package/dist/cli.mjs +175 -0
  140. package/dist/cli.mjs.map +1 -0
  141. package/package.json +17 -32
  142. package/CHANGELOG.md +0 -1461
  143. package/bin/cli.js +0 -817
  144. package/bin/report.js +0 -141
  145. package/core/adapter/render.js +0 -415
  146. package/core/agents/implementer.template.md +0 -142
  147. package/core/agents/profile-reader.md +0 -50
  148. package/core/agents/release.md +0 -58
  149. package/core/agents/review.md +0 -179
  150. package/core/commands/cohorte-align-ds.md +0 -33
  151. package/core/commands/cohorte-audit.md +0 -58
  152. package/core/commands/cohorte-brainstorm.md +0 -70
  153. package/core/commands/cohorte-build.md +0 -219
  154. package/core/commands/cohorte-doctor.md +0 -194
  155. package/core/commands/cohorte-fix.md +0 -80
  156. package/core/commands/cohorte-fleet.md +0 -103
  157. package/core/commands/cohorte-init-pipeline.md +0 -31
  158. package/core/commands/cohorte-intake.md +0 -92
  159. package/core/commands/cohorte-patch.md +0 -118
  160. package/core/commands/cohorte-refactor.md +0 -59
  161. package/core/commands/cohorte-retro.md +0 -85
  162. package/core/commands/cohorte-review.md +0 -270
  163. package/core/commands/cohorte-ship.md +0 -122
  164. package/core/commands/cohorte-spec.md +0 -101
  165. package/core/commands/cohorte-update-pipeline.md +0 -165
  166. package/core/hooks/gate.py +0 -588
  167. package/core/runtimes/claude.json +0 -74
  168. package/core/runtimes/codex.json +0 -85
  169. package/core/runtimes/cursor.json +0 -76
  170. package/core/runtimes/gemini.json +0 -76
  171. package/core/runtimes/opencode.json +0 -73
  172. package/core/templates/agent-handoff.md +0 -34
  173. package/core/templates/brainstorm-return.md +0 -36
  174. package/core/templates/decisions.template.md +0 -42
  175. package/core/templates/design-brief.md +0 -44
  176. package/core/templates/patch.template.md +0 -86
  177. package/core/templates/pr-body.md +0 -25
  178. package/core/templates/review-feedback.md +0 -38
  179. package/core/templates/spec.template.md +0 -87
  180. package/core/templates/steps/init-pipeline/01-detect-stack.md +0 -44
  181. package/core/templates/steps/init-pipeline/02-interview-gaps.md +0 -55
  182. package/core/templates/steps/init-pipeline/03-draft-profile.md +0 -10
  183. package/core/templates/steps/init-pipeline/04-write-render.md +0 -145
  184. package/core/templates/steps/init-pipeline/05-report.md +0 -12
  185. package/core/workflows/audit.js +0 -240
  186. package/core/workflows/loop.js +0 -641
  187. package/core/workflows/refactor.js +0 -276
  188. package/core/workflows/review.js +0 -456
  189. package/install.ps1 +0 -103
  190. package/install.sh +0 -114
  191. package/lib/doctor.js +0 -534
  192. package/lib/runtime.js +0 -139
  193. package/lib/versions.js +0 -149
  194. package/lib/yaml.js +0 -129
  195. package/profile/PIPELINE.template.md +0 -259
  196. package/profile/SCHEMA.md +0 -735
  197. package/profile/cohorte.config.template.yaml +0 -43
  198. package/scripts/assert-gate-hook.mjs +0 -75
  199. package/scripts/kanban-move.sh +0 -313
  200. package/scripts/metrics/collect.mjs +0 -531
  201. package/scripts/metrics/prices.json +0 -42
  202. package/scripts/new-feature.sh.template +0 -98
  203. package/scripts/preflight.sh +0 -124
  204. package/scripts/remove-feature.sh.template +0 -56
  205. package/scripts/test-adapter.mjs +0 -437
  206. package/scripts/test-gate.mjs +0 -443
  207. package/scripts/test-kanban.mjs +0 -304
  208. package/scripts/test-lib.mjs +0 -356
  209. package/scripts/test-metrics.mjs +0 -156
  210. package/scripts/test-workflows.mjs +0 -758
  211. package/scripts/validate-core.mjs +0 -325
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-s7YRvk0t.mjs","names":["count","count","count","count","count","count","count","count","count","count"],"sources":["../../../../packages/protocol/src/open-enum.ts","../../../../packages/protocol/src/vocabulary.ts","../../../../packages/protocol/src/agent-output.ts","../../../../packages/protocol/src/refs.ts","../../../../packages/protocol/src/envelope.ts","../../../../packages/protocol/src/compile.ts","../../../../packages/protocol/src/events/declare.ts","../../../../packages/protocol/src/events/agent.ts","../../../../packages/protocol/src/events/git.ts","../../../../packages/protocol/src/commands.ts","../../../../packages/protocol/src/events/governance.ts","../../../../packages/protocol/src/events/run.ts","../../../../packages/protocol/src/documents.ts","../../../../packages/protocol/src/events/stream.ts","../../../../packages/protocol/src/events/tool.ts","../../../../packages/protocol/src/catalogue.ts"],"sourcesContent":["import { type TUnsafe, Type } from 'typebox';\n\n/** The keyword a PUBLISHED schema carries instead of `enum`: the values this version knows, as documentation. */\nexport const OPEN_ENUM_KEYWORD = 'x-cohorte-known';\n\n/** The known values stay visible to completion and to exhaustive switches; any other string is still assignable. */\nexport type OpenEnumOf<K extends string> = K | (string & Record<never, never>);\n\nexport interface EnumOptions {\n description?: string;\n}\n\nconst checked = (values: readonly string[], what: string): string[] => {\n if (values.length === 0) throw new RangeError(`${what}: at least one value is required`);\n if (new Set(values).size !== values.length)\n throw new RangeError(`${what}: duplicate value in [${values.join(', ')}]`);\n return [...values];\n};\n\n/**\n * OPEN enums (values may be added in a minor): strict compile -> enum [...known];\n * published schema -> { type: 'string', 'x-cohorte-known': [...] } (compile.ts does the rewrite).\n * The authored form carries BOTH keywords: `enum` is what the writer-side validator enforces, the marker is what\n * tells the generator that this enum, unlike a closed one, must lose its `enum` when published.\n */\nexport function OpenEnum<const V extends readonly string[]>(\n known: V,\n opts: EnumOptions = {},\n): TUnsafe<OpenEnumOf<V[number]>> {\n const values = checked(known, 'OpenEnum');\n return Type.Unsafe<OpenEnumOf<V[number]>>({\n type: 'string',\n enum: values,\n [OPEN_ENUM_KEYWORD]: [...values],\n ...opts,\n });\n}\n\n/** A CLOSED string enum: adding a value is a MAJOR. One `enum` keyword rather than an `anyOf` of constants. */\nexport function ClosedEnum<const V extends readonly string[]>(values: V, opts: EnumOptions = {}): TUnsafe<V[number]> {\n return Type.Unsafe<V[number]>({ type: 'string', enum: checked(values, 'ClosedEnum'), ...opts });\n}\n\n/** The known values of an authored or published open enum; undefined for anything else. */\nexport function knownValuesOf(schema: unknown): readonly string[] | undefined {\n if (typeof schema !== 'object' || schema === null) return undefined;\n const known: unknown = (schema as Record<string, unknown>)[OPEN_ENUM_KEYWORD];\n return Array.isArray(known) && known.every((value) => typeof value === 'string') ? known : undefined;\n}\n","// DESIGN 2.3.1 — the ONE home of the shared pipeline vocabulary. `core`, `config` and `persistence` import it from\n// `protocol`; `protocol` never imports them. This file is the leaf of the package: it imports nothing from its siblings\n// except the enum helpers.\n//\n// OPEN ON THE WIRE (spec 32: a provisional ADR is never frozen as a closed wire enum): PipelineProfile (ADR-0018),\n// Actor.transport (ADR-0004), CohorteRole, StopRecord.resumeRequires, ArtifactRef.kind. The TS unions list the KNOWN\n// values; `core` still switches exhaustively over them and rejects an unknown one at the door.\nimport { ArtifactId, ModelCapability, Sha256 } from '@cohorte/base';\nimport { type Static, Type } from 'typebox';\nimport { ClosedEnum, OpenEnum } from './open-enum.ts';\n\nexport const PIPELINE_PROFILES = ['feature', 'bugfix', 'review'] as const;\n/** D6 / R3. Known values only: the wire schema below is open. */\nexport type PipelineProfile = (typeof PIPELINE_PROFILES)[number];\nexport const PipelineProfile = OpenEnum(PIPELINE_PROFILES);\n/** A parsed payload carries `OpenEnumOf<PipelineProfile>` (any string): narrow it here, at the door, before a switch. */\nexport const isKnownProfile = (value: string): value is PipelineProfile =>\n (PIPELINE_PROFILES as readonly string[]).includes(value);\n\nexport const ACTIVE_PIPELINE_STATES = [\n 'BRAINSTORM',\n 'SPEC',\n 'PREFLIGHT',\n 'BUILD',\n 'TEST',\n 'REVIEW',\n 'FIX',\n 'SHIP',\n] as const;\n/** spec 11.1 + the two states spec 10.1 names */\nexport const SUSPENDED_STATES = ['PAUSED', 'WAITING_APPROVAL', 'AUTH_REQUIRED', 'QUOTA_EXCEEDED'] as const;\n/** FAILED: recoverable checkpoint (spec 24). BLOCKED: human inspection mandatory. */\nexport const HALTED_STATES = ['FAILED', 'BLOCKED'] as const;\nexport const TERMINAL_STATES = ['COMPLETED', 'CANCELLED'] as const;\nexport const PIPELINE_STATES = [\n 'IDLE',\n ...ACTIVE_PIPELINE_STATES,\n ...SUSPENDED_STATES,\n ...HALTED_STATES,\n ...TERMINAL_STATES,\n] as const;\n\nexport const ActivePipelineState = ClosedEnum(ACTIVE_PIPELINE_STATES);\nexport type ActivePipelineState = Static<typeof ActivePipelineState>;\nexport const SuspendedState = ClosedEnum(SUSPENDED_STATES);\nexport type SuspendedState = Static<typeof SuspendedState>;\nexport const HaltedState = ClosedEnum(HALTED_STATES);\nexport type HaltedState = Static<typeof HaltedState>;\nexport const TerminalState = ClosedEnum(TERMINAL_STATES);\nexport type TerminalState = Static<typeof TerminalState>;\nexport const PipelineState = ClosedEnum(PIPELINE_STATES);\nexport type PipelineState = Static<typeof PipelineState>;\n\nexport const TRANSITION_REASONS = [\n 'start',\n 'ready',\n 'built',\n 'tests-pass',\n 'tests-fail',\n 'review-approved',\n 'review-findings',\n 'review-delivered',\n 'fixed',\n 'shipped',\n 'needs-human',\n 'approval-resolved',\n 'pause-command',\n 'resume-command',\n 'cancel-command',\n 'retry-command',\n 'skip-command',\n 'auth-required',\n 'auth-restored',\n 'quota-exceeded',\n 'quota-reset',\n 'stop-rule',\n 'security-violation',\n 'unexpected-error',\n] as const;\nexport const TransitionReason = ClosedEnum(TRANSITION_REASONS);\nexport type TransitionReason = Static<typeof TransitionReason>;\n\nexport const STOP_REASONS = [\n // the ten of spec 11.2, in spec order:\n 'review-clean',\n 'iteration-limit',\n 'budget-exhausted',\n 'timeout',\n 'identical-failure',\n 'no-progress',\n 'policy-violation',\n 'approval-required',\n 'unexpected-repo-change',\n 'runtime-incompatible',\n // required by spec 10.1, 17.2, 24:\n 'auth-required',\n 'quota-exceeded',\n 'paused',\n 'cancelled',\n 'agent-dead',\n 'unreviewed',\n 'internal-error',\n // required by table totality (2.5.1 T16): a check that ERRORED (spawn failure, timeout, sandbox denial) is\n // neither \"tests pass\" nor \"tests fail\":\n 'check-environment',\n] as const;\nexport const StopReason = ClosedEnum(STOP_REASONS);\nexport type StopReason = Static<typeof StopReason>;\n\nexport const AGENT_STATES = [\n 'declared',\n 'planned',\n 'spawning',\n 'running',\n 'waiting',\n 'paused',\n 'completed',\n 'failed',\n 'retrying',\n 'escalated',\n 'cancelled',\n] as const;\nexport const AgentState = ClosedEnum(AGENT_STATES);\nexport type AgentState = Static<typeof AgentState>;\n\n/** R2 */\nexport const NODE_STATUSES = [\n 'pending',\n 'running',\n 'completed',\n 'failed',\n 'paused',\n 'waiting-approval',\n 'cancelled',\n 'skipped',\n 'blocked',\n] as const;\nexport const NodeStatus = ClosedEnum(NODE_STATUSES);\nexport type NodeStatus = Static<typeof NodeStatus>;\n\n/** The eleven roles of spec 8, and `verifier`: the id is reserved, the adversarial cross-check is off in V3.0 (2.9). */\nexport const COHORTE_ROLES = [\n 'discoverer',\n 'brainstormer',\n 'architect',\n 'spec-author',\n 'implementer',\n 'tester',\n 'reviewer',\n 'security-reviewer',\n 'fixer',\n 'release-manager',\n 'reconciler',\n 'verifier',\n] as const;\nexport type CohorteRole = (typeof COHORTE_ROLES)[number];\n/** OpenEnum on the wire. Inside Cohorte a role is one of the known ones: see {@link KnownCohorteRole}. */\nexport const CohorteRole = OpenEnum(COHORTE_ROLES);\n/** Closed: for data Cohorte itself authors and switches over (the escalation ladder). */\nexport const KnownCohorteRole = ClosedEnum(COHORTE_ROLES);\n\n/** spec 22 speaks of 'major' */\nexport const SEVERITIES = ['critical', 'major', 'minor', 'info'] as const;\nexport const Severity = ClosedEnum(SEVERITIES);\nexport type Severity = Static<typeof Severity>;\n\n/** V3.0 implements ONE transport; 'stdin' / 'socket' are future open-enum values, not promises. Identity rules: 2.6.7 */\nexport const ACTOR_TRANSPORTS = ['cli'] as const;\nexport const Actor = Type.Object({\n kind: ClosedEnum(['human', 'client', 'system']),\n id: Type.String(),\n transport: OpenEnum(ACTOR_TRANSPORTS),\n});\nexport type Actor = Static<typeof Actor>;\n\nexport const GuardOutcome = Type.Object({\n id: Type.String(),\n ok: Type.Boolean(),\n detail: Type.Optional(Type.String()),\n});\nexport type GuardOutcome = Static<typeof GuardOutcome>;\n\nexport const RESUME_REQUIREMENTS = [\n 'approval',\n 'auth-login',\n 'quota-reset',\n 'budget-raise',\n 'human-ack',\n 'repo-repair',\n 'reinstall-pinned-version',\n 'environment-repair',\n] as const;\nexport const StopRecord = Type.Object({\n reason: StopReason,\n detail: Type.String(),\n resumable: Type.Boolean(),\n resumeRequires: Type.Optional(OpenEnum(RESUME_REQUIREMENTS)),\n});\nexport type StopRecord = Static<typeof StopRecord>;\n\n/** Declared in base/usage.ts (DESIGN 2.1, PLAN PC-8); re-exported so protocol consumers keep one import. */\nexport { BudgetCounters } from '@cohorte/base';\n\nexport const EscalationStep = Type.Union([\n Type.Object({\n kind: Type.Literal('model-tier'),\n role: KnownCohorteRole,\n from: ModelCapability,\n to: ModelCapability,\n }),\n Type.Object({ kind: Type.Literal('role'), from: KnownCohorteRole, to: KnownCohorteRole }),\n Type.Object({ kind: Type.Literal('human') }),\n]);\nexport type EscalationStep = Static<typeof EscalationStep>;\n\n/** Data: used by config AND by `escalation.applied`. Defaults: sameFailureCount 2, maxPerRun 2. */\nexport const EscalationPolicy = Type.Object({\n sameFailureCount: Type.Integer({ minimum: 1 }),\n ladder: Type.Array(EscalationStep),\n maxPerRun: Type.Integer({ minimum: 0 }),\n});\nexport type EscalationPolicy = Static<typeof EscalationPolicy>;\n\nexport const ARTIFACT_KINDS = [\n 'diff',\n 'file',\n 'log',\n 'report',\n 'agent-output',\n 'transcript',\n 'context',\n 'prompt',\n 'patch',\n] as const;\n/**\n * DESIGN 2.3.3. Declared HERE and re-exported by refs.ts: CheckResult needs it, and refs.ts needs the states and the\n * profile of this file. Schemas are values, so an import cycle between the two files would read a const before it is set.\n */\nexport const ArtifactRef = Type.Object({\n artifactId: ArtifactId,\n kind: OpenEnum(ARTIFACT_KINDS),\n path: Type.String(),\n sha256: Sha256,\n bytes: Type.Integer({ minimum: 0 }),\n});\nexport type ArtifactRef = Static<typeof ArtifactRef>;\n\nexport const CheckResult = Type.Object({\n name: Type.String(),\n status: ClosedEnum(['passed', 'failed', 'errored', 'skipped']),\n argv: Type.Array(Type.String()),\n exitCode: Type.Optional(Type.Integer()),\n durationMs: Type.Number({ minimum: 0 }),\n treeDigest: Type.String(),\n output: Type.Optional(ArtifactRef),\n});\nexport type CheckResult = Static<typeof CheckResult>;\n","// DESIGN 2.9 / spec 22 — the agent output envelope and review findings.\n//\n// AgentOutput IS `submit_result.inputSchema`: a model reads it. It is therefore FLAT — everything inlined, no $ref,\n// no $defs, no oneOf/anyOf — and built from ClosedEnum (`enum`) rather than unions of literals.\n// A Finding without `location` or without `reproduction` VALIDATES: routing it to `needsInvestigation` is\n// TypeScript in core (review/normalize.ts), never a schema failure that would cost the agent its whole output.\nimport { FindingId, SurfaceId } from '@cohorte/base';\nimport { type Static, Type } from 'typebox';\nimport { ClosedEnum } from './open-enum.ts';\nimport { Severity } from './vocabulary.ts';\n\nexport const AGENT_OUTPUT_MAX_SUMMARY = 2000;\nexport const AGENT_OUTPUT_MAX_FINDINGS = 30;\n\nconst confidence = () => Type.Number({ minimum: 0, maximum: 1 });\nconst lineNumber = () => Type.Integer({ minimum: 1 });\n\nexport const FINDING_KINDS = ['spec-violation', 'security', 'quality', 'complexity', 'check-failure'] as const;\n\nexport const Finding = Type.Object({\n /** assigned by Cohorte */\n id: Type.Optional(FindingId),\n severity: Severity,\n kind: ClosedEnum(FINDING_KINDS),\n rule: Type.String(),\n location: Type.Optional(\n Type.Object({\n file: Type.String(),\n line: Type.Optional(lineNumber()),\n endLine: Type.Optional(lineNumber()),\n symbol: Type.Optional(Type.String()),\n }),\n ),\n reproduction: Type.Optional(Type.String()),\n expected: Type.String(),\n actual: Type.String(),\n confidence: confidence(),\n suggestedFix: Type.Optional(Type.String()),\n scope: ClosedEnum(['in-scope', 'deferred']),\n outOfScopeReason: Type.Optional(Type.String()),\n});\nexport type Finding = Static<typeof Finding>;\n\nexport const AgentOutput = Type.Object({\n status: ClosedEnum(['completed', 'failed', 'blocked', 'needs-input']),\n summary: Type.String({ maxLength: AGENT_OUTPUT_MAX_SUMMARY }),\n artifacts: Type.Array(\n Type.Object({\n path: Type.String(),\n kind: ClosedEnum(['diff', 'file', 'test', 'report', 'contract']),\n /** ignored; Cohorte recomputes. A plain string on purpose: a wrong digest from a model must not fail its output. */\n sha256: Type.Optional(Type.String()),\n }),\n ),\n findings: Type.Array(Finding, { maxItems: AGENT_OUTPUT_MAX_FINDINGS }),\n /** claims; TEST is the truth */\n checks: Type.Array(\n Type.Object({\n name: Type.String(),\n status: ClosedEnum(['passed', 'failed', 'skipped', 'not-run']),\n command: Type.Optional(Type.String()),\n }),\n ),\n questions: Type.Array(Type.String()),\n confidence: confidence(),\n assumptions: Type.Optional(Type.Array(Type.Object({ gap: Type.String(), decision: Type.String() }))),\n remediationAddressed: Type.Optional(Type.Array(Type.Object({ findingId: Type.String(), how: Type.String() }))),\n});\nexport type AgentOutput = Static<typeof AgentOutput>;\n\nconst count = () => Type.Integer({ minimum: 0 });\n\n/** Computed by core, never read from a model (2.9 rule 5). */\nexport const ReviewResult = Type.Object({\n verdict: ClosedEnum(['approved', 'findings', 'needs-human']),\n kept: Type.Array(Finding),\n refuted: Type.Array(Finding),\n deferred: Type.Array(Finding),\n needsInvestigation: Type.Array(Finding),\n blocking: count(),\n blockingItems: Type.Array(Type.String()),\n /** sha256(items)[0:16]; '' when there is nothing to fix */\n fingerprint: Type.String({ pattern: '^(?:[0-9a-f]{16})?$' }),\n unreviewed: Type.Array(SurfaceId),\n clean: Type.Boolean(),\n counts: Type.Object({ critical: count(), major: count(), minor: count(), info: count() }),\n});\nexport type ReviewResult = Static<typeof ReviewResult>;\n","// DESIGN 2.3.3 (the records that event payloads, documents and commands share).\n//\n// OPEN ON THE WIRE: SandboxReport.level / .backend / .filesystem / .network (ADR-0003), RunPlan.profile and\n// RunPlan.trust.grantedBy, ApprovalRequest.kind, and every ResumeReport verdict.\nimport {\n AgentId,\n ApprovalId,\n AuthMode,\n BudgetCounters,\n CommandId,\n EffectId,\n IsoInstant,\n JsonValueSchema,\n ModelRef,\n PhaseRunId,\n Sha256,\n SurfaceId,\n ThinkingLevel,\n ToolCallId,\n} from '@cohorte/base';\nimport { type Static, Type } from 'typebox';\nimport { ClosedEnum, OpenEnum } from './open-enum.ts';\nimport { ActivePipelineState, PipelineProfile } from './vocabulary.ts';\n\nexport { ARTIFACT_KINDS, ArtifactRef } from './vocabulary.ts';\n\nconst count = () => Type.Integer({ minimum: 0 });\n\nexport const PhaseRef = Type.Object({\n phaseRunId: PhaseRunId,\n state: ActivePipelineState,\n iteration: count(),\n});\nexport type PhaseRef = Static<typeof PhaseRef>;\n\n/** `role` is a plain string here (DESIGN 2.3.3): a reader must be able to show an agent whose role it does not know. */\nexport const AgentRef = Type.Object({\n agentId: AgentId,\n role: Type.String(),\n surface: Type.Optional(SurfaceId),\n incarnation: count(),\n attempt: count(),\n});\nexport type AgentRef = Static<typeof AgentRef>;\n\n/** R8: optional wherever it appears, and opaque. A client never needs it. */\nexport const RuntimeRef = Type.Object({\n runtime: Type.String(),\n version: Type.String(),\n sessionId: Type.String(),\n transcriptRef: Type.String(),\n});\nexport type RuntimeRef = Static<typeof RuntimeRef>;\n\nexport const FileTouch = Type.Object({\n /** worktree-relative, POSIX */\n path: Type.String(),\n op: ClosedEnum(['read', 'create', 'modify', 'delete']),\n beforeSha256: Type.Optional(Sha256),\n afterSha256: Type.Optional(Sha256),\n bytes: Type.Optional(count()),\n});\nexport type FileTouch = Static<typeof FileTouch>;\n\nexport const SANDBOX_LEVELS = ['L0-process', 'L1-os'] as const;\nexport const SANDBOX_BACKENDS = ['none', 'seatbelt', 'bubblewrap'] as const;\n/** 'partial' = backend active but its escape test (S-28 / S-29) has not passed on this platform */\nexport const SANDBOX_FILESYSTEM_VERDICTS = ['enforced', 'partial', 'advisory'] as const;\nexport const SANDBOX_NETWORK_VERDICTS = ['enforced-off', 'partial', 'unenforced'] as const;\nexport const SandboxReport = Type.Object({\n level: OpenEnum(SANDBOX_LEVELS),\n backend: OpenEnum(SANDBOX_BACKENDS),\n filesystem: OpenEnum(SANDBOX_FILESYSTEM_VERDICTS),\n network: OpenEnum(SANDBOX_NETWORK_VERDICTS),\n});\nexport type SandboxReport = Static<typeof SandboxReport>;\n\nexport const TRUST_GRANTS = ['none-needed', 'user-config', 'cli-flag', 'trust-record'] as const;\nexport const RunPlan = Type.Object({\n profile: PipelineProfile,\n runtime: Type.Object({ id: Type.String(), version: Type.String() }),\n /** 2.10.1: WHO consented to every security-loosening key of the project file */\n trust: Type.Object({\n policySha256: Sha256,\n loosenedKeys: Type.Array(Type.String()),\n grantedBy: OpenEnum(TRUST_GRANTS),\n }),\n models: Type.Array(\n Type.Object({\n role: Type.String(),\n requested: ModelRef,\n thinking: ThinkingLevel,\n authMode: AuthMode,\n billing: ClosedEnum(['plan-limits', 'metered']),\n reason: Type.String(),\n }),\n ),\n apiBillingEnabled: Type.Boolean(),\n /** non-empty => the plan printed to the human names per-token billing */\n meteredProviders: Type.Array(Type.String()),\n sandbox: SandboxReport,\n sandboxRequire: ClosedEnum(['native', 'best-effort']),\n brainIsolation: ClosedEnum(['os', 'process']),\n budgets: Type.Object({\n run: BudgetCounters,\n perPhase: BudgetCounters,\n perAgent: BudgetCounters,\n perProvider: Type.Record(Type.String(), BudgetCounters),\n perTool: Type.Record(Type.String(), BudgetCounters),\n }),\n network: Type.Object({ provisioning: Type.Boolean() }),\n promptOverrides: Type.Array(Type.String()),\n unattended: Type.Boolean(),\n});\nexport type RunPlan = Static<typeof RunPlan>;\n\nexport const APPROVAL_KINDS = [\n 'tool',\n 'shared-path',\n 'ship',\n 'budget',\n 'loop-stalled',\n 'contract-change',\n 'spec-not-ready',\n 'review-leftovers',\n 'unowned-path',\n 'api-billing',\n 'blocked-ack',\n 'provision-network',\n] as const;\n/** R6 — everything a human needs without reading a transcript */\nexport const ApprovalRequest = Type.Object({\n approvalId: ApprovalId,\n kind: OpenEnum(APPROVAL_KINDS),\n agent: Type.Optional(AgentRef),\n phase: Type.Optional(PhaseRef),\n tool: Type.Optional(Type.String()),\n /** sealed */\n args: Type.Optional(JsonValueSchema),\n affectedPaths: Type.Array(Type.String()),\n /** sealed; agent-controlled text: clients MUST render it through the sanitiser of 2.3.6 */\n preview: Type.Object({ kind: ClosedEnum(['diff', 'command', 'text']), text: Type.String() }),\n /** only for the `approval_request` tool: the answers the agent offered; `approve.answer` must be one of them */\n options: Type.Optional(Type.Array(Type.String())),\n ruleId: Type.String(),\n reason: Type.String(),\n asks: Type.Array(Type.Object({ stage: Type.String(), ruleId: Type.String(), reason: Type.String() })),\n allowedDecisions: Type.Array(ClosedEnum(['allow-once', 'allow-for-run', 'deny'])),\n /** what the decision is bound to (4.5): the target's beforeSha256 (write/patch) or the slot's treeDigest (command) */\n preStateSha256: Type.Optional(Sha256),\n expiresAt: Type.Optional(IsoInstant),\n unattended: ClosedEnum(['deny', 'wait']),\n /** literal \"cohorte approve <id>\" */\n cli: Type.String(),\n});\nexport type ApprovalRequest = Static<typeof ApprovalRequest>;\n\nexport const WORKTREE_VERDICTS = [\n 'ok',\n 're-added',\n 'ledger-explained',\n 'quarantined-reset',\n 'unexplained-change',\n 'missing-branch',\n] as const;\nexport const EFFECT_VERDICTS = ['done', 'failed', 're-executed', 'in-doubt', 'compensated'] as const;\nexport const APPROVED_REPLAY_OUTCOMES = ['executed', 'binding-changed', 'denied-by-gate'] as const;\nexport const ResumeReport = Type.Object({\n takeover: Type.Boolean(),\n hostId: Type.String(),\n fencingToken: count(),\n locks: Type.Object({ rebuilt: Type.Array(Type.String()), conflicts: Type.Array(Type.String()) }),\n orphans: Type.Array(\n Type.Object({\n agentId: Type.Optional(AgentId),\n incarnation: Type.Optional(count()),\n pid: count(),\n kind: ClosedEnum(['brain', 'command']),\n killed: Type.Boolean(),\n }),\n ),\n worktrees: Type.Array(\n Type.Object({ slot: Type.String(), path: Type.String(), verdict: OpenEnum(WORKTREE_VERDICTS) }),\n ),\n effects: Type.Array(\n Type.Object({\n effectId: EffectId,\n kind: Type.String(),\n replayClass: ClosedEnum(['idempotent', 'verifiable', 'at-most-once']),\n verdict: OpenEnum(EFFECT_VERDICTS),\n }),\n ),\n approvalsCarried: Type.Array(ApprovalId),\n commandsApplied: Type.Array(CommandId),\n inDoubt: Type.Array(EffectId),\n /** 4.5 parked path */\n approvedReplays: Type.Array(\n Type.Object({ approvalId: ApprovalId, toolCallId: ToolCallId, outcome: OpenEnum(APPROVED_REPLAY_OUTCOMES) }),\n ),\n});\nexport type ResumeReport = Static<typeof ResumeReport>;\n","// DESIGN 2.3.2 / ADR-0019 — one envelope for durable and ephemeral events; total order = (sequence, sub).\nimport { EventId, IsoInstant, Redaction, RunId } from '@cohorte/base';\nimport { type Static, type TSchema, Type } from 'typebox';\nimport { ClosedEnum } from './open-enum.ts';\nimport { AgentRef, PhaseRef } from './refs.ts';\n\nexport const PROTOCOL_VERSION = '1.0';\n\nexport const DURABILITIES = ['durable', 'ephemeral'] as const;\nexport const Durability = ClosedEnum(DURABILITIES);\nexport type Durability = Static<typeof Durability>;\n\nexport const EVENT_SOURCES = ['cohorte', 'runtime', 'client', 'human'] as const;\nexport const EVENT_SEVERITIES = ['info', 'success', 'warning', 'error', 'progress'] as const;\n\nexport const SUMMARY_MAX_LENGTH = 200;\n/** No C0/C1 control character at all (no tab, no newline, no ESC): the shared presentation contract of every client (2.3.6). */\nexport const SUMMARY_PATTERN = '^[^\\\\u0000-\\\\u001f\\\\u007f-\\\\u009f]*$';\n\nexport const EnvelopeBase = Type.Object({\n protocolVersion: Type.Literal(PROTOCOL_VERSION),\n eventId: EventId,\n /** durable: own gapless per-run sequence (1..n). ephemeral: sequence of the last COMMITTED durable event when it is STAMPED */\n sequence: Type.Integer({ minimum: 0 }),\n /** durable: 0. ephemeral: 1.. after that durable sequence */\n sub: Type.Integer({ minimum: 0 }),\n durability: Durability,\n timestamp: IsoInstant,\n runId: RunId,\n /** narrowed per event */\n type: Type.String({ minLength: 1 }),\n source: ClosedEnum(EVENT_SOURCES),\n phase: Type.Optional(PhaseRef),\n agent: Type.Optional(AgentRef),\n /** eventId or commandId that caused this event */\n causationId: Type.Optional(Type.String()),\n /** one line, sealed; EventWriter replaces control characters by U+FFFD BEFORE validation */\n summary: Type.String({ maxLength: SUMMARY_MAX_LENGTH, pattern: SUMMARY_PATTERN }),\n severity: ClosedEnum(EVENT_SEVERITIES),\n /** narrowed per event */\n payload: Type.Unknown(),\n redactions: Type.Array(Redaction),\n});\nexport type EnvelopeBase = Static<typeof EnvelopeBase>;\n\n/** One row of an events table: this pair IS the catalogue entry of a type (2.3.3). */\nexport interface EventDeclaration<P extends TSchema = TSchema> {\n readonly payload: P;\n readonly durability: Durability;\n}\nexport type EventTable = Readonly<Record<string, EventDeclaration>>;\n\nexport type PayloadOf<E extends EventTable, T extends keyof E> = Static<E[T]['payload']>;\n\n/** `Envelope<T>` of DESIGN 2.3.2, over any table: the catalogue binds it to EVENTS. Distributes over a union of types. */\nexport type EnvelopeOf<E extends EventTable, T extends keyof E & string = keyof E & string> = {\n [K in T]: Omit<EnvelopeBase, 'type' | 'payload' | 'durability'> & {\n type: K;\n durability: E[K]['durability'];\n payload: PayloadOf<E, K>;\n };\n}[T];\n\n/** The types of a table that are durable: the only ones a reducer may consume (C5). */\nexport type DurableTypeOf<E extends EventTable> = {\n [K in keyof E & string]: E[K]['durability'] extends 'durable' ? K : never;\n}[keyof E & string];\n\n/** Total order of a stream. */\nexport function compareOrder(\n a: { readonly sequence: number; readonly sub: number },\n b: { readonly sequence: number; readonly sub: number },\n): number {\n return a.sequence - b.sequence || a.sub - b.sub;\n}\n","// DESIGN 0.1 C3 / 2.3.2 — TypeBox is the only place a wire shape is written. From ONE authored schema this file derives:\n// strict (writer side): every object is closed, an OpenEnum is `enum [...known]`\n// open (published side): no object is closed, an OpenEnum is { type: 'string', 'x-cohorte-known': [...] },\n// and a table of types becomes a `oneOf` over `type` WITH a catch-all branch.\n// Forward compatibility is therefore a property of this generator, not of each author's discipline.\nimport { err, type JsonValue, ok, type Result } from '@cohorte/base';\nimport type { Static, TSchema } from 'typebox';\nimport { Compile } from 'typebox/compile';\nimport { EnvelopeBase, type EnvelopeOf, type EventTable, type PayloadOf } from './envelope.ts';\nimport { knownValuesOf } from './open-enum.ts';\n\nexport type { EventDeclaration, EventTable } from './envelope.ts';\n\nexport interface SchemaIssue {\n /** JSON pointer into the VALUE ('' = the value itself) */\n path: string;\n /** the JSON Schema keyword that failed: 'additionalProperties', 'enum', 'type', 'required', ... */\n keyword: string;\n message: string;\n}\nexport type Validator<T> = (value: unknown) => Result<T, SchemaIssue[]>;\n\ntype JsonObject = { [key: string]: JsonValue };\ntype Mode = 'strict' | 'open';\n\nconst SCHEMA_DIALECT = 'https://json-schema.org/draft/2020-12/schema';\nexport const EVENTS_SCHEMA_ID = 'https://cohorte.dev/schemas/3/events.schema.json';\n\n// Keyword-aware walk: a PROPERTY may be named `enum`, `const` or `additionalProperties`, so \"recurse into everything\"\n// would rewrite data. Only these keywords hold schemas; every other keyword is copied as it is.\nconst SCHEMA_MAPS = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas']);\nconst SCHEMA_LISTS = new Set(['anyOf', 'oneOf', 'prefixItems']);\nconst SCHEMA_SINGLES = new Set([\n 'items',\n 'additionalItems',\n 'additionalProperties',\n 'unevaluatedProperties',\n 'unevaluatedItems',\n 'not',\n 'if',\n 'then',\n 'else',\n 'contains',\n 'propertyNames',\n]);\n\nconst isObject = (value: JsonValue | undefined): value is JsonObject =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** TypeBox keeps its own bookkeeping under non-enumerable or `~`-prefixed keys: a JSON round trip leaves the JSON Schema. */\nconst plain = (schema: unknown): JsonValue => JSON.parse(JSON.stringify(schema)) as JsonValue;\n\n/** Post-order map over every SCHEMA of a document: `post` sees a node whose sub-schemas are already mapped. */\nfunction mapSchemas(\n node: JsonValue,\n post: (out: JsonObject, closable: boolean) => JsonValue,\n closable = true,\n): JsonValue {\n if (!isObject(node)) return node;\n const out: JsonObject = {};\n for (const [keyword, value] of Object.entries(node)) {\n if (SCHEMA_MAPS.has(keyword) && isObject(value)) {\n out[keyword] = Object.fromEntries(\n Object.entries(value).map(([name, member]) => [name, mapSchemas(member, post)]),\n );\n } else if ((SCHEMA_LISTS.has(keyword) || keyword === 'items') && Array.isArray(value)) {\n // `items` as a LIST is how TypeBox writes a tuple (with `additionalItems`), where 2020-12 says `prefixItems`.\n out[keyword] = value.map((member) => mapSchemas(member, post));\n } else if (keyword === 'allOf' && Array.isArray(value)) {\n // The members of an intersection describe ONE object together: closing each of them would refuse every value.\n out[keyword] = value.map((member) => mapSchemas(member, post, false));\n } else if (SCHEMA_SINGLES.has(keyword) && isObject(value)) {\n out[keyword] = mapSchemas(value, post);\n } else {\n out[keyword] = value;\n }\n }\n return post(out, closable);\n}\n\nfunction rewrite(node: JsonValue, mode: Mode): JsonValue {\n return mapSchemas(node, (out, closable) => {\n if (mode === 'open') {\n if (out.additionalProperties === false) delete out.additionalProperties;\n if (knownValuesOf(out) !== undefined) delete out.enum;\n } else if (closable && isObject(out.properties) && !('additionalProperties' in out)) {\n out.additionalProperties = false;\n }\n return out;\n });\n}\n\n/**\n * TypeBox inlines a `Type.Cyclic` at EVERY use as `{ $defs: { X: { $id: 'X', … } }, $ref: 'X' }`. Its own compiler\n * accepts the repetition; a second implementation (ajv) refuses two schemas with one `$id` in one document, and the\n * published schema exists for second implementations (AC-07). So a published DOCUMENT carries each such definition\n * once, under the root `$defs`, without its `$id`, and every reference becomes a pointer. Two different definitions\n * under one name are an authoring error, never merged. The result is a whole document: embed authored schemas in a\n * bigger one, not published ones (their pointers are relative to the root).\n */\nfunction hoistDefinitions(document: JsonValue): JsonValue {\n const hoisted: JsonObject = {};\n const hoist = (name: string, definition: JsonObject): void => {\n const { $id: _id, ...body } = definition;\n const found = hoisted[name];\n if (found !== undefined && JSON.stringify(found) !== JSON.stringify(body)) {\n throw new TypeError(`two different definitions are named ${JSON.stringify(name)} in one published schema`);\n }\n hoisted[name] = body;\n };\n const lifted = mapSchemas(document, (out) => {\n if (!isObject(out.$defs)) return out;\n const kept: JsonObject = {};\n for (const [name, member] of Object.entries(out.$defs)) {\n if (isObject(member) && member.$id === name) hoist(name, member);\n else kept[name] = member;\n }\n if (Object.keys(kept).length > 0) out.$defs = kept;\n else delete out.$defs;\n return out;\n });\n if (!isObject(lifted) || Object.keys(hoisted).length === 0) return lifted;\n const own = isObject(lifted.$defs) ? lifted.$defs : {};\n for (const name of Object.keys(hoisted)) {\n if (name in own)\n throw new TypeError(`two different definitions are named ${JSON.stringify(name)} in one published schema`);\n }\n return mapSchemas({ ...lifted, $defs: { ...own, ...hoisted } }, (out) => {\n if (typeof out.$ref === 'string' && Object.hasOwn(hoisted, out.$ref)) out.$ref = `#/$defs/${out.$ref}`;\n return out;\n });\n}\n\n/** Writer side. Closes every object that declares `properties`, whether or not its author remembered to. */\nexport function toStrictSchema(schema: TSchema | JsonValue): JsonValue {\n return rewrite(plain(schema), 'strict');\n}\n\n/** Published side. Readers MUST ignore unknown fields and unknown open-enum values: the schema must let them. */\nexport function toOpenSchema(schema: TSchema | JsonValue): JsonValue {\n return hoistDefinitions(rewrite(plain(schema), 'open'));\n}\n\nfunction validatorOf<T>(jsonSchema: JsonValue): Validator<T> {\n const compiled = Compile(jsonSchema as TSchema);\n return (value) => {\n if (compiled.Check(value)) return ok(value as T);\n const issues: SchemaIssue[] = [];\n for (const issue of compiled.Errors(value)) {\n issues.push({ path: issue.instancePath, keyword: issue.keyword, message: issue.message });\n }\n return err(issues);\n };\n}\n\nconst strictCache = new WeakMap<object, Validator<unknown>>();\n\n/** The STRICT validator of any authored schema: commands, documents, agent output. Compiled once per schema object. */\nexport function compileSchema<S extends TSchema>(schema: S): Validator<Static<S>> {\n let found = strictCache.get(schema);\n if (!found) {\n found = validatorOf<unknown>(toStrictSchema(schema));\n strictCache.set(schema, found);\n }\n return found as Validator<Static<S>>;\n}\n\n/**\n * The validator a READER of this version would run: the open form of an authored schema, or an already published\n * schema (the transform is idempotent). It proves nothing about the static type of the value: a future field or a\n * future enum value is in it.\n */\nexport function compileOpen(schema: TSchema | JsonValue): Validator<JsonValue> {\n return validatorOf<JsonValue>(toOpenSchema(schema));\n}\n\nconst rowOf = <E extends EventTable>(events: E, type: string): E[keyof E] => {\n if (!Object.hasOwn(events, type)) throw new RangeError(`no event type ${JSON.stringify(type)} in this catalogue`);\n return events[type as keyof E];\n};\n\n/** Writer side: the payload of one event type, unknown keys rejected. Generic over the table, so a catalogue only adds rows. */\nexport function compileStrict<E extends EventTable, T extends keyof E & string>(\n events: E,\n type: T,\n): Validator<PayloadOf<E, T>> {\n return compileSchema(rowOf(events, type).payload) as Validator<PayloadOf<E, T>>;\n}\n\n/**\n * The properties that make a base envelope the envelope of ONE row: the discriminant, the narrowed body and whatever\n * the row pins (an event pins its durability). Shared by the strict and the open form, so the two cannot disagree.\n */\nfunction narrowed(\n base: JsonValue,\n discriminant: string,\n type: string,\n body: string,\n bodySchema: JsonValue,\n pinned: JsonObject,\n) {\n if (!isObject(base) || !isObject(base.properties)) throw new TypeError('an envelope schema must be an object schema');\n const properties: JsonObject = { ...base.properties, [discriminant]: { const: type }, [body]: bodySchema };\n for (const [name, value] of Object.entries(pinned)) properties[name] = { const: value };\n return { ...base, properties };\n}\n\nconst envelopeCache = new WeakMap<object, Map<string, Validator<unknown>>>();\n\n/** Writer side: the WHOLE envelope of one event type — closed, its `type` and its durability pinned by the table. */\nexport function compileStrictEnvelope<E extends EventTable, T extends keyof E & string>(\n events: E,\n type: T,\n): Validator<EnvelopeOf<E, T>> {\n const row = rowOf(events, type);\n let perTable = envelopeCache.get(events);\n if (!perTable) {\n perTable = new Map();\n envelopeCache.set(events, perTable);\n }\n let found = perTable.get(type);\n if (!found) {\n const schema = narrowed(toStrictSchema(EnvelopeBase), 'type', type, 'payload', toStrictSchema(row.payload), {\n durability: row.durability,\n });\n found = validatorOf<unknown>(schema);\n perTable.set(type, found);\n }\n return found as Validator<EnvelopeOf<E, T>>;\n}\n\nexport interface OpenTableOptions {\n $id: string;\n title: string;\n /** the envelope every row shares */\n base: TSchema;\n /** the property that names the row: `type` */\n discriminant: string;\n /** the property each row narrows: `payload` */\n body: string;\n rows: readonly { type: string; body: TSchema; pinned?: JsonObject }[];\n}\n\n/**\n * The published form of a table of types: the open base envelope, then a `oneOf` with one branch per KNOWN type and a\n * catch-all branch for the types of a later minor. Exactly one branch matches any envelope, because the base requires\n * the discriminant. Used for events here and for commands in commands.ts.\n */\nexport function toOpenTableSchema(options: OpenTableOptions): JsonValue {\n // the parts stay un-hoisted: definitions are lifted ONCE, to the root of the whole document\n const base = rewrite(plain(options.base), 'open');\n if (!isObject(base)) throw new TypeError('an envelope schema must be an object schema');\n const known = options.rows.map((row) => row.type);\n const branches: JsonValue[] = options.rows.map((row) => {\n const branch = narrowed(\n { properties: {} },\n options.discriminant,\n row.type,\n options.body,\n rewrite(plain(row.body), 'open'),\n row.pinned ?? {},\n );\n return { title: row.type, ...branch };\n });\n branches.push({\n title: 'a type added by a later minor version: readers MUST ignore it',\n properties: { [options.discriminant]: { not: { enum: known } } },\n });\n return hoistDefinitions({\n $schema: SCHEMA_DIALECT,\n $id: options.$id,\n title: options.title,\n ...base,\n oneOf: branches,\n });\n}\n\n/** Generator side of DESIGN 2.3.2, over any events table. */\nexport function toOpenJsonSchema(events: EventTable, options: { $id?: string; title?: string } = {}): JsonValue {\n return toOpenTableSchema({\n $id: options.$id ?? EVENTS_SCHEMA_ID,\n title: options.title ?? 'Cohorte Protocol event envelope',\n base: EnvelopeBase,\n discriminant: 'type',\n body: 'payload',\n rows: Object.entries(events).map(([type, row]) => ({\n type,\n body: row.payload,\n pinned: { durability: row.durability },\n })),\n });\n}\n\nexport interface BoundCatalogue<E extends EventTable> {\n compileStrict<T extends keyof E & string>(type: T): Validator<PayloadOf<E, T>>;\n compileStrictEnvelope<T extends keyof E & string>(type: T): Validator<EnvelopeOf<E, T>>;\n toOpenJsonSchema(): JsonValue;\n}\n\n/** The exact signatures of DESIGN 2.3.2, bound to one table: `bindCatalogue(EVENTS)` is all a catalogue has to write. */\nexport function bindCatalogue<E extends EventTable>(events: E): BoundCatalogue<E> {\n return {\n compileStrict: (type) => compileStrict(events, type),\n compileStrictEnvelope: (type) => compileStrictEnvelope(events, type),\n toOpenJsonSchema: () => toOpenJsonSchema(events),\n };\n}\n","// DESIGN 2.3.2 — one row of the catalogue = a payload schema + a durability. The family files of this directory declare\n// rows; catalogue.ts assembles them into EVENTS. Authoring rules (docs/v3/requests/U0.04.md R1): objects are closed by\n// the generator, never by the author; no Type.Intersect on a wire shape; OpenEnum where DESIGN says OpenEnum, ClosedEnum\n// for every literal union.\nimport { type TSchema, Type } from 'typebox';\n\nexport const durable = <P extends TSchema>(payload: P) => ({ payload, durability: 'durable' }) as const;\nexport const ephemeral = <P extends TSchema>(payload: P) => ({ payload, durability: 'ephemeral' }) as const;\n\nexport const count = () => Type.Integer({ minimum: 0 });\nexport const milliseconds = () => Type.Number({ minimum: 0 });\n\n/** `{ ref; sha; treeDigest }`: what a review looked at, and what an approval of it is bound to. */\nexport const ReviewRef = Type.Object({ ref: Type.String(), sha: Type.String(), treeDigest: Type.String() });\n\nexport const REPLAY_CLASSES = ['idempotent', 'verifiable', 'at-most-once'] as const;\n","// DESIGN 2.3.3 — agents, their turns and messages, the model calls and the context they were given (R9).\nimport {\n AgentId,\n AuthMode,\n BudgetCounters,\n ErrorInfo,\n ModelRef,\n MonetaryCost,\n QuotaInfo,\n Sha256,\n ThinkingLevel,\n TokenUsage,\n} from '@cohorte/base';\nimport { Type } from 'typebox';\nimport { AgentOutput } from '../agent-output.ts';\nimport { ClosedEnum, OpenEnum } from '../open-enum.ts';\nimport { AgentRef, RuntimeRef, SandboxReport } from '../refs.ts';\nimport { AgentState, ArtifactRef, EscalationStep } from '../vocabulary.ts';\nimport { count, durable, ephemeral, milliseconds } from './declare.ts';\n\nexport const AGENT_STATE_CHANGE_REASONS = [\n 'planned',\n 'spawned',\n 'tool-wait',\n 'approval-wait',\n 'quota-wait',\n 'peer-wait',\n 'paused',\n 'resumed',\n 'completed',\n 'failed',\n 'cancelled',\n 'retry',\n 'escalation',\n 'recovery',\n 'park',\n 'pause-expiry',\n] as const;\n/** `agent.state.changed.attemptConsumed` is true ONLY for these reasons (2.5.4): a reincarnation that is not a retry costs no attempt. */\nexport const ATTEMPT_CONSUMING_REASONS = ['retry', 'escalation'] as const;\n\nexport const MESSAGE_ROLES = ['assistant', 'user', 'tool-result'] as const;\nexport const MESSAGE_CHANNELS = ['text', 'thinking', 'tool-input'] as const;\nexport const MESSAGE_STOPS = ['stop', 'length', 'tool-use', 'error', 'aborted'] as const;\nexport const MESSAGE_DELIVERIES = ['steer', 'follow-up'] as const;\nexport const MESSAGE_DELTA_MAX_LENGTH = 8192;\nexport const MESSAGE_PREVIEW_MAX_LENGTH = 512;\n\nexport const CONTEXT_TIERS = ['system', 'doctrine', 'data', 'task', 'prior-results'] as const;\nexport const CONTEXT_TRUST_LEVELS = ['cohorte', 'human', 'untrusted-repository', 'agent-output'] as const;\nexport const CONTEXT_SOURCE_KINDS = ['asset', 'project-file', 'artifact', 'event-summary', 'inline'] as const;\nexport const CONTEXT_REDUCTION_STRATEGIES = ['excerpt', 'outline', 'summary-with-refs', 'dropped'] as const;\nexport const CONTEXT_EXCLUSION_REASONS = ['secret', 'outside-scope', 'size', 'binary'] as const;\n\n/**\n * R9. The shapes of the context manifest (DESIGN 2.2.4), declared here a second time: protocol imports no other\n * package than base (C4). Exported because `inspect { kind: 'context' }` returns this payload as it is.\n */\nexport const ContextBuiltPayload = Type.Object({\n agent: AgentRef,\n manifestSha256: Sha256,\n tokenEstimate: count(),\n tokenLimit: count(),\n entries: Type.Array(\n Type.Object({\n id: Type.String(),\n tier: ClosedEnum(CONTEXT_TIERS),\n trust: ClosedEnum(CONTEXT_TRUST_LEVELS),\n source: Type.Object({ kind: ClosedEnum(CONTEXT_SOURCE_KINDS), ref: Type.String() }),\n sha256: Sha256,\n bytes: count(),\n tokenEstimate: count(),\n }),\n ),\n reductions: Type.Array(\n Type.Object({\n entryId: Type.String(),\n strategy: ClosedEnum(CONTEXT_REDUCTION_STRATEGIES),\n fromBytes: count(),\n toBytes: count(),\n }),\n ),\n exclusions: Type.Array(Type.Object({ pattern: Type.String(), reason: ClosedEnum(CONTEXT_EXCLUSION_REASONS) })),\n manifest: ArtifactRef,\n});\n\nexport const AGENT_EVENTS = {\n 'agent.declared': durable(\n Type.Object({\n agent: AgentRef,\n parentAgentId: Type.Optional(AgentId),\n owner: Type.String(),\n ownedPaths: Type.Array(Type.String()),\n grantsDigest: Sha256,\n requestedModel: ModelRef,\n thinking: ThinkingLevel,\n routingReason: Type.String(),\n budget: BudgetCounters,\n }),\n ),\n 'agent.spawned': durable(\n Type.Object({\n agent: AgentRef,\n worktree: Type.Optional(\n Type.Object({ slot: Type.String(), path: Type.String(), branch: Type.String(), baseSha: Type.String() }),\n ),\n tools: Type.Array(Type.String()),\n systemPromptSha256: Sha256,\n effectiveSystemPromptSha256: Sha256,\n authMode: AuthMode,\n isolation: SandboxReport,\n runtimeRef: Type.Optional(RuntimeRef),\n }),\n ),\n 'agent.started': durable(Type.Object({ agent: AgentRef, taskSha256: Sha256 })),\n 'agent.state.changed': durable(\n Type.Object({\n agent: AgentRef,\n from: AgentState,\n to: AgentState,\n reason: OpenEnum(AGENT_STATE_CHANGE_REASONS),\n pausedAt: Type.Optional(ClosedEnum(['tool-boundary', 'model-boundary'])),\n attemptConsumed: Type.Boolean(),\n }),\n ),\n 'agent.completed': durable(\n Type.Object({\n agent: AgentRef,\n status: AgentOutput.properties.status,\n summary: Type.String(),\n confidence: Type.Number({ minimum: 0, maximum: 1 }),\n output: ArtifactRef,\n artifacts: Type.Array(ArtifactRef),\n findings: count(),\n questions: Type.Array(Type.String()),\n usage: BudgetCounters,\n }),\n ),\n 'agent.failed': durable(\n Type.Object({\n agent: AgentRef,\n error: ErrorInfo,\n willRetry: Type.Boolean(),\n nextIncarnation: Type.Optional(count()),\n }),\n ),\n 'agent.turn.started': ephemeral(Type.Object({ turn: count() })),\n 'agent.turn.completed': durable(Type.Object({ turn: count(), toolCalls: count() })),\n /** R1 */\n 'agent.message.started': ephemeral(Type.Object({ messageId: Type.String(), role: ClosedEnum(MESSAGE_ROLES) })),\n 'agent.message.delta': ephemeral(\n Type.Object({\n messageId: Type.String(),\n channel: ClosedEnum(MESSAGE_CHANNELS),\n contentIndex: count(),\n delta: Type.String({ maxLength: MESSAGE_DELTA_MAX_LENGTH }),\n }),\n ),\n 'agent.message.completed': durable(\n Type.Object({\n messageId: Type.String(),\n role: ClosedEnum(MESSAGE_ROLES),\n preview: Type.String({ maxLength: MESSAGE_PREVIEW_MAX_LENGTH }),\n textSha256: Sha256,\n bytes: count(),\n stop: Type.Optional(ClosedEnum(MESSAGE_STOPS)),\n }),\n ),\n /** the runtime took a `send` (host note, nudge, or `agent.send`) into its queue */\n 'agent.message.accepted': durable(\n Type.Object({ agent: AgentRef, messageId: Type.String(), delivery: ClosedEnum(MESSAGE_DELIVERIES) }),\n ),\n /** non-fatal runtime diagnostics (unmapped stop reason, stale auth snapshot, degraded capability); `message` is sealed */\n 'runtime.warning': durable(\n Type.Object({ agent: Type.Optional(AgentRef), code: Type.String(), message: Type.String() }),\n ),\n 'model.requested': durable(\n Type.Object({\n requestId: Type.String(),\n model: ModelRef,\n expectedAuthMode: AuthMode,\n contextSha256: Type.Optional(Sha256),\n attempt: count(),\n }),\n ),\n 'model.responded': durable(\n Type.Object({\n requestId: Type.String(),\n requestedModel: ModelRef,\n effectiveModel: Type.Object({\n provider: Type.String(),\n model: Type.String(),\n api: Type.Optional(Type.String()),\n baseUrl: Type.Optional(Type.String()),\n }),\n authMode: AuthMode,\n authSource: ClosedEnum(['oauth', 'api-key', 'none']),\n status: ClosedEnum(['ok', 'error']),\n httpStatus: Type.Optional(Type.Integer({ minimum: 100, maximum: 599 })),\n durationMs: milliseconds(),\n tokens: TokenUsage,\n monetaryCost: MonetaryCost,\n quota: QuotaInfo,\n attempt: count(),\n error: Type.Optional(ErrorInfo),\n }),\n ),\n 'context.built': durable(ContextBuiltPayload),\n 'escalation.applied': durable(Type.Object({ agent: AgentRef, step: EscalationStep, because: Type.String() })),\n} as const;\n","// DESIGN 2.3.3 — worktrees, commits, merges, unexpected repository changes, locks.\nimport { EffectId, Sha256 } from '@cohorte/base';\nimport { Type } from 'typebox';\nimport { ClosedEnum } from '../open-enum.ts';\nimport { FileTouch } from '../refs.ts';\nimport { ArtifactRef } from '../vocabulary.ts';\nimport { count, durable } from './declare.ts';\n\nexport const LOCK_SCOPES = ['project', 'zone', 'run', 'integration', 'slot'] as const;\nexport const LOCK_MODES = ['shared', 'exclusive'] as const;\n\nconst Lock = Type.Object({\n scope: ClosedEnum(LOCK_SCOPES),\n key: Type.String(),\n mode: ClosedEnum(LOCK_MODES),\n owner: Type.String(),\n fencingToken: Type.Optional(count()),\n});\n\nexport const GIT_EVENTS = {\n 'git.worktree.created': durable(\n Type.Object({\n slot: Type.String(),\n path: Type.String(),\n branch: Type.String(),\n baseSha: Type.String(),\n effectId: EffectId,\n }),\n ),\n 'git.worktree.provisioned': durable(\n Type.Object({ slot: Type.String(), lockfileSha256: Sha256, network: Type.Boolean(), effectId: EffectId }),\n ),\n 'git.worktree.quarantined': durable(\n Type.Object({\n slot: Type.String(),\n resetTo: Type.String(),\n patch: ArtifactRef,\n compensated: Type.Array(EffectId),\n }),\n ),\n 'git.worktree.removed': durable(Type.Object({ slot: Type.String(), path: Type.String() })),\n 'git.commit.created': durable(\n Type.Object({\n slot: Type.String(),\n branch: Type.String(),\n sha: Type.String(),\n kind: ClosedEnum(['result', 'checkpoint']),\n treeDigest: Type.String(),\n paths: Type.Array(Type.String()),\n effectId: EffectId,\n }),\n ),\n 'git.merge.completed': durable(\n Type.Object({\n from: Type.String(),\n into: Type.String(),\n mergeSha: Type.String(),\n treeDigest: Type.String(),\n effectId: EffectId,\n }),\n ),\n 'git.merge.conflicted': durable(\n Type.Object({ from: Type.String(), into: Type.String(), files: Type.Array(Type.String()) }),\n ),\n 'repo.change.detected': durable(\n Type.Object({\n slot: Type.String(),\n expected: Type.String(),\n actual: Type.String(),\n files: Type.Array(FileTouch),\n }),\n ),\n 'lock.acquired': durable(Lock),\n 'lock.released': durable(Lock),\n 'lock.stolen': durable(Lock),\n} as const;\n","// DESIGN 2.3.4 / spec 17.2 / ADR-0004 — commands. One-shot CLI spawns are the only V3.0 transport, so every command\n// type has a CLI verb, and what differs between them is DATA: the COMMANDS table below (payload schema, route,\n// whether it carries an authenticator, whether it produces a result event).\nimport {\n AgentId,\n ApprovalId,\n ArtifactId,\n BudgetCounters,\n CommandId,\n canonicalJson,\n EffectId,\n IsoInstant,\n type JsonValue,\n JsonValueSchema,\n ModelRef,\n RunId,\n Sha256,\n SpecId,\n SurfaceId,\n} from '@cohorte/base';\nimport { type Static, type TSchema, Type } from 'typebox';\nimport { compileSchema, toOpenTableSchema, type Validator } from './compile.ts';\nimport { PROTOCOL_VERSION } from './envelope.ts';\nimport { ClosedEnum, OpenEnum } from './open-enum.ts';\nimport { ActivePipelineState, Actor, PipelineProfile } from './vocabulary.ts';\n\nexport const COMMANDS_SCHEMA_ID = 'https://cohorte.dev/schemas/3/commands.schema.json';\n\n/** `inspect { kind: 'artifact' }`: default 1 MiB, cap 3 MiB, so the document stays under a 4 MiB one-shot client. */\nexport const INSPECT_ARTIFACT_DEFAULT_BYTES = 1024 * 1024;\nexport const INSPECT_ARTIFACT_MAX_BYTES = 3 * 1024 * 1024;\n\nconst count = () => Type.Integer({ minimum: 0 });\n\nexport const COMMAND_AUTH_SCHEMES = ['hmac-sha256'] as const;\n/**\n * Scheme-neutral, so an asymmetric signature (ADR-0022 \"Revisit\") is a MINOR. V3.0: value = hex\n * HMAC-SHA256(projectKey, canonicalCommandBody(envelope)). An unknown scheme VALIDATES under the open schema:\n * refusing it (`security/command-auth-invalid`) is the host's job, not the parser's.\n */\nexport const CommandAuth = Type.Object({\n scheme: OpenEnum(COMMAND_AUTH_SCHEMES),\n value: Type.String({ minLength: 1 }),\n});\nexport type CommandAuth = Static<typeof CommandAuth>;\n\nconst StartPayload = Type.Object({\n profile: PipelineProfile,\n spec: Type.Optional(Type.Union([Type.Object({ id: SpecId }), Type.Object({ path: Type.String() })])),\n reviewTarget: Type.Optional(\n Type.Union([\n Type.Object({ ref: Type.String() }),\n Type.Object({ base: Type.String(), head: Type.String() }),\n Type.Object({ runId: RunId }),\n ]),\n ),\n withFix: Type.Optional(Type.Boolean()),\n phases: Type.Optional(Type.Array(ActivePipelineState)),\n /** keyed by role */\n modelOverrides: Type.Optional(Type.Record(Type.String(), ModelRef)),\n runtime: Type.Optional(Type.String()),\n fakeScript: Type.Optional(Type.String()),\n unattended: Type.Boolean(),\n budgets: Type.Optional(BudgetCounters),\n sandboxRequire: Type.Optional(ClosedEnum(['native', 'best-effort'])),\n /** 2.10.1: `--trust-project-config` travels in the SIGNED start command, so the host's re-check sees the consent the CLI saw */\n consent: Type.Optional(Type.Object({ policySha256: Sha256, via: Type.Literal('cli-flag') })),\n});\n\nconst InspectPayload = Type.Object({\n target: Type.Union([\n Type.Object({ kind: Type.Literal('agent'), agentId: AgentId }),\n Type.Object({ kind: Type.Literal('context'), agentId: AgentId, incarnation: count() }),\n Type.Object({ kind: Type.Literal('approval'), approvalId: ApprovalId }),\n Type.Object({ kind: Type.Literal('effect'), effectId: EffectId }),\n Type.Object({ kind: Type.Literal('snapshot') }),\n Type.Object({ kind: Type.Literal('locks') }),\n Type.Object({ kind: Type.Literal('diff'), surface: Type.Optional(SurfaceId) }),\n Type.Object({\n kind: Type.Literal('artifact'),\n artifactId: ArtifactId,\n maxBytes: Type.Optional(\n Type.Integer({ minimum: 1, maximum: INSPECT_ARTIFACT_MAX_BYTES, default: INSPECT_ARTIFACT_DEFAULT_BYTES }),\n ),\n offset: Type.Optional(count()),\n }),\n ]),\n});\n\nexport type CommandRoute =\n /** read of the store by the CLI process itself: no inbox, no authenticator, no host needed, no lock (SIGKILL-safe) */\n | 'direct-read'\n /** the CLI validates, then ONE project transaction: putRun(IDLE) + enqueue the signed start; spawns the detached host */\n | 'start'\n /** signed, INSERT ... ON CONFLICT(command_id) DO NOTHING, poke file; the CLI waits at most `--wait` */\n | 'inbox'\n /** runs inside the CLI with no run at all */\n | 'cli-local';\n\nexport interface CommandDeclaration<P extends TSchema = TSchema> {\n readonly payload: P;\n readonly route: CommandRoute;\n /** `auth` is REQUIRED: the host answers command.rejected{security/command-auth-invalid} without it and applies nothing */\n readonly authenticated: boolean;\n /** false for the pure readers (D-23): a SIGKILL-safe reader writes nothing; its result is the document itself */\n readonly emitsResultEvent: boolean;\n}\n\nconst reader = <P extends TSchema>(payload: P, route: 'direct-read' | 'cli-local') =>\n ({ payload, route, authenticated: false, emitsResultEvent: false }) as const;\nconst mutating = <P extends TSchema, R extends 'start' | 'inbox' = 'inbox'>(payload: P, route?: R) =>\n ({ payload, route: route ?? 'inbox', authenticated: true, emitsResultEvent: true }) as const;\n\nexport const COMMANDS = {\n start: mutating(StartPayload, 'start'),\n /** no runId => ProjectStatusDocument (R4 \"current pipeline\") */\n status: reader(Type.Object({ runId: Type.Optional(RunId) }), 'direct-read'),\n inspect: reader(InspectPayload, 'direct-read'),\n tail: reader(\n Type.Object({\n sinceSequence: Type.Optional(count()),\n replay: Type.Optional(count()),\n follow: Type.Boolean(),\n ephemeral: Type.Boolean(),\n }),\n 'direct-read',\n ),\n pause: mutating(Type.Object({ reason: Type.Optional(Type.String()) })),\n resume: mutating(\n Type.Object({\n acknowledge: Type.Optional(Type.Literal('blocked-inspected')),\n raiseBudgets: Type.Optional(BudgetCounters),\n takeover: Type.Optional(Type.Boolean()),\n }),\n ),\n cancel: mutating(Type.Object({ reason: Type.Optional(Type.String()), keepWorktrees: Type.Boolean() })),\n approve: mutating(\n Type.Object({\n approvalId: ApprovalId,\n scope: ClosedEnum(['once', 'run']),\n /** required when the request carries `options`; must be one of them; echoed in the tool result */\n answer: Type.Optional(Type.String()),\n note: Type.Optional(Type.String()),\n }),\n ),\n deny: mutating(Type.Object({ approvalId: ApprovalId, note: Type.Optional(Type.String()) })),\n retry: mutating(\n Type.Object({\n target: Type.Union([\n Type.Object({ kind: Type.Literal('phase'), state: Type.Optional(ActivePipelineState) }),\n Type.Object({ kind: Type.Literal('agent'), agentId: AgentId }),\n ]),\n }),\n ),\n /** only if policy.skip lists that phase */\n skip: mutating(Type.Object({ phase: ActivePipelineState, justification: Type.String({ minLength: 1 }) })),\n /** admin; rejected unless policy.admin.runTool; still goes through the full gate chain */\n 'run-tool': mutating(\n Type.Object({\n agentId: Type.Optional(AgentId),\n tool: Type.String({ minLength: 1 }),\n input: JsonValueSchema,\n justification: Type.String({ minLength: 1 }),\n }),\n ),\n /** V3.0: 'plan' only */\n reconcile: reader(Type.Object({ mode: ClosedEnum(['plan', 'apply']) }), 'cli-local'),\n shutdown: mutating(Type.Object({ graceMs: count() })),\n /** R11: optional, policy.steer.enabled, default false */\n 'agent.send': mutating(\n Type.Object({ agentId: AgentId, text: Type.String(), delivery: ClosedEnum(['steer', 'follow-up']) }),\n ),\n} as const satisfies Record<string, CommandDeclaration>;\n\nexport type CommandType = keyof typeof COMMANDS;\nexport const COMMAND_TYPES = Object.keys(COMMANDS) as readonly CommandType[];\nexport type CommandPayloads = { [T in CommandType]: Static<(typeof COMMANDS)[T]['payload']> };\n\nexport const CommandEnvelopeBase = Type.Object({\n protocolVersion: Type.Literal(PROTOCOL_VERSION),\n /** client-generated; THE idempotency key. Same id + same body = same outcome; same id + other body = conflict/command-id-reuse */\n commandId: CommandId,\n /** narrowed per command */\n type: Type.String({ minLength: 1 }),\n runId: Type.Optional(RunId),\n issuedAt: IsoInstant,\n actor: Actor,\n /** optimistic guard: reject if the run moved past this sequence */\n expectedSequence: Type.Optional(count()),\n /** narrowed per command */\n payload: Type.Unknown(),\n auth: Type.Optional(CommandAuth),\n});\n\nexport type CommandEnvelope<T extends CommandType = CommandType> = {\n [K in T]: Omit<Static<typeof CommandEnvelopeBase>, 'type' | 'payload'> & { type: K; payload: CommandPayloads[K] };\n}[T];\n\n/** Writer side: the payload of one command type, unknown keys rejected. */\nexport function compileCommandPayload<T extends CommandType>(type: T): Validator<CommandPayloads[T]> {\n return compileSchema(COMMANDS[type].payload) as Validator<CommandPayloads[T]>;\n}\n\nconst envelopeSchemas = new Map<CommandType, TSchema>();\n\n/** Writer side: the whole envelope of one command type, unknown keys rejected at every depth. */\nexport function compileCommand<T extends CommandType>(type: T): Validator<CommandEnvelope<T>> {\n let schema = envelopeSchemas.get(type);\n if (!schema) {\n // Built from the base's own properties rather than an intersection: a closed intersection refuses every value.\n const { type: _type, payload: _payload, ...shared } = CommandEnvelopeBase.properties;\n schema = Type.Object({ ...shared, type: Type.Literal(type), payload: COMMANDS[type].payload });\n envelopeSchemas.set(type, schema);\n }\n return compileSchema(schema) as Validator<CommandEnvelope<T>>;\n}\n\n/** Published side: open envelope, one branch per known command and a catch-all (a MINOR may add commands). */\nexport function toOpenCommandsJsonSchema(): JsonValue {\n return toOpenTableSchema({\n $id: COMMANDS_SCHEMA_ID,\n title: 'Cohorte Protocol command envelope',\n base: CommandEnvelopeBase,\n discriminant: 'type',\n body: 'payload',\n rows: COMMAND_TYPES.map((type) => ({ type, body: COMMANDS[type].payload })),\n });\n}\n\n/**\n * The envelope MINUS `auth`, as canonical JSON: exactly what the authenticator covers, and the only thing `security`\n * ever sees of a command (it signs bytes, not envelopes). Key order never matters; every other field does.\n */\nexport function canonicalCommandBody(\n envelope: CommandEnvelope | (Omit<CommandEnvelope, 'auth'> & { auth?: unknown }),\n): string {\n const { auth: _auth, ...body } = envelope;\n return canonicalJson(body as JsonValue);\n}\n\n/** Controller exit codes. 4 is not an error: the inbox is durable, the command is accepted but still pending at `--wait` expiry. */\nexport const CONTROLLER_EXIT_CODES = { completed: 0, usage: 2, rejected: 3, pending: 4 } as const;\nexport type ControllerOutcome = keyof typeof CONTROLLER_EXIT_CODES;\n\n/** Default `--wait` of a controller, under the 10 s after which François kills a one-shot spawn. */\nexport const CONTROLLER_DEFAULT_WAIT_MS = 8000;\n","// DESIGN 2.3.3 — what a human or a limit decides: approvals, budgets, quotas, authentication, retries, commands.\nimport { ApprovalId, AuthMode, BudgetCounters, CommandId, ErrorInfo, JsonValueSchema, QuotaInfo } from '@cohorte/base';\nimport { Type } from 'typebox';\nimport { COMMAND_AUTH_SCHEMES, COMMAND_TYPES, CommandAuth } from '../commands.ts';\nimport { ClosedEnum, OpenEnum } from '../open-enum.ts';\nimport { ApprovalRequest } from '../refs.ts';\nimport { Actor } from '../vocabulary.ts';\nimport { count, durable, milliseconds } from './declare.ts';\n\nexport const APPROVAL_DECISIONS = ['allow-once', 'allow-for-run', 'deny', 'expired', 'superseded'] as const;\nexport const BUDGET_LEVELS = ['run', 'phase', 'agent', 'provider', 'tool'] as const;\nexport const BUDGET_THRESHOLDS = [50, 80, 100] as const;\nexport const BUDGET_COUNTER_NAMES = [\n 'tokens',\n 'modelRequests',\n 'toolCalls',\n 'wallClockMs',\n 'retries',\n 'fixRounds',\n 'contextTokens',\n 'concurrentAgents',\n 'estimatedQuotaPercent',\n] as const satisfies readonly (keyof BudgetCounters)[];\ntype Assert<T extends true> = T;\ntype _EveryCounterIsNamed = Assert<\n [keyof BudgetCounters] extends [(typeof BUDGET_COUNTER_NAMES)[number]] ? true : false\n>;\n\nexport const AUTH_REQUIRED_CAUSES = [\n 'absent',\n 'expired',\n 'refresh-failed',\n 'revoked',\n 'entitlement',\n 'mode-mismatch',\n 'ambient-source',\n] as const;\nexport const RETRY_TARGET_KINDS = ['agent', 'model-request', 'tool', 'phase'] as const;\n\nconst BudgetScope = Type.Object({ level: ClosedEnum(BUDGET_LEVELS), id: Type.String() });\n\n/** A MINOR may add commands (2.3.2), so the `type` a command event names is open on the wire. */\nconst CommandTypeName = OpenEnum(COMMAND_TYPES);\n\n/** Exported because `inspect { kind: 'approval' }` returns this payload as the decision (R6). */\nexport const ApprovalResolvedPayload = Type.Object({\n approvalId: ApprovalId,\n decision: ClosedEnum(APPROVAL_DECISIONS),\n actor: Actor,\n commandId: Type.Optional(CommandId),\n /** the authenticator of the approve / deny command, copied so that the decision stays verifiable from the journal */\n commandAuth: Type.Optional(CommandAuth),\n grantId: Type.Optional(Type.String()),\n /** one of `ApprovalRequest.options` */\n answer: Type.Optional(Type.String()),\n note: Type.Optional(Type.String()),\n});\n\nexport const GOVERNANCE_EVENTS = {\n /** R6 */\n 'approval.requested': durable(ApprovalRequest),\n 'approval.resolved': durable(ApprovalResolvedPayload),\n /** coalesced: thresholds + at most 1 per 5 s per scope */\n 'budget.updated': durable(\n Type.Object({\n scope: BudgetScope,\n consumed: BudgetCounters,\n limit: BudgetCounters,\n threshold: Type.Optional(\n Type.Unsafe<(typeof BUDGET_THRESHOLDS)[number]>({ type: 'integer', enum: [...BUDGET_THRESHOLDS] }),\n ),\n }),\n ),\n 'budget.exceeded': durable(\n Type.Object({\n scope: BudgetScope,\n counter: ClosedEnum(BUDGET_COUNTER_NAMES),\n limit: Type.Number({ minimum: 0 }),\n consumed: Type.Number({ minimum: 0 }),\n }),\n ),\n /** on change only */\n 'quota.updated': durable(Type.Object({ provider: Type.String(), authMode: AuthMode, quota: QuotaInfo })),\n 'auth.required': durable(\n Type.Object({ provider: Type.String(), cause: ClosedEnum(AUTH_REQUIRED_CAUSES), cli: Type.String() }),\n ),\n 'retry.scheduled': durable(\n Type.Object({\n target: Type.Object({ kind: ClosedEnum(RETRY_TARGET_KINDS), id: Type.String() }),\n attempt: count(),\n maxAttempts: count(),\n delayMs: milliseconds(),\n cause: ErrorInfo,\n }),\n ),\n /** `actor` as normalised by the host (2.6.7). An accepted command was authenticated: `authVerified` has one value. */\n 'command.accepted': durable(\n Type.Object({\n commandId: CommandId,\n type: CommandTypeName,\n actor: Actor,\n authVerified: Type.Literal(true),\n scheme: OpenEnum(COMMAND_AUTH_SCHEMES),\n }),\n ),\n 'command.completed': durable(Type.Object({ commandId: CommandId, type: CommandTypeName, result: JsonValueSchema })),\n 'command.rejected': durable(Type.Object({ commandId: CommandId, type: CommandTypeName, error: ErrorInfo })),\n} as const;\n","// DESIGN 2.3.3 — the run, its host, its phases and its checks.\nimport {\n AgentId,\n BudgetCounters,\n CommandId,\n EffectId,\n ErrorInfo,\n MonetaryCost,\n Sha256,\n SpecId,\n SurfaceId,\n TokenUsage,\n} from '@cohorte/base';\nimport { Type } from 'typebox';\nimport { ClosedEnum } from '../open-enum.ts';\nimport { PhaseRef, ResumeReport, RunPlan } from '../refs.ts';\nimport {\n ActivePipelineState,\n Actor,\n ArtifactRef,\n CheckResult,\n GuardOutcome,\n HaltedState,\n PipelineProfile,\n PipelineState,\n StopRecord,\n TransitionReason,\n} from '../vocabulary.ts';\nimport { count, durable, milliseconds } from './declare.ts';\n\nexport const SPEC_KINDS = ['feature', 'patch', 'review'] as const;\nexport const HOST_DETACH_CAUSES = ['exit', 'signal', 'lease-lost', 'shutdown-command', 'fatal'] as const;\nexport const PHASE_OUTCOMES = ['passed', 'failed', 'needs-human', 'skipped'] as const;\nexport const CHECKPOINT_CAUSES = ['phase-boundary', 'interval', 'pause', 'shutdown', 'pre-effect', 'fatal'] as const;\n\nexport const RUN_EVENTS = {\n 'pipeline.started': durable(\n Type.Object({\n profile: PipelineProfile,\n tableVersion: count(),\n spec: Type.Object({ id: SpecId, sha256: Sha256, kind: ClosedEnum(SPEC_KINDS) }),\n snapshotDigest: Sha256,\n runtime: Type.Object({ id: Type.String(), version: Type.String(), pinDigest: Type.String() }),\n plan: RunPlan,\n base: Type.Object({ branch: Type.String(), sha: Type.String() }),\n integrationBranch: Type.String(),\n cohorteVersion: Type.String(),\n hostId: Type.String(),\n }),\n ),\n 'pipeline.completed': durable(\n Type.Object({\n stop: StopRecord,\n integration: Type.Object({ branch: Type.String(), headSha: Type.String(), treeDigest: Type.String() }),\n totals: Type.Object({\n usage: BudgetCounters,\n tokens: TokenUsage,\n monetaryCost: MonetaryCost,\n fixRounds: count(),\n durationMs: milliseconds(),\n }),\n }),\n ),\n 'pipeline.failed': durable(\n Type.Object({ state: HaltedState, error: ErrorInfo, stop: StopRecord, checkpointSequence: count() }),\n ),\n 'run.state.changed': durable(\n Type.Object({\n transitionId: Type.String(),\n defId: Type.String(),\n tableVersion: count(),\n from: PipelineState,\n to: PipelineState,\n reason: TransitionReason,\n actor: Actor,\n guards: Type.Array(GuardOutcome),\n idempotencyKey: Type.String(),\n resumeTo: Type.Optional(ActivePipelineState),\n stop: Type.Optional(StopRecord),\n }),\n ),\n 'run.paused': durable(\n Type.Object({\n commandId: Type.Optional(CommandId),\n parkedAgents: Type.Array(AgentId),\n inFlightEffects: Type.Array(EffectId),\n }),\n ),\n 'run.resumed': durable(\n Type.Object({\n commandId: Type.Optional(CommandId),\n mode: ClosedEnum(['unpause', 'recovery', 'retry']),\n report: ResumeReport,\n }),\n ),\n 'run.cancelled': durable(\n Type.Object({\n commandId: Type.Optional(CommandId),\n reason: Type.String(),\n cancelledAgents: Type.Array(AgentId),\n worktreesKept: Type.Boolean(),\n }),\n ),\n 'run.host.attached': durable(\n Type.Object({\n hostId: Type.String(),\n pid: count(),\n cohorteVersion: Type.String(),\n fencingToken: count(),\n takeover: Type.Boolean(),\n }),\n ),\n 'run.host.detached': durable(Type.Object({ hostId: Type.String(), cause: ClosedEnum(HOST_DETACH_CAUSES) })),\n 'phase.started': durable(\n Type.Object({\n phase: PhaseRef,\n contractId: Type.String(),\n /** PhaseContract.version (DESIGN 2.5.2): a number */\n contractVersion: count(),\n planned: Type.Array(Type.Object({ agentId: AgentId, role: Type.String(), surface: Type.Optional(SurfaceId) })),\n budget: BudgetCounters,\n }),\n ),\n 'phase.completed': durable(\n Type.Object({\n phase: PhaseRef,\n outcome: ClosedEnum(PHASE_OUTCOMES),\n outputs: Type.Array(ArtifactRef),\n checks: Type.Array(CheckResult),\n durationMs: milliseconds(),\n }),\n ),\n 'check.started': durable(Type.Object({ name: Type.String(), argv: Type.Array(Type.String()), slot: Type.String() })),\n 'check.completed': durable(CheckResult),\n error: durable(Type.Object({ error: ErrorInfo, fatal: Type.Boolean() })),\n 'checkpoint.created': durable(\n Type.Object({\n atSequence: count(),\n snapshotSha256: Sha256,\n chainHash: Type.String(),\n chainMac: Type.String(),\n cause: ClosedEnum(CHECKPOINT_CAUSES),\n }),\n ),\n} as const;\n","// DESIGN 2.3.5 — ONE [S] document per `--json` output (spec 21), all computable from the store alone (R2, R4).\n// A document is a READ model: where an event payload says ClosedEnum, a document often says `string`, because it must\n// stay printable when the store was written by a later minor.\nimport {\n AgentId,\n ApprovalId,\n AuthMode,\n BudgetCounters,\n CommandId,\n EffectId,\n ErrorInfo,\n IsoInstant,\n type JsonValue,\n JsonValueSchema,\n ModelRef,\n MonetaryCost,\n PhaseRunId,\n QuotaInfo,\n RunId,\n Sha256,\n SpecId,\n SurfaceId,\n TokenUsage,\n ToolCallId,\n} from '@cohorte/base';\nimport { type Static, type TSchema, type TUnsafe, Type } from 'typebox';\nimport { COMMAND_TYPES, INSPECT_ARTIFACT_MAX_BYTES } from './commands.ts';\nimport { compileSchema, toOpenSchema, type Validator } from './compile.ts';\nimport { PROTOCOL_VERSION } from './envelope.ts';\nimport { ContextBuiltPayload } from './events/agent.ts';\nimport { ApprovalResolvedPayload } from './events/governance.ts';\nimport { ClosedEnum, OpenEnum } from './open-enum.ts';\nimport { ApprovalRequest, FileTouch, RunPlan, RuntimeRef } from './refs.ts';\nimport {\n ActivePipelineState,\n AgentState,\n ArtifactRef,\n CheckResult,\n NodeStatus,\n PipelineProfile,\n PipelineState,\n StopRecord,\n} from './vocabulary.ts';\n\nconst count = () => Type.Integer({ minimum: 0 });\nconst documentVersion = () => Type.Literal(1);\nconst protocolVersion = () => Type.Literal(PROTOCOL_VERSION);\nconst BILLING = ['plan-limits', 'metered'] as const;\n\nexport const APPROVAL_VIEW_MAX_WHAT = 512;\nexport const ApprovalView = Type.Object({\n approvalId: ApprovalId,\n kind: Type.String(),\n agentId: Type.Optional(AgentId),\n /** sealed */\n what: Type.String({ maxLength: APPROVAL_VIEW_MAX_WHAT }),\n since: IsoInstant,\n expiresAt: Type.Optional(IsoInstant),\n cli: Type.String(),\n});\nexport type ApprovalView = Static<typeof ApprovalView>;\n\nexport const AgentNode = Type.Object({\n agentId: AgentId,\n role: Type.String(),\n surface: Type.Optional(SurfaceId),\n label: Type.String(),\n status: NodeStatus,\n lifecycle: AgentState,\n attempt: count(),\n incarnation: count(),\n model: Type.Object({\n requested: ModelRef,\n effective: Type.Optional(Type.Object({ provider: Type.String(), model: Type.String() })),\n }),\n authMode: Type.Optional(AuthMode),\n worktree: Type.Optional(Type.String()),\n usage: BudgetCounters,\n summary: Type.Optional(Type.String()),\n lastError: Type.Optional(ErrorInfo),\n pendingApproval: Type.Optional(ApprovalId),\n /** R8: optional and opaque */\n runtimeRef: Type.Optional(RuntimeRef),\n});\nexport type AgentNode = Static<typeof AgentNode>;\n\nexport const PhaseNode = Type.Object({\n state: ActivePipelineState,\n label: Type.String(),\n status: NodeStatus,\n runs: Type.Array(\n Type.Object({\n phaseRunId: PhaseRunId,\n iteration: count(),\n status: NodeStatus,\n startedAt: Type.Optional(IsoInstant),\n endedAt: Type.Optional(IsoInstant),\n outcome: Type.Optional(Type.String()),\n agents: Type.Array(AgentNode),\n checks: Type.Array(CheckResult),\n }),\n ),\n});\nexport type PhaseNode = Static<typeof PhaseNode>;\n\nconst RunNode = Type.Object({\n runId: RunId,\n profile: PipelineProfile,\n title: Type.String(),\n spec: Type.Object({ id: SpecId, kind: Type.String(), sha256: Sha256 }),\n state: PipelineState,\n status: NodeStatus,\n since: IsoInstant,\n resumeTo: Type.Optional(ActivePipelineState),\n stop: Type.Optional(StopRecord),\n lastError: Type.Optional(ErrorInfo),\n iteration: Type.Object({ fixRounds: count(), maxFixRounds: count(), reviewRounds: count() }),\n host: Type.Object({\n hostId: Type.Optional(Type.String()),\n alive: Type.Boolean(),\n heartbeatAt: Type.Optional(IsoInstant),\n pid: Type.Optional(count()),\n }),\n git: Type.Object({\n base: Type.Object({ branch: Type.String(), sha: Type.String() }),\n integrationBranch: Type.String(),\n integrationHead: Type.Optional(Type.String()),\n approvedTreeDigest: Type.Optional(Type.String()),\n }),\n plan: RunPlan,\n snapshotDigest: Sha256,\n startedAt: IsoInstant,\n endedAt: Type.Optional(IsoInstant),\n});\n\n/** `cohorte status <run> --json`, `inspect { kind: 'snapshot' }`, and the first line of every stream (R2). */\nexport const RunSnapshotDocument = Type.Object({\n documentVersion: documentVersion(),\n protocolVersion: protocolVersion(),\n cohorteVersion: Type.String(),\n generatedAt: IsoInstant,\n lastSequence: count(),\n run: RunNode,\n /** table order for the profile, not-yet-run phases as 'pending' */\n phases: Type.Array(PhaseNode),\n approvals: Type.Object({ pending: Type.Array(ApprovalView), resolved: count() }),\n budgets: Type.Array(\n Type.Object({\n scope: Type.Object({ level: Type.String(), id: Type.String() }),\n consumed: BudgetCounters,\n limit: BudgetCounters,\n }),\n ),\n usage: Type.Object({\n tokens: TokenUsage,\n monetaryCost: MonetaryCost,\n byProvider: Type.Array(\n Type.Object({\n provider: Type.String(),\n authMode: AuthMode,\n billing: ClosedEnum(BILLING),\n tokens: TokenUsage,\n quota: QuotaInfo,\n accountLabel: Type.Optional(Type.String()),\n }),\n ),\n }),\n locks: Type.Array(Type.Object({ scope: Type.String(), key: Type.String(), mode: Type.String() })),\n inDoubtEffects: Type.Array(EffectId),\n});\nexport type RunSnapshotDocument = Static<typeof RunSnapshotDocument>;\n\nexport const PROJECT_RUN_SUMMARY_KEYS = [\n 'runId',\n 'profile',\n 'title',\n 'state',\n 'status',\n 'since',\n 'startedAt',\n 'endedAt',\n 'stop',\n] as const;\nexport type ProjectRunSummary = Pick<RunSnapshotDocument['run'], (typeof PROJECT_RUN_SUMMARY_KEYS)[number]>;\n/**\n * One row of `ProjectStatusDocument.runs`: a PROJECTION of `RunSnapshotDocument.run`, never a second definition.\n *\n * KEEP THE EXPLICIT ANNOTATION. Biome 2.5.14 overflows its stack when it has to INFER the type of this pick, in every\n * file that names the const, and then exits 0 having linted nothing (docs/v3/requests/U0.02.md R1).\n */\nexport const ProjectRunSummary: TUnsafe<ProjectRunSummary> = Type.Unsafe<ProjectRunSummary>(\n Type.Pick(RunNode, PROJECT_RUN_SUMMARY_KEYS),\n);\n\n/** `cohorte status --json` without a run: the \"current pipeline\" of R4. */\nexport const ProjectStatusDocument = Type.Object({\n documentVersion: documentVersion(),\n protocolVersion: protocolVersion(),\n project: Type.Object({ id: Type.String(), root: Type.String() }),\n runs: Type.Array(ProjectRunSummary),\n pendingApprovals: Type.Array(ApprovalView),\n});\nexport type ProjectStatusDocument = Static<typeof ProjectStatusDocument>;\n\n/** spec 17.1 \"diffs\"; `cohorte diff --json`. A patch is fetched with `inspect { kind: 'artifact' }`. */\nexport const RunDiffDocument = Type.Object({\n documentVersion: documentVersion(),\n runId: RunId,\n base: Type.Object({ branch: Type.String(), sha: Type.String() }),\n head: Type.Object({ branch: Type.String(), sha: Type.String(), treeDigest: Type.String() }),\n surfaces: Type.Array(\n Type.Object({\n surface: Type.Union([Type.Literal('shared'), SurfaceId]),\n files: Type.Array(FileTouch),\n stat: Type.Object({ added: count(), removed: count() }),\n patch: ArtifactRef,\n }),\n ),\n});\nexport type RunDiffDocument = Static<typeof RunDiffDocument>;\n\n/**\n * The artifact window is capped in BYTES by the command (`maxBytes` <= INSPECT_ARTIFACT_MAX_BYTES). `content` is\n * those bytes as utf8 (never more characters than bytes) or as base64 (4 characters per 3 bytes): the base64 length\n * of the byte cap bounds both.\n */\nexport const INSPECT_ARTIFACT_MAX_CONTENT_LENGTH = 4 * Math.ceil(INSPECT_ARTIFACT_MAX_BYTES / 3);\n\nconst inspectHeader = () => ({\n documentVersion: documentVersion(),\n protocolVersion: protocolVersion(),\n runId: RunId,\n lastSequence: count(),\n});\n\n/**\n * `cohorte inspect --json`: one variant per target of the `inspect` command. Every variant repeats the header instead\n * of intersecting with it: the members of an `allOf` cannot be closed (docs/v3/requests/U0.04.md R1).\n */\nexport const InspectDocument = Type.Union([\n Type.Object({\n ...inspectHeader(),\n kind: Type.Literal('agent'),\n agent: AgentNode,\n grantsDigest: Sha256,\n tools: Type.Array(Type.String()),\n incarnations: Type.Array(\n Type.Object({\n n: count(),\n state: Type.String(),\n startedAt: Type.Optional(IsoInstant),\n endedAt: Type.Optional(IsoInstant),\n stop: Type.Optional(Type.String()),\n reason: Type.Optional(Type.String()),\n }),\n ),\n }),\n /** R9 */\n Type.Object({\n ...inspectHeader(),\n kind: Type.Literal('context'),\n agentId: AgentId,\n incarnation: count(),\n context: ContextBuiltPayload,\n }),\n /** R6 */\n Type.Object({\n ...inspectHeader(),\n kind: Type.Literal('approval'),\n request: ApprovalRequest,\n status: Type.String(),\n decision: Type.Optional(ApprovalResolvedPayload),\n }),\n Type.Object({\n ...inspectHeader(),\n kind: Type.Literal('effect'),\n effect: Type.Object({\n effectId: EffectId,\n kind: Type.String(),\n replayClass: Type.String(),\n state: Type.String(),\n toolCallId: Type.Optional(ToolCallId),\n slot: Type.Optional(Type.String()),\n request: JsonValueSchema,\n result: Type.Optional(JsonValueSchema),\n error: Type.Optional(ErrorInfo),\n }),\n }),\n Type.Object({ ...inspectHeader(), kind: Type.Literal('snapshot'), document: RunSnapshotDocument }),\n Type.Object({\n ...inspectHeader(),\n kind: Type.Literal('locks'),\n locks: Type.Array(\n Type.Object({\n scope: Type.String(),\n key: Type.String(),\n mode: Type.String(),\n owner: Type.String(),\n leaseExpiresAt: IsoInstant,\n }),\n ),\n }),\n Type.Object({ ...inspectHeader(), kind: Type.Literal('diff'), diff: RunDiffDocument }),\n Type.Object({\n ...inspectHeader(),\n kind: Type.Literal('artifact'),\n artifact: ArtifactRef,\n offset: count(),\n bytes: Type.Integer({ minimum: 0, maximum: INSPECT_ARTIFACT_MAX_BYTES }),\n truncated: Type.Boolean(),\n encoding: ClosedEnum(['utf8', 'base64']),\n /** sealed at write time */\n content: Type.String({ maxLength: INSPECT_ARTIFACT_MAX_CONTENT_LENGTH }),\n }),\n]);\nexport type InspectDocument = Static<typeof InspectDocument>;\n\nexport const COMMAND_RESULT_STATUSES = ['completed', 'rejected', 'pending'] as const;\n/**\n * What every controller prints. Also `config validate`, `spec validate`, `migrate --check` and `policy explain`, whose\n * `result` is respectively the issue list, the issue list, the MigrationReport and a PolicyVerdict.\n */\nexport const CommandResultDocument = Type.Object({\n documentVersion: documentVersion(),\n commandId: CommandId,\n /** open on the wire: a MINOR may add commands */\n type: OpenEnum(COMMAND_TYPES),\n status: ClosedEnum(COMMAND_RESULT_STATUSES),\n result: Type.Optional(JsonValueSchema),\n error: Type.Optional(ErrorInfo),\n lastSequence: Type.Optional(count()),\n});\nexport type CommandResultDocument = Static<typeof CommandResultDocument>;\n\nexport const DOCTOR_CHECK_STATUSES = ['ok', 'warning', 'error', 'skipped'] as const;\n/**\n * `sandbox` and `runtimeCapabilities` are SandboxCapabilities / RuntimeCapabilities VERBATIM, carried opaque: protocol\n * imports neither `security` nor `runtime-contract` (C4). Their own schemas are published beside this one.\n */\nexport const DoctorReport = Type.Object({\n documentVersion: documentVersion(),\n cohorteVersion: Type.String(),\n generatedAt: IsoInstant,\n ok: Type.Boolean(),\n checks: Type.Array(\n Type.Object({\n id: Type.String(),\n status: OpenEnum(DOCTOR_CHECK_STATUSES),\n summary: Type.String(),\n detail: Type.Optional(Type.String()),\n remediation: Type.Optional(Type.String()),\n }),\n ),\n sandbox: JsonValueSchema,\n runtimeCapabilities: JsonValueSchema,\n});\nexport type DoctorReport = Static<typeof DoctorReport>;\n\n/** Declared here a second time, not imported from runtime-contract (C4). */\nexport const AuthStatusDocument = Type.Object({\n documentVersion: documentVersion(),\n generatedAt: IsoInstant,\n runtime: Type.Object({ id: Type.String(), version: Type.String() }),\n providers: Type.Array(\n Type.Object({\n provider: Type.String(),\n state: Type.String(),\n subscription: Type.Boolean(),\n billing: ClosedEnum([...BILLING, 'unknown']),\n source: Type.Optional(Type.String()),\n accountLabel: Type.Optional(Type.String()),\n accountLabelNote: Type.Optional(Type.String()),\n caveat: Type.Optional(Type.String()),\n checkedAt: IsoInstant,\n }),\n ),\n});\nexport type AuthStatusDocument = Static<typeof AuthStatusDocument>;\n\n/** Keyed by the published file name: `schemas/<name>.schema.json` (DESIGN 7.5 AC-07 lists them). */\nexport const DOCUMENTS = {\n 'run-state': RunSnapshotDocument,\n 'project-status': ProjectStatusDocument,\n inspect: InspectDocument,\n 'run-diff': RunDiffDocument,\n 'command-result': CommandResultDocument,\n 'doctor-report': DoctorReport,\n 'auth-status': AuthStatusDocument,\n} as const satisfies Record<string, TSchema>;\nexport type DocumentName = keyof typeof DOCUMENTS;\nexport const DOCUMENT_NAMES = Object.keys(DOCUMENTS) as readonly DocumentName[];\n\nconst DOCUMENT_TITLES: Record<DocumentName, string> = {\n 'run-state': 'Cohorte run snapshot (status <run> --json, inspect snapshot, first stream line)',\n 'project-status': 'Cohorte project status (status --json)',\n inspect: 'Cohorte inspect document (inspect --json)',\n 'run-diff': 'Cohorte run diff (diff --json)',\n 'command-result': 'Cohorte command result (every controller, and the validators)',\n 'doctor-report': 'Cohorte doctor report (doctor --json)',\n 'auth-status': 'Cohorte authentication status (auth status --json)',\n};\n\nexport type DocumentOf<N extends DocumentName> = Static<(typeof DOCUMENTS)[N]>;\n\n/** Writer side: the strict validator of one document. Every `--json` printer validates what it prints with it. */\nexport function compileDocument<N extends DocumentName>(name: N): Validator<DocumentOf<N>> {\n return compileSchema(DOCUMENTS[name]) as Validator<DocumentOf<N>>;\n}\n\nexport const documentSchemaId = (name: DocumentName): string => `https://cohorte.dev/schemas/3/${name}.schema.json`;\n\n/** Published side: the open form of one document, with its stable `$id`. */\nexport function toOpenDocumentJsonSchema(name: DocumentName): JsonValue {\n const open = toOpenSchema(DOCUMENTS[name]);\n if (typeof open !== 'object' || open === null || Array.isArray(open)) throw new TypeError(`${name}: not a schema`);\n return {\n $schema: 'https://json-schema.org/draft/2020-12/schema',\n $id: documentSchemaId(name),\n title: DOCUMENT_TITLES[name],\n ...open,\n };\n}\n","// DESIGN 2.3.3 — the two synthetic, ephemeral lines of a stream. Kept apart from the other families because\n// `snapshot` embeds a document, and documents.ts itself reads two payloads of this directory.\nimport { Type } from 'typebox';\nimport { RunSnapshotDocument } from '../documents.ts';\nimport { count, ephemeral } from './declare.ts';\n\nexport const HEARTBEAT_INTERVAL_MS = 15_000;\n\nexport const STREAM_EVENTS = {\n /** synthetic first line of every stream: a late client gets this, then the durable events after `lastSequence` */\n snapshot: ephemeral(Type.Object({ document: RunSnapshotDocument, lastSequence: count() })),\n /** every 15 s on `--follow` */\n heartbeat: ephemeral(Type.Object({ hostAlive: Type.Boolean(), lastSequence: count() })),\n} as const;\n","// DESIGN 2.3.3 — tool calls, the files they touch, and review.\nimport {\n AgentId,\n ApprovalId,\n EffectId,\n FindingId,\n JsonValueSchema,\n Sha256,\n SurfaceId,\n ToolCallId,\n} from '@cohorte/base';\nimport { Type } from 'typebox';\nimport { Finding, ReviewResult } from '../agent-output.ts';\nimport { ClosedEnum, OpenEnum } from '../open-enum.ts';\nimport { AgentRef, FileTouch, PhaseRef, SandboxReport } from '../refs.ts';\nimport { ArtifactRef } from '../vocabulary.ts';\nimport { count, durable, ephemeral, milliseconds, REPLAY_CLASSES, ReviewRef } from './declare.ts';\n\nexport const TOOL_DENIAL_STAGES = [\n 'liveness',\n 'schema',\n 'capability',\n 'path',\n 'command',\n 'network',\n 'budget',\n 'approval',\n] as const;\nexport const TOOL_REJECTION_CAUSES = ['unknown-tool', 'invalid-input', 'output-truncated'] as const;\nexport const TOOL_DECISIONS = ['allow', 'allow-once', 'allow-for-run'] as const;\nexport const FINDING_DISPOSITIONS = ['kept', 'refuted', 'deferred', 'needs-investigation', 'duplicate'] as const;\n\nconst FileAccess = Type.Object({\n toolCallId: ToolCallId,\n file: FileTouch,\n diffStat: Type.Optional(Type.Object({ added: count(), removed: count() })),\n});\n\nexport const TOOL_EVENTS = {\n /** `args` is sealed */\n 'tool.requested': durable(\n Type.Object({ toolCallId: ToolCallId, tool: Type.String(), args: JsonValueSchema, argsSha256: Sha256 }),\n ),\n 'tool.denied': durable(\n Type.Object({\n toolCallId: ToolCallId,\n tool: Type.String(),\n stage: OpenEnum(TOOL_DENIAL_STAGES),\n ruleId: Type.String(),\n reason: Type.String(),\n overridable: Type.Boolean(),\n evaluatedRules: Type.Array(Type.String()),\n approvalId: Type.Optional(ApprovalId),\n }),\n ),\n /**\n * The ENGINE refused the call before the host saw it: no `toolCallId`, no gate, no rule ids — which is why it is\n * not a `tool.denied`. `message` is sealed.\n */\n 'tool.rejected': durable(\n Type.Object({\n engineToolCallId: Type.Optional(Type.String()),\n tool: Type.String(),\n cause: OpenEnum(TOOL_REJECTION_CAUSES),\n message: Type.String(),\n }),\n ),\n 'tool.started': durable(\n Type.Object({\n toolCallId: ToolCallId,\n tool: Type.String(),\n effectId: EffectId,\n decision: ClosedEnum(TOOL_DECISIONS),\n ruleId: Type.String(),\n grantId: Type.Optional(Type.String()),\n normalizedArgs: JsonValueSchema,\n replayClass: ClosedEnum(REPLAY_CLASSES),\n sandbox: SandboxReport,\n /** marks a host-side replay of an approved call (4.5) */\n replayOfApproval: Type.Optional(ApprovalId),\n }),\n ),\n 'tool.progress': ephemeral(\n Type.Object({ toolCallId: ToolCallId, text: Type.Optional(Type.String()), bytes: Type.Optional(count()) }),\n ),\n 'tool.completed': durable(\n Type.Object({\n toolCallId: ToolCallId,\n tool: Type.String(),\n effectId: EffectId,\n isError: Type.Boolean(),\n exitCode: Type.Optional(Type.Integer()),\n signal: Type.Optional(Type.String()),\n timedOut: Type.Boolean(),\n durationMs: milliseconds(),\n /** time the runtime waited for the host, from the delivery of the call */\n waitedMs: milliseconds(),\n output: Type.Object({\n sha256: Sha256,\n bytes: count(),\n truncated: Type.Boolean(),\n preview: Type.String(),\n artifact: Type.Optional(ArtifactRef),\n }),\n filesTouched: Type.Array(FileTouch),\n /** hits dropped by output filtering (2.7) */\n filteredPaths: Type.Optional(count()),\n replayed: Type.Boolean(),\n }),\n ),\n 'file.read': durable(FileAccess),\n 'file.written': durable(FileAccess),\n 'file.changed': durable(\n Type.Object({\n slot: Type.String(),\n files: Type.Array(FileTouch),\n detectedBy: ClosedEnum(['post-command-scan', 'ledger-audit']),\n attributedTo: Type.Optional(ToolCallId),\n }),\n ),\n 'review.started': durable(\n Type.Object({\n phase: PhaseRef,\n reviewRef: ReviewRef,\n surfaces: Type.Array(SurfaceId),\n reviewers: Type.Array(AgentId),\n }),\n ),\n 'review.finding': durable(\n Type.Object({ finding: Finding, reviewer: AgentRef, disposition: ClosedEnum(FINDING_DISPOSITIONS) }),\n ),\n 'review.completed': durable(\n Type.Object({\n verdict: ReviewResult.properties.verdict,\n blocking: count(),\n blockingItems: Type.Array(Type.String()),\n fingerprint: ReviewResult.properties.fingerprint,\n unreviewed: Type.Array(SurfaceId),\n counts: ReviewResult.properties.counts,\n clean: Type.Boolean(),\n }),\n ),\n 'review.approved': durable(\n Type.Object({\n reviewRef: ReviewRef,\n waivers: Type.Array(Type.Object({ findingId: FindingId, approvalId: ApprovalId })),\n }),\n ),\n} as const;\n","// DESIGN 2.3.2 / 2.3.3 — the EVENTS table IS the catalogue of Cohorte Protocol 1.0: one declaration per event type\n// (payload schema + durability). No `effect.*` type (effect-journal rows are not events), no engine identifier.\n// Changing the durability of a row, removing a row or adding a required field is a MAJOR.\nimport { bindCatalogue } from './compile.ts';\nimport type { DurableTypeOf, EnvelopeOf, EventTable, PayloadOf } from './envelope.ts';\nimport { AGENT_EVENTS } from './events/agent.ts';\nimport { GIT_EVENTS } from './events/git.ts';\nimport { GOVERNANCE_EVENTS } from './events/governance.ts';\nimport { RUN_EVENTS } from './events/run.ts';\nimport { STREAM_EVENTS } from './events/stream.ts';\nimport { TOOL_EVENTS } from './events/tool.ts';\n\nexport const EVENTS = {\n ...RUN_EVENTS,\n ...AGENT_EVENTS,\n ...TOOL_EVENTS,\n ...GOVERNANCE_EVENTS,\n ...GIT_EVENTS,\n ...STREAM_EVENTS,\n} as const satisfies EventTable;\n\nexport type EventType = keyof typeof EVENTS;\nexport type Payload<T extends EventType> = PayloadOf<typeof EVENTS, T>;\nexport type Envelope<T extends EventType = EventType> = EnvelopeOf<typeof EVENTS, T>;\n/** The only types a reducer may consume (C5): `evolve` takes `Envelope<DurableEventType>`. */\nexport type DurableEventType = DurableTypeOf<typeof EVENTS>;\nexport type EphemeralEventType = Exclude<EventType, DurableEventType>;\n\nexport const EVENT_TYPES = Object.keys(EVENTS) as readonly EventType[];\nexport const DURABLE_EVENT_TYPES = EVENT_TYPES.filter(\n (type) => EVENTS[type].durability === 'durable',\n) as readonly DurableEventType[];\n\nexport const isEventType = (type: string): type is EventType => Object.hasOwn(EVENTS, type);\nexport const isDurableEventType = (type: string): type is DurableEventType =>\n isEventType(type) && EVENTS[type].durability === 'durable';\n\n/**\n * `compileStrict(type)`, `compileStrictEnvelope(type)` and `toOpenJsonSchema()` with the exact signatures of\n * DESIGN 2.3.2, bound to EVENTS. The functions of the same names in compile.ts are generic over a table.\n */\nexport const catalogue = bindCatalogue(EVENTS);\n"],"mappings":";;;;;;AAGA,MAAa,oBAAoB;AASjC,MAAM,WAAW,QAA2B,SAA2B;CACrE,IAAI,OAAO,WAAW,GAAG,MAAM,IAAI,WAAW,GAAG,KAAK,iCAAiC;CACvF,IAAI,IAAI,IAAI,MAAM,CAAC,CAAC,SAAS,OAAO,QAClC,MAAM,IAAI,WAAW,GAAG,KAAK,wBAAwB,OAAO,KAAK,IAAI,EAAE,EAAE;CAC3E,OAAO,CAAC,GAAG,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AM,KAAK,OAAO;GAAE,WAAW;GAAW,YAAY;EAAW,CAAC,CAAC;CACnF,CAAC,CACH;AACF;;;ACxIA,MAAa,SAAS;CACpB,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL;AAS2B,OAAO,KAAK,MACJ,CAAA,CAAY,QAC5C,SAAS,OAAO,KAAK,CAAC,eAAe,SACxC;AAEA,MAAa,eAAe,SAAoC,OAAO,OAAO,QAAQ,IAAI;AAC1F,MAAa,sBAAsB,SACjC,YAAY,IAAI,KAAK,OAAO,KAAK,CAAC,eAAe;;;;;AAMnD,MAAa,YAAY,cAAc,MAAM"}
@@ -0,0 +1,29 @@
1
+ import { N as errorOf, j as CohorteError } from "./src-Cu3TxNob.mjs";
2
+ import { n as writeHuman } from "./render-DyZr5Lgi.mjs";
3
+ import { join } from "node:path";
4
+ import { existsSync } from "node:fs";
5
+ //#region src/commands/status/index.ts
6
+ const status = {
7
+ verb: "status",
8
+ async run(ctx, args) {
9
+ if (!existsSync(join(ctx.cwd, ".cohorte", "project.yaml"))) throw new CohorteError(errorOf("configuration/unexpected", `not a Cohorte project: ${ctx.cwd}`));
10
+ const store = await ctx.openStore();
11
+ const runId = args.positionals[0];
12
+ const value = runId ? await store.getRun(runId) : await store.listRuns({
13
+ limit: 100,
14
+ offset: 0
15
+ });
16
+ try {
17
+ if (args.json) ctx.stdio.stdout.write(`${JSON.stringify(value)}\n`);
18
+ else if (Array.isArray(value)) for (const run of value) writeHuman(ctx, `${run.runId} ${run.state}`);
19
+ else writeHuman(ctx, value ? `${value.runId} ${value.state}` : "run not found");
20
+ return value === void 0 ? 1 : 0;
21
+ } finally {
22
+ await store.close();
23
+ }
24
+ }
25
+ };
26
+ //#endregion
27
+ export { status as default };
28
+
29
+ //# sourceMappingURL=status-SMjiOMYy.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status-SMjiOMYy.mjs","names":[],"sources":["../../../../apps/cli/src/commands/status/index.ts"],"sourcesContent":["// apps/cli/src/commands/status/index.ts — DESIGN §9 verb `status` (PLAN §3 rule 3 \"later units fill\n// stub files that lie inside their owned paths; they never edit ... the registry\"). Wave-0 stub: exits with the\n// documented not-available error (spec 24 `configuration/phase-not-available`); filled by the Wave-4/5\n// unit that owns `apps/cli/src/commands/status/**`.\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { CohorteError, errorOf } from '@cohorte/base';\nimport type { CommandModule } from '../../contract/index.ts';\nimport { writeHuman } from '../../render/index.ts';\n\nconst status: CommandModule = {\n verb: 'status',\n async run(ctx, args) {\n if (!existsSync(join(ctx.cwd, '.cohorte', 'project.yaml')))\n throw new CohorteError(errorOf('configuration/unexpected', `not a Cohorte project: ${ctx.cwd}`));\n const store = await ctx.openStore();\n const runId = args.positionals[0];\n const value = runId ? await store.getRun(runId as never) : await store.listRuns({ limit: 100, offset: 0 });\n try {\n if (args.json) ctx.stdio.stdout.write(`${JSON.stringify(value)}\\n`);\n else if (Array.isArray(value)) for (const run of value) writeHuman(ctx, `${run.runId} ${run.state}`);\n else writeHuman(ctx, value ? `${value.runId} ${value.state}` : 'run not found');\n return value === undefined ? 1 : 0;\n } finally {\n await store.close();\n }\n },\n};\n\nexport default status;\n"],"mappings":";;;;;AAUA,MAAM,SAAwB;CAC5B,MAAM;CACN,MAAM,IAAI,KAAK,MAAM;EACnB,IAAI,CAAC,WAAW,KAAK,IAAI,KAAK,YAAY,cAAc,CAAC,GACvD,MAAM,IAAI,aAAa,QAAQ,4BAA4B,0BAA0B,IAAI,KAAK,CAAC;EACjG,MAAM,QAAQ,MAAM,IAAI,UAAU;EAClC,MAAM,QAAQ,KAAK,YAAY;EAC/B,MAAM,QAAQ,QAAQ,MAAM,MAAM,OAAO,KAAc,IAAI,MAAM,MAAM,SAAS;GAAE,OAAO;GAAK,QAAQ;EAAE,CAAC;EACzG,IAAI;GACF,IAAI,KAAK,MAAM,IAAI,MAAM,OAAO,MAAM,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;QAC7D,IAAI,MAAM,QAAQ,KAAK,GAAG,KAAK,MAAM,OAAO,OAAO,WAAW,KAAK,GAAG,IAAI,MAAM,GAAG,IAAI,OAAO;QAC9F,WAAW,KAAK,QAAQ,GAAG,MAAM,MAAM,GAAG,MAAM,UAAU,eAAe;GAC9E,OAAO,UAAU,KAAA,IAAY,IAAI;EACnC,UAAU;GACR,MAAM,MAAM,MAAM;EACpB;CACF;AACF"}
@@ -0,0 +1,25 @@
1
+ import { n as writeHuman } from "./render-DyZr5Lgi.mjs";
2
+ //#region src/commands/tail/index.ts
3
+ const tail = {
4
+ verb: "tail",
5
+ async run(ctx, args) {
6
+ const runId = args.positionals[0];
7
+ if (!runId) return 2;
8
+ const store = await ctx.openStore();
9
+ const events = await store.readEvents(runId, {
10
+ afterSequence: 0,
11
+ limit: 1e3
12
+ });
13
+ try {
14
+ for (const event of events) if (args.json) ctx.stdio.stdout.write(`${JSON.stringify(event)}\n`);
15
+ else writeHuman(ctx, JSON.stringify(event));
16
+ return 0;
17
+ } finally {
18
+ await store.close();
19
+ }
20
+ }
21
+ };
22
+ //#endregion
23
+ export { tail as default };
24
+
25
+ //# sourceMappingURL=tail-BuhT-2PH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tail-BuhT-2PH.mjs","names":[],"sources":["../../../../apps/cli/src/commands/tail/index.ts"],"sourcesContent":["// apps/cli/src/commands/tail/index.ts — DESIGN §9 verb `tail` (PLAN §3 rule 3 \"later units fill\n// stub files that lie inside their owned paths; they never edit ... the registry\"). Wave-0 stub: exits with the\n// documented not-available error (spec 24 `configuration/phase-not-available`); filled by the Wave-4/5\n// unit that owns `apps/cli/src/commands/tail/**`.\nimport type { CommandModule } from '../../contract/index.ts';\nimport { writeHuman } from '../../render/index.ts';\n\nconst tail: CommandModule = {\n verb: 'tail',\n async run(ctx, args) {\n const runId = args.positionals[0];\n if (!runId) return 2;\n const store = await ctx.openStore();\n const events = await store.readEvents(runId as never, { afterSequence: 0, limit: 1000 });\n try {\n for (const event of events) {\n if (args.json) ctx.stdio.stdout.write(`${JSON.stringify(event)}\\n`);\n else writeHuman(ctx, JSON.stringify(event));\n }\n return 0;\n } finally {\n await store.close();\n }\n },\n};\n\nexport default tail;\n"],"mappings":";;AAOA,MAAM,OAAsB;CAC1B,MAAM;CACN,MAAM,IAAI,KAAK,MAAM;EACnB,MAAM,QAAQ,KAAK,YAAY;EAC/B,IAAI,CAAC,OAAO,OAAO;EACnB,MAAM,QAAQ,MAAM,IAAI,UAAU;EAClC,MAAM,SAAS,MAAM,MAAM,WAAW,OAAgB;GAAE,eAAe;GAAG,OAAO;EAAK,CAAC;EACvF,IAAI;GACF,KAAK,MAAM,SAAS,QAClB,IAAI,KAAK,MAAM,IAAI,MAAM,OAAO,MAAM,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;QAC7D,WAAW,KAAK,KAAK,UAAU,KAAK,CAAC;GAE5C,OAAO;EACT,UAAU;GACR,MAAM,MAAM,MAAM;EACpB;CACF;AACF"}
@@ -0,0 +1,16 @@
1
+ //#region src/commands/update/index.ts
2
+ const update = {
3
+ verb: "update",
4
+ async run(ctx, args) {
5
+ if (!args.positionals.includes("--check")) return 10;
6
+ ctx.stdio.stdout.write(`${JSON.stringify({
7
+ install: ctx.install.installDir(),
8
+ updateAvailable: false
9
+ })}\n`);
10
+ return 0;
11
+ }
12
+ };
13
+ //#endregion
14
+ export { update as default };
15
+
16
+ //# sourceMappingURL=update-BXIppsbi.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-BXIppsbi.mjs","names":[],"sources":["../../../../apps/cli/src/commands/update/index.ts"],"sourcesContent":["// apps/cli/src/commands/update/index.ts — DESIGN §9 verb `update` (PLAN §3 rule 3 \"later units fill\n// stub files that lie inside their owned paths; they never edit ... the registry\"). Wave-0 stub: exits with the\n// documented not-available error (spec 24 `configuration/phase-not-available`); filled by the Wave-4/5\n// unit that owns `apps/cli/src/commands/update/**`.\nimport type { CommandModule } from '../../contract/index.ts';\n\nconst update: CommandModule = {\n verb: 'update',\n async run(ctx, args) {\n if (!args.positionals.includes('--check')) return 10;\n ctx.stdio.stdout.write(`${JSON.stringify({ install: ctx.install.installDir(), updateAvailable: false })}\\n`);\n return 0;\n },\n};\n\nexport default update;\n"],"mappings":";AAMA,MAAM,SAAwB;CAC5B,MAAM;CACN,MAAM,IAAI,KAAK,MAAM;EACnB,IAAI,CAAC,KAAK,YAAY,SAAS,SAAS,GAAG,OAAO;EAClD,IAAI,MAAM,OAAO,MAAM,GAAG,KAAK,UAAU;GAAE,SAAS,IAAI,QAAQ,WAAW;GAAG,iBAAiB;EAAM,CAAC,EAAE,GAAG;EAC3G,OAAO;CACT;AACF"}
package/dist/cli.mjs ADDED
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env node
2
+ import { F as EXIT_CODE_BY_CLASS, P as toErrorInfo } from "./chunks/src-Cu3TxNob.mjs";
3
+ import { n as formatExitCodesHelp, t as VERBS } from "./chunks/contract-B0ra2-bm.mjs";
4
+ import { r as CONTROLLER_EXIT_CODES } from "./chunks/src-s7YRvk0t.mjs";
5
+ import { Command, CommanderError } from "commander";
6
+ //#region src/lazy.ts
7
+ /**
8
+ * One LITERAL specifier per verb, closed over a thunk. A computed specifier (`` import(`./commands/${verb}/…`) ``)
9
+ * is invisible to every bundler: rolldown would leave the template in `dist/cli.mjs` and emit no verb chunk, so the
10
+ * SHIPPED cli could not execute a single verb (it would try to load a `.ts` file next to `dist/`). Written out, each
11
+ * specifier is statically analysable: rolldown code-splits one chunk per verb, laziness is preserved, and
12
+ * `apps/cli/test/registry/lazy.test.ts` pins this map against `VERBS` in both directions so a verb added to the
13
+ * registry without a loader — or the reverse — fails Wave 0's own check.
14
+ */
15
+ const COMMAND_MODULES = Object.freeze({
16
+ init: () => import("./chunks/init-Okz4mlhW.mjs"),
17
+ doctor: () => import("./chunks/doctor-DfCrKpfT.mjs"),
18
+ discover: () => import("./chunks/discover-30Ciya_0.mjs"),
19
+ run: () => import("./chunks/run-CgTWYlcd.mjs"),
20
+ status: () => import("./chunks/status-SMjiOMYy.mjs"),
21
+ inspect: () => import("./chunks/inspect-Buby4cQD.mjs"),
22
+ resume: () => import("./chunks/resume-GJQRb2Eb.mjs"),
23
+ pause: () => import("./chunks/pause-BASBfKLO.mjs"),
24
+ cancel: () => import("./chunks/cancel-KV_cpsqS.mjs"),
25
+ shutdown: () => import("./chunks/shutdown-BM92Iyv2.mjs"),
26
+ approve: () => import("./chunks/approve-Cv135UqI.mjs"),
27
+ deny: () => import("./chunks/deny-ClTxSvHJ.mjs"),
28
+ retry: () => import("./chunks/retry-CLrUem1H.mjs"),
29
+ skip: () => import("./chunks/skip-DZG5kpcH.mjs"),
30
+ logs: () => import("./chunks/logs-Giq5sUau.mjs"),
31
+ tail: () => import("./chunks/tail-BuhT-2PH.mjs"),
32
+ diff: () => import("./chunks/diff-Qw0II0sj.mjs"),
33
+ review: () => import("./chunks/review-BDdjb6kB.mjs"),
34
+ fix: () => import("./chunks/fix-D4Tj8RVA.mjs"),
35
+ ship: () => import("./chunks/ship-DTuLGoaJ.mjs"),
36
+ auth: () => import("./chunks/auth-D8rCVY33.mjs"),
37
+ providers: () => import("./chunks/providers-Dx78imKj.mjs"),
38
+ models: () => import("./chunks/models-Btp6X2YZ.mjs"),
39
+ config: () => import("./chunks/config-DefHA2Lw.mjs"),
40
+ migrate: () => import("./chunks/migrate-DRoFUg53.mjs"),
41
+ reconcile: () => import("./chunks/reconcile-BfD785gd.mjs"),
42
+ spec: () => import("./chunks/spec-Bq0P3jVh.mjs"),
43
+ policy: () => import("./chunks/policy-DUIgzF3W.mjs"),
44
+ gc: () => import("./chunks/gc-BBXlBF5w.mjs"),
45
+ update: () => import("./chunks/update-BXIppsbi.mjs"),
46
+ brainstorm: () => import("./chunks/brainstorm-CU10T1tm.mjs"),
47
+ "run-tool": () => import("./chunks/run-tool-C3rAv4XF.mjs"),
48
+ send: () => import("./chunks/send-BdnJ85Nz.mjs"),
49
+ __host: () => import("./chunks/__host-DgGPyco9.mjs")
50
+ });
51
+ /** Loads `commands/<verb>/index.ts` and returns its default export. */
52
+ async function loadCommandModule(verb) {
53
+ const load = COMMAND_MODULES[verb];
54
+ if (!load) throw new RangeError(`lazy.ts: no command module registered for verb "${verb}"`);
55
+ const mod = await load();
56
+ if (!mod.default || typeof mod.default.run !== "function") throw new TypeError(`lazy.ts: commands/${verb}/index.ts has no default CommandModule export`);
57
+ return mod.default;
58
+ }
59
+ /**
60
+ * The one `import(` of `./compose/index.ts` (DESIGN 1.2 net 3 rule g): `cli.ts` reaches the real `CliContext`
61
+ * only through here, so a read-only verb whose action never runs never pays for it either (DESIGN 1.3).
62
+ */
63
+ async function loadCliContext(inputs) {
64
+ const mod = await import("./chunks/compose-Cr0hP0qm.mjs");
65
+ if (typeof mod.composeCliContext !== "function") throw new TypeError("lazy.ts: compose/index.ts has no composeCliContext export");
66
+ return mod.composeCliContext(inputs);
67
+ }
68
+ //#endregion
69
+ //#region src/cli.ts
70
+ /** Mirrors `apps/cli/package.json` "version"; `apps/cli/test/registry/version.test.ts` reads that file and fails
71
+ * if the two ever drift (a literal keeps `--version` free of any file read on the one-shot start-up path). */
72
+ const COHORTE_VERSION = "3.0.0-dev.0";
73
+ function printError(deps, info) {
74
+ deps.stderr.write(`error: ${info.code}: ${info.message}\n`);
75
+ deps.stderr.write(`impact: ${info.impact}\n`);
76
+ deps.stderr.write(`next action: ${info.remediation}\n`);
77
+ }
78
+ /** Loads the verb's module, builds its `CliContext` and runs it, converting any throw at this one boundary
79
+ * (DESIGN 2.8: "Every error has ... an exit code"; the module itself never writes to stdio on error). */
80
+ async function dispatch(deps, verb, args) {
81
+ try {
82
+ const mod = await loadCommandModule(verb);
83
+ const ctx = await deps.context();
84
+ return await mod.run(ctx, args);
85
+ } catch (error) {
86
+ const info = toErrorInfo(error, {
87
+ code: "configuration/unexpected",
88
+ class: "configuration"
89
+ });
90
+ printError(deps, info);
91
+ return EXIT_CODE_BY_CLASS[info.class];
92
+ }
93
+ }
94
+ function addAction(command, deps, exit, verb, subVerb) {
95
+ command.allowUnknownOption(true).allowExcessArguments(true);
96
+ if (verb.json) command.option("--json", "print the machine-readable document for this verb (DESIGN 2.3.5)");
97
+ command.argument("[args...]", "verb arguments").action(async (positionals, options) => {
98
+ const args = {
99
+ positionals,
100
+ options,
101
+ json: Boolean(options.json),
102
+ ...subVerb === void 0 ? {} : { subVerb }
103
+ };
104
+ exit.code = await dispatch(deps, verb.name, args);
105
+ });
106
+ }
107
+ /** Builds the whole commander tree. Exported so a test can assert on `--help` / registration without spawning a
108
+ * process (PLAN U0.10 test list: "every DESIGN §9 verb is registered exactly once and appears in --help"). */
109
+ function buildProgram(deps, exit) {
110
+ const program = new Command("cohorte").description("Cohorte: a durable multi-agent development pipeline with a runtime-independent orchestrator.").version(COHORTE_VERSION, "--version", "print the Cohorte version").exitOverride().configureOutput({
111
+ writeOut: (str) => deps.stdout.write(str),
112
+ writeErr: (str) => deps.stderr.write(str)
113
+ }).addHelpText("after", `\n${formatExitCodesHelp()}\n`);
114
+ for (const verb of VERBS) {
115
+ const sub = program.command(verb.name, verb.hidden ? { hidden: true } : void 0).description(verb.summary);
116
+ if (verb.subVerbs && verb.subVerbs.length > 0) {
117
+ addAction(sub, deps, exit, verb);
118
+ for (const subVerb of verb.subVerbs) addAction(sub.command(subVerb), deps, exit, verb, subVerb);
119
+ } else addAction(sub, deps, exit, verb);
120
+ }
121
+ return program;
122
+ }
123
+ /**
124
+ * `CONTROLLER_EXIT_CODES.usage` (2) for anything commander itself refuses (bad flag, unknown command, no command at
125
+ * all), `completed` (0) for the routes where commander did exactly what was asked and then stopped the parse.
126
+ *
127
+ * Keyed off commander's OWN `exitCode`, not off the code NAME: commander raises `commander.help` both for the
128
+ * advertised `help [command]` route (which prints the help and means exit 0) and for a bare `cohorte` with no
129
+ * command (exit 1 there — a usage error), and an allow-list of names got the first case wrong while `--help`,
130
+ * raising `commander.helpDisplayed`, was right. `error.exitCode` already separates the two.
131
+ */
132
+ function commanderExitCode(error) {
133
+ return error.exitCode === 0 ? CONTROLLER_EXIT_CODES.completed : CONTROLLER_EXIT_CODES.usage;
134
+ }
135
+ /** Parses `argv` (no leading node/script entries) and runs the matched verb. Never calls `process.exit`: the
136
+ * caller (`main()` below, or a test) owns that decision. */
137
+ async function runCli(argv, deps) {
138
+ const exit = { code: CONTROLLER_EXIT_CODES.completed };
139
+ const program = buildProgram(deps, exit);
140
+ try {
141
+ await program.parseAsync(argv, { from: "user" });
142
+ } catch (error) {
143
+ if (error instanceof CommanderError) return commanderExitCode(error);
144
+ throw error;
145
+ }
146
+ return exit.code;
147
+ }
148
+ async function realContext() {
149
+ return loadCliContext({
150
+ cwd: process.cwd(),
151
+ env: process.env,
152
+ stdio: {
153
+ stdout: process.stdout,
154
+ stderr: process.stderr,
155
+ stdin: process.stdin
156
+ }
157
+ });
158
+ }
159
+ async function main() {
160
+ const deps = {
161
+ stdout: process.stdout,
162
+ stderr: process.stderr,
163
+ context: realContext
164
+ };
165
+ const code = await runCli(process.argv.slice(2), deps);
166
+ process.exitCode = code;
167
+ }
168
+ if (import.meta.main) main().catch((error) => {
169
+ process.stderr.write(`fatal: ${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
170
+ process.exitCode = 1;
171
+ });
172
+ //#endregion
173
+ export { COHORTE_VERSION, buildProgram, runCli };
174
+
175
+ //# sourceMappingURL=cli.mjs.map