minicode-ai 0.11.0 → 0.13.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 (221) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -66
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +17 -7
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +598 -133
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -165
  221. package/docs/USAGE.md +0 -11
@@ -0,0 +1,293 @@
1
+ // PHASE 6U — PRODUCTION SCHEDULER COMPOSITION.
2
+ //
3
+ // This is the first phase allowed to make the Scheduler reachable from
4
+ // production. It is NOT the enablement phase: the gate is OFF by default and
5
+ // nothing about ordinary MiniCode execution changes.
6
+ //
7
+ // ── WHY A SEPARATE MODULE ────────────────────────────────────────────────────
8
+ //
9
+ // The composition root needs to own seven things at once — scheduler lifecycle,
10
+ // trigger, the autonomous adapter, session ownership, cancellation, shutdown and
11
+ // the enablement gate. Threading that through `cli/setup.ts` (1500+ lines that
12
+ // already build providers, MCP, LSP, RAG, presentation and shadow-git state) would
13
+ // bury the one thing a reader most needs to check: whether the gate is consulted
14
+ // BEFORE anything is constructed.
15
+ //
16
+ // So the policy lives here, in a module small enough to read in full, and
17
+ // `cli/setup.ts` calls exactly one function from it — behind a flag that defaults
18
+ // to false.
19
+ //
20
+ // ── THE CENTRAL INVARIANT ────────────────────────────────────────────────────
21
+ //
22
+ // > Scheduler must remain completely inert when autonomous scheduling is disabled.
23
+ //
24
+ // [DESIGN DECISION] The gate is checked BEFORE construction, not after. The
25
+ // alternative — build the Scheduler, then refuse to activate it — satisfies the
26
+ // letter of "inert" while still opening a SQLite handle, registering a
27
+ // cancellation listener and allocating a trigger coordinator on every single
28
+ // run. The mission's disabled-mode invariants (zero claims, zero child sessions,
29
+ // zero triggers, zero background resources, and P1's "no Scheduler construction")
30
+ // are only *structurally* satisfiable if nothing is built.
31
+ //
32
+ // [DESIGN DECISION] Dependencies arrive as a THUNK. `deps()` is not called when
33
+ // disabled, which is what makes "no DB handle, no provider, no session factory
34
+ // touched" a property of the control flow rather than a promise in a comment.
35
+
36
+ import {
37
+ type AutonomousAdapterConfig,
38
+ type AutonomousExecutionBinding,
39
+ buildAutonomousRunTurn,
40
+ } from "./autonomous-adapter.ts"
41
+ import type { ContinuityGate } from "./continuity.ts"
42
+ import { type CancelReason, Scheduler, type SchedulerEvent } from "./scheduler.ts"
43
+ import { onSessionInvalidated, releaseSessionOwnershipFor } from "./session-ownership.ts"
44
+ import type { TaskStore } from "./store.ts"
45
+ import type { TriggerEvent, TriggerResult, TriggerSource } from "./trigger.ts"
46
+ import { TriggerCoordinator } from "./trigger.ts"
47
+
48
+ /** The single enablement mechanism. Default OFF. */
49
+ export const SCHEDULER_FLAG = "--enable-scheduler"
50
+
51
+ export type SchedulerGateSource = "cli-flag" | "absent"
52
+
53
+ /**
54
+ * [PHASE 6U][DESIGN DECISION] EXACTLY ONE gate: a CLI boolean flag.
55
+ *
56
+ * The alternatives were each rejected against the requirement "cannot be
57
+ * accidentally inherited from unrelated configuration":
58
+ *
59
+ * - **Environment variable.** Rejected. `process.env` is inherited by every child
60
+ * this runtime spawns — sub-agents (`src/tools/task.ts`), MCP servers
61
+ * (`src/mcp/server.ts`), LSP servers. A sub-agent that inherited the gate would
62
+ * build its own Scheduler for the same session, and `acquireSessionOwnership`
63
+ * would fail closed and leave a stopped instance holding nothing. Inheritable by
64
+ * construction, and the inheritance is exactly the accident the requirement
65
+ * forbids.
66
+ * - **Config file.** Rejected. `~/.minicode/config.json` is global, so enabling
67
+ * it once would silently enable it for every project on the machine. The
68
+ * repo-local `.minicode/config.json` is gated behind `--allow-local-config`, but
69
+ * once a user passes that flag for an unrelated reason, a repository could ship
70
+ * a config that turns autonomous execution on. That is unrelated configuration
71
+ * with a scheduling consequence.
72
+ * - **Runtime setting.** Rejected. Nothing reads a scheduler setting at runtime,
73
+ * and a mutable runtime switch could not stop a *live* turn anyway without the
74
+ * polling loop 6T rejected in ADR-14.
75
+ *
76
+ * A CLI flag is per-invocation, is not in `process.env`, is not read from any file,
77
+ * and must be typed by whoever runs the process. It is also the only one of the
78
+ * four that a process-boundary test can vary without a fixture.
79
+ */
80
+ export interface SchedulerGate {
81
+ readonly enabled: boolean
82
+ readonly source: SchedulerGateSource
83
+ }
84
+
85
+ export const GATE_DISABLED: SchedulerGate = { enabled: false, source: "absent" }
86
+ export const GATE_ENABLED: SchedulerGate = { enabled: true, source: "cli-flag" }
87
+
88
+ /**
89
+ * Resolve the gate from an argv array.
90
+ *
91
+ * Parsed here rather than in `cli/index.ts` so the rule is testable without
92
+ * spawning a process, and so there is exactly one place that knows what enables
93
+ * the Scheduler. Anything other than the literal flag — a config key, an env var,
94
+ * a default — leaves it off.
95
+ */
96
+ export function resolveSchedulerGate(argv: readonly string[]): SchedulerGate {
97
+ // Exact token match, and nothing else. Deliberately NOT `argv.includes`-with-
98
+ // fuzzy-matching and NOT `--enable-scheduler=false` semantics: the flag has no
99
+ // value form, so `--enable-scheduler=anything` does not enable it.
100
+ //
101
+ // [PHASE 6X] The scan also STOPS at `--`, which `Array.prototype.some` did not.
102
+ // `--` is the conventional end-of-options marker, and everything after it is the
103
+ // user's prompt text, not flags. Without this, `minicode "explain -- --enable-scheduler"`
104
+ // would switch autonomous execution ON from inside a quoted prompt - a fail-open
105
+ // from a non-flag position, and strictly worse than the value-form bug it fixed.
106
+ // `hasFlag` already behaved this way, so this preserves the pre-6X parsing shape
107
+ // while making the flag itself strict.
108
+ for (const token of argv) {
109
+ if (token === "--") break
110
+ if (token === SCHEDULER_FLAG) return GATE_ENABLED
111
+ }
112
+ return GATE_DISABLED
113
+ }
114
+
115
+ /**
116
+ * [PHASE 6U] The CALL SITE's whole decision, in one testable line.
117
+ *
118
+ * [DESIGN DECISION] `cli/setup.ts` calls this rather than assembling argv itself.
119
+ * Without it, the production call site was a *tested module plus an untested
120
+ * expression*, and mutation M2 ("make it default-on") survived every test in the
121
+ * suite — the module was covered, the wiring was not. A one-line seam that the
122
+ * tests can reach is the difference between "the policy is correct" and "the
123
+ * policy is correct AND the product calls it correctly".
124
+ *
125
+ * Anything other than literal `true` is OFF. `undefined` — the ordinary case, a
126
+ * process that never passed the flag — is off by construction rather than by
127
+ * defaulting.
128
+ */
129
+ export function schedulerGateFor(enabled: boolean | undefined): SchedulerGate {
130
+ return enabled === true ? GATE_ENABLED : GATE_DISABLED
131
+ }
132
+
133
+ /** Everything the composition root needs — but ONLY if the gate is open. */
134
+ export interface ProductionSchedulerDeps {
135
+ readonly sessionId: string
136
+ readonly cwd: string
137
+ readonly store: TaskStore
138
+ readonly instruction: string
139
+ readonly adapter: AutonomousAdapterConfig
140
+ /** Reads the durable binding for a task at claim time. */
141
+ readonly bindingFor: (taskId: string) => AutonomousExecutionBinding
142
+ readonly model?: string
143
+ /** P2.2: token otoritas milik composition root (satu penulis per boot).
144
+ * Diteruskan ke Scheduler agar sesi + scheduler-nya memakai lease yang
145
+ * sama; absen = perilaku lama (Scheduler mint sendiri). */
146
+ readonly authorityToken?: string
147
+ /**
148
+ * [P13.3 Stage C] Retry-safety evidence for automatic reconciliation.
149
+ *
150
+ * ABSENT means HOLD, not legacy recovery: the composition root must prove
151
+ * that a fresh attempt cannot repeat unsafe external effects.
152
+ */
153
+ readonly continuity?: ContinuityGate
154
+ readonly onSchedulerEvent?: (e: SchedulerEvent) => void
155
+ readonly onTriggerEvent?: (e: TriggerEvent) => void
156
+ }
157
+
158
+ /**
159
+ * The handle production code holds.
160
+ *
161
+ * [DESIGN DECISION] Every method is safe to call when disabled, and every one
162
+ * reports `null`/`false` rather than throwing. A caller that forgets to check the
163
+ * gate gets an inert object, not a crash — a missing `if` must degrade to "nothing
164
+ * happens", never to "autonomous execution runs because the error was swallowed".
165
+ */
166
+ export interface ProductionSchedulerHandle {
167
+ readonly enabled: boolean
168
+ /** [PHASE 6U] §13's headline invariant, readable by tests and operators. */
169
+ readonly constructed: boolean
170
+ /** True between activation and stop. */
171
+ isActive(): boolean
172
+ /** Request an evaluation. `null` when disabled. */
173
+ fire(source: TriggerSource): Promise<TriggerResult | null>
174
+ /** Cancel the live execution and release everything. Idempotent. */
175
+ stop(reason: CancelReason): Promise<void>
176
+ /** Session deletion notification. Idempotent, safe after stop. */
177
+ notifySessionDeleted(): Promise<void>
178
+ getScheduler(): Scheduler | null
179
+ getTrigger(): TriggerCoordinator | null
180
+ }
181
+
182
+ /** The inert handle. Allocates nothing beyond the object itself. */
183
+ function inertHandle(gate: SchedulerGate): ProductionSchedulerHandle {
184
+ return {
185
+ enabled: gate.enabled,
186
+ constructed: false,
187
+ isActive: () => false,
188
+ fire: () => Promise.resolve(null),
189
+ stop: () => Promise.resolve(),
190
+ notifySessionDeleted: () => Promise.resolve(),
191
+ getScheduler: () => null,
192
+ getTrigger: () => null,
193
+ }
194
+ }
195
+
196
+ /**
197
+ * [PHASE 6U] THE PRODUCTION COMPOSITION ROOT.
198
+ *
199
+ * `deps` is a thunk and is invoked only when the gate is open. That single fact
200
+ * is what makes disabled mode provably free: not "we decided not to use the
201
+ * store" but "we never asked for it".
202
+ */
203
+ export async function createProductionScheduler(
204
+ gate: SchedulerGate,
205
+ deps: () => ProductionSchedulerDeps | Promise<ProductionSchedulerDeps>,
206
+ ): Promise<ProductionSchedulerHandle> {
207
+ if (!gate.enabled) return inertHandle(gate)
208
+
209
+ // ── construction ───────────────────────────────────────────────────────────
210
+ // [DESIGN DECISION] Awaited, because a real composition root may need async
211
+ // imports (TaskStore, the 6S matrix) before it can describe its dependencies.
212
+ const d = await deps()
213
+
214
+ // [DESIGN DECISION] The tool set is NOT recomputed here. It comes from the
215
+ // caller's dapter.tools, and uildAutonomousRunTurn validates it against
216
+ // the 6S matrix's own ssertAutonomousToolScope at construction. Deriving it
217
+ // here would create a THIRD copy of one policy, furthest from the tests that
218
+ // justify it and therefore most likely to drift.
219
+
220
+ const scheduler = new Scheduler(d.sessionId, {
221
+ store: d.store,
222
+ runTurn: buildAutonomousRunTurn(d.bindingFor, d.adapter),
223
+ instruction: d.instruction,
224
+ ...(d.model ? { model: d.model } : {}),
225
+ // P2.2: teruskan token komposisi (bila ada) — satu penulis per boot.
226
+ ...(d.authorityToken ? { authorityToken: d.authorityToken } : {}),
227
+ ...(d.continuity ? { continuity: d.continuity } : {}),
228
+ ...(d.onSchedulerEvent ? { onEvent: d.onSchedulerEvent } : {}),
229
+ })
230
+
231
+ const trigger = new TriggerCoordinator({
232
+ runCycle: () => scheduler.cycle(),
233
+ isRunning: () => scheduler.getLifecycle() === "RUNNING" || scheduler.getLifecycle() === "IDLE",
234
+ ...(d.onTriggerEvent ? { onEvent: d.onTriggerEvent } : {}),
235
+ })
236
+
237
+ // ── activation ─────────────────────────────────────────────────────────────
238
+ //
239
+ // Separate from construction, and separately observable: `constructed` is true
240
+ // here while `isActive()` is still false until `start()` succeeds. That gap is
241
+ // deliberate — it is where a future activation policy (a health check, a budget
242
+ // ceiling) would sit without touching construction.
243
+ let active = false
244
+ scheduler.start()
245
+ active = true
246
+
247
+ // ── cancellation wiring ────────────────────────────────────────────────────
248
+ //
249
+ // [DESIGN DECISION] Reuse `session-ownership`'s existing per-session channel
250
+ // rather than introducing a second process-local registry. That module is
251
+ // ALREADY the process's per-session authority, it is already consulted by the
252
+ // Scheduler, and 6Q's design refused to add a registry precisely so that
253
+ // deletion works without one. A scheduler that holds a deletion subscription
254
+ // under the same authority that already gates its reconciliation keeps those two
255
+ // facts in one place.
256
+ //
257
+ // [DESIGN DECISION] Cancel BEFORE stop, and idempotently. A turn that is still
258
+ // unwinding when `stop()` awaits the cycle is exactly the case where the abort
259
+ // has to have been sent first.
260
+ let stopping = false
261
+ const unsubscribe = onSessionInvalidated(d.sessionId, () => {
262
+ // Fire-and-forget: the notification must not block the deletion path, and the
263
+ // abort itself is synchronous. `stop()` completes on its own.
264
+ void handle.stop("session-deleted")
265
+ })
266
+
267
+ const handle: ProductionSchedulerHandle = {
268
+ enabled: true,
269
+ constructed: true,
270
+ isActive: () => active && !stopping,
271
+ fire: (source) => (handle.isActive() ? trigger.fire(source) : Promise.resolve(null)),
272
+ async stop(reason) {
273
+ if (stopping) return
274
+ stopping = true
275
+ active = false
276
+ // 1. stop accepting triggers
277
+ trigger.dispose()
278
+ // 2. signal the live execution
279
+ scheduler.cancelActive(reason)
280
+ // 3. bounded wait for the cycle to unwind, then release authority
281
+ await trigger.awaitSettled()
282
+ await scheduler.stop()
283
+ // 4. release the process-local authority for this session
284
+ unsubscribe()
285
+ releaseSessionOwnershipFor(d.sessionId, "scheduler")
286
+ },
287
+ notifySessionDeleted: () => handle.stop("session-deleted"),
288
+ getScheduler: () => scheduler,
289
+ getTrigger: () => trigger,
290
+ }
291
+
292
+ return handle
293
+ }
@@ -0,0 +1,229 @@
1
+ // TaskGraph readiness and blockers — Phase 5C.
2
+ //
3
+ // NEW ARCHITECTURE. Implements design lock S7 (dependency satisfaction),
4
+ // S8 (readiness) and S9 (blockers) of
5
+ // `PHASE-5B-TASKGRAPH-NEW-ARCHITECTURE-DESIGN-LOCK.md`.
6
+ //
7
+ // PURE (design lock S22). No TaskStore access, no filesystem, no process
8
+ // state, no randomness, no identity allocation, no status mutation.
9
+ //
10
+ // THE CENTRAL RULE: readiness is DERIVED. `TaskStore` coerces a written
11
+ // "READY" to `PENDING` (verified), so a durable `READY` cannot exist and this
12
+ // module must never pretend to persist one.
13
+ //
14
+ // NO `PAUSED`. `TaskStatus` contains exactly eight values; this module refers
15
+ // only to those. `READY` is not one of them either — it is a derived answer,
16
+ // not a status.
17
+
18
+ import type { Diagnostic, GraphNode, RelationAnalysis } from "./graph-validate.ts"
19
+ import type { TaskStatus } from "./model.ts"
20
+
21
+ export type BlockerKind =
22
+ | "DEPENDENCY_UNSATISFIED"
23
+ | "DEPENDENCY_TERMINAL"
24
+ | "DEPENDENCY_CYCLE"
25
+ | "DANGLING_DEPENDENCY"
26
+ | "PARENT_MISSING"
27
+ | "PARENT_CYCLE"
28
+ | "SELF_REFERENCE"
29
+
30
+ export interface Blocker {
31
+ readonly kind: BlockerKind
32
+ readonly relation: "dependency" | "parent"
33
+ /** The task that causes the block; `""` for a self-reference (design lock S9). */
34
+ readonly taskId: string
35
+ /** Temporary blockers may resolve on their own; permanent ones need an operator. */
36
+ readonly permanent: boolean
37
+ /** Human-readable, explicitly non-contractual. */
38
+ readonly detail: string
39
+ }
40
+
41
+ /**
42
+ * Why a task is or is not ready (design lock S9, AMENDED by Phase 5C.1).
43
+ *
44
+ * FIVE states, not four. The original 5B union could not name the case of a
45
+ * durably-`BLOCKED` task with zero derived blockers: such a task IS eligible
46
+ * (so `eligibleTasks()` lists it) yet is never ready, and the four-state union
47
+ * forced it to be mislabelled `not-eligible` — the very negation of eligibility.
48
+ * `eligible-not-ready` states the distinction the public API must preserve:
49
+ *
50
+ * eligible != ready
51
+ *
52
+ * The set is exhaustive and mutually exclusive for a VALID graph and a known id:
53
+ * - no blockers + PENDING -> `ready`
54
+ * - blockers (any status) -> `blocked`
55
+ * - no blockers + eligible but not PENDING -> `eligible-not-ready`
56
+ * - no blockers + not eligible -> `not-eligible`
57
+ * - invalid graph -> `graph-invalid`
58
+ *
59
+ * Durable status is NOT a blocker: a cancelled task is *not eligible*, not
60
+ * *blocked*. Conflating the two is what would let a durably-`BLOCKED` task be
61
+ * reported ready.
62
+ */
63
+ export type NotReady =
64
+ | { readonly kind: "ready" }
65
+ | { readonly kind: "eligible-not-ready"; readonly status: TaskStatus }
66
+ | { readonly kind: "not-eligible"; readonly status: TaskStatus }
67
+ | { readonly kind: "blocked"; readonly blockers: readonly Blocker[] }
68
+ | { readonly kind: "graph-invalid"; readonly diagnostics: readonly Diagnostic[] }
69
+
70
+ /** Statuses that can never satisfy a dependency (design lock S7). */
71
+ const TERMINAL_STATUSES: ReadonlySet<TaskStatus> = new Set<TaskStatus>(["CANCELLED", "FAILED"])
72
+
73
+ /** Statuses from which a task is *eligible* for readiness (design lock S8). */
74
+ const ELIGIBLE_STATUSES: ReadonlySet<TaskStatus> = new Set<TaskStatus>(["PENDING", "BLOCKED"])
75
+
76
+ /**
77
+ * A dependency is satisfied by completion and by nothing else (design lock S7).
78
+ *
79
+ * `FAILED` and `CANCELLED` deliberately do NOT satisfy. Treating them as
80
+ * satisfied would claim finished work that does not exist, and the failure
81
+ * mode is asymmetric: a false negative merely leaves a task unready, a false
82
+ * positive executes dependent work on a false premise.
83
+ */
84
+ export function dependencySatisfied(dependency: GraphNode): boolean {
85
+ return dependency.status === "COMPLETED"
86
+ }
87
+
88
+ /**
89
+ * `PENDING` and `BLOCKED` are eligible; nothing else is.
90
+ *
91
+ * `BLOCKED` being *eligible* is what lets the graph model "this could become
92
+ * ready once its cause is resolved" while still never reporting it ready.
93
+ */
94
+ export function eligibleForReadiness(node: GraphNode): boolean {
95
+ return ELIGIBLE_STATUSES.has(node.status)
96
+ }
97
+
98
+ /** True when a task is in a state from which it will never proceed. */
99
+ export function isTerminalStatus(status: TaskStatus): boolean {
100
+ return TERMINAL_STATUSES.has(status)
101
+ }
102
+
103
+ /**
104
+ * Every reason `node` is not ready, derived from its relations.
105
+ *
106
+ * A task with no blockers is a candidate for readiness, but readiness still
107
+ * requires `status === "PENDING"` (see `isReady`) — so `BLOCKED` with an empty
108
+ * blocker list is reported as not ready, never as ready.
109
+ *
110
+ * Precedence, and why:
111
+ * 1. Cycle membership first — a member of a dependency cycle can never be
112
+ * satisfied regardless of its status, so that is the dominant reason.
113
+ * 2. Terminal before merely-unsatisfied, so an operator sees the actionable
114
+ * "this will not proceed" rather than a misleading "still working on it".
115
+ */
116
+ export function computeBlockers(
117
+ node: GraphNode,
118
+ byId: ReadonlyMap<string, GraphNode>,
119
+ analysis: RelationAnalysis,
120
+ ): readonly Blocker[] {
121
+ const blockers: Blocker[] = []
122
+
123
+ // --- containment: STRUCTURE, never an execution gate (design lock S5) ----
124
+ if (node.parentId !== null) {
125
+ if (node.parentId === node.id) {
126
+ blockers.push({
127
+ kind: "SELF_REFERENCE",
128
+ relation: "parent",
129
+ taskId: "",
130
+ permanent: true,
131
+ detail: `task ${node.id} is its own parent`,
132
+ })
133
+ } else if (!byId.has(node.parentId)) {
134
+ blockers.push({
135
+ kind: "PARENT_MISSING",
136
+ relation: "parent",
137
+ taskId: node.parentId,
138
+ permanent: true,
139
+ detail: `parent ${node.parentId} is not present in the snapshot`,
140
+ })
141
+ } else if (analysis.parentCycleMembers.has(node.id)) {
142
+ blockers.push({
143
+ kind: "PARENT_CYCLE",
144
+ relation: "parent",
145
+ taskId: node.id,
146
+ permanent: true,
147
+ detail: `task ${node.id} participates in a containment cycle`,
148
+ })
149
+ }
150
+ }
151
+
152
+ // --- dependencies: EXECUTION --------------------------------------------
153
+ const counted = new Set<string>()
154
+ for (const depId of node.dependsOn) {
155
+ if (depId === node.id) {
156
+ blockers.push({
157
+ kind: "SELF_REFERENCE",
158
+ relation: "dependency",
159
+ taskId: "",
160
+ permanent: true,
161
+ detail: `task ${node.id} depends on itself`,
162
+ })
163
+ continue
164
+ }
165
+ // A duplicated dependency is already an INVALID graph; do not emit the
166
+ // same blocker twice.
167
+ if (counted.has(depId)) continue
168
+ counted.add(depId)
169
+
170
+ const dependency = byId.get(depId)
171
+ if (dependency === undefined) {
172
+ blockers.push({
173
+ kind: "DANGLING_DEPENDENCY",
174
+ relation: "dependency",
175
+ taskId: depId,
176
+ permanent: true,
177
+ detail: `dependency ${depId} is not present in the snapshot`,
178
+ })
179
+ continue
180
+ }
181
+ if (analysis.dependencyCycleMembers.has(depId)) {
182
+ blockers.push({
183
+ kind: "DEPENDENCY_CYCLE",
184
+ relation: "dependency",
185
+ taskId: depId,
186
+ permanent: true,
187
+ detail: `dependency ${depId} is part of a dependency cycle and can never be satisfied`,
188
+ })
189
+ continue
190
+ }
191
+ if (dependencySatisfied(dependency)) continue
192
+ if (isTerminalStatus(dependency.status)) {
193
+ blockers.push({
194
+ kind: "DEPENDENCY_TERMINAL",
195
+ relation: "dependency",
196
+ taskId: depId,
197
+ permanent: true,
198
+ detail: `dependency ${depId} is ${dependency.status} and will not proceed`,
199
+ })
200
+ continue
201
+ }
202
+ blockers.push({
203
+ kind: "DEPENDENCY_UNSATISFIED",
204
+ relation: "dependency",
205
+ taskId: depId,
206
+ permanent: false,
207
+ detail: `dependency ${depId} is ${dependency.status}`,
208
+ })
209
+ }
210
+
211
+ return blockers
212
+ }
213
+
214
+ /**
215
+ * Ready means: `PENDING` AND no blockers AND the graph is structurally valid.
216
+ *
217
+ * The `status === "PENDING"` clause is the whole point of the design. It makes
218
+ * it *unconstructible* for a durably-`BLOCKED` task to be reported ready, which
219
+ * is the contradiction the design lock forbids (S13).
220
+ */
221
+ export function isReady(
222
+ node: GraphNode,
223
+ byId: ReadonlyMap<string, GraphNode>,
224
+ analysis: RelationAnalysis,
225
+ ): boolean {
226
+ if (!analysis.valid) return false
227
+ if (node.status !== "PENDING") return false
228
+ return computeBlockers(node, byId, analysis).length === 0
229
+ }