minicode-ai 0.11.1 → 0.13.1

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 (222) hide show
  1. package/CHANGELOG.md +95 -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/minicode.js +6 -0
  15. package/cli/recovery-warning.ts +115 -0
  16. package/cli/router.ts +32 -1
  17. package/cli/setup.ts +2332 -171
  18. package/cli/tui.ts +113 -7
  19. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  20. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  21. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  22. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  23. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  24. package/docs/OUTPUT_UX_RULES.md +449 -0
  25. package/docs/PLAN_UIUX_V6.md +2 -2
  26. package/docs/README.md +4 -3
  27. package/docs/TERMINAL_CONTRACT.md +278 -71
  28. package/docs/architecture.md +89 -7
  29. package/docs/changelog.md +1 -1
  30. package/docs/choosing-mode.md +2 -2
  31. package/docs/cli.md +9 -5
  32. package/docs/concepts.md +1 -1
  33. package/docs/contributing.md +9 -2
  34. package/docs/environment.md +6 -2
  35. package/docs/exec.md +46 -5
  36. package/docs/memory-sessions.md +2 -0
  37. package/docs/policy-sandbox.md +1 -1
  38. package/docs/pricing-budget.md +1 -1
  39. package/docs/quickstart.md +2 -2
  40. package/docs/repl.md +6 -2
  41. package/docs/security-model.md +1 -1
  42. package/docs/security.md +1 -1
  43. package/docs/skills.md +2 -2
  44. package/docs/terminal.md +9 -5
  45. package/docs/tools.md +1 -1
  46. package/package.json +36 -6
  47. package/src/app/session.ts +261 -15
  48. package/src/app/tool-layer.ts +94 -7
  49. package/src/daemon/approvals.ts +361 -0
  50. package/src/daemon/capability.ts +145 -0
  51. package/src/daemon/children.ts +142 -0
  52. package/src/daemon/client.ts +267 -0
  53. package/src/daemon/control.ts +350 -0
  54. package/src/daemon/discovery.ts +234 -0
  55. package/src/daemon/feed.ts +155 -0
  56. package/src/daemon/framing.ts +94 -0
  57. package/src/daemon/host.ts +316 -0
  58. package/src/daemon/protocol.ts +217 -0
  59. package/src/daemon/resource.ts +170 -0
  60. package/src/daemon/sanitize.ts +57 -0
  61. package/src/daemon/server.ts +627 -0
  62. package/src/daemon/store.ts +317 -0
  63. package/src/daemon/subscription.ts +270 -0
  64. package/src/daemon/telemetry.ts +81 -0
  65. package/src/hooks/run.ts +12 -1
  66. package/src/lib/atomic-write.ts +29 -3
  67. package/src/lib/db-path.ts +26 -0
  68. package/src/lib/keystore.ts +544 -42
  69. package/src/lib/net.ts +43 -1
  70. package/src/lib/safe-open.ts +116 -1
  71. package/src/lib/session-id.ts +15 -0
  72. package/src/lsp/client.ts +123 -5
  73. package/src/mcp/client.ts +139 -17
  74. package/src/mcp/server.ts +177 -50
  75. package/src/mcp/transport.ts +16 -19
  76. package/src/memory/vector.ts +770 -55
  77. package/src/policy/allowlist.ts +14 -2
  78. package/src/policy/bash-guard.ts +105 -10
  79. package/src/policy/compaction.ts +82 -5
  80. package/src/policy/consequence-engine.ts +220 -0
  81. package/src/policy/context.ts +132 -0
  82. package/src/policy/executor.ts +187 -121
  83. package/src/policy/no-progress.ts +559 -0
  84. package/src/policy/permission.ts +4 -8
  85. package/src/policy/pricing.ts +17 -3
  86. package/src/policy/scrub.ts +69 -2
  87. package/src/policy/tool-contract.ts +515 -0
  88. package/src/policy/usage.ts +310 -24
  89. package/src/policy/verifier.ts +6 -3
  90. package/src/policy/work-mode.ts +182 -0
  91. package/src/presentation/adapter.ts +533 -26
  92. package/src/presentation/events.ts +151 -0
  93. package/src/presentation/model.ts +180 -27
  94. package/src/presentation/projection.ts +858 -0
  95. package/src/presentation/reducer.ts +645 -310
  96. package/src/presentation/store.ts +12 -7
  97. package/src/providers/anthropic.ts +18 -10
  98. package/src/providers/responses.ts +2 -2
  99. package/src/runtime/capability.ts +409 -0
  100. package/src/runtime/child-execution.ts +274 -0
  101. package/src/runtime/composition.ts +958 -0
  102. package/src/runtime/dispatch.ts +591 -0
  103. package/src/runtime/execution-backend.ts +632 -0
  104. package/src/runtime/execution-events.ts +272 -0
  105. package/src/runtime/execution-id.ts +230 -0
  106. package/src/runtime/execution-journal.ts +926 -0
  107. package/src/runtime/execution-kernel.ts +456 -0
  108. package/src/runtime/execution-registry.ts +379 -0
  109. package/src/runtime/process-supervision.ts +276 -0
  110. package/src/runtime/production-execution.ts +551 -0
  111. package/src/runtime/production-runtime.ts +217 -0
  112. package/src/runtime/recovery-safety.ts +70 -0
  113. package/src/runtime/recovery.ts +477 -0
  114. package/src/runtime/runtime-capabilities.ts +179 -0
  115. package/src/runtime/runtime-diagnostics.ts +141 -0
  116. package/src/runtime/runtime-host.ts +365 -0
  117. package/src/runtime/runtime-status-facts.ts +222 -0
  118. package/src/runtime/runtime-status-provider.ts +74 -0
  119. package/src/runtime/runtime-status.ts +459 -0
  120. package/src/runtime/runtime-task-admission.ts +101 -0
  121. package/src/runtime/supervisor.ts +444 -0
  122. package/src/session/authority.ts +168 -0
  123. package/src/session/checkpoint.ts +88 -1
  124. package/src/session/context-adapter.ts +251 -0
  125. package/src/session/context-assembly.ts +242 -0
  126. package/src/session/context-identity.ts +389 -0
  127. package/src/session/context-projection.ts +248 -0
  128. package/src/session/context-selector.ts +500 -0
  129. package/src/session/cross-session-adoption.ts +249 -0
  130. package/src/session/full-history-fold.ts +171 -0
  131. package/src/session/identity.ts +192 -0
  132. package/src/session/journal.ts +805 -102
  133. package/src/session/open-work-intent.ts +732 -0
  134. package/src/session/open-work.ts +767 -0
  135. package/src/session/pending-tools.ts +94 -0
  136. package/src/session/persistence.ts +3569 -127
  137. package/src/session/runtime-header.ts +208 -0
  138. package/src/session/shadow-git.ts +13 -5
  139. package/src/session/verification.ts +1623 -0
  140. package/src/task/assignment.ts +136 -0
  141. package/src/task/autonomous-adapter.ts +168 -0
  142. package/src/task/autonomous-context.ts +630 -0
  143. package/src/task/autonomous-policy.ts +490 -0
  144. package/src/task/continuity.ts +179 -0
  145. package/src/task/execution-cancellation.ts +165 -0
  146. package/src/task/graph-validate.ts +379 -0
  147. package/src/task/graph.ts +305 -0
  148. package/src/task/identity.ts +230 -0
  149. package/src/task/model.ts +417 -0
  150. package/src/task/production-scheduler.ts +293 -0
  151. package/src/task/readiness.ts +229 -0
  152. package/src/task/scheduler-observability.ts +387 -0
  153. package/src/task/scheduler.ts +1197 -0
  154. package/src/task/scheduling-policy.ts +165 -0
  155. package/src/task/session-authority.ts +148 -0
  156. package/src/task/session-ownership.ts +211 -0
  157. package/src/task/store.ts +2887 -0
  158. package/src/task/sync.ts +343 -0
  159. package/src/task/trigger.ts +260 -0
  160. package/src/tools/bash.ts +377 -211
  161. package/src/tools/code_run.ts +1 -1
  162. package/src/tools/delete_file.ts +1 -1
  163. package/src/tools/edit.ts +33 -6
  164. package/src/tools/evidence.ts +30 -0
  165. package/src/tools/git.ts +4 -4
  166. package/src/tools/glob.ts +12 -3
  167. package/src/tools/grep.ts +1 -1
  168. package/src/tools/lsp.ts +4 -4
  169. package/src/tools/mcp_call.ts +11 -4
  170. package/src/tools/memory.ts +153 -18
  171. package/src/tools/move_file.ts +1 -1
  172. package/src/tools/patch.ts +1 -1
  173. package/src/tools/read_file.ts +1 -1
  174. package/src/tools/read_image.ts +1 -1
  175. package/src/tools/submit_result.ts +1 -1
  176. package/src/tools/task.ts +437 -41
  177. package/src/tools/todo.ts +662 -35
  178. package/src/tools/web_fetch.ts +4 -2
  179. package/src/tools/web_search.ts +9 -3
  180. package/src/tools/write_file.ts +1 -1
  181. package/src/ui/assistant/simple.ts +123 -50
  182. package/src/ui/assistant/turn-status.ts +17 -3
  183. package/src/ui/contract.ts +184 -0
  184. package/src/ui/footer.ts +52 -19
  185. package/src/ui/i18n/en.ts +58 -6
  186. package/src/ui/i18n/id.ts +58 -6
  187. package/src/ui/input/prompt-engine.ts +120 -25
  188. package/src/ui/render/errors.ts +39 -1
  189. package/src/ui/render/markdown-table.ts +455 -0
  190. package/src/ui/render/markdown.ts +22 -1
  191. package/src/ui/render/table-grid.ts +184 -0
  192. package/src/ui/render/table.ts +15 -76
  193. package/src/ui/runtime/screen.ts +7 -2
  194. package/src/ui/runtime/statusline.ts +25 -6
  195. package/src/ui/tui/app.ts +507 -169
  196. package/src/ui/tui/transcript.ts +531 -89
  197. package/vendor/minicore/VENDOR.md +1 -1
  198. package/vendor/minicore/src/core/budget.ts +25 -25
  199. package/vendor/minicore/src/core/compact.ts +75 -75
  200. package/vendor/minicore/src/core/errors.ts +59 -59
  201. package/vendor/minicore/src/core/events.ts +73 -73
  202. package/vendor/minicore/src/core/executor.ts +139 -139
  203. package/vendor/minicore/src/core/history.ts +31 -31
  204. package/vendor/minicore/src/core/index.ts +41 -41
  205. package/vendor/minicore/src/core/loop.ts +355 -355
  206. package/vendor/minicore/src/core/permission.ts +22 -22
  207. package/vendor/minicore/src/core/provider.ts +39 -39
  208. package/vendor/minicore/src/core/recovery.ts +35 -35
  209. package/vendor/minicore/src/core/session.ts +327 -327
  210. package/vendor/minicore/src/core/snapshot.ts +146 -146
  211. package/vendor/minicore/src/core/tokens.ts +107 -107
  212. package/vendor/minicore/src/core/tool.ts +115 -115
  213. package/vendor/minicore/src/core/types.ts +50 -50
  214. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  215. package/AGENTS.md +0 -45
  216. package/PLAN.md +0 -491
  217. package/docs/ARCHITECTURE.html +0 -1248
  218. package/docs/CONTROL-PLANE-MAP.md +0 -139
  219. package/docs/HARNESS.md +0 -150
  220. package/docs/SUMMARY.md +0 -52
  221. package/docs/UI_RENDER_PIPELINE.md +0 -169
  222. package/docs/USAGE.md +0 -11
@@ -0,0 +1,986 @@
1
+ // P14.4 — portofolio open-work lintas sesi (CLI read-only) + P14.3 merge
2
+ // eksplisit. Satu subcommand, lima aksi:
3
+ //
4
+ // minicode openwork [--session <id>] [--status <S>] [--state <S>]
5
+ // [--priority <P0..P3>] [--min-age-days <n>] [--blocked]
6
+ // [--depends-on <taskId>] [--stale-days <n>] [--closed]
7
+ // [--json]
8
+ // minicode openwork inventory [--json]
9
+ // minicode openwork context --session <id> --task <taskId> [--json]
10
+ // minicode openwork export --out <path> [--format json|md] [--force] [filters...]
11
+ // minicode openwork merge --session <id> --keep <taskId> --drop <taskId>
12
+ // --evidence "<alasan>"
13
+ //
14
+ // Kontrak output (TERMINAL_CONTRACT I2/I28):
15
+ // - human → stdout, dikumpulkan lalu ditulis SEKALI (OAP-008) lewat
16
+ // printLines/emitJson — dua sink bersama untuk SEMUA aksi.
17
+ // - --json → SATU objek JSON di stdout, tanpa apa pun yang lain.
18
+ // - exit 0 sukses (termasuk daftar kosong) · 1 gagal runtime/lookup/refusal
19
+ // kebijakan (termasuk kegagalan tulis ekspor) · 2 salah pakai.
20
+ //
21
+ // Teks tak-terpercaya (judul task, ringkasan intent, evidence operator, id
22
+ // sesi dari DB) tidak pernah dicetak mentah di luar tabel: renderList
23
+ // menyani tiap sel, dan baris bebas (ringkasan merge, refusal, ekspor MD)
24
+ // lewat sanitizeAnsi eksplisit.
25
+ //
26
+ // Batas otoritas yang dijaga DI SINI: subcommand ini tidak pernah
27
+ // mengeksekusi apa pun. Resume/laju hidup dikerjakan jalur yang sudah ada
28
+ // (--adopt-task + /scheduler run + gate continuity P13.3).
29
+
30
+ import { existsSync } from "node:fs"
31
+ import { resolve as resolvePath } from "node:path"
32
+ import { atomicWriteText } from "../../src/lib/atomic-write.ts"
33
+ import { readCheckpointInventorySync } from "../../src/session/checkpoint.ts"
34
+ import {
35
+ formatAge,
36
+ type OpenWorkEntry,
37
+ type OpenWorkReport,
38
+ projectOpenWork,
39
+ } from "../../src/session/open-work.ts"
40
+ import {
41
+ nextActionFor,
42
+ type OpenWorkState,
43
+ type WorkPriorityLevel,
44
+ } from "../../src/session/open-work-intent.ts"
45
+ import { isTaskId, isTaskStatus, type TaskStatus } from "../../src/task/model.ts"
46
+ import { TaskStore } from "../../src/task/store.ts"
47
+ import { sanitizeAnsi, sanitizeAnsiLine } from "../../src/ui/render/sanitize.ts"
48
+ import { c } from "../../src/ui/render/theme.ts"
49
+ import { truncateToWidth } from "../../src/ui/render/width.ts"
50
+
51
+ const OPENWORK_STATES: readonly OpenWorkState[] = [
52
+ "OPEN",
53
+ "PARTIAL",
54
+ "BLOCKED",
55
+ "WAITING_FOR_USER",
56
+ "DELEGATED",
57
+ "FAILED_NEEDS_FOLLOWUP",
58
+ "UNKNOWN",
59
+ "COMPLETED",
60
+ "CANCELLED",
61
+ "DECLINED",
62
+ ]
63
+
64
+ const PRIORITY_LEVELS: readonly WorkPriorityLevel[] = ["P0", "P1", "P2", "P3"]
65
+
66
+ const OPENWORK_HELP = `minicode openwork — cross-session unfinished work (P14, read-only)
67
+
68
+ minicode openwork [--session <id>] [--status <S>] [--state <S>] [--priority <P>]
69
+ [--min-age-days <n>] [--blocked] [--depends-on <taskId>]
70
+ [--stale-days <n>] [--closed] [--json]
71
+ Portfolio of unfinished work across sessions in THIS workspace, with
72
+ state, priority, blockers, dependencies, next action, and provenance
73
+ (transfer source, plan steps, age). Structured intent from history
74
+ (pending approvals, delegated child sessions, interrupted runs, plan
75
+ steps without a canonical task) is listed separately. Similar titles
76
+ across sessions are flagged UNPROVEN — they are never merged for you.
77
+
78
+ minicode openwork inventory [--json]
79
+ P14.0 read-only inventory: sessions, workspace binding, tasks, plan
80
+ artifacts, approvals, runs, checkpoints, sub-agent outcomes, and which
81
+ sessions were excluded (foreign/unbound workspace) with reasons.
82
+
83
+ minicode openwork context --session <id> --task <taskId> [--json]
84
+ P14.5 context pack for one task: canonical fields, blockers,
85
+ dependencies, plan evidence, checkpoint availability, freshness, and
86
+ the resume checklist. Read-only — openwork never executes anything;
87
+ permission/WorkMode/continuity are enforced by the resume path.
88
+
89
+ minicode openwork export --out <path> [--format json|md] [--force] [filters...]
90
+ P14.4 export: write the portfolio (including inventory) to a file,
91
+ atomically. json = machine envelope; md = sanitized human report.
92
+ Refuses to overwrite an existing file unless --force.
93
+
94
+ minicode openwork merge --session <id> --keep <taskId> --drop <taskId> --evidence "<why>"
95
+ Explicitly close <drop> as a CANCELLED duplicate of <keep> (same session).
96
+ The duplicate is CANCELLED, never COMPLETED. Your evidence text is kept
97
+ in an append-only audit ledger. Cross-session duplicates must be adopted
98
+ first (--adopt-task), then merged within one session.`
99
+
100
+ // ── dua sink bersama (OAP-008): SEMUA keluaran aksi lewat sini ──────────────
101
+
102
+ /** Mesin: SATU objek JSON di stdout, tanpa baris lain (kontrak I2). */
103
+ function emitJson(value: unknown): void {
104
+ console.log(JSON.stringify(value))
105
+ }
106
+
107
+ /** Manusia: baris dikumpulkan, ditulis SEKALI. */
108
+ function printLines(lines: readonly string[]): void {
109
+ console.log(lines.join("\n"))
110
+ }
111
+
112
+ function usageError(message: string): never {
113
+ console.error(`${message}\n\n${OPENWORK_HELP}`)
114
+ process.exit(2)
115
+ }
116
+
117
+ /**
118
+ * Kegagalan runtime/lookup/refusal kebijakan (exit 1, I28) — SATU writer
119
+ * stderr untuk semua jalur gagal manusia (OAP-008). Pesan sudah disani
120
+ * pemanggilnya bila membawa teks operator.
121
+ */
122
+ function exit1(message: string): never {
123
+ console.error(message)
124
+ process.exit(1)
125
+ }
126
+
127
+ function line(value: string, width: number): string {
128
+ return truncateToWidth(sanitizeAnsiLine(value), width, "…")
129
+ }
130
+
131
+ function flagsOf(e: OpenWorkEntry): string {
132
+ const flags: string[] = []
133
+ if (e.stale) flags.push("STALE")
134
+ if (e.provenance === "SESSION_MISSING") flags.push("PROVENANCE-UNKNOWN")
135
+ if (e.transferredFromSessionId !== null) {
136
+ flags.push(`FROM:${e.transferredFromSessionId}`)
137
+ }
138
+ if (e.similarCount > 1) flags.push(`SIMILAR×${e.similarCount}(UNPROVEN)`)
139
+ if (e.duplicate !== null && e.duplicate.sessions.length > 1) {
140
+ flags.push(`DUP-GROUP×${e.duplicate.count}(UNPROVEN)`)
141
+ }
142
+ return flags.join(" · ")
143
+ }
144
+
145
+ interface ListFilters {
146
+ readonly sessionId?: string
147
+ readonly status?: TaskStatus
148
+ readonly state?: OpenWorkState
149
+ readonly priority?: WorkPriorityLevel
150
+ readonly minAgeDays?: number
151
+ readonly blockedOnly?: boolean
152
+ readonly dependsOn?: string
153
+ readonly includeClosed: boolean
154
+ readonly staleMs?: number
155
+ }
156
+
157
+ function parseListFilters(getArg: (name: string) => string | undefined): ListFilters {
158
+ const sessionId = getArg("--session")
159
+ const statusRaw = getArg("--status")
160
+ let status: TaskStatus | undefined
161
+ if (statusRaw !== undefined) {
162
+ if (!isTaskStatus(statusRaw)) {
163
+ usageError(
164
+ `invalid --status value: "${statusRaw}" (expected one of PENDING|IN_PROGRESS|VERIFYING|BLOCKED|FAILED|RETRYING|COMPLETED|CANCELLED)`,
165
+ )
166
+ }
167
+ status = statusRaw
168
+ }
169
+ const stateRaw = getArg("--state")
170
+ let state: OpenWorkState | undefined
171
+ if (stateRaw !== undefined) {
172
+ if (!OPENWORK_STATES.includes(stateRaw as OpenWorkState)) {
173
+ usageError(
174
+ `invalid --state value: "${stateRaw}" (expected one of ${OPENWORK_STATES.join("|")})`,
175
+ )
176
+ }
177
+ state = stateRaw as OpenWorkState
178
+ }
179
+ const priorityRaw = getArg("--priority")
180
+ let priority: WorkPriorityLevel | undefined
181
+ if (priorityRaw !== undefined) {
182
+ if (!PRIORITY_LEVELS.includes(priorityRaw as WorkPriorityLevel)) {
183
+ usageError(`invalid --priority value: "${priorityRaw}" (expected one of P0|P1|P2|P3)`)
184
+ }
185
+ priority = priorityRaw as WorkPriorityLevel
186
+ }
187
+ const minAgeRaw = getArg("--min-age-days")
188
+ let minAgeDays: number | undefined
189
+ if (minAgeRaw !== undefined) {
190
+ const n = Number(minAgeRaw)
191
+ if (!Number.isFinite(n) || n < 0) {
192
+ usageError(`invalid --min-age-days value: "${minAgeRaw}" (expected a non-negative number)`)
193
+ }
194
+ minAgeDays = n
195
+ }
196
+ const dependsOn = getArg("--depends-on")
197
+ if (dependsOn !== undefined && !isTaskId(dependsOn)) {
198
+ usageError(`invalid --depends-on value: "${dependsOn}" (expected canonical id like t1)`)
199
+ }
200
+ const staleDaysRaw = getArg("--stale-days")
201
+ let staleMs: number | undefined
202
+ if (staleDaysRaw !== undefined) {
203
+ const n = Number(staleDaysRaw)
204
+ if (!Number.isFinite(n) || n < 0) {
205
+ usageError(`invalid --stale-days value: "${staleDaysRaw}" (expected a non-negative number)`)
206
+ }
207
+ staleMs = n * 24 * 60 * 60 * 1000
208
+ }
209
+ return {
210
+ ...(sessionId !== undefined ? { sessionId } : {}),
211
+ ...(status !== undefined ? { status } : {}),
212
+ ...(state !== undefined ? { state } : {}),
213
+ ...(priority !== undefined ? { priority } : {}),
214
+ ...(minAgeDays !== undefined ? { minAgeDays } : {}),
215
+ ...(getArg("--blocked") !== undefined || process.argv.includes("--blocked")
216
+ ? { blockedOnly: true }
217
+ : {}),
218
+ ...(dependsOn !== undefined ? { dependsOn } : {}),
219
+ includeClosed: getArg("--closed") !== undefined || process.argv.includes("--closed"),
220
+ ...(staleMs !== undefined ? { staleMs } : {}),
221
+ }
222
+ }
223
+
224
+ function ageOfClosed(closedAt: string | null, now: number): string {
225
+ if (closedAt === null) return "-"
226
+ const t = Date.parse(closedAt)
227
+ if (!Number.isFinite(t)) return "-"
228
+ return formatAge(Math.max(0, now - t))
229
+ }
230
+
231
+ function renderListHuman(report: OpenWorkReport, filters: ListFilters, cwd: string): string[] {
232
+ const lines: string[] = []
233
+ const scope = filters.sessionId === undefined ? "" : ` · session=${filters.sessionId}`
234
+ const similarNote =
235
+ report.counts.similarGroups > 0
236
+ ? ` · ${report.counts.similarGroups} similar group(s) UNPROVEN`
237
+ : ""
238
+ const conflictNote = report.counts.conflicts > 0 ? ` · ${report.counts.conflicts} DIVERGENT` : ""
239
+ lines.push(
240
+ c.bold(
241
+ `Open Work — ${report.counts.open} item(s) · ${report.counts.intent} intent · ${report.counts.stale} stale · ${report.counts.unknownProvenance} unknown-provenance${similarNote}${conflictNote}${scope}`,
242
+ ),
243
+ )
244
+ lines.push(
245
+ c.dim(
246
+ `workspace: ${resolvePath(cwd)} · stale after ${formatAge(report.staleMs)} · TaskStore remains the sole status authority`,
247
+ ),
248
+ )
249
+ if (report.open.length === 0 && report.intent.length === 0) {
250
+ lines.push(c.dim("(no unfinished work in this workspace)"))
251
+ }
252
+ for (const e of report.open) {
253
+ lines.push("")
254
+ lines.push(
255
+ `${c.cyan(line(e.sessionId, 60))}/${line(e.taskId, 12)} · ${line(e.status, 12)} · ${line(e.state, 20)} · ${e.priority.level} · ${formatAge(e.ageMs)} old`,
256
+ )
257
+ lines.push(` ${c.dim("title:")} ${line(e.title, 60)}`)
258
+ const flags = flagsOf(e)
259
+ lines.push(` ${c.dim("flags:")} ${line(flags.length > 0 ? flags : "none", 90)}`)
260
+ if (e.blockers.length > 0) {
261
+ lines.push(
262
+ ` ${c.dim("blockers:")} ${line(e.blockers.map((b) => `${b.kind}: ${b.detail}`).join(" · "), 90)}`,
263
+ )
264
+ }
265
+ if (e.dependencies.length > 0) {
266
+ lines.push(
267
+ ` ${c.dim("depends on:")} ${line(e.dependencies.map((d) => `${d.taskId} (${d.status}${d.satisfied ? "" : ", unsatisfied"})`).join(" · "), 90)}`,
268
+ )
269
+ }
270
+ if (e.verification !== null) {
271
+ lines.push(
272
+ ` ${c.dim("verification:")} ${line(`${e.verification.verdict} @ ${e.verification.checkedAt}`, 80)}`,
273
+ )
274
+ }
275
+ if (e.planSteps.length > 0) {
276
+ lines.push(
277
+ ` ${c.dim("plan evidence:")} ${line(e.planSteps.map((p) => `${p.stepId}=${p.claimedStatus}@turn${p.turnId}`).join(" · "), 90)}`,
278
+ )
279
+ }
280
+ lines.push(` ${c.dim("next:")} ${line(e.nextAction, 90)}`)
281
+ }
282
+ for (const ic of report.intent) {
283
+ lines.push("")
284
+ lines.push(
285
+ `${c.magenta(line(`INTENT·${ic.source}`, 24))} · ${line(ic.state, 20)} · ${formatAge(Math.max(0, Date.parse(report.generatedAtIso) - Date.parse(ic.observedAtIso)))} old`,
286
+ )
287
+ lines.push(` ${c.dim("summary:")} ${line(ic.summary, 70)}`)
288
+ lines.push(` ${c.dim("session:")} ${line(ic.sessionId, 60)}`)
289
+ const prov = ic.provenance
290
+ const provBits = [
291
+ prov.eventSeq !== null ? `event=${prov.eventSeq}` : null,
292
+ prov.turnId !== null ? `turn=${prov.turnId}` : null,
293
+ prov.planId !== null ? `plan=${prov.planId}` : null,
294
+ prov.stepId !== null ? `step=${prov.stepId}` : null,
295
+ prov.approvalId !== null ? `approval=${prov.approvalId}` : null,
296
+ prov.childSessionId !== null ? `child=${prov.childSessionId}` : null,
297
+ prov.runId !== null ? `run=${prov.runId}` : null,
298
+ prov.taskId !== null ? `task=${prov.taskId}` : null,
299
+ ].filter((s): s is string => s !== null)
300
+ lines.push(` ${c.dim("provenance:")} ${line(provBits.join(" · "), 90)}`)
301
+ lines.push(` ${c.dim("reason:")} ${line(ic.reason, 90)}`)
302
+ lines.push(` ${c.dim("next:")} ${line(nextActionFor(ic.state), 90)}`)
303
+ }
304
+ if (report.duplicateGroups.length > 0) {
305
+ lines.push("")
306
+ lines.push(
307
+ c.bold(`Similar groups — ${report.duplicateGroups.length} (UNPROVEN, never auto-merged)`),
308
+ )
309
+ for (const g of report.duplicateGroups) {
310
+ const divergence = g.divergentStates ? c.yellow(" · DIVERGENT states") : ""
311
+ lines.push(
312
+ ` ${line(`"${g.key}" ×${g.count} across ${g.sessions.length} session(s)`, 70)}${divergence}`,
313
+ )
314
+ lines.push(` ${c.dim("sessions:")} ${line(g.sessions.join(" · "), 90)}`)
315
+ }
316
+ }
317
+ if (filters.includeClosed) {
318
+ lines.push("")
319
+ if (report.closed.length === 0) {
320
+ lines.push(c.dim("Closure feedback: no P14-provenanced work is closed yet."))
321
+ } else {
322
+ lines.push(
323
+ c.bold(`Closure feedback — ${report.counts.closed} closed item(s) with P14 provenance`),
324
+ )
325
+ const nowMs = Date.parse(report.generatedAtIso)
326
+ for (const e of report.closed) {
327
+ const age = ageOfClosed(e.closedAt, nowMs)
328
+ const taskId = e.taskId === null ? "(no task)" : e.taskId
329
+ const origin =
330
+ e.kind === "TRANSFERRED"
331
+ ? ` · FROM ${line(e.transferredFromSessionId ?? "?", 60)}`
332
+ : e.kind === "MERGED_DUPLICATE"
333
+ ? ` · duplicate-of ${line(e.mergeSurvivorId ?? "?", 12)}`
334
+ : ` · intent ${line(e.intentState ?? "?", 20)}`
335
+ const shownStatus = e.status ?? e.intentState ?? "?"
336
+ lines.push("")
337
+ lines.push(
338
+ `${c.cyan(line(e.sessionId, 60))}/${line(taskId, 12)} · ${line(String(shownStatus), 12)} · closed ${age} ago · claim ${line(e.claim, 12)}${origin}`,
339
+ )
340
+ if (e.title !== null) lines.push(` ${c.dim("title:")} ${line(e.title, 60)}`)
341
+ if (e.kind === "MERGED_DUPLICATE" && e.mergeEvidence !== null) {
342
+ lines.push(` ${c.dim("evidence:")} ${line(e.mergeEvidence, 70)}`)
343
+ }
344
+ lines.push(` ${c.dim("reason:")} ${line(e.reason, 90)}`)
345
+ }
346
+ }
347
+ }
348
+ lines.push("")
349
+ lines.push(
350
+ c.dim(
351
+ "Continue explicitly: minicode --session <target> --adopt-task <source>/<task> — the scheduler is never started by adoption.",
352
+ ),
353
+ )
354
+ return lines
355
+ }
356
+
357
+ function applyListFilters(report: OpenWorkReport, filters: ListFilters): OpenWorkReport {
358
+ const hasFilter =
359
+ filters.status !== undefined ||
360
+ filters.state !== undefined ||
361
+ filters.priority !== undefined ||
362
+ filters.minAgeDays !== undefined ||
363
+ filters.blockedOnly === true ||
364
+ filters.dependsOn !== undefined
365
+ if (!hasFilter) return report
366
+
367
+ const minAgeMs = filters.minAgeDays !== undefined ? filters.minAgeDays * 24 * 60 * 60 * 1000 : 0
368
+ const open = report.open.filter((e) => {
369
+ if (filters.status !== undefined && e.status !== filters.status) return false
370
+ if (filters.state !== undefined && e.state !== filters.state) return false
371
+ if (filters.priority !== undefined && e.priority.level !== filters.priority) return false
372
+ if (filters.minAgeDays !== undefined && e.ageMs < minAgeMs) return false
373
+ if (filters.blockedOnly === true && e.blockers.length === 0) return false
374
+ if (
375
+ filters.dependsOn !== undefined &&
376
+ !e.dependencies.some((d) => d.taskId === filters.dependsOn)
377
+ ) {
378
+ return false
379
+ }
380
+ return true
381
+ })
382
+ const intent =
383
+ filters.state === undefined
384
+ ? report.intent
385
+ : report.intent.filter((ic) => ic.state === filters.state)
386
+ return {
387
+ ...report,
388
+ open,
389
+ intent,
390
+ counts: {
391
+ ...report.counts,
392
+ open: open.length,
393
+ intent: intent.length,
394
+ stale: open.filter((e) => e.stale).length,
395
+ unknownProvenance: open.filter((e) => e.provenance === "SESSION_MISSING").length,
396
+ },
397
+ }
398
+ }
399
+
400
+ function projectionOptions(filters: ListFilters, includeInventory: boolean) {
401
+ return {
402
+ ...(filters.staleMs !== undefined ? { staleMs: filters.staleMs } : {}),
403
+ ...(filters.sessionId !== undefined ? { sessionId: filters.sessionId } : {}),
404
+ includeClosed: filters.includeClosed,
405
+ includeIntent: true,
406
+ includeInventory,
407
+ }
408
+ }
409
+
410
+ function handleList(getArg: (name: string) => string | undefined): never {
411
+ const cwd = getArg("--cwd") ?? process.cwd()
412
+ const asJson = getArg("--json") !== undefined || process.argv.includes("--json")
413
+ const filters = parseListFilters(getArg)
414
+
415
+ const report = projectOpenWork({ cwd, ...projectionOptions(filters, false) })
416
+ const filtered = applyListFilters(report, filters)
417
+
418
+ if (asJson) {
419
+ emitJson(filtered)
420
+ process.exit(0)
421
+ }
422
+ printLines(renderListHuman(filtered, filters, cwd))
423
+ process.exit(0)
424
+ }
425
+
426
+ function handleMerge(getArg: (name: string) => string | undefined): never {
427
+ const cwd = getArg("--cwd") ?? process.cwd()
428
+ const asJson = getArg("--json") !== undefined || process.argv.includes("--json")
429
+ const sessionId = getArg("--session")
430
+ const keep = getArg("--keep")
431
+ const drop = getArg("--drop")
432
+ const evidence = getArg("--evidence")
433
+
434
+ if (
435
+ sessionId === undefined ||
436
+ keep === undefined ||
437
+ drop === undefined ||
438
+ evidence === undefined
439
+ ) {
440
+ usageError(
441
+ 'openwork merge requires --session <id> --keep <taskId> --drop <taskId> --evidence "<why>"',
442
+ )
443
+ }
444
+ if (evidence.trim().length === 0) {
445
+ usageError("openwork merge requires non-empty --evidence — similar wording is not proof")
446
+ }
447
+
448
+ const store = new TaskStore(cwd)
449
+ const survivor = store.getTask(sessionId, keep)
450
+ if (survivor === null) {
451
+ exit1(`task "${keep}" not found in session "${sessionId}"`)
452
+ }
453
+ const duplicate = store.getTask(sessionId, drop)
454
+ if (duplicate === null) {
455
+ exit1(`task "${drop}" not found in session "${sessionId}"`)
456
+ }
457
+
458
+ const result = store.declareTaskDuplicate({
459
+ sessionId,
460
+ survivorId: keep,
461
+ duplicateId: drop,
462
+ evidence,
463
+ // Revisi dibaca BARU-BARU INI: menangkap stale berurutan, semantik yang
464
+ // sama dengan patchTask (bukan CAS — itu kontrak substrat yang ada).
465
+ expectedRevision: duplicate.revision,
466
+ })
467
+
468
+ if (result.outcome !== "DECLARED") {
469
+ if (asJson) {
470
+ emitJson(result)
471
+ process.exit(1)
472
+ }
473
+ exit1(sanitizeAnsi(`[openwork] merge refused: ${result.outcome} — ${result.detail}`))
474
+ }
475
+
476
+ if (asJson) {
477
+ emitJson(result)
478
+ process.exit(0)
479
+ }
480
+ // Baris bebas: evidence adalah teks operator — disani eksplisit. Kedua
481
+ // baris dikumpulkan jadi SATU panggilan tulis (OAP-008).
482
+ printLines([
483
+ sanitizeAnsi(
484
+ `[openwork] closed ${drop} as duplicate of ${keep} (CANCELLED, not COMPLETED) — evidence: ${evidence}`,
485
+ ),
486
+ c.dim(
487
+ `audit ledger: ${result.merge?.mergeId ?? "?"} · duplicate revision ${result.duplicate?.revision ?? "?"} · reversal is an ordinary lifecycle write (ledger keeps the declaration)`,
488
+ ),
489
+ ])
490
+ process.exit(0)
491
+ }
492
+
493
+ function renderInventoryHuman(report: OpenWorkReport, cwd: string): string[] {
494
+ const inv = report.inventory
495
+ const lines: string[] = []
496
+ if (inv === null) {
497
+ lines.push(c.dim("(inventory not computed)"))
498
+ return lines
499
+ }
500
+ lines.push(c.bold(`Open Work Inventory — workspace ${resolvePath(cwd)}`))
501
+ lines.push(c.dim("TaskStore remains the sole status authority; this is a read-only audit."))
502
+ lines.push("")
503
+ lines.push(
504
+ `sessions: ${inv.sessions.total} total · ${inv.sessions.inScope} in-scope · ${inv.sessions.foreignWorkspace} foreign-workspace · ${inv.sessions.unboundWorkspace} unbound · ${inv.sessions.childSessions} child`,
505
+ )
506
+ lines.push(
507
+ `tasks: ${inv.tasks.total} total · ${inv.tasks.open} open · ${inv.tasks.terminal} terminal`,
508
+ )
509
+ lines.push(
510
+ `presentation events: ${inv.presentationEvents.total} (plan.updated ${inv.plans.events} · approval.requested ${inv.approvals.requested} · approval.settled ${inv.approvals.settled})`,
511
+ )
512
+ lines.push(
513
+ `runs: ${inv.runs.total} total · ${inv.runs.active} active · ${inv.runs.interrupted} interrupted · ${inv.runs.terminal} terminal`,
514
+ )
515
+ lines.push(
516
+ `checkpoints: ${inv.checkpoints.sessionsWithManifest} session(s) with manifest · ${inv.checkpoints.entries} entries · ${inv.checkpoints.corrupt} corrupt`,
517
+ )
518
+ lines.push(
519
+ `plans: ${inv.plans.events} event(s) · ${inv.plans.openSteps} open step(s) · ${inv.plans.closedSteps} closed step(s)`,
520
+ )
521
+ lines.push(
522
+ `approvals: ${inv.approvals.requested} requested · ${inv.approvals.settled} settled · ${inv.approvals.pending} pending`,
523
+ )
524
+ lines.push(
525
+ `sub-agents: ${inv.subAgents.childSessions} child session(s) · ${inv.subAgents.resultsProduced} with result · ${inv.subAgents.failedTurns} with failed turn`,
526
+ )
527
+ if (inv.excludedSessions.length === 0) {
528
+ lines.push(c.dim("excluded sessions: none"))
529
+ } else {
530
+ lines.push(`excluded sessions: ${inv.excludedSessions.length}`)
531
+ for (const x of inv.excludedSessions.slice(0, 20)) {
532
+ lines.push(` ${line(x.sessionId, 60)} · ${x.reason}`)
533
+ }
534
+ if (inv.excludedSessions.length > 20) {
535
+ lines.push(c.dim(` … and ${inv.excludedSessions.length - 20} more`))
536
+ }
537
+ }
538
+ if (report.rejectedEvents > 0) {
539
+ lines.push(
540
+ c.yellow(
541
+ `unreadable events: ${report.rejectedEvents} (decode rejected — evidence not hidden)`,
542
+ ),
543
+ )
544
+ }
545
+ return lines
546
+ }
547
+
548
+ function handleInventory(getArg: (name: string) => string | undefined): never {
549
+ const cwd = getArg("--cwd") ?? process.cwd()
550
+ const asJson = getArg("--json") !== undefined || process.argv.includes("--json")
551
+ const report = projectOpenWork({
552
+ cwd,
553
+ includeClosed: false,
554
+ includeIntent: true,
555
+ includeInventory: true,
556
+ })
557
+ if (asJson) {
558
+ emitJson({
559
+ generatedAtIso: report.generatedAtIso,
560
+ staleMs: report.staleMs,
561
+ counts: report.counts,
562
+ inventory: report.inventory,
563
+ duplicateGroups: report.duplicateGroups,
564
+ rejectedEvents: report.rejectedEvents,
565
+ })
566
+ process.exit(0)
567
+ }
568
+ printLines(renderInventoryHuman(report, cwd))
569
+ process.exit(0)
570
+ }
571
+
572
+ interface ContextPack {
573
+ readonly generatedAtIso: string
574
+ readonly workspace: string
575
+ readonly task: Record<string, unknown>
576
+ readonly portfolio: Record<string, unknown> | null
577
+ readonly closed: Record<string, unknown> | null
578
+ readonly checkpoint: Record<string, unknown>
579
+ readonly declaredDuplicateOf: string | null
580
+ readonly rejectedEvents: number
581
+ readonly resume: Record<string, unknown>
582
+ }
583
+
584
+ function buildContextPack(cwd: string, sessionId: string, taskId: string): ContextPack | null {
585
+ const store = new TaskStore(cwd)
586
+ const task = store.getTask(sessionId, taskId)
587
+ if (task === null) return null
588
+ const report = projectOpenWork({
589
+ cwd,
590
+ ...(sessionId !== undefined ? { sessionId } : {}),
591
+ includeClosed: true,
592
+ includeIntent: true,
593
+ includeInventory: false,
594
+ })
595
+ const entry = report.open.find((e) => e.taskId === taskId) ?? null
596
+ const closed = report.closed.find((e) => e.taskId === taskId) ?? null
597
+ const cp = readCheckpointInventorySync(sessionId, cwd)
598
+ const merges = store.listTaskMerges({ sessionId, duplicateId: taskId })
599
+ return {
600
+ generatedAtIso: report.generatedAtIso,
601
+ workspace: resolvePath(cwd),
602
+ task: {
603
+ sessionId,
604
+ taskId,
605
+ title: task.title,
606
+ status: task.status,
607
+ revision: task.revision,
608
+ createdAt: task.createdAt,
609
+ updatedAt: task.updatedAt,
610
+ blockedReason: task.blockedReason,
611
+ verification: task.verification,
612
+ provenance: task.provenance,
613
+ dependsOn: task.dependsOn,
614
+ evidence: task.evidence.slice(-10),
615
+ },
616
+ portfolio:
617
+ entry === null
618
+ ? null
619
+ : {
620
+ state: entry.state,
621
+ stateReason: entry.stateReason,
622
+ priority: entry.priority,
623
+ blockers: entry.blockers,
624
+ dependencies: entry.dependencies,
625
+ nextAction: entry.nextAction,
626
+ planSteps: entry.planSteps,
627
+ duplicate: entry.duplicate,
628
+ stale: entry.stale,
629
+ ageMs: entry.ageMs,
630
+ transferredFromSessionId: entry.transferredFromSessionId,
631
+ },
632
+ closed:
633
+ closed === null
634
+ ? null
635
+ : {
636
+ kind: closed.kind,
637
+ status: closed.status,
638
+ intentState: closed.intentState,
639
+ claim: closed.claim,
640
+ reason: closed.reason,
641
+ closedAt: closed.closedAt,
642
+ },
643
+ checkpoint: {
644
+ exists: cp.exists,
645
+ corrupt: cp.corrupt,
646
+ count: cp.checkpointCount,
647
+ latestTurn: cp.latestTurn,
648
+ latestTimestamp: cp.latestTimestamp,
649
+ },
650
+ declaredDuplicateOf: merges.length > 0 ? (merges[merges.length - 1]?.survivorId ?? null) : null,
651
+ rejectedEvents: report.rejectedEvents,
652
+ resume: {
653
+ autoExecute: false,
654
+ enforcedBy: [
655
+ "P12 permission/WorkMode ceiling at session start",
656
+ "P13.3 continuity gate before any claim",
657
+ "TaskStore claimTask generation fencing",
658
+ "P12/P13 budgets and cancellation",
659
+ ],
660
+ operatorFlow: "adopt (--adopt-task), then /scheduler run",
661
+ note: "openwork never executes; authority/freshness are enforced by the resume path, not projected here",
662
+ },
663
+ }
664
+ }
665
+
666
+ function renderContextHuman(pack: ContextPack): string[] {
667
+ const lines: string[] = []
668
+ const t = pack.task as {
669
+ title: string
670
+ status: string
671
+ revision: number
672
+ updatedAt: string
673
+ blockedReason: string | null
674
+ verification: { verdict: string; checkedAt: string } | null
675
+ dependsOn: string[]
676
+ }
677
+ lines.push(c.bold(`Open Work Context — ${pack.workspace}`))
678
+ lines.push("")
679
+ lines.push(`task: ${line(String(t.title), 70)}`)
680
+ lines.push(`status: ${t.status} · revision ${t.revision} · updated ${t.updatedAt}`)
681
+ if (t.blockedReason !== null) lines.push(`blocked reason: ${line(t.blockedReason, 90)}`)
682
+ if (t.verification !== null) {
683
+ lines.push(`verification: ${t.verification.verdict} @ ${t.verification.checkedAt}`)
684
+ }
685
+ if (t.dependsOn.length > 0) lines.push(`depends on: ${t.dependsOn.join(" · ")}`)
686
+ const portfolio = pack.portfolio as {
687
+ state: string
688
+ priority: { level: string }
689
+ nextAction: string
690
+ blockers: unknown[]
691
+ } | null
692
+ if (portfolio !== null) {
693
+ lines.push(`state: ${portfolio.state} · priority ${portfolio.priority.level}`)
694
+ lines.push(`next: ${line(portfolio.nextAction, 90)}`)
695
+ lines.push(`blockers: ${portfolio.blockers.length}`)
696
+ } else {
697
+ lines.push(c.dim("state: not open in the portfolio (terminal or out of scope)"))
698
+ }
699
+ const cp = pack.checkpoint as {
700
+ exists: boolean
701
+ corrupt: boolean
702
+ count: number
703
+ latestTurn: number | null
704
+ }
705
+ lines.push(
706
+ `checkpoint: ${cp.exists ? `${cp.count} entr(ies)${cp.corrupt ? " · CORRUPT" : ""}${cp.latestTurn !== null ? ` · latest turn ${cp.latestTurn}` : ""}` : "none"}`,
707
+ )
708
+ if (pack.declaredDuplicateOf !== null) {
709
+ lines.push(`declared duplicate of: ${pack.declaredDuplicateOf} (audit ledger)`)
710
+ }
711
+ lines.push("")
712
+ lines.push(c.dim(String((pack.resume as { note: string }).note)))
713
+ lines.push(
714
+ c.dim(
715
+ "Resume explicitly: minicode --session <target> --adopt-task <source>/<task>, then /scheduler run.",
716
+ ),
717
+ )
718
+ return lines
719
+ }
720
+
721
+ function handleContext(getArg: (name: string) => string | undefined): never {
722
+ const cwd = getArg("--cwd") ?? process.cwd()
723
+ const asJson = getArg("--json") !== undefined || process.argv.includes("--json")
724
+ const sessionId = getArg("--session")
725
+ const taskId = getArg("--task")
726
+ if (sessionId === undefined || taskId === undefined) {
727
+ usageError("openwork context requires --session <id> --task <taskId>")
728
+ }
729
+ if (!isTaskId(taskId)) {
730
+ usageError(`invalid --task value: "${taskId}" (expected canonical id like t1)`)
731
+ }
732
+ const pack = buildContextPack(cwd, sessionId, taskId)
733
+ if (pack === null) {
734
+ exit1(`task "${taskId}" not found in session "${sessionId}"`)
735
+ }
736
+ if (asJson) {
737
+ emitJson(pack)
738
+ process.exit(0)
739
+ }
740
+ printLines(renderContextHuman(pack))
741
+ process.exit(0)
742
+ }
743
+
744
+ /** MD dieksport ke file = permukaan baca manusia: teks tak-terpercaya disani. */
745
+ function mdCell(value: string): string {
746
+ const safe = sanitizeAnsiLine(value).replace(/\|/g, "\\|").replace(/\r?\n/g, " ")
747
+ return safe.length > 120 ? `${safe.slice(0, 119)}…` : safe
748
+ }
749
+
750
+ function renderMarkdownExport(report: OpenWorkReport, cwd: string, filters: ListFilters): string {
751
+ const out: string[] = []
752
+ out.push(`# Open Work — ${mdCell(resolvePath(cwd))}`)
753
+ out.push("")
754
+ out.push(`- generated: ${report.generatedAtIso}`)
755
+ out.push(`- stale after: ${formatAge(report.staleMs)}`)
756
+ out.push(
757
+ `- counts: ${report.counts.open} open · ${report.counts.intent} intent · ${report.counts.stale} stale · ${report.counts.unknownProvenance} unknown-provenance · ${report.counts.closed} closed · ${report.counts.duplicateGroups} duplicate group(s) · ${report.counts.conflicts} divergent`,
758
+ )
759
+ out.push(`- TaskStore remains the sole status authority; this export is a read-only projection.`)
760
+ if (filters.sessionId !== undefined) out.push(`- session filter: ${mdCell(filters.sessionId)}`)
761
+ out.push("")
762
+ out.push("## Open tasks")
763
+ if (report.open.length === 0) {
764
+ out.push("_none_")
765
+ } else {
766
+ for (const e of report.open) {
767
+ out.push("")
768
+ out.push(`### ${e.sessionId}/${e.taskId} — ${mdCell(e.title)}`)
769
+ out.push(
770
+ `- status: ${e.status} · state: ${e.state} · priority: ${e.priority.level} (${e.priority.reason})`,
771
+ )
772
+ out.push(`- age: ${formatAge(e.ageMs)} old${e.stale ? " · STALE" : ""}`)
773
+ out.push(
774
+ `- provenance: ${e.provenance}${e.transferredFromSessionId !== null ? ` · FROM ${e.transferredFromSessionId}` : ""}`,
775
+ )
776
+ if (e.blockers.length > 0) {
777
+ for (const b of e.blockers) out.push(`- blocker (${b.kind}): ${mdCell(b.detail)}`)
778
+ }
779
+ for (const d of e.dependencies) {
780
+ out.push(
781
+ `- depends on: ${d.taskId} (${d.status}${d.satisfied ? ", satisfied" : ", UNSATISFIED"})`,
782
+ )
783
+ }
784
+ if (e.verification !== null) {
785
+ out.push(`- verification: ${e.verification.verdict} @ ${e.verification.checkedAt}`)
786
+ }
787
+ for (const p of e.planSteps) {
788
+ out.push(
789
+ `- plan evidence: step ${p.stepId} claims "${p.claimedStatus}" (turn ${p.turnId}, event ${p.eventSeq})`,
790
+ )
791
+ }
792
+ if (e.duplicate !== null) {
793
+ out.push(
794
+ `- duplicate group (UNPROVEN): "${mdCell(e.duplicate.key)}" ×${e.duplicate.count} across ${e.duplicate.sessions.length} session(s)${e.duplicate.divergentStates ? " · DIVERGENT STATES" : ""}`,
795
+ )
796
+ }
797
+ out.push(`- next: ${mdCell(e.nextAction)}`)
798
+ }
799
+ }
800
+ out.push("")
801
+ out.push("## Structured intent (from history, read-only)")
802
+ if (report.intent.length === 0) {
803
+ out.push("_none_")
804
+ } else {
805
+ for (const ic of report.intent) {
806
+ out.push(`- [${ic.source}] ${ic.sessionId} · ${ic.state} — ${mdCell(ic.summary)}`)
807
+ out.push(
808
+ ` - reason: ${mdCell(ic.reason)} · provenance: event ${ic.provenance.eventSeq ?? "-"} turn ${ic.provenance.turnId ?? "-"}`,
809
+ )
810
+ out.push(` - next: ${mdCell(nextActionFor(ic.state))}`)
811
+ }
812
+ }
813
+ out.push("")
814
+ out.push("## Duplicate groups (UNPROVEN — never auto-merged)")
815
+ if (report.duplicateGroups.length === 0) {
816
+ out.push("_none_")
817
+ } else {
818
+ for (const g of report.duplicateGroups) {
819
+ out.push(
820
+ `- "${mdCell(g.key)}" ×${g.count} · sessions: ${g.sessions.map((s) => mdCell(s)).join(", ")}${g.divergentStates ? " · DIVERGENT STATES" : ""}`,
821
+ )
822
+ }
823
+ }
824
+ if (report.closed.length > 0) {
825
+ out.push("")
826
+ out.push("## Closure feedback (P14 provenance)")
827
+ for (const e of report.closed) {
828
+ const shown = e.status ?? e.intentState ?? "?"
829
+ out.push(
830
+ `- ${e.sessionId}/${e.taskId ?? "(no task)"} — ${shown} · claim ${e.claim}${e.transferredFromSessionId !== null ? ` · FROM ${e.transferredFromSessionId}` : ""}${e.mergeSurvivorId !== null ? ` · duplicate-of ${e.mergeSurvivorId}` : ""}`,
831
+ )
832
+ out.push(` - ${mdCell(e.reason)}`)
833
+ }
834
+ }
835
+ if (report.inventory !== null) {
836
+ const inv = report.inventory
837
+ out.push("")
838
+ out.push("## Inventory (P14.0)")
839
+ out.push(
840
+ `- sessions: ${inv.sessions.total} total · ${inv.sessions.inScope} in-scope · ${inv.sessions.foreignWorkspace} foreign · ${inv.sessions.unboundWorkspace} unbound · ${inv.sessions.childSessions} child`,
841
+ )
842
+ out.push(
843
+ `- tasks: ${inv.tasks.total} total · ${inv.tasks.open} open · ${inv.tasks.terminal} terminal`,
844
+ )
845
+ out.push(
846
+ `- presentation events: ${inv.presentationEvents.total} (plan ${inv.plans.events} · approvals ${inv.approvals.requested}/${inv.approvals.settled})`,
847
+ )
848
+ out.push(
849
+ `- runs: ${inv.runs.total} total · ${inv.runs.active} active · ${inv.runs.interrupted} interrupted · ${inv.runs.terminal} terminal`,
850
+ )
851
+ out.push(
852
+ `- checkpoints: ${inv.checkpoints.sessionsWithManifest} manifest(s) · ${inv.checkpoints.entries} entries · ${inv.checkpoints.corrupt} corrupt`,
853
+ )
854
+ for (const x of inv.excludedSessions) {
855
+ out.push(`- excluded session: ${mdCell(x.sessionId)} (${x.reason})`)
856
+ }
857
+ }
858
+ if (report.rejectedEvents > 0) {
859
+ out.push("")
860
+ out.push(
861
+ `> ${report.rejectedEvents} presentation event(s) could not be decoded and are reported as unreadable, not hidden.`,
862
+ )
863
+ }
864
+ return out.join("\n")
865
+ }
866
+
867
+ async function handleExport(getArg: (name: string) => string | undefined): Promise<never> {
868
+ const cwd = getArg("--cwd") ?? process.cwd()
869
+ const out = getArg("--out")
870
+ if (out === undefined || out.trim() === "") {
871
+ usageError("openwork export requires --out <path>")
872
+ }
873
+ const format = (getArg("--format") ?? "json").toLowerCase()
874
+ if (format !== "json" && format !== "md") {
875
+ usageError(`invalid --format value: "${getArg("--format")}" (expected json|md)`)
876
+ }
877
+ const force = getArg("--force") !== undefined || process.argv.includes("--force")
878
+ const asJson = getArg("--json") !== undefined || process.argv.includes("--json")
879
+ const filters = parseListFilters(getArg)
880
+ const report = projectOpenWork({ cwd, ...projectionOptions(filters, true) })
881
+ const filtered = applyListFilters(report, filters)
882
+ const content =
883
+ format === "json"
884
+ ? JSON.stringify(filtered, null, 2)
885
+ : renderMarkdownExport(filtered, cwd, filters)
886
+ // `length` = unit UTF-16, bukan byte: judul non-ASCII akan salah lapor.
887
+ const bytes = Buffer.byteLength(content, "utf8")
888
+
889
+ if (existsSync(out) && !force) {
890
+ exit1(
891
+ sanitizeAnsi(`[openwork] export refused: "${out}" already exists (use --force to overwrite)`),
892
+ )
893
+ }
894
+ try {
895
+ await atomicWriteText(resolvePath(out), content)
896
+ } catch (e) {
897
+ exit1(sanitizeAnsi(`[openwork] export failed: ${String((e as Error)?.message ?? e)}`))
898
+ }
899
+ if (asJson) {
900
+ emitJson({ exported: resolvePath(out), format, bytes })
901
+ process.exit(0)
902
+ }
903
+ printLines([sanitizeAnsi(`[openwork] exported ${format} → ${resolvePath(out)} (${bytes} bytes)`)])
904
+ process.exit(0)
905
+ }
906
+
907
+ /**
908
+ * Flag subcommand ini yang MEMAKAN nilai — dipakai `actionAfter` agar nilai
909
+ * flag tidak salah dibaca sebagai nama aksi (`openwork --stale-days 1`).
910
+ */
911
+ const ACTION_VALUE_FLAGS: ReadonlySet<string> = new Set([
912
+ "--cwd",
913
+ "--session",
914
+ "--status",
915
+ "--state",
916
+ "--priority",
917
+ "--min-age-days",
918
+ "--depends-on",
919
+ "--stale-days",
920
+ "--keep",
921
+ "--drop",
922
+ "--evidence",
923
+ "--task",
924
+ "--format",
925
+ "--out",
926
+ ])
927
+
928
+ /**
929
+ * Aksi subcommand = token non-flag PERTAMA setelah token "openwork".
930
+ *
931
+ * `minicode --cwd X openwork merge` → args[1] adalah nilai flag, bukan aksi
932
+ * (pola yang sama dengan I34: flag global mendahului subcommand tetap sah).
933
+ * Router menjamin "openwork" adalah token cmd; di sini kita hanya mencari
934
+ * token sesudahnya, melewati flag DAN nilai flag yang memakannya.
935
+ */
936
+ function actionAfter(args: string[]): string | undefined {
937
+ const at = args.indexOf("openwork")
938
+ if (at < 0) return undefined
939
+ let i = at + 1
940
+ while (i < args.length) {
941
+ const t = args[i]
942
+ if (t === undefined) {
943
+ i++
944
+ continue
945
+ }
946
+ if (t.startsWith("-")) {
947
+ // `--flag=value` sudah satu token; `--flag value` melompati keduanya.
948
+ if (ACTION_VALUE_FLAGS.has(t) && !t.includes("=")) i++
949
+ i++
950
+ continue
951
+ }
952
+ return t
953
+ }
954
+ return undefined
955
+ }
956
+
957
+ export async function handleOpenwork(
958
+ args: string[],
959
+ getArg: (name: string) => string | undefined,
960
+ ): Promise<never> {
961
+ // `--help`/`-h` adalah flag, jadi `actionAfter` (yang hanya mengembalikan
962
+ // token non-flag) tidak akan pernah melihatnya. Tanpa cek eksplisit ini,
963
+ // `minicode openwork --help` diam-diam menjalankan aksi list — kontrak
964
+ // help/exit 0 dilanggar dan teks bantuan tak pernah terbaca.
965
+ if (args.includes("--help") || args.includes("-h")) {
966
+ printLines([OPENWORK_HELP])
967
+ process.exit(0)
968
+ }
969
+ const sub = actionAfter(args)
970
+ if (sub === "merge") {
971
+ handleMerge(getArg)
972
+ }
973
+ if (sub === "inventory") {
974
+ handleInventory(getArg)
975
+ }
976
+ if (sub === "context") {
977
+ handleContext(getArg)
978
+ }
979
+ if (sub === "export") {
980
+ await handleExport(getArg)
981
+ }
982
+ if (sub !== undefined) {
983
+ usageError(`unknown openwork action: ${sub}`)
984
+ }
985
+ handleList(getArg)
986
+ }