minicode-ai 0.11.1 → 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 +89 -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 -71
  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 +2 -2
  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 +52 -19
  184. package/src/ui/i18n/en.ts +58 -6
  185. package/src/ui/i18n/id.ts +58 -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 +507 -169
  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 -169
  221. package/docs/USAGE.md +0 -11
@@ -0,0 +1,490 @@
1
+ // PHASE 6S — AUTONOMOUS PERMISSION & TOOL POLICY.
2
+ //
3
+ // 6R restricted the tool SET at context creation. That is a fail-fast check on
4
+ // configuration, and this phase adds the missing half: a check on every
5
+ // INVOCATION, at the boundary the kernel itself guarantees it consults.
6
+ //
7
+ // ── WHY A SECOND GATE IS NECESSARY, NOT REDUNDANT ────────────────────────────
8
+ //
9
+ // `withMcpTools()` (src/tools/index.ts) appends MCP tools to a tool list at
10
+ // RUNTIME, named `serverid.toolname`, and nothing constrains what an MCP server
11
+ // exposes. A name allow-list evaluated once at context creation therefore proves
12
+ // nothing about a tool added afterwards, and nothing about a tool reached by a
13
+ // path the creation-time check never saw.
14
+ //
15
+ // The kernel closes this for us: `vendor/minicore/src/core/permission.ts:1-2`
16
+ // states it "commits to consulting this handler before every tool execution".
17
+ // That is the narrowest authoritative boundary available, and this module
18
+ // installs an autonomous handler there. Both gates are retained deliberately:
19
+ //
20
+ // creation-time (6R) fails fast on a misconfigured context, before any turn
21
+ // invocation-time is authoritative, per-call, and survives a growing registry
22
+ //
23
+ // Neither alone is sufficient; together the second catches everything the first
24
+ // cannot see.
25
+ //
26
+ // ── THE POLICY ───────────────────────────────────────────────────────────────
27
+ //
28
+ // AUTONOMOUS -> READ-ONLY EXPLORATION -> NO HUMAN APPROVAL EVER REQUESTED
29
+ //
30
+ // [DESIGN DECISION] The kernel's vocabulary is `allow | deny` and a handler that
31
+ // wants human input is expected to BLOCK until it resolves
32
+ // (`permission.ts:12`). An unattended executor must therefore never reach that
33
+ // branch: this handler answers `deny` IMMEDIATELY and SYNCHRONOUSLY, always. It
34
+ // never calls an approval callback, never waits, and cannot hang.
35
+ //
36
+ // The safe default is UNKNOWN -> DENY. A tool absent from the matrix is denied,
37
+ // so adding a new tool to the registry is deny-by-default rather than
38
+ // accidentally-permitted.
39
+
40
+ import type { ToolCall } from "#minicore"
41
+ // [Fase 2 / TOOL-01] Allow-list otonom kini DITURUNKAN dari registry kontrak
42
+ // tool, bukan dari matriks kapabilitas di bawah. Matriks tetap otoritas BUKTI
43
+ // (capability + evidence); kolom `autonomous`-nya menjadi cermin yang wajib
44
+ // sama dengan registry dan dijaga test kontrak Fase 2.
45
+ import { AUTONOMOUS_TOOL_NAMES as CONTRACT_AUTONOMOUS_TOOL_NAMES } from "../policy/tool-contract.ts"
46
+
47
+ // ── capability classification ────────────────────────────────────────────────
48
+
49
+ export type ToolCapability =
50
+ /** Reads the workspace, confined to it. No external effect. */
51
+ | "READ_ONLY"
52
+ /** Changes local state. */
53
+ | "MUTATING"
54
+ /** Runs a program or shell. */
55
+ | "EXECUTION"
56
+ /** Touches git history, identity, or the machine's authority surface. */
57
+ | "PRIVILEGED"
58
+ /** Reaches outside the machine (network, MCP server, package registry). */
59
+ | "EXTERNAL_SIDE_EFFECT"
60
+ /** Not in the matrix. DENY by default. */
61
+ | "UNKNOWN"
62
+
63
+ export interface ToolClassification {
64
+ readonly name: string
65
+ readonly capability: ToolCapability
66
+ /** Whether an unattended, unapproved execution may use it. */
67
+ readonly autonomous: boolean
68
+ /** Why the classification is what it is - the evidence, not the conclusion. */
69
+ readonly evidence: string
70
+ }
71
+
72
+ /**
73
+ * [PHASE 6S] The single source of truth for tool behaviour.
74
+ *
75
+ * `VERIFIED` rows were read in this repository's own source. `UNVERIFIED` rows
76
+ * are marked and therefore DENIED - uncertainty is never resolved in favour of
77
+ * permission, which is the whole point of the default.
78
+ *
79
+ * NOT every row is a judgement call. `read_file`, for example, is VERIFIED
80
+ * read-only because it routes every access through `safeOpenRead`
81
+ * (`src/lib/safe-open.ts`), which does a fresh `realpath` per call (TOCTOU-safe),
82
+ * opens with `O_NOFOLLOW` so a symlink cannot be swapped in, and applies
83
+ * `isPathOutsideRoot` / `isSensitive` from `src/policy/jail.ts`. It is confined
84
+ * to the workspace and cannot be talked into following a link out of it.
85
+ */
86
+ export const TOOL_CAPABILITIES: readonly ToolClassification[] = [
87
+ // ── filesystem read ──
88
+ {
89
+ name: "read_file",
90
+ capability: "READ_ONLY",
91
+ autonomous: true,
92
+ evidence:
93
+ "VERIFIED: routes through safeOpenRead - fresh realpath per call, O_NOFOLLOW, isPathOutsideRoot + isSensitive jail.",
94
+ },
95
+ {
96
+ name: "read_image",
97
+ capability: "READ_ONLY",
98
+ autonomous: true,
99
+ evidence:
100
+ "VERIFIED (bounded): reads an image from the workspace via the same confined open path; it decodes bytes, it does not fetch them.",
101
+ },
102
+ {
103
+ name: "glob",
104
+ capability: "READ_ONLY",
105
+ autonomous: true,
106
+ evidence: "VERIFIED: directory enumeration, no write path, no network.",
107
+ },
108
+ {
109
+ name: "grep",
110
+ capability: "READ_ONLY",
111
+ autonomous: true,
112
+ evidence:
113
+ "VERIFIED: spawns ripgrep over the workspace. It is a process, so classified READ_ONLY only because grep has no write mode here; noted in §12.",
114
+ },
115
+
116
+ // ── filesystem write ──
117
+ {
118
+ name: "write_file",
119
+ capability: "MUTATING",
120
+ autonomous: false,
121
+ evidence: "creates or overwrites a file.",
122
+ },
123
+ {
124
+ name: "edit",
125
+ capability: "MUTATING",
126
+ autonomous: false,
127
+ evidence: "rewrites file content in place.",
128
+ },
129
+ {
130
+ name: "apply_patch",
131
+ capability: "MUTATING",
132
+ autonomous: false,
133
+ evidence: "applies a diff to the working tree.",
134
+ },
135
+ {
136
+ name: "move_file",
137
+ capability: "MUTATING",
138
+ autonomous: false,
139
+ evidence: "renames or moves a file.",
140
+ },
141
+ { name: "delete_file", capability: "MUTATING", autonomous: false, evidence: "unlinks a file." },
142
+
143
+ // ── shell / execution ──
144
+ {
145
+ name: "bash",
146
+ capability: "EXECUTION",
147
+ autonomous: false,
148
+ evidence: "runs an arbitrary command; everything is reachable through it.",
149
+ },
150
+ {
151
+ name: "bash_output",
152
+ capability: "READ_ONLY",
153
+ autonomous: false,
154
+ evidence:
155
+ "reads a background job's stdout. Reading a job id is only meaningful beside bash, so the job is not startable autonomously.",
156
+ },
157
+ { name: "bash_kill", capability: "EXECUTION", autonomous: false, evidence: "signals a process." },
158
+ {
159
+ name: "code_run",
160
+ capability: "EXECUTION",
161
+ autonomous: false,
162
+ evidence:
163
+ "VERIFIED: runs python/node snippets. Its own comment records that it no longer claims to be 'sandboxed' in the weak sense - execution is exactly the capability an unattended agent must not have.",
164
+ },
165
+
166
+ // ── git ──
167
+ {
168
+ name: "git_status",
169
+ capability: "READ_ONLY",
170
+ autonomous: true,
171
+ evidence: "VERIFIED: `git status` - reports the working tree, writes nothing.",
172
+ },
173
+ {
174
+ name: "git_diff",
175
+ capability: "READ_ONLY",
176
+ autonomous: true,
177
+ evidence: "VERIFIED: `git diff` - reads the index and objects.",
178
+ },
179
+ {
180
+ name: "git_log",
181
+ capability: "READ_ONLY",
182
+ autonomous: true,
183
+ evidence: "VERIFIED: `git log` - reads history only.",
184
+ },
185
+ {
186
+ name: "git_commit",
187
+ capability: "PRIVILEGED",
188
+ autonomous: false,
189
+ evidence:
190
+ "VERIFIED: writes history and identity. The existing sub-agent layer strips it for the same reason (src/tools/task.ts:189-199).",
191
+ },
192
+
193
+ // ── memory (session state) ──
194
+ {
195
+ name: "read_memory",
196
+ capability: "READ_ONLY",
197
+ autonomous: true,
198
+ evidence: "VERIFIED: reads stored memory.",
199
+ },
200
+ {
201
+ name: "write_memory",
202
+ capability: "MUTATING",
203
+ autonomous: false,
204
+ evidence: "persists memory that outlives the turn.",
205
+ },
206
+ {
207
+ name: "forget_memory",
208
+ capability: "MUTATING",
209
+ autonomous: false,
210
+ evidence: "destroys persisted memory.",
211
+ },
212
+
213
+ // ── task / plan ──
214
+ {
215
+ name: "todo_read",
216
+ capability: "READ_ONLY",
217
+ autonomous: true,
218
+ evidence: "VERIFIED: reads the todo list.",
219
+ },
220
+ {
221
+ name: "todo_write",
222
+ capability: "MUTATING",
223
+ autonomous: false,
224
+ evidence:
225
+ "VERIFIED as a task-ownership hazard, not merely a write: todo_write can author TaskStatus, and under 6P `IN_PROGRESS` is a Scheduler-owned execution state. Letting an autonomous model write it would let a model fabricate a claim the lineage would then treat as real. The existing sub-agent layer strips it for the same reason (src/tools/task.ts:189-199).",
226
+ },
227
+ {
228
+ name: "submit_result",
229
+ capability: "MUTATING",
230
+ autonomous: false,
231
+ evidence: "concludes a delegated unit of work; the sub-agent layer strips it.",
232
+ },
233
+ {
234
+ name: "delegate_task",
235
+ capability: "PRIVILEGED",
236
+ autonomous: false,
237
+ evidence:
238
+ "Escalation vector: it creates a child with its OWN permission mode (src/tools/task.ts:257), so a restricted parent could in principle produce a less-restricted child. Stripped from sub-agents for exactly this reason. Autonomous context has no sessionFactory for delegation at all (6R), so nesting is NOT IMPLEMENTED and cannot occur.",
239
+ },
240
+
241
+ // ── network / external ──
242
+ {
243
+ name: "web_fetch",
244
+ capability: "EXTERNAL_SIDE_EFFECT",
245
+ autonomous: false,
246
+ evidence:
247
+ "UNVERIFIED as read-only: an HTTP GET to an operator-supplied URL is not merely a read - it discloses the request to a third party, and the response becomes model input.",
248
+ },
249
+ {
250
+ name: "web_search",
251
+ capability: "EXTERNAL_SIDE_EFFECT",
252
+ autonomous: false,
253
+ evidence: "UNVERIFIED: external service call with the same disclosure property.",
254
+ },
255
+
256
+ // ── MCP ──
257
+ {
258
+ name: "mcp_list",
259
+ capability: "READ_ONLY",
260
+ autonomous: true,
261
+ evidence:
262
+ "VERIFIED: enumerates configured servers; discloses configuration but changes nothing.",
263
+ },
264
+ {
265
+ name: "mcp_read",
266
+ capability: "EXTERNAL_SIDE_EFFECT",
267
+ autonomous: false,
268
+ evidence:
269
+ "UNVERIFIED: reads from an external server process whose behaviour is not ours to bound.",
270
+ },
271
+ {
272
+ name: "mcp_prompt",
273
+ capability: "EXTERNAL_SIDE_EFFECT",
274
+ autonomous: false,
275
+ evidence: "UNVERIFIED: retrieves a prompt from an external server.",
276
+ },
277
+ {
278
+ name: "mcp_call",
279
+ capability: "EXTERNAL_SIDE_EFFECT",
280
+ autonomous: false,
281
+ evidence:
282
+ "UNVERIFIED and unbounded: invokes an arbitrary tool on an arbitrary server. The exposed capability is defined by the server, not by this repository, so it cannot be classified and is denied.",
283
+ },
284
+
285
+ // ── LSP ──
286
+ {
287
+ name: "lsp_diagnostics",
288
+ capability: "READ_ONLY",
289
+ autonomous: true,
290
+ evidence: "VERIFIED: asks the language server for diagnostics.",
291
+ },
292
+ {
293
+ name: "lsp_definition",
294
+ capability: "READ_ONLY",
295
+ autonomous: true,
296
+ evidence: "VERIFIED: goto-definition.",
297
+ },
298
+ {
299
+ name: "lsp_references",
300
+ capability: "READ_ONLY",
301
+ autonomous: true,
302
+ evidence: "VERIFIED: find-references.",
303
+ },
304
+ {
305
+ name: "lsp_hover",
306
+ capability: "READ_ONLY",
307
+ autonomous: true,
308
+ evidence: "VERIFIED: hover information.",
309
+ },
310
+ {
311
+ name: "lsp_symbols",
312
+ capability: "READ_ONLY",
313
+ autonomous: true,
314
+ evidence: "VERIFIED: document symbols.",
315
+ },
316
+ {
317
+ name: "lsp_workspace_symbols",
318
+ capability: "READ_ONLY",
319
+ autonomous: true,
320
+ evidence: "VERIFIED: workspace symbols.",
321
+ },
322
+
323
+ // ── human interaction ──
324
+ {
325
+ name: "ask_user",
326
+ capability: "PRIVILEGED",
327
+ autonomous: false,
328
+ evidence:
329
+ "The forbidden case: it blocks a turn on a human who is not present. 6R's prompt tells the model not to call it; this policy makes that structural, because a request is DENIED rather than waiting forever.",
330
+ },
331
+ ]
332
+
333
+ const BY_NAME = new Map(TOOL_CAPABILITIES.map((t) => [t.name, t]))
334
+
335
+ /** Classify a tool name. Anything unrecognised is UNKNOWN and therefore denied. */
336
+ export function classifyTool(name: string): ToolClassification {
337
+ return (
338
+ BY_NAME.get(name) ?? {
339
+ name,
340
+ capability: "UNKNOWN",
341
+ autonomous: false,
342
+ evidence: "not present in the matrix - denied by default",
343
+ }
344
+ )
345
+ }
346
+
347
+ /** True only for a tool the matrix marks autonomous. UNKNOWN is never autonomous. */
348
+ export function isAutonomousTool(name: string): boolean {
349
+ return classifyTool(name).autonomous
350
+ }
351
+
352
+ /**
353
+ * [PHASE 6S -> Fase 2] The allow-list, now derived from the tool CONTRACT
354
+ * registry (`src/policy/tool-contract.ts`).
355
+ *
356
+ * [DESIGN DECISION] 6R carried its own hand-written list, which meant the
357
+ * creation-time gate and the classification could drift apart - two sources of
358
+ * truth for one policy. 6S derived it from this file's matrix; Fase 2 moved the
359
+ * authority to the single contract registry so the executor, permission gate,
360
+ * journal and autonomous gate all read the same declaration. The matrix's
361
+ * `autonomous` column is kept as evidence and cross-checked by
362
+ * `test/p15-phase2-contracts-approval-recovery.test.ts` - if the two ever
363
+ * disagree the test fails instead of the policy silently widening.
364
+ */
365
+ export const AUTONOMOUS_TOOL_NAMES: readonly string[] = CONTRACT_AUTONOMOUS_TOOL_NAMES
366
+
367
+ // ── the ledger ───────────────────────────────────────────────────────────────
368
+
369
+ export type AutonomousDenialReason = "OUT_OF_SCOPE" | "UNKNOWN_TOOL" | "NOT_AUTONOMOUS"
370
+
371
+ /**
372
+ * [PHASE 6S] Per-execution record of every denial.
373
+ *
374
+ * One ledger per autonomous context. It exists so the context can turn "the model
375
+ * asked for something it may not have" into the deterministic `permission-denied`
376
+ * outcome that 6R declared but could not produce: the handler sees the call, but
377
+ * the turn's return value alone does not say WHY it failed.
378
+ *
379
+ * [DESIGN DECISION] Owned by the execution, not module-global, so two concurrent
380
+ * contexts cannot read each other's denials.
381
+ */
382
+ export class AutonomousPolicyLedger {
383
+ private readonly denials: { tool: string; reason: AutonomousDenialReason }[] = []
384
+ private readonly allowances: string[] = []
385
+
386
+ deny(tool: string, reason: AutonomousDenialReason): void {
387
+ this.denials.push({ tool, reason })
388
+ }
389
+
390
+ allow(tool: string): void {
391
+ this.allowances.push(tool)
392
+ }
393
+
394
+ get denials_(): readonly { tool: string; reason: AutonomousDenialReason }[] {
395
+ return this.denials
396
+ }
397
+
398
+ get allowedTools(): readonly string[] {
399
+ return this.allowances
400
+ }
401
+
402
+ /** True when at least one call was refused. Drives the `permission-denied` outcome. */
403
+ get denied(): boolean {
404
+ return this.denials.length > 0
405
+ }
406
+
407
+ summary(): string {
408
+ return this.denials.map((d) => `${d.tool} (${d.reason})`).join(", ")
409
+ }
410
+ }
411
+
412
+ // ── the invocation-time gate ─────────────────────────────────────────────────
413
+
414
+ /**
415
+ * Structurally the kernel's `PermissionHandler`; declared here to avoid a kernel
416
+ * type import.
417
+ *
418
+ * [PHASE 6S] The second parameter is `deps` (`ExecutorDeps`), which the kernel
419
+ * passes and this policy deliberately IGNORES. The interactive handler uses it to
420
+ * read the turn's `AbortSignal` and to race a late approval against cancellation;
421
+ * an autonomous decision needs neither, because it never waits for anything. The
422
+ * parameter exists so this type is assignable to the kernel's `PermissionHandler`
423
+ * without a cast — a cast would hide exactly the structural mismatch that would
424
+ * otherwise break the composition root.
425
+ */
426
+ export interface AutonomousPermissionHandler {
427
+ check(call: ToolCall, deps?: unknown): Promise<"allow" | "deny">
428
+ describeDenial?(call: ToolCall): string | undefined
429
+ }
430
+
431
+ /**
432
+ * [PHASE 6S] THE AUTONOMOUS PERMISSION HANDLER.
433
+ *
434
+ * [DESIGN DECISION] Answers `deny` synchronously and immediately for anything
435
+ * outside the matrix. It never consults an approval callback, never awaits
436
+ * anything a human must answer, and therefore cannot block. That is the whole
437
+ * reason the kernel's `allow | deny` vocabulary is SUFFICIENT here despite having
438
+ * no DEFER state: the autonomy policy never needs to defer, because it never
439
+ * asks.
440
+ *
441
+ * The decision is data, not control flow: `classifyTool` is a table lookup, so
442
+ * the same input always yields the same decision, and a tool added to the
443
+ * registry later is denied until someone classifies it.
444
+ */
445
+ export function createAutonomousPermissionHandler(
446
+ ledger: AutonomousPolicyLedger,
447
+ ): AutonomousPermissionHandler {
448
+ return {
449
+ check(call: ToolCall, _deps?: unknown): Promise<"allow" | "deny"> {
450
+ const c = classifyTool(call.name)
451
+ if (c.autonomous) {
452
+ ledger.allow(call.name)
453
+ return Promise.resolve("allow")
454
+ }
455
+ const reason: AutonomousDenialReason =
456
+ c.capability === "UNKNOWN" ? "UNKNOWN_TOOL" : "NOT_AUTONOMOUS"
457
+ ledger.deny(call.name, reason)
458
+ return Promise.resolve("deny")
459
+ },
460
+ describeDenial(call: ToolCall): string | undefined {
461
+ const c = classifyTool(call.name)
462
+ if (c.autonomous) return undefined
463
+ return (
464
+ `autonomous execution may not use "${call.name}" (${c.capability}). ` +
465
+ `This execution is read-only and runs unattended, so nothing can approve it. ` +
466
+ `Reason: ${c.evidence}`
467
+ )
468
+ },
469
+ }
470
+ }
471
+
472
+ /**
473
+ * [PHASE 6S] The creation-time gate, now derived from the matrix.
474
+ *
475
+ * Kept in addition to the invocation-time handler for the reason given at the top
476
+ * of this file: it fails fast on a misconfigured context, before any turn runs.
477
+ */
478
+ export function assertAutonomousToolScope(toolNames: readonly string[]): void {
479
+ const offending = toolNames.filter((n) => !isAutonomousTool(n))
480
+ if (offending.length === 0) return
481
+ const named = offending.filter((n) => classifyTool(n).capability !== "UNKNOWN")
482
+ const unknown = offending.filter((n) => classifyTool(n).capability === "UNKNOWN")
483
+ const bits: string[] = []
484
+ if (named.length > 0) bits.push(`not autonomous: ${named.join(", ")}`)
485
+ if (unknown.length > 0) bits.push(`unclassified: ${unknown.join(", ")}`)
486
+ throw new Error(
487
+ `autonomous execution context refused: tool scope is not read-only (${bits.join("; ")}). ` +
488
+ `An unattended execution cannot use these; see TOOL_CAPABILITIES.`,
489
+ )
490
+ }
@@ -0,0 +1,179 @@
1
+ // P13.3 Stage C — klasifikasi kontinuitas task durable (MURNI, tanpa I/O).
2
+ //
3
+ // Kenapa modul ini ada: Scheduler sudah punya rekonsiliasi berbasis lineage,
4
+ // tetapi "tidak ada completion marker" BUKAN bukti "tidak ada efek samping".
5
+ // Reconcile otomatis yang lama menganggap setiap generasi tanpa marker aman
6
+ // dijalankan ulang. Itu benar untuk lineage, tetapi salah untuk eksekusi yang
7
+ // bisa menulis berkas atau menjalankan perintah: attempt baru dapat MENGULANG
8
+ // efek eksternal yang sudah terjadi sebelum proses mati.
9
+ //
10
+ // Modul ini memisahkan dua pertanyaan yang dulu tercampur:
11
+ // 1. Apakah generasi ini stranded? -> TaskStore (predikat lineage atomik)
12
+ // 2. Apakah aman menjalankannya ULANG? -> kebijakan di berkas ini
13
+ //
14
+ // Hanya SAFE_TO_RETRY yang boleh kembali ke siklus claim/dispatch otomatis.
15
+ // REQUIRES_VERIFIER dan HOLD sama-sama MENAHAN record. Bedanya: yang pertama
16
+ // secara prinsip bisa dibuktikan aman oleh verifier yang belum tersedia;
17
+ // yang kedua kehilangan bukti/otoritas yang wajib ada lebih dulu.
18
+ //
19
+ // TIDAK ADA I/O DI SINI. Database, runtime, jam, dan environment tidak dibaca;
20
+ // semua fakta masuk lewat argumen. Dengan begitu keputusan bisa diuji
21
+ // deterministik dan tidak ada sumber kebenaran kedua di samping TaskStore.
22
+
23
+ import { classifyTool } from "./autonomous-policy.ts"
24
+ import type { TaskStatus } from "./model.ts"
25
+
26
+ /**
27
+ * Bukti cakupan tool yang menentukan keselamatan retry.
28
+ *
29
+ * READ_ONLY_TOOL_SCOPE bukan tebakan: nilainya hanya boleh dipakai bila
30
+ * SELURUH tool yang bisa dipanggil bridge berasal dari matriks 6S dan
31
+ * berkemampuan READ_ONLY. Untuk bridge otonom produksi, `AUTONOMOUS_TOOL_NAMES`
32
+ * adalah output matriks itu sendiri (lihat `retrySafetyForToolScope`).
33
+ */
34
+ export type RetrySafety =
35
+ /** Tool bridge terbukti read-only: attempt baru tidak bisa mengulang efek tulis. */
36
+ | "READ_ONLY_TOOL_SCOPE"
37
+ /** Tidak ada bukti yang menutup efek eksternal; retry butuh verifier. */
38
+ | "UNPROVEN"
39
+
40
+ export type ContinuityClass = "SAFE_TO_RETRY" | "REQUIRES_VERIFIER" | "HOLD"
41
+
42
+ /** Fakta task yang dibaca dari TaskStore. Bukan status presentasi. */
43
+ export interface ContinuityFacts {
44
+ readonly status: TaskStatus
45
+ readonly executionOwner: "scheduler" | null
46
+ readonly execGeneration: number
47
+ /** `null` = belum ada attempt yang mencatat akhir untuk generasi ini. */
48
+ readonly attemptGeneration: number | null
49
+ /** Ownership proses-lokal masih milik instance ini. */
50
+ readonly ownsSession: boolean
51
+ /** Lease/authority lintas-proses masih valid untuk token instance ini. */
52
+ readonly authorityHeld: boolean
53
+ /** Incarnation sesi persisten masih sama dengan yang dipegang instance. */
54
+ readonly incarnationMatches: boolean
55
+ }
56
+
57
+ /**
58
+ * Bukti tambahan yang datang dari luar lapisan task.
59
+ *
60
+ * `resume`/`missing` adalah hasil `evaluateResume` (runtime-status.ts), bukan
61
+ * evaluasi ulang di sini: aturan empat-bukti tetap milik satu fungsi. Modul ini
62
+ * hanya memutuskan apakah bukti itu cukup untuk MENJALANKAN ULANG.
63
+ */
64
+ export interface ContinuityEvidence {
65
+ readonly resume: boolean
66
+ readonly missing: readonly string[]
67
+ readonly admission: "ALLOW" | "SCOPED" | "REFUSE"
68
+ readonly retrySafety: RetrySafety
69
+ }
70
+
71
+ export interface ContinuityVerdict {
72
+ readonly class: ContinuityClass
73
+ readonly reason: string
74
+ /** Hanya true untuk SAFE_TO_RETRY. Keputusan revert tetap milik TaskStore. */
75
+ readonly mayReconcile: boolean
76
+ }
77
+
78
+ /** Fakta yang hanya diketahui Scheduler saat reconcile berjalan. */
79
+ export interface ContinuityContext {
80
+ readonly ownsSession: boolean
81
+ readonly authorityHeld: boolean
82
+ readonly incarnationMatches: boolean
83
+ }
84
+
85
+ /**
86
+ * Sumber bukti kontinuitas. Composition root yang memasangnya; Scheduler tidak
87
+ * menebak apakah bridge-nya read-only.
88
+ */
89
+ export interface ContinuityGate {
90
+ readonly evidence: (ctx: ContinuityContext) => ContinuityEvidence
91
+ }
92
+
93
+ /**
94
+ * Marker kompletion = attempt untuk generasi BERJALAN sudah mencatat akhir.
95
+ *
96
+ * Sengaja `>=`, bukan `===`: attempt yang lebih baru dari exec adalah korupsi
97
+ * dan diperlakukan sebagai "sudah ada tanda" (menahan), bukan alasan menulis
98
+ * ulang. Scheduler memeriksa relasi mustahil itu secara eksplisit sebelum
99
+ * memanggil fungsi ini.
100
+ */
101
+ export function hasCompletionMarker(generations: {
102
+ readonly execGeneration: number
103
+ readonly attemptGeneration: number | null
104
+ }): boolean {
105
+ const attempt = generations.attemptGeneration
106
+ return attempt !== null && attempt >= generations.execGeneration
107
+ }
108
+
109
+ /**
110
+ * Turunkan retry safety dari NAMA tool yang benar-benar dipegang bridge.
111
+ *
112
+ * Fail-closed:
113
+ * - daftar kosong = tidak ada bukti cakupan (bisa berarti miswiring) -> UNPROVEN;
114
+ * - satu tool saja yang tidak ada di matriks, tidak autonomous, atau bukan
115
+ * READ_ONLY -> UNPROVEN. Tidak ada "sebagian besar read-only".
116
+ */
117
+ export function retrySafetyForToolScope(toolNames: readonly string[]): RetrySafety {
118
+ if (toolNames.length === 0) return "UNPROVEN"
119
+ for (const name of toolNames) {
120
+ const tool = classifyTool(name)
121
+ if (!tool.autonomous || tool.capability !== "READ_ONLY") return "UNPROVEN"
122
+ }
123
+ return "READ_ONLY_TOOL_SCOPE"
124
+ }
125
+
126
+ /**
127
+ * Satu-satunya klasifikasi recovery untuk task durable.
128
+ *
129
+ * Urutan pemeriksaan disengaja: otoritas/identitas lebih dulu (tanpa itu tak
130
+ * ada yang boleh disentuh), lalu marker (attempt sudah berakhir -> bukan urusan
131
+ * scheduler), lalu bukti resume/admission, terakhir keselamatan retry.
132
+ *
133
+ * "Marker tidak ada" TIDAK pernah menjadi bukti keselamatan. Keselamatan hanya
134
+ * datang dari `retrySafety` yang dibuktikan sumbernya (mis. cakupan tool).
135
+ */
136
+ export function classifyContinuity(
137
+ facts: ContinuityFacts,
138
+ evidence: ContinuityEvidence,
139
+ ): ContinuityVerdict {
140
+ const hold = (reason: string): ContinuityVerdict => ({
141
+ class: "HOLD",
142
+ reason,
143
+ mayReconcile: false,
144
+ })
145
+ const verifier = (reason: string): ContinuityVerdict => ({
146
+ class: "REQUIRES_VERIFIER",
147
+ reason,
148
+ mayReconcile: false,
149
+ })
150
+
151
+ // Terminal dan operator states tidak pernah menjadi target. Ini pengulangan
152
+ // yang disengaja dari kontrak TaskStore: klasifikasi tidak boleh melonggarkan
153
+ // RECONCILABLE_STATUSES hanya karena dipanggil dari tempat lain.
154
+ if (facts.status !== "IN_PROGRESS" && facts.status !== "VERIFYING") {
155
+ return hold("not-in-flight")
156
+ }
157
+ if (!facts.ownsSession) return hold("ownership-not-held")
158
+ if (!facts.authorityHeld) return hold("authority-lost")
159
+ if (!facts.incarnationMatches) return hold("session-superseded")
160
+ if (facts.executionOwner !== "scheduler") return hold("not-scheduler-owned")
161
+ if (facts.execGeneration <= 0) return hold("no-claim")
162
+
163
+ // [Owner decision 2] Completion marker ada -> attempt sudah berakhir. Tanpa
164
+ // marker pun, ketiadaan itu bukan bukti tidak ada efek; karena itu marker
165
+ // hanya menahan lebih awal, tidak pernah menjadi izin.
166
+ if (hasCompletionMarker(facts)) return hold("attempt-completed")
167
+
168
+ if (!evidence.resume) {
169
+ const missing = evidence.missing.length > 0 ? evidence.missing.join(",") : "unknown"
170
+ return hold(`resume-missing:${missing}`)
171
+ }
172
+ if (evidence.admission !== "ALLOW") {
173
+ return hold(`admission-${evidence.admission.toLowerCase()}`)
174
+ }
175
+ if (evidence.retrySafety !== "READ_ONLY_TOOL_SCOPE") {
176
+ return verifier("retry-safety-unproven")
177
+ }
178
+ return { class: "SAFE_TO_RETRY", reason: "eligible", mayReconcile: true }
179
+ }