@kodax-ai/kodax 0.7.96-rc.13 → 0.7.96-rc.14

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 (82) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +12 -0
  3. package/README_CN.md +10 -1
  4. package/dist/chunks/{agent-UJ7BHOUG.js → agent-VVWK3SNK.js} +1 -1
  5. package/dist/chunks/argument-completer-J42AXXQB.js +2 -0
  6. package/dist/chunks/{chunk-GPC6UUWX.js → chunk-2FRCX7VC.js} +1 -1
  7. package/dist/chunks/{chunk-JKRRFQQJ.js → chunk-5LIWAPYP.js} +2 -2
  8. package/dist/chunks/chunk-BTXW4XR7.js +324 -0
  9. package/dist/chunks/{chunk-LTEH6FVZ.js → chunk-C7U542KM.js} +1 -1
  10. package/dist/chunks/{chunk-WHQCTZKI.js → chunk-DSXUXUZG.js} +1 -1
  11. package/dist/chunks/{chunk-DL22WMXJ.js → chunk-EDGG6R2E.js} +2 -2
  12. package/dist/chunks/{chunk-756FJMN2.js → chunk-EM4XJBTK.js} +1 -1
  13. package/dist/chunks/{chunk-PP4KUTUG.js → chunk-EQYIOHS2.js} +62 -52
  14. package/dist/chunks/{chunk-WCI7MBST.js → chunk-F3JMNBTR.js} +136 -136
  15. package/dist/chunks/{chunk-LB33ZKTK.js → chunk-FF35TUVY.js} +1 -1
  16. package/dist/chunks/{chunk-EHXQHDRY.js → chunk-G5K5FFNK.js} +1 -1
  17. package/dist/chunks/{chunk-IDQ7JZ77.js → chunk-GFQZG53I.js} +2 -2
  18. package/dist/chunks/{chunk-W5XGIRQQ.js → chunk-HZYRLIOC.js} +1 -1
  19. package/dist/chunks/{chunk-QOR4VNBV.js → chunk-NI7PBPUR.js} +1 -1
  20. package/dist/chunks/{chunk-4FOZK6GC.js → chunk-PFWOZDUJ.js} +6 -6
  21. package/dist/chunks/{chunk-SSCW54JN.js → chunk-T7CWLQAK.js} +1 -1
  22. package/dist/chunks/{chunk-Y5364PDZ.js → chunk-UGJQV7AQ.js} +4 -4
  23. package/dist/chunks/{chunk-ZNXVQXDU.js → chunk-VXLWL3R4.js} +8 -8
  24. package/dist/chunks/{chunk-AXKQ3UP4.js → chunk-WV3DJVW4.js} +145 -145
  25. package/dist/chunks/{chunk-JUELOCSB.js → chunk-YEAUDI6U.js} +1 -1
  26. package/dist/chunks/chunk-YXNCYPCT.js +487 -0
  27. package/dist/chunks/{client-RLM3NTBX.js → client-6WZZTTSV.js} +1 -1
  28. package/dist/chunks/{compaction-config-ZH5OJSGN.js → compaction-config-ZMEJU4U7.js} +1 -1
  29. package/dist/chunks/{construction-bootstrap-PUMPMKGZ.js → construction-bootstrap-25PNMLRI.js} +1 -1
  30. package/dist/chunks/dist-3RV2YXUK.js +2 -0
  31. package/dist/chunks/{dist-222EMRS3.js → dist-F5IWZSAY.js} +1 -1
  32. package/dist/chunks/host-4VJ232OA.js +2 -0
  33. package/dist/chunks/run-manager-VBS36P6F.js +2 -0
  34. package/dist/chunks/{utils-NQM56MWV.js → utils-CHRWNLXU.js} +1 -1
  35. package/dist/index.d.ts +9 -9
  36. package/dist/index.js +1 -1
  37. package/dist/kodax_bootstrap.js +1 -1
  38. package/dist/kodax_cli.js +1331 -1320
  39. package/dist/native/win32-x64/kodax-windows-sandbox.exe +0 -0
  40. package/dist/native/win32-x64/kodax-windows-text-transaction.node +0 -0
  41. package/dist/native/win32-x64/manifest.json +2 -2
  42. package/dist/runtime-worker.js +1205 -1194
  43. package/dist/sandbox-network-broker.js +37 -37
  44. package/dist/sdk-a2a.d.ts +5 -5
  45. package/dist/sdk-a2a.js +1 -1
  46. package/dist/sdk-agent.d.ts +52 -5
  47. package/dist/sdk-agent.js +1 -1
  48. package/dist/sdk-coding.d.ts +9 -9
  49. package/dist/sdk-coding.js +1 -1
  50. package/dist/sdk-experimental-memory.js +1 -1
  51. package/dist/sdk-llm.js +1 -1
  52. package/dist/sdk-mcp.js +1 -1
  53. package/dist/sdk-media.js +1 -1
  54. package/dist/sdk-repl.d.ts +9 -9
  55. package/dist/sdk-repl.js +1 -1
  56. package/dist/sdk-runtime.d.ts +5 -5
  57. package/dist/sdk-runtime.js +1 -1
  58. package/dist/sdk-sandbox.js +1 -1
  59. package/dist/sdk-session.d.ts +3 -3
  60. package/dist/sdk-session.js +1 -1
  61. package/dist/sdk-skills.js +1 -1
  62. package/dist/semantic-worker.js +55 -55
  63. package/dist/types-chunks/{bash-prefix-extractor.d-D9JqJf87.d.ts → bash-prefix-extractor.d-DWFIMg0v.d.ts} +42 -2
  64. package/dist/types-chunks/{capsule.d-gqTRID3o.d.ts → capsule.d-Dj1n6s0Y.d.ts} +12 -8
  65. package/dist/types-chunks/{exec-policy.d-W3RIoR8N.d.ts → exec-policy.d-BPESl90L.d.ts} +1 -1
  66. package/dist/types-chunks/{public-api.d-Begw7CBI.d.ts → public-api.d-amBop8Nk.d.ts} +2 -2
  67. package/dist/types-chunks/{sdk-session-BwQpDe2N.d.ts → sdk-session-B6XjHNU1.d.ts} +1 -1
  68. package/dist/types-chunks/{shell-command-sets.d-HJBUc3lt.d.ts → shell-command-sets.d-oejwpP_7.d.ts} +1 -1
  69. package/dist/types-chunks/{trusted-repl-entry-BWSNtIL6.d.ts → trusted-repl-entry-D0w5M0UZ.d.ts} +4 -4
  70. package/dist/types-chunks/{types.d-CqdxWKIF.d.ts → types.d-CtO8mR1s.d.ts} +1 -1
  71. package/dist/types-chunks/{utils.d-ysjiP5BR.d.ts → utils.d-DcznBeQ3.d.ts} +3 -3
  72. package/package.json +1 -1
  73. package/public_docs/README.md +2 -2
  74. package/public_docs/configuration/providers.md +6 -0
  75. package/public_docs/configuration/sandbox.md +14 -5
  76. package/public_docs/sdk/embedder-guide.md +74 -7
  77. package/dist/chunks/argument-completer-TWAD3ONJ.js +0 -2
  78. package/dist/chunks/chunk-HQTFW77B.js +0 -324
  79. package/dist/chunks/chunk-RCKQNNA7.js +0 -486
  80. package/dist/chunks/dist-LSUIJBVY.js +0 -2
  81. package/dist/chunks/host-Z5PRROMO.js +0 -2
  82. package/dist/chunks/run-manager-EC443FWI.js +0 -2
package/CHANGELOG.md CHANGED
@@ -8,6 +8,91 @@ All notable changes to this project will be documented in this file.
8
8
 
9
9
  ---
10
10
 
11
+ ## [0.7.96-rc.14] - 2026-10-01
12
+
13
+ Fourteenth release candidate of the v0.7.96 line: interrupted-Run recovery
14
+ reaches coding Runs and managed execution with budgeted turn-matched
15
+ records, tool-history pairing and compaction-copy tracing become provable,
16
+ Anthropic-compatible providers ignore inherited `ANTHROPIC_AUTH_TOKEN`, the
17
+ Ink host defers to the Runtime as the single transcript writer, and Windows
18
+ interactive startup re-verifies the NUL account ACE behind a current setup
19
+ marker after a reboot. CI now runs inside the tag-triggered Release
20
+ workflow instead of on branch pushes. Every rc.13 contract is retained. npm
21
+ publication remains a manual maintainer action.
22
+
23
+ ### Fixed
24
+
25
+ - Interactive Windows startup verifies the live NUL sandbox-account grant
26
+ before trusting the durable setup marker. Missing access enters the existing
27
+ setup recovery boundary; installation omits historical read roots whose
28
+ files disappeared. SDK/daemon startup and ordinary admission remain
29
+ read-only and do not activate setup automatically (Issue 341).
30
+ - Windows sandbox unit tests provision mock-SID artifacts and remove recovery
31
+ fixtures in a private temporary native cache, so they no longer interfere
32
+ with live sandbox commands using the host's shared cache. The native
33
+ provisioning suite still requires an ordinary host token (Issue 343).
34
+ - Tool-history validation pairs calls with results across the whole assistant
35
+ scope, so an internal managed-run context message between them no longer
36
+ strips both halves of the pair (Issue 340).
37
+ - Failed managed provider calls hand back the Runner transcript they received,
38
+ not provider-normalized request copies, so compatibility cleanup never becomes
39
+ persisted history.
40
+ - Conversation resolution restores active-path entries damaged by the old
41
+ adjacent-only cleanup when a retained sibling chain reproduces the damage
42
+ exactly; unproven cases stay ambiguous. The page cache version is bumped so
43
+ existing v6 caches rebuild once.
44
+ - The next managed or coding Run of a Session receives a labelled, bounded,
45
+ transient record of journaled progress from an earlier unfinished Run on the
46
+ active branch: confirmed results, operations whose result is unknown, and
47
+ unconfirmed excerpts of assistant text the Run streamed but never saved. The
48
+ record is never saved and each part disappears once history contains it.
49
+ Operations from every included Run take the size bound before any excerpt.
50
+ Operations match history per turn, so a provider reusing a tool call id in a
51
+ later turn no longer hides an earlier unfinished operation, and the source
52
+ tracing also covers histories compacted again before this fix.
53
+ - Conversation resolution traces a compaction copy of a copy back to its first
54
+ retained predecessor, so re-compacted history no longer shows the same
55
+ message twice. When an older compaction boundary cannot be proven, history
56
+ is truncated at that boundary and reported as `partial` with
57
+ `compaction_history_truncated`, instead of flattening unproven regions into
58
+ one conversation. The page cache version is bumped to 9.
59
+ - Anthropic-compatible providers no longer pick up an inherited
60
+ `ANTHROPIC_AUTH_TOKEN`. The SDK sent it as a Bearer header next to the
61
+ provider key, so gateways such as zhipu-coding and deepseek returned 401 and
62
+ the Anthropic token reached a third-party endpoint. The native Anthropic
63
+ provider is unchanged.
64
+ - Compare PowerShell-emitted native artifact and control-directory paths
65
+ through long-form realpaths when the literal comparison disagrees.
66
+ PowerShell's `GetFullPath` expands 8.3 path components, so a runner whose
67
+ `TEMP` root uses a short name (`C:\Users\RUNNER~1\...`) made the private
68
+ test native-artifact cache provisioning fail with an unexpected-path error
69
+ even though the provisioner returned the canonical destination.
70
+ - The interactive REPL no longer forks a duplicate branch every round when a
71
+ Runtime owns the Session. The host stops writing its own lineage. Storage
72
+ reconciles host saves against the Runtime's durable lineage, and the host
73
+ continues from the Runtime's entry ids. That fixes three problems:
74
+ - The next host save no longer replaces the Runtime's branch.
75
+ - A crash between the two writes no longer leaves a permanent fork.
76
+ - A Run cancelled before it produced a result no longer clears the host's
77
+ transcript copy.
78
+
79
+ ### Changed
80
+
81
+ - CI runs through `workflow_call` or manual dispatch instead of branch pushes
82
+ and pull requests. Tag and manually dispatched release builds run the full
83
+ reusable CI workflow before their build matrix.
84
+
85
+ ### Documentation
86
+
87
+ - Align the public SDK guide with read-only legacy history repair, partial
88
+ compaction truncation, transient interrupted-Run recovery, and Runtime-owned
89
+ transcript persistence. Document the CLI-only NUL recovery boundary and
90
+ provider authentication isolation.
91
+ - Track unexpected interactive REPL exit as unresolved (Issue 342). Successful
92
+ SDK concurrency and full-TTY trace replay do not resolve that failure.
93
+
94
+ ---
95
+
11
96
  ## [0.7.96-rc.13] - 2026-09-29
12
97
 
13
98
  Thirteenth release candidate of the v0.7.96 line: Runtime-owned managed
package/README.md CHANGED
@@ -786,6 +786,18 @@ provider's model, REPL `/compact` clears the UI only after a durable save, and
786
786
  successful reports carry bounded `summaryRequests` plus `commitMs` per
787
787
  physical summary call.
788
788
 
789
+ **v0.7.96-rc.14 release:** Fourteenth release candidate of the v0.7.96
790
+ line. Interrupted-Run recovery reaches coding Runs and managed execution
791
+ with a labelled, bounded, transient record of journaled progress matched
792
+ per turn; tool-history pairing spans the whole assistant scope;
793
+ conversation resolution traces compaction copies to a provable root and
794
+ truncates unproven boundaries as `partial`; Anthropic-compatible providers
795
+ ignore an inherited `ANTHROPIC_AUTH_TOKEN`; the Ink host defers to the
796
+ Runtime as the single transcript writer; and Windows interactive startup
797
+ re-verifies the NUL account ACE behind a current setup marker after a
798
+ reboot (Issues 340-341). CI now runs inside the tag-triggered Release
799
+ workflow instead of on branch pushes. Every rc.13 contract is retained.
800
+
789
801
  **v0.7.96-rc.13 release:** Thirteenth release candidate of the v0.7.96
790
802
  line. Runtime-owned managed runs persist generated assistant messages and
791
803
  tool results at Runner commit boundaries, before tools or subsequent
package/README_CN.md CHANGED
@@ -296,6 +296,15 @@ SDK 系统代码契约更新,但没有放宽 shell/sandbox 的 fail-closed 边
296
296
  `handleRuntimePermissionRequest()` 管理 SDK 权限 UI,并在 prepared Session 尾部遇到
297
297
  `data_changed` 时通过权威 delta 合并恢复;后台持久化失败会显示为诊断,不再静默丢失。
298
298
 
299
+ **v0.7.96-rc.14 发布**:v0.7.96 线第十四个发布候选。中断 Run 的恢复进入
300
+ coding Run 与托管执行:以带标签、有界、临时的记录按回合匹配交接已日志化的
301
+ 进度;工具历史配对覆盖整个 assistant 范围;会话解析把压缩副本追溯到可证明
302
+ 的根,无法证明的边界以 `partial` 截断;Anthropic 兼容 Provider 不再继承
303
+ `ANTHROPIC_AUTH_TOKEN`;Ink 宿主让位给 Runtime 作为唯一转录写入者;
304
+ Windows 交互启动在重启后面对仍有效的 setup 标记会重新校验 NUL 账户 ACE
305
+ (Issues 340-341)。CI 改为在 tag 触发的 Release workflow 内运行,普通
306
+ push 不再触发。所有 rc.13 契约全部保留。
307
+
299
308
  **v0.7.96-rc.13 发布**:v0.7.96 线第十三个发布候选。Runtime 拥有的托管 Run
300
309
  在 Runner 消息提交边界持久化已生成的助手消息与工具结果,赶在工具或后续
301
310
  Provider 调用可能挂起之前:当前压缩后的转录与排队输入身份在中断的 Run 中
@@ -461,7 +470,7 @@ native 文本权威改在摘要固定的 `manylinux_2_28` 构建器中编译,
461
470
  scope 在 SDK、Agent 摘要、CLI 与 Runtime Worker 请求间共享,保留结构化的 Child Agent Provider
462
471
  失败信息,精确遵循 run-scoped 凭据校验,并为严格 vLLM 网关省略空 `tools` 数组(Issues 329-332)。
463
472
  npm 发布仍由
464
- 维护者手动执行。详见 [v0.7.96-rc.13 发布清单](docs/release.md#v0796-rc13-release-preparation)。
473
+ 维护者手动执行。详见 [v0.7.96-rc.14 发布清单](docs/release.md#v0796-rc14-release-preparation)。
465
474
 
466
475
  **v0.7.96-alpha.3 发布**:Provider 凭据成为惰性、受限、可撤销的能力(ADR-068)。v2
467
476
  credential broker 将 Provider 密钥保留在 OS keychain,按每次 wire call、为单一封闭
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ab as k,Qa as g,Sa as h,a as c,la as d,ma as e,na as f,rb as i,sb as j}from"./chunk-PP4KUTUG.js";import"./chunk-756FJMN2.js";import"./chunk-4FOZK6GC.js";import"./chunk-LTEH6FVZ.js";import"./chunk-QOR4VNBV.js";import{Rb as a,Sb as b}from"./chunk-AXKQ3UP4.js";import"./chunk-WHQCTZKI.js";import"./chunk-W5XGIRQQ.js";import"./chunk-ONUPGMER.js";export{e as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,f as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,c as emitResilienceDebug,d as estimateProviderPayloadBytes,k as runKodaX,j as saveRequiredSessionSnapshot,i as saveSessionSnapshot,a as validateAndFixToolHistory};
2
+ import{Fb as k,Va as g,Xa as h,a as c,qa as d,ra as e,sa as f,wb as i,xb as j}from"./chunk-EQYIOHS2.js";import"./chunk-EM4XJBTK.js";import"./chunk-PFWOZDUJ.js";import"./chunk-C7U542KM.js";import"./chunk-NI7PBPUR.js";import{Rb as a,Sb as b}from"./chunk-WV3DJVW4.js";import"./chunk-DSXUXUZG.js";import"./chunk-HZYRLIOC.js";import"./chunk-ONUPGMER.js";export{e as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,f as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,c as emitResilienceDebug,d as estimateProviderPayloadBytes,k as runKodaX,j as saveRequiredSessionSnapshot,i as saveSessionSnapshot,a as validateAndFixToolHistory};
@@ -0,0 +1,2 @@
1
+ // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
+ import{Ma as a,Na as b}from"./chunk-GFQZG53I.js";import"./chunk-EDGG6R2E.js";import"./chunk-YEAUDI6U.js";import"./chunk-F3JMNBTR.js";import"./chunk-T7CWLQAK.js";import"./chunk-5LIWAPYP.js";import"./chunk-EQYIOHS2.js";import"./chunk-EM4XJBTK.js";import"./chunk-PFWOZDUJ.js";import"./chunk-C7U542KM.js";import"./chunk-NI7PBPUR.js";import"./chunk-WV3DJVW4.js";import"./chunk-DSXUXUZG.js";import"./chunk-HZYRLIOC.js";import"./chunk-ONUPGMER.js";export{a as ArgumentCompleter,b as createArgumentCompleter};
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{g,i as x,j as v}from"./chunk-Y5364PDZ.js";import{c as T}from"./chunk-4FOZK6GC.js";import{a as d}from"./chunk-ONUPGMER.js";import u from"node:fs";import{createHash as C}from"node:crypto";import{createRequire as O}from"node:module";import l from"node:path";var h=5;var E=O(import.meta.url),S=3e4,f;function P(t,o){let e=t.replaceAll("/","\\"),a=e.toLowerCase(),r=e.slice(3),c=(r===""?[]:r.split("\\")).some(n=>{let i=n.split(".",1)[0].toUpperCase(),p=["CON","PRN","AUX","NUL","CONIN$","CONOUT$"].includes(i)||/^(?:COM|LPT)[1-9¹²³]$/.test(i);return n===""||n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||/[\u0000-\u001f<>"|?*]/.test(n)||/~[0-9¹²³]/.test(n)||p});if(t.includes("\0")||e.startsWith("\\\\")||a.startsWith("\\??\\")||a.startsWith("\\device\\")||a.startsWith("\\global??\\")||a.startsWith("globalroot\\")||!/^[A-Za-z]:\\/.test(e)||e.slice(2).includes(":")||c)throw new T({code:"text_mutation_unsafe_path",path:t,message:`Trusted text mutation ${o} must use a local drive-absolute path; UNC and device namespaces are denied: ${t}`})}d(P,"assertLocalDriveAbsolutePath");function m(t,o){if(process.platform==="win32"){P(t,o);return}if(t.includes("\0")||!l.isAbsolute(t)||t.startsWith("//"))throw new T({code:"text_mutation_unsafe_path",path:t,message:`Trusted text mutation ${o} must use a local absolute path: ${t}`})}d(m,"assertSupportedAbsolutePath");function y(t,o){let e=l.relative(t,o);return e===""||!e.startsWith("..")&&!l.isAbsolute(e)}d(y,"sameOrInside");function A(t){let o=new Map;for(let e of t){let a=l.resolve(e),r=process.platform==="win32"?a.toLowerCase():a;o.has(r)||o.set(r,a)}return[...o.values()].sort((e,a)=>a.length-e.length)}d(A,"normalizedRootCandidates");function w(t,o,e=!1){m(t,"target");for(let n of o)m(n,"write root");let a=l.resolve(t),r=[...A(o)];if(e){let n=l.dirname(a);for(;!u.existsSync(n);){let i=l.dirname(n);if(i===n)break;n=i}r.unshift(n)}let s=r.find(n=>n!==a&&y(n,a)),c=d(n=>{try{if(!u.lstatSync(n).isDirectory())throw new Error("write root is not a directory");return u.realpathSync.native(n)}catch(i){throw new T({code:"text_mutation_unsafe_path",path:t,message:`Trusted text mutation write root is unavailable: ${n}`,cause:i})}},"canonicalizeRoot");if(s!==void 0){let n=c(s);return{canonicalRoot:n,canonicalTarget:l.join(n,l.relative(s,a))}}for(let n of r){let i=c(n);if(i!==a&&y(i,a))return{canonicalRoot:i,canonicalTarget:a}}throw new T({code:"text_mutation_policy_denied",path:t,message:`Trusted text mutation target is outside the Runtime write roots: ${t}`})}d(w,"authorizeTarget");function _(t,o=t){if(g(t),f!==void 0)return f;let e=v(import.meta.url,h,t,o),a=K(e);return f=X(a),f}d(_,"loadNativeBinding");function X(t){if(typeof t.textTransactionProtocol!="function"||typeof t.TrustedTextTransactionRoot!="function"||t.textTransactionProtocol()!==h)throw new Error(`The KodaX trusted text transaction binding must implement protocol ${h}.`);return t}d(X,"validateNativeBinding");function K(t){if(process.platform==="win32")return E(t);let o=u.openSync(t,u.constants.O_RDONLY|u.constants.O_NOFOLLOW);try{let e=u.fstatSync(o);if(!e.isFile()||e.nlink!==1||e.size>64*1024*1024)throw new Error("The protected native text binding has an unsafe identity.");let a=l.basename(l.dirname(t)).toLowerCase(),r=u.readFileSync(o),s=C("sha256").update(r).digest("hex");if(!/^[0-9a-f]{64}$/.test(a)||s!==a)throw new Error("The protected native text binding changed after provisioning.");let c={exports:{}},n=process.platform==="linux"?`/proc/self/fd/${o}`:`/dev/fd/${o}`;return process.dlopen(c,n),c.exports}finally{u.closeSync(o)}}d(K,"loadNativeBindingFile");function N(t,o,e){return process.platform==="win32"?new t.TrustedTextTransactionRoot(o,void 0,e):new t.TrustedTextTransactionRoot(o,x(),e)}d(N,"createNativeRoot");function k(t){switch(t){case"invalid_path":case"reparse_point":case"hard_link":return"text_mutation_unsafe_path";case"unauthorized_path":return"text_mutation_policy_denied";case"remote_filesystem":case"unsupported_filesystem":case"unsupported_platform":return"text_mutation_unsupported_filesystem";case"contended":return"text_mutation_contended";case"stale":return"text_mutation_stale";case"metadata_preservation":return"text_mutation_metadata_preservation_failed";default:return"text_mutation_io_failed"}}d(k,"mappedNativeErrorCode");function R(t,o){if(o instanceof T)throw o;let e=o instanceof Error?o.message:String(o),a="KODAX_TEXT_TRANSACTION:",r=e.indexOf(a),s={};if(r>=0)try{let c=JSON.parse(e.slice(r+a.length));c!==null&&typeof c=="object"&&!Array.isArray(c)&&(s=c)}catch{s={}}throw new T({code:k(s.code),path:t,message:s.message??e,...typeof s.os_code=="number"?{osCode:s.os_code}:{},cause:o})}d(R,"translateNativeError");function B(t){return{state:t.state,content:t.content,revision:t.revision,slot:t.slotId,canonicalPath:t.canonicalPath}}d(B,"publicSnapshot");function L(t,o,e){if(e.status==="stale"){if(typeof e.currentRevision!="string")throw new Error("Native text transaction returned a stale result without a revision.");return{status:"stale",currentRevision:e.currentRevision}}if(typeof e.slotId!="string"||typeof e.preContent!="string"||typeof e.preRevision!="string"||typeof e.postRevision!="string")throw new Error("Native text transaction returned an incomplete commit receipt.");let a={before:{state:e.preRevision.startsWith("missing:")?"missing":"present",content:e.preContent,revision:e.preRevision,slot:e.slotId,canonicalPath:t},after:{state:"present",content:o,revision:e.postRevision,slot:e.slotId,canonicalPath:t},recoveredAbandonedLock:e.abandonedLock===!0};if(e.status==="committed_uncertain"){if(typeof e.message!="string"||e.message==="")throw new Error("Native text transaction returned an uncertain commit without a reason.");return{status:"committed_uncertain",...a,reason:e.message}}return{status:"written",...a}}d(L,"requireWrittenOutcome");function F(t,o,e=()=>!1,a){return{async snapshot(r){if(r.signal?.aborted)throw r.signal.reason;m(r.path,"target");let s=e(),c=a?.(r.toolCall,r.path,"snapshot")===!0,n=w(r.path,t(),s||c);o(n.canonicalTarget),g([n.canonicalTarget]);try{let i=_([n.canonicalTarget],t()),p=N(i,n.canonicalRoot,s);return B(await p.snapshot(n.canonicalTarget))}catch(i){R(n.canonicalTarget,i)}},async commit(r){if(r.signal?.aborted)throw r.signal.reason;m(r.path,"target");let s=e(),c=a?.(r.toolCall,r.path,"commit")===!0,n=w(r.path,t(),s||c);o(n.canonicalTarget),g([n.canonicalTarget]);try{let i=_([n.canonicalTarget],t()),b=await N(i,n.canonicalRoot,s).commit(n.canonicalTarget,r.expectedRevision,r.content,r.createParentDirectories,S);return L(n.canonicalTarget,r.content,b)}catch(i){R(n.canonicalTarget,i)}}}}d(F,"createTrustedTextMutationHost");import W from"node:path";import{isDeepStrictEqual as I}from"node:util";var $=new Set(["write","edit","multi_edit","insert_after_anchor"]);function Z(t,o){let e=new Map,a=d(r=>{let s=W.resolve(t,r);return process.platform==="win32"?s.toLowerCase():s},"normalize");return{grant(r){!o()||!$.has(r.name)||typeof r.input.path!="string"||e.set(r.id,{call:structuredClone(r),target:a(r.input.path),phase:"snapshot"})},authorize(r,s,c){if(!o())return e.clear(),!1;let n=r===void 0?void 0:e.get(r.id);return!n||n.phase!==c||a(s)!==n.target||!I(r,n.call)?!1:(c==="snapshot"?n.phase="commit":e.delete(n.call.id),!0)},revoke(r){e.delete(r)},clear(){e.clear()}}}d(Z,"createTrustedTextApprovals");export{F as a,Z as b};
2
+ import{g,i as x,j as v}from"./chunk-UGJQV7AQ.js";import{c as T}from"./chunk-PFWOZDUJ.js";import{a as d}from"./chunk-ONUPGMER.js";import u from"node:fs";import{createHash as C}from"node:crypto";import{createRequire as O}from"node:module";import l from"node:path";var h=5;var E=O(import.meta.url),S=3e4,f;function P(t,o){let e=t.replaceAll("/","\\"),a=e.toLowerCase(),r=e.slice(3),c=(r===""?[]:r.split("\\")).some(n=>{let i=n.split(".",1)[0].toUpperCase(),p=["CON","PRN","AUX","NUL","CONIN$","CONOUT$"].includes(i)||/^(?:COM|LPT)[1-9¹²³]$/.test(i);return n===""||n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||/[\u0000-\u001f<>"|?*]/.test(n)||/~[0-9¹²³]/.test(n)||p});if(t.includes("\0")||e.startsWith("\\\\")||a.startsWith("\\??\\")||a.startsWith("\\device\\")||a.startsWith("\\global??\\")||a.startsWith("globalroot\\")||!/^[A-Za-z]:\\/.test(e)||e.slice(2).includes(":")||c)throw new T({code:"text_mutation_unsafe_path",path:t,message:`Trusted text mutation ${o} must use a local drive-absolute path; UNC and device namespaces are denied: ${t}`})}d(P,"assertLocalDriveAbsolutePath");function m(t,o){if(process.platform==="win32"){P(t,o);return}if(t.includes("\0")||!l.isAbsolute(t)||t.startsWith("//"))throw new T({code:"text_mutation_unsafe_path",path:t,message:`Trusted text mutation ${o} must use a local absolute path: ${t}`})}d(m,"assertSupportedAbsolutePath");function y(t,o){let e=l.relative(t,o);return e===""||!e.startsWith("..")&&!l.isAbsolute(e)}d(y,"sameOrInside");function A(t){let o=new Map;for(let e of t){let a=l.resolve(e),r=process.platform==="win32"?a.toLowerCase():a;o.has(r)||o.set(r,a)}return[...o.values()].sort((e,a)=>a.length-e.length)}d(A,"normalizedRootCandidates");function w(t,o,e=!1){m(t,"target");for(let n of o)m(n,"write root");let a=l.resolve(t),r=[...A(o)];if(e){let n=l.dirname(a);for(;!u.existsSync(n);){let i=l.dirname(n);if(i===n)break;n=i}r.unshift(n)}let s=r.find(n=>n!==a&&y(n,a)),c=d(n=>{try{if(!u.lstatSync(n).isDirectory())throw new Error("write root is not a directory");return u.realpathSync.native(n)}catch(i){throw new T({code:"text_mutation_unsafe_path",path:t,message:`Trusted text mutation write root is unavailable: ${n}`,cause:i})}},"canonicalizeRoot");if(s!==void 0){let n=c(s);return{canonicalRoot:n,canonicalTarget:l.join(n,l.relative(s,a))}}for(let n of r){let i=c(n);if(i!==a&&y(i,a))return{canonicalRoot:i,canonicalTarget:a}}throw new T({code:"text_mutation_policy_denied",path:t,message:`Trusted text mutation target is outside the Runtime write roots: ${t}`})}d(w,"authorizeTarget");function _(t,o=t){if(g(t),f!==void 0)return f;let e=v(import.meta.url,h,t,o),a=K(e);return f=X(a),f}d(_,"loadNativeBinding");function X(t){if(typeof t.textTransactionProtocol!="function"||typeof t.TrustedTextTransactionRoot!="function"||t.textTransactionProtocol()!==h)throw new Error(`The KodaX trusted text transaction binding must implement protocol ${h}.`);return t}d(X,"validateNativeBinding");function K(t){if(process.platform==="win32")return E(t);let o=u.openSync(t,u.constants.O_RDONLY|u.constants.O_NOFOLLOW);try{let e=u.fstatSync(o);if(!e.isFile()||e.nlink!==1||e.size>64*1024*1024)throw new Error("The protected native text binding has an unsafe identity.");let a=l.basename(l.dirname(t)).toLowerCase(),r=u.readFileSync(o),s=C("sha256").update(r).digest("hex");if(!/^[0-9a-f]{64}$/.test(a)||s!==a)throw new Error("The protected native text binding changed after provisioning.");let c={exports:{}},n=process.platform==="linux"?`/proc/self/fd/${o}`:`/dev/fd/${o}`;return process.dlopen(c,n),c.exports}finally{u.closeSync(o)}}d(K,"loadNativeBindingFile");function N(t,o,e){return process.platform==="win32"?new t.TrustedTextTransactionRoot(o,void 0,e):new t.TrustedTextTransactionRoot(o,x(),e)}d(N,"createNativeRoot");function k(t){switch(t){case"invalid_path":case"reparse_point":case"hard_link":return"text_mutation_unsafe_path";case"unauthorized_path":return"text_mutation_policy_denied";case"remote_filesystem":case"unsupported_filesystem":case"unsupported_platform":return"text_mutation_unsupported_filesystem";case"contended":return"text_mutation_contended";case"stale":return"text_mutation_stale";case"metadata_preservation":return"text_mutation_metadata_preservation_failed";default:return"text_mutation_io_failed"}}d(k,"mappedNativeErrorCode");function R(t,o){if(o instanceof T)throw o;let e=o instanceof Error?o.message:String(o),a="KODAX_TEXT_TRANSACTION:",r=e.indexOf(a),s={};if(r>=0)try{let c=JSON.parse(e.slice(r+a.length));c!==null&&typeof c=="object"&&!Array.isArray(c)&&(s=c)}catch{s={}}throw new T({code:k(s.code),path:t,message:s.message??e,...typeof s.os_code=="number"?{osCode:s.os_code}:{},cause:o})}d(R,"translateNativeError");function B(t){return{state:t.state,content:t.content,revision:t.revision,slot:t.slotId,canonicalPath:t.canonicalPath}}d(B,"publicSnapshot");function L(t,o,e){if(e.status==="stale"){if(typeof e.currentRevision!="string")throw new Error("Native text transaction returned a stale result without a revision.");return{status:"stale",currentRevision:e.currentRevision}}if(typeof e.slotId!="string"||typeof e.preContent!="string"||typeof e.preRevision!="string"||typeof e.postRevision!="string")throw new Error("Native text transaction returned an incomplete commit receipt.");let a={before:{state:e.preRevision.startsWith("missing:")?"missing":"present",content:e.preContent,revision:e.preRevision,slot:e.slotId,canonicalPath:t},after:{state:"present",content:o,revision:e.postRevision,slot:e.slotId,canonicalPath:t},recoveredAbandonedLock:e.abandonedLock===!0};if(e.status==="committed_uncertain"){if(typeof e.message!="string"||e.message==="")throw new Error("Native text transaction returned an uncertain commit without a reason.");return{status:"committed_uncertain",...a,reason:e.message}}return{status:"written",...a}}d(L,"requireWrittenOutcome");function F(t,o,e=()=>!1,a){return{async snapshot(r){if(r.signal?.aborted)throw r.signal.reason;m(r.path,"target");let s=e(),c=a?.(r.toolCall,r.path,"snapshot")===!0,n=w(r.path,t(),s||c);o(n.canonicalTarget),g([n.canonicalTarget]);try{let i=_([n.canonicalTarget],t()),p=N(i,n.canonicalRoot,s);return B(await p.snapshot(n.canonicalTarget))}catch(i){R(n.canonicalTarget,i)}},async commit(r){if(r.signal?.aborted)throw r.signal.reason;m(r.path,"target");let s=e(),c=a?.(r.toolCall,r.path,"commit")===!0,n=w(r.path,t(),s||c);o(n.canonicalTarget),g([n.canonicalTarget]);try{let i=_([n.canonicalTarget],t()),b=await N(i,n.canonicalRoot,s).commit(n.canonicalTarget,r.expectedRevision,r.content,r.createParentDirectories,S);return L(n.canonicalTarget,r.content,b)}catch(i){R(n.canonicalTarget,i)}}}}d(F,"createTrustedTextMutationHost");import W from"node:path";import{isDeepStrictEqual as I}from"node:util";var $=new Set(["write","edit","multi_edit","insert_after_anchor"]);function Z(t,o){let e=new Map,a=d(r=>{let s=W.resolve(t,r);return process.platform==="win32"?s.toLowerCase():s},"normalize");return{grant(r){!o()||!$.has(r.name)||typeof r.input.path!="string"||e.set(r.id,{call:structuredClone(r),target:a(r.input.path),phase:"snapshot"})},authorize(r,s,c){if(!o())return e.clear(),!1;let n=r===void 0?void 0:e.get(r.id);return!n||n.phase!==c||a(s)!==n.target||!I(r,n.call)?!1:(c==="snapshot"?n.phase="commit":e.delete(n.call.id),!0)},revoke(r){e.delete(r)},clear(){e.clear()}}}d(Z,"createTrustedTextApprovals");export{F as a,Z as b};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Fe as Ye,Ge as Ze,He as Qe,Ke as et,Qb as Le,Rb as ze,Ub as Ge,Vb as Je,ye as he,ze as Xe}from"./chunk-4FOZK6GC.js";import{Ag as Z,Eg as pe,Kg as we,Lg as B,Mg as ge,Ng as Ve,Ug as Be,Vg as He,Wa as re,Wg as Ke,ug as oe,v as me,xg as je,yg as Ue}from"./chunk-AXKQ3UP4.js";import{aa as De}from"./chunk-W5XGIRQQ.js";import{a as i}from"./chunk-ONUPGMER.js";import{basename as vr,dirname as Sr}from"node:path";import{execFile as en}from"node:child_process";import ie from"node:path";import{promisify as tn}from"node:util";var nn=tn(en),rn=1e4,st=2,tt=new Set(["write","edit","multi_edit","insert_after_anchor"]),nt=new Set(["read"]);function on(e,t){if(t.includes("*"))return e;if(e.includes("*"))return t;let n=new Set(t);return e.filter(r=>n.has(r))}i(on,"intersectWorkflowToolCeilings");var an=/^\s*(?:let me|i will|i'll|i am going to)\b[\s\S]{0,120}\b(?:start|create|implement|write|build|plan)\b|^\s*(?:我将|让我|接下来)[\s\S]{0,80}(?:开始|创建|编写|实现|制定)/i;function sn(e){if(e?.timeoutMs!==void 0){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new Error("workflow wait timeoutMs must be a positive number");return Math.floor(e.timeoutMs)}}i(sn,"normalizeWaitTimeoutMs");function ye(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}i(ye,"hasVerificationWork");function H(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}i(H,"normalizeWorkspacePath");function ke(e,t){let n=t.gitRoot?ie.resolve(t.gitRoot):void 0,r=ie.isAbsolute(e)&&n?ie.relative(n,ie.resolve(e)):e;return H(r)}i(ke,"normalizeRequiredPath");function cn(e){let t=(e.readOnly??!1)===!1?{enforcement:"warn",requiresMutation:!0,rejectPreparatoryFinalText:!0}:void 0;if(e.verification!==void 0){let n={...t??{},...e.verification,enforcement:e.verification.enforcement??"hard"},r=e.verification.requiredChangedPaths;return{verification:{...n,...r!==void 0&&r.length>0&&n.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}i(cn,"resolveVerificationForInput");function dn(e,t){if(t===!0&&e.readOnly===!1)throw new Error(`workflow manifest readOnly=true cannot spawn write-capable child "${e.name}"; set the workflow manifest readOnly=false or use child readOnly:true`);let n=e.readOnly??t??!1;return e.readOnly===n?e:{...e,readOnly:n}}i(dn,"resolveSpawnAgentInput");function ct(e){let t=e.trim();return t.length>0&&an.test(t)}i(ct,"isPreparatoryOnlyText");function un(e,t){let n=e.trim(),r=t?.trim();return r&&(n.length===0||ct(n))?r:e}i(un,"selectWorkflowFinalText");async function ae(e,t){return await re({cwd:t}),(await nn("git",[...e],{cwd:t,timeout:rn,windowsHide:!0,maxBuffer:4*1024*1024})).stdout.toString()}i(ae,"runGit");async function ln(e){let t=e.gitRoot??e.executionCwd??process.cwd(),n=(await ae(["rev-parse","--show-toplevel"],t)).trim(),r=await Promise.all([ae(["diff","--name-only","--"],n),ae(["diff","--cached","--name-only","--"],n),ae(["ls-files","--others","--exclude-standard"],n)]);return[...new Set(r.flatMap(a=>a.split(/\r?\n/)).map(H).filter(a=>a.length>0))]}i(ln,"listGitChangedFiles");async function ve(e,t){try{return{paths:(await t(e)).map(H).filter(r=>r.length>0)}}catch(n){return{paths:[],error:n instanceof Error?n.message:String(n)}}}i(ve,"captureChangedPaths");function fn(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[],readPathById:new Map,succeededReadPaths:[]}}i(fn,"createMutationRecorder");function rt(e){if(e)for(let t of["path","file_path","target_path"]){let n=e[t];if(typeof n=="string"&&n.trim().length>0)return H(n)}}i(rt,"readMutationPath");function mn(e,t){return{...e??{},onToolUseStart:i((n,r)=>{if(tt.has(n.name)){t.toolNameById.set(n.id,n.name);let a=rt(n.input);a!==void 0&&t.toolPathById.set(n.id,a)}if(nt.has(n.name)){let a=rt(n.input);a!==void 0&&t.readPathById.set(n.id,a)}e?.onToolUseStart?.(n,r)},"onToolUseStart"),onToolResult:i((n,r)=>{let a=t.toolNameById.get(n.id)??n.name;if(tt.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(a);let o=t.toolPathById.get(n.id);o!==void 0&&t.succeededPaths.push(o)}if(nt.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){let o=t.readPathById.get(n.id);o!==void 0&&t.succeededReadPaths.push(o)}e?.onToolResult?.(n,r)},"onToolResult")}}i(mn,"wrapEventsForMutationRecording");function se(e){return[...new Set(e.filter(t=>t.trim().length>0))]}i(se,"uniqueItems");function ot(e){let t=e.verification;if(!t)return;let n=[],r=new Set(e.before.paths.map(H)),a=se(e.after.paths.map(H)),o=a.filter(m=>!r.has(m)),s=se(e.mutationRecorder.succeededToolCalls),d=e.acceptToolMutationEvidence?s:[],g=e.acceptToolMutationEvidence?se(e.mutationRecorder.succeededPaths.map(H)):[],h=o.length>0||d.length>0,y=t.enforcement??"hard",p=(t.requiredChangedPaths??[]).map(m=>ke(m,e.ctx)),b=se(e.mutationRecorder.succeededReadPaths.map(m=>ke(m,e.ctx))),v=(t.requiredReadPaths??[]).map(m=>ke(m,e.ctx));t.requiresMutation===!0&&(e.before.error!==void 0||e.after.error!==void 0?n.push(`workspace mutation verification could not read changed files: ${e.after.error??e.before.error}`):h||n.push(e.acceptToolMutationEvidence||s.length===0?"expected file mutations, but no new workspace changes or successful write tools were observed":"write tools ran in an isolated worktree, but no main workspace changes were present after cleanup")),e.term.limitReached===!0&&!h&&n.push("workflow child reached its iteration limit before satisfying the task");for(let m of p)!a.includes(m)&&!g.includes(m)&&n.push(`required changed path was not present in workspace changes: ${m}`);for(let m of v)b.includes(m)||n.push(`required review evidence was not read: ${m}`);let W=t.minFinalTextChars;return W!==void 0&&!h&&e.term.finalText.trim().length<W&&n.push(`finalText was shorter than the required ${W} characters`),t.rejectPreparatoryFinalText===!0&&!h&&ct(e.term.finalText)&&n.push("finalText looks preparatory instead of terminal"),{ok:n.length===0,enforcement:y,reasons:n,changedPaths:a,mutationToolCalls:s,mutationEvidence:h,...b.length>0?{readPaths:b}:{}}}i(ot,"evaluateVerification");function Se(e,t){if(t.ok)return e;let r=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(a=>`- ${a}`)].join(`
2
+ import{Fe as Ye,Ge as Ze,He as Qe,Ke as et,Qb as Le,Rb as ze,Ub as Ge,Vb as Je,ye as he,ze as Xe}from"./chunk-PFWOZDUJ.js";import{Ag as Ue,Cg as Z,Gg as pe,Mg as we,Ng as B,Og as ge,Pg as Ve,Wa as re,Wg as Be,Xg as He,Yg as Ke,v as me,wg as oe,zg as je}from"./chunk-WV3DJVW4.js";import{aa as De}from"./chunk-HZYRLIOC.js";import{a as i}from"./chunk-ONUPGMER.js";import{basename as vr,dirname as Sr}from"node:path";import{execFile as en}from"node:child_process";import ie from"node:path";import{promisify as tn}from"node:util";var nn=tn(en),rn=1e4,st=2,tt=new Set(["write","edit","multi_edit","insert_after_anchor"]),nt=new Set(["read"]);function on(e,t){if(t.includes("*"))return e;if(e.includes("*"))return t;let n=new Set(t);return e.filter(r=>n.has(r))}i(on,"intersectWorkflowToolCeilings");var an=/^\s*(?:let me|i will|i'll|i am going to)\b[\s\S]{0,120}\b(?:start|create|implement|write|build|plan)\b|^\s*(?:我将|让我|接下来)[\s\S]{0,80}(?:开始|创建|编写|实现|制定)/i;function sn(e){if(e?.timeoutMs!==void 0){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new Error("workflow wait timeoutMs must be a positive number");return Math.floor(e.timeoutMs)}}i(sn,"normalizeWaitTimeoutMs");function ye(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}i(ye,"hasVerificationWork");function H(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}i(H,"normalizeWorkspacePath");function ke(e,t){let n=t.gitRoot?ie.resolve(t.gitRoot):void 0,r=ie.isAbsolute(e)&&n?ie.relative(n,ie.resolve(e)):e;return H(r)}i(ke,"normalizeRequiredPath");function cn(e){let t=(e.readOnly??!1)===!1?{enforcement:"warn",requiresMutation:!0,rejectPreparatoryFinalText:!0}:void 0;if(e.verification!==void 0){let n={...t??{},...e.verification,enforcement:e.verification.enforcement??"hard"},r=e.verification.requiredChangedPaths;return{verification:{...n,...r!==void 0&&r.length>0&&n.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}i(cn,"resolveVerificationForInput");function dn(e,t){if(t===!0&&e.readOnly===!1)throw new Error(`workflow manifest readOnly=true cannot spawn write-capable child "${e.name}"; set the workflow manifest readOnly=false or use child readOnly:true`);let n=e.readOnly??t??!1;return e.readOnly===n?e:{...e,readOnly:n}}i(dn,"resolveSpawnAgentInput");function ct(e){let t=e.trim();return t.length>0&&an.test(t)}i(ct,"isPreparatoryOnlyText");function un(e,t){let n=e.trim(),r=t?.trim();return r&&(n.length===0||ct(n))?r:e}i(un,"selectWorkflowFinalText");async function ae(e,t){return await re({cwd:t}),(await nn("git",[...e],{cwd:t,timeout:rn,windowsHide:!0,maxBuffer:4*1024*1024})).stdout.toString()}i(ae,"runGit");async function ln(e){let t=e.gitRoot??e.executionCwd??process.cwd(),n=(await ae(["rev-parse","--show-toplevel"],t)).trim(),r=await Promise.all([ae(["diff","--name-only","--"],n),ae(["diff","--cached","--name-only","--"],n),ae(["ls-files","--others","--exclude-standard"],n)]);return[...new Set(r.flatMap(a=>a.split(/\r?\n/)).map(H).filter(a=>a.length>0))]}i(ln,"listGitChangedFiles");async function ve(e,t){try{return{paths:(await t(e)).map(H).filter(r=>r.length>0)}}catch(n){return{paths:[],error:n instanceof Error?n.message:String(n)}}}i(ve,"captureChangedPaths");function fn(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[],readPathById:new Map,succeededReadPaths:[]}}i(fn,"createMutationRecorder");function rt(e){if(e)for(let t of["path","file_path","target_path"]){let n=e[t];if(typeof n=="string"&&n.trim().length>0)return H(n)}}i(rt,"readMutationPath");function mn(e,t){return{...e??{},onToolUseStart:i((n,r)=>{if(tt.has(n.name)){t.toolNameById.set(n.id,n.name);let a=rt(n.input);a!==void 0&&t.toolPathById.set(n.id,a)}if(nt.has(n.name)){let a=rt(n.input);a!==void 0&&t.readPathById.set(n.id,a)}e?.onToolUseStart?.(n,r)},"onToolUseStart"),onToolResult:i((n,r)=>{let a=t.toolNameById.get(n.id)??n.name;if(tt.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(a);let o=t.toolPathById.get(n.id);o!==void 0&&t.succeededPaths.push(o)}if(nt.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){let o=t.readPathById.get(n.id);o!==void 0&&t.succeededReadPaths.push(o)}e?.onToolResult?.(n,r)},"onToolResult")}}i(mn,"wrapEventsForMutationRecording");function se(e){return[...new Set(e.filter(t=>t.trim().length>0))]}i(se,"uniqueItems");function ot(e){let t=e.verification;if(!t)return;let n=[],r=new Set(e.before.paths.map(H)),a=se(e.after.paths.map(H)),o=a.filter(m=>!r.has(m)),s=se(e.mutationRecorder.succeededToolCalls),d=e.acceptToolMutationEvidence?s:[],g=e.acceptToolMutationEvidence?se(e.mutationRecorder.succeededPaths.map(H)):[],h=o.length>0||d.length>0,y=t.enforcement??"hard",p=(t.requiredChangedPaths??[]).map(m=>ke(m,e.ctx)),b=se(e.mutationRecorder.succeededReadPaths.map(m=>ke(m,e.ctx))),v=(t.requiredReadPaths??[]).map(m=>ke(m,e.ctx));t.requiresMutation===!0&&(e.before.error!==void 0||e.after.error!==void 0?n.push(`workspace mutation verification could not read changed files: ${e.after.error??e.before.error}`):h||n.push(e.acceptToolMutationEvidence||s.length===0?"expected file mutations, but no new workspace changes or successful write tools were observed":"write tools ran in an isolated worktree, but no main workspace changes were present after cleanup")),e.term.limitReached===!0&&!h&&n.push("workflow child reached its iteration limit before satisfying the task");for(let m of p)!a.includes(m)&&!g.includes(m)&&n.push(`required changed path was not present in workspace changes: ${m}`);for(let m of v)b.includes(m)||n.push(`required review evidence was not read: ${m}`);let W=t.minFinalTextChars;return W!==void 0&&!h&&e.term.finalText.trim().length<W&&n.push(`finalText was shorter than the required ${W} characters`),t.rejectPreparatoryFinalText===!0&&!h&&ct(e.term.finalText)&&n.push("finalText looks preparatory instead of terminal"),{ok:n.length===0,enforcement:y,reasons:n,changedPaths:a,mutationToolCalls:s,mutationEvidence:h,...b.length>0?{readPaths:b}:{}}}i(ot,"evaluateVerification");function Se(e,t){if(t.ok)return e;let r=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(a=>`- ${a}`)].join(`
3
3
  `);return e.trim().length>0?`${e}
4
4
 
5
5
  ${r}`:r}i(Se,"appendVerificationFailure");function it(){return{ok:!1,enforcement:"warn",reasons:["workflow child reached its iteration limit before satisfying the task"],mutationEvidence:!1}}i(it,"limitReachedWarningVerification");function pn(e){return e.entry.bundle.readOnly!==!0&&e.entry.repairAttempts<st&&e.term.status==="completed"&&e.verification!==void 0&&e.verification.ok!==!0&&e.verification.enforcement!=="warn"}i(pn,"shouldRepairVerificationFailure");function wn(e){let t=e.verification.reasons.map(r=>`- ${r}`).join(`
@@ -13,7 +13,7 @@ ${s.text}`),rubric:t.rubric??Sn}))).text,findings:r,degraded:a}}i(Mn,"runParalle
13
13
  `).trim().replace(/[\t\n\f\r ]+/g," ")}i(j,"normalizeText");function ft(e){return j(e).replace(/\\/g,"/")}i(ft,"normalizeLocation");function ce(e){return[...new Set(e.map(j).filter(Boolean))].sort((t,n)=>t<n?-1:t>n?1:0)}i(ce,"uniqueSorted");function En(e,t,n){return An("sha256").update(`${e}\0${ft(t)}\0${j(n)}`,"utf8").digest("hex")}i(En,"findingId");function mt(e,t,n){if(!t&&n.specVerdict!=="not-verifiable")throw new Error('review result must use specVerdict "not-verifiable" when requirements are absent');return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,findings:n.findings.map(r=>{let a=ft(r.location),o=j(r.claim),s=j(r.evidence);return{findingId:En(e,a,o),severity:r.severity,location:a,claim:o,evidence:s,...r.suggestedFix?{suggestedFix:j(r.suggestedFix)}:{}}}).sort((r,a)=>r.findingId<a.findingId?-1:r.findingId>a.findingId?1:0),unverifiedRequirements:ce(n.unverifiedRequirements)}}i(mt,"normalizeScopedReviewResult");var lt={low:0,medium:1,high:2,critical:3};function Wn(e){return e.reduce((t,n)=>lt[n]>lt[t]?n:t,"low")}i(Wn,"maxSeverity");function pt(e){if(e.length===0)throw new Error("at least one primary review result is required");let t=new Map;for(let a of e)for(let o of a.findings)t.set(o.findingId,[...t.get(o.findingId)??[],o]);let n=[...t.entries()].map(([a,o])=>({findingId:a,severity:Wn(o.map(s=>s.severity)),location:o[0].location,claim:o[0].claim,evidence:ce(o.map(s=>s.evidence)),suggestedFixes:ce(o.flatMap(s=>s.suggestedFix?[s.suggestedFix]:[]))})).sort((a,o)=>a.findingId<o.findingId?-1:a.findingId>o.findingId?1:0);return{specVerdict:e.some(a=>a.specVerdict==="issues")?"issues":e.some(a=>a.specVerdict==="not-verifiable")?"not-verifiable":"compliant",qualityVerdict:e.some(a=>a.qualityVerdict==="needs-fixes")?"needs-fixes":"approved",findings:n,unverifiedRequirements:ce(e.flatMap(a=>a.unverifiedRequirements))}}i(pt,"mergeScopedReviewResults");function wt(e,t){let n=new Set(e.findings.map(s=>s.findingId)),r=new Set;for(let s of t.findings){if(!n.has(s.findingId)||r.has(s.findingId))throw new Error("verifier must return every input findingId exactly once");r.add(s.findingId)}if(r.size!==n.size)throw new Error("verifier must return every input findingId exactly once");let a=new Map(t.findings.map(s=>[s.findingId,s])),o=e.findings.flatMap(s=>{let d=a.get(s.findingId);if(d.disposition==="refuted")return[];let g=d.severityReason?.trim(),h=d.effectiveSeverity!==void 0&&!!g;return[{...s,disposition:d.disposition,severity:h?d.effectiveSeverity:s.severity,verificationEvidence:j(d.evidence),...g?{severityReason:j(g)}:{}}]});return{specVerdict:e.specVerdict,qualityVerdict:e.qualityVerdict,unverifiedRequirements:e.unverifiedRequirements,actionable:o,audit:t,unqualifiedApprovalAllowed:o.length===0&&e.unverifiedRequirements.length===0&&e.specVerdict==="compliant"&&e.qualityVerdict==="approved"}}i(wt,"applyFindingVerification");var Fn={type:"object",additionalProperties:!1,required:["summary"],properties:{summary:{type:"string"}}};function ht(e){return[e.packetPath,...e.evidenceChunks.map(t=>t.path)]}i(ht,"evidencePaths");function On(e){let t=he(e,Re);if(t.length>0)throw new Error(`primary reviewer structured result is invalid: ${t.join("; ")}`);return e}i(On,"rawReview");function qn(e){let t=he(e,be);if(t.length>0)throw new Error(`finding verifier structured result is invalid: ${t.join("; ")}`);return e}i(qn,"rawVerification");function Te(e,t){if(e===null||e.status!=="completed")throw new Error(`${t} did not complete; no verdict was accepted`);if(e.verification!==void 0&&!e.verification.ok)throw new Error(`${t} did not read every required packet path; no verdict was accepted`);return e}i(Te,"resultOrThrow");function Cn(e,t,n){return["Review one immutable KodaX packet as an independent third-party reviewer.",`Packet manifest: ${e.packetPath}`,...e.evidenceChunks.map(r=>`Evidence chunk: ${r.path}`),`This packet has binding requirements: ${e.requirementsPresent?"yes":"no"}.`,t?"This is the additional high-risk primary. Actively seek a disagreement with the first reader; do not assume it was correct.":"Own both specification and implementation-quality verdicts for this scope.",n.lean?"Also identify unnecessary additions, but never remove validation, security, data-loss protection, accessibility, or requested behavior.":"",n.reviewFocus?`Additional user focus: ${n.reviewFocus}`:"","Read the manifest and every listed chunk with the read tool before deciding.","Begin with the required JSON result. No preamble or process narration.","The findings array contains only actionable defects, never approval evidence or positive observations.","When the scope is compliant and approved with no actionable defect, findings must be empty.","If a named requirement cannot be proven compliant or violated from surfaced evidence, use specVerdict not-verifiable, list it in unverifiedRequirements, and emit no finding for that uncertainty; absence of evidence is not proof of a defect.","If requirements are absent, specVerdict must be not-verifiable."].filter(Boolean).join(`
14
14
  `)}i(Cn,"buildScopedReviewPrimaryPrompt");function $n(e,t){return["Independently attempt to refute every candidate finding in this batch.",`Packet manifest: ${e.packetPath}`,...e.evidenceChunks.map(n=>`Evidence chunk: ${n.path}`),`Canonical candidates: ${JSON.stringify(t.findings)}`,"Read the packet evidence. You may run one focused check after naming the concrete doubt.","Return every findingId exactly once. A severity change requires severityReason.","Begin with the required JSON result; no preamble."].join(`
15
15
  `)}i($n,"buildScopedReviewVerificationPrompt");function _n(e){return["Synthesize the structured review results below without rereading packet bodies.","Lead with confirmed findings, keep unresolved findings visibly unresolved, omit refuted findings from the actionable list, and never silently downgrade severity.","Cite locations and state explicitly when no actionable issue was confirmed.",JSON.stringify(e)].join(`
16
- `)}i(_n,"buildScopedReviewFinalPrompt");async function gt(e,t,n,r){let a=Te(await e.runAgent({name:`${n?"high-risk-":""}primary-${t.partitionKey}`,phase:"primary-review",prompt:Cn(t,n,r),scopeSummary:`${t.partitionKey}: ${t.scopePaths.join(", ")}`,constraints:["read every required packet path","return both verdicts","cite evidence at each finding"],readOnly:!0,modelHint:n?"deep":"balanced",verification:{enforcement:"hard",requiredReadPaths:ht(t)},outputSchema:Re,terseResult:!0}),"primary reviewer");return e.log({message:`primary read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"primary",contentHash:t.contentHash}}),On(a.structured)}i(gt,"runPrimary");async function Nn(e,t,n){if(n.findings.length===0)return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,unverifiedRequirements:n.unverifiedRequirements,actionable:[],audit:{findings:[]},unqualifiedApprovalAllowed:n.unverifiedRequirements.length===0&&n.specVerdict==="compliant"&&n.qualityVerdict==="approved"};let r=Te(await e.runAgent({name:`verify-${t.partitionKey}`,phase:"verifier",prompt:$n(t,n),scopeSummary:`verify ${n.findings.length} candidate finding(s) in ${t.partitionKey}`,constraints:["fresh context","attempt refutation","one disposition per findingId"],readOnly:!0,modelHint:"deep",verification:{enforcement:"hard",requiredReadPaths:ht(t)},outputSchema:be,terseResult:!0}),"finding verifier");return e.log({message:`verification read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"verification",contentHash:t.contentHash,reason:"candidate findings"}}),wt(n,qn(r.structured))}i(Nn,"verifyFindings");async function Dn(e,t,n){let r=[await gt(e,t,!1,n)];t.riskFlags.includes("routing-high")&&r.push(await gt(e,t,!0,n));let a=r.map(d=>mt(t.contentHash,t.requirementsPresent,d)),o=pt(a),s=await Nn(e,t,o);return e.log({message:`quality gate completed for ${t.partitionKey}`,data:{kind:"review_quality_gate",contentHash:t.contentHash,actionableFindings:s.actionable.length,unresolvedFindings:s.actionable.filter(d=>d.disposition==="unresolved").length,unqualifiedApprovalAllowed:s.unqualifiedApprovalAllowed}}),{contentHash:t.contentHash,result:s}}i(Dn,"reviewPacket");async function jn(e,t){if(!Array.isArray(t.packets)||t.packets.length===0)throw new Error("scoped-review requires at least one review packet");let n=await e.parallel(t.packets.map(d=>()=>Dn(e,d,t)),{concurrency:4});if(n.some(d=>d===null))throw new Error("one or more scope packets failed review; no final verdict was accepted");let r=n.filter(d=>d!==null);await e.artifact("scoped-review-audit",r);let a=Te(await e.runAgent({name:"final-review-synthesis",phase:"final-synthesis",prompt:_n(r),scopeSummary:`cross-scope synthesis for ${r.length} packet(s)`,constraints:["preserve severity","preserve unresolved uncertainty","do not invent evidence"],readOnly:!0,modelHint:"deep",outputSchema:Fn,terseResult:!0}),"final synthesis"),o=a.structured;return{summary:typeof o?.summary=="string"?o.summary:a.finalText,packetResults:r}}i(jn,"runScopedReview");var yt={meta:{name:"scoped-review",description:"Review immutable scope packets once, verify only candidate findings, then synthesize.",readOnly:!0,phases:["primary-review","verifier","final-synthesis"],maxAgents:64,maxConcurrency:4},run:jn};function kt(e){return{meta:e.meta,run:i((t,n)=>e.run(t,n),"run")}}i(kt,"erase");var vt=[kt(ut),kt(yt)];function St(e){return vt.find(t=>t.meta.name===e)}i(St,"getBuiltinWorkflow");function oo(){return vt.map(e=>e.meta)}i(oo,"listBuiltinWorkflows");import{mkdir as It,readdir as Un,readFile as Q,rename as Vn,unlink as Me,writeFile as Ae}from"node:fs/promises";import{basename as Bn,dirname as Pe,join as K}from"node:path";import{pathToFileURL as Hn}from"node:url";var Pt=[".workflow.json",".ts",".mjs",".js"],ee="0.7.49";function Mt(){return"0.7.96-rc.13"}i(Mt,"currentKodaxWorkflowVersion");function Kn(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}i(Kn,"executionForPath");function Ln(e){let t=Pt.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}i(Ln,"stripWorkflowSuffix");function Ee(e){let t=e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").slice(0,80);if(!t||t==="."||t==="..")throw new Error("workflow name must contain at least one safe filename character");return t}i(Ee,"safeWorkflowName");function We(e){return typeof e=="object"&&e!==null}i(We,"isRecord");function xt(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}i(xt,"readRequiredString");async function Rt(e,t){if(!e)return[];let n;try{n=await Un(e)}catch{return[]}let r=new Map;for(let a of Pt)for(let o of n){if(!o.endsWith(a))continue;let s=Ln(o);if(!s||s.length===0||r.has(s))continue;let d=K(e,o);r.set(s,{name:s,path:d,source:t,execution:Kn(d)})}return[...r.values()]}i(Rt,"scanDir");async function te(e){let t=await Rt(e.personal,"personal"),n=await Rt(e.project,"project"),r=new Map;for(let a of t)r.set(a.name,a);for(let a of n)r.set(a.name,a);return[...r.values()].sort((a,o)=>a.name.localeCompare(o.name))}i(te,"discoverSavedWorkflows");function zn(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}i(zn,"isWorkflowModule");function Gn(e){let t=e.default;if(zn(t))return t;let n=typeof t=="function"?t:e.run,r=e.workflow??e.meta;if(typeof n=="function"&&typeof r=="object"&&r!==null&&"name"in r)return{meta:r,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}i(Gn,"normalizeWorkflowModule");function Jn(e){let t=JSON.parse(e);if(!We(t))throw new Error("generated workflow file must be an object");if(t.format!==void 0&&t.format!=="kodax.workflow")throw new Error(`unsupported workflow capsule format: ${String(t.format)}`);if(t.format==="kodax.workflow"){let a=we(t);return{manifest:a.manifest,source:a.source,capsule:a,legacy:!1}}let n=t.source;if(typeof n!="string"||n.trim().length===0)throw new Error("generated workflow file source must be a non-empty string");let r=Z(t.manifest);return{manifest:r,source:n,capsule:B({minKodaxVersion:ee,manifest:r,source:n}),legacy:!0}}i(Jn,"parseGeneratedWorkflowFile");async function Fe(e){let t=Jn(await Q(e,"utf8"));return t.capsule??B({minKodaxVersion:ee,manifest:t.manifest,source:t.source})}i(Fe,"loadSavedWorkflowCapsule");async function At(e){if(e.endsWith(".workflow.json"))return ge(await Fe(e));let t=await import(Hn(e).href);return Gn(t)}i(At,"loadSavedWorkflow");function Oe(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}i(Oe,"deriveRequirements");function de(e,t){pe(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}i(de,"assertGeneratedCapsuleSource");async function Xn(e){let t=Ee(e.name),n=Z(e.manifest);de(n,e.source);let r=e.requires??Oe(n),a=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:n,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...r!==void 0?{requires:r}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}});await It(e.dir,{recursive:!0});let o=K(e.dir,`${t}.workflow.json`);return await Ae(o,`${JSON.stringify(a,null,2)}
16
+ `)}i(_n,"buildScopedReviewFinalPrompt");async function gt(e,t,n,r){let a=Te(await e.runAgent({name:`${n?"high-risk-":""}primary-${t.partitionKey}`,phase:"primary-review",prompt:Cn(t,n,r),scopeSummary:`${t.partitionKey}: ${t.scopePaths.join(", ")}`,constraints:["read every required packet path","return both verdicts","cite evidence at each finding"],readOnly:!0,modelHint:n?"deep":"balanced",verification:{enforcement:"hard",requiredReadPaths:ht(t)},outputSchema:Re,terseResult:!0}),"primary reviewer");return e.log({message:`primary read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"primary",contentHash:t.contentHash}}),On(a.structured)}i(gt,"runPrimary");async function Nn(e,t,n){if(n.findings.length===0)return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,unverifiedRequirements:n.unverifiedRequirements,actionable:[],audit:{findings:[]},unqualifiedApprovalAllowed:n.unverifiedRequirements.length===0&&n.specVerdict==="compliant"&&n.qualityVerdict==="approved"};let r=Te(await e.runAgent({name:`verify-${t.partitionKey}`,phase:"verifier",prompt:$n(t,n),scopeSummary:`verify ${n.findings.length} candidate finding(s) in ${t.partitionKey}`,constraints:["fresh context","attempt refutation","one disposition per findingId"],readOnly:!0,modelHint:"deep",verification:{enforcement:"hard",requiredReadPaths:ht(t)},outputSchema:be,terseResult:!0}),"finding verifier");return e.log({message:`verification read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"verification",contentHash:t.contentHash,reason:"candidate findings"}}),wt(n,qn(r.structured))}i(Nn,"verifyFindings");async function Dn(e,t,n){let r=[await gt(e,t,!1,n)];t.riskFlags.includes("routing-high")&&r.push(await gt(e,t,!0,n));let a=r.map(d=>mt(t.contentHash,t.requirementsPresent,d)),o=pt(a),s=await Nn(e,t,o);return e.log({message:`quality gate completed for ${t.partitionKey}`,data:{kind:"review_quality_gate",contentHash:t.contentHash,actionableFindings:s.actionable.length,unresolvedFindings:s.actionable.filter(d=>d.disposition==="unresolved").length,unqualifiedApprovalAllowed:s.unqualifiedApprovalAllowed}}),{contentHash:t.contentHash,result:s}}i(Dn,"reviewPacket");async function jn(e,t){if(!Array.isArray(t.packets)||t.packets.length===0)throw new Error("scoped-review requires at least one review packet");let n=await e.parallel(t.packets.map(d=>()=>Dn(e,d,t)),{concurrency:4});if(n.some(d=>d===null))throw new Error("one or more scope packets failed review; no final verdict was accepted");let r=n.filter(d=>d!==null);await e.artifact("scoped-review-audit",r);let a=Te(await e.runAgent({name:"final-review-synthesis",phase:"final-synthesis",prompt:_n(r),scopeSummary:`cross-scope synthesis for ${r.length} packet(s)`,constraints:["preserve severity","preserve unresolved uncertainty","do not invent evidence"],readOnly:!0,modelHint:"deep",outputSchema:Fn,terseResult:!0}),"final synthesis"),o=a.structured;return{summary:typeof o?.summary=="string"?o.summary:a.finalText,packetResults:r}}i(jn,"runScopedReview");var yt={meta:{name:"scoped-review",description:"Review immutable scope packets once, verify only candidate findings, then synthesize.",readOnly:!0,phases:["primary-review","verifier","final-synthesis"],maxAgents:64,maxConcurrency:4},run:jn};function kt(e){return{meta:e.meta,run:i((t,n)=>e.run(t,n),"run")}}i(kt,"erase");var vt=[kt(ut),kt(yt)];function St(e){return vt.find(t=>t.meta.name===e)}i(St,"getBuiltinWorkflow");function oo(){return vt.map(e=>e.meta)}i(oo,"listBuiltinWorkflows");import{mkdir as It,readdir as Un,readFile as Q,rename as Vn,unlink as Me,writeFile as Ae}from"node:fs/promises";import{basename as Bn,dirname as Pe,join as K}from"node:path";import{pathToFileURL as Hn}from"node:url";var Pt=[".workflow.json",".ts",".mjs",".js"],ee="0.7.49";function Mt(){return"0.7.96-rc.14"}i(Mt,"currentKodaxWorkflowVersion");function Kn(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}i(Kn,"executionForPath");function Ln(e){let t=Pt.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}i(Ln,"stripWorkflowSuffix");function Ee(e){let t=e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").slice(0,80);if(!t||t==="."||t==="..")throw new Error("workflow name must contain at least one safe filename character");return t}i(Ee,"safeWorkflowName");function We(e){return typeof e=="object"&&e!==null}i(We,"isRecord");function xt(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}i(xt,"readRequiredString");async function Rt(e,t){if(!e)return[];let n;try{n=await Un(e)}catch{return[]}let r=new Map;for(let a of Pt)for(let o of n){if(!o.endsWith(a))continue;let s=Ln(o);if(!s||s.length===0||r.has(s))continue;let d=K(e,o);r.set(s,{name:s,path:d,source:t,execution:Kn(d)})}return[...r.values()]}i(Rt,"scanDir");async function te(e){let t=await Rt(e.personal,"personal"),n=await Rt(e.project,"project"),r=new Map;for(let a of t)r.set(a.name,a);for(let a of n)r.set(a.name,a);return[...r.values()].sort((a,o)=>a.name.localeCompare(o.name))}i(te,"discoverSavedWorkflows");function zn(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}i(zn,"isWorkflowModule");function Gn(e){let t=e.default;if(zn(t))return t;let n=typeof t=="function"?t:e.run,r=e.workflow??e.meta;if(typeof n=="function"&&typeof r=="object"&&r!==null&&"name"in r)return{meta:r,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}i(Gn,"normalizeWorkflowModule");function Jn(e){let t=JSON.parse(e);if(!We(t))throw new Error("generated workflow file must be an object");if(t.format!==void 0&&t.format!=="kodax.workflow")throw new Error(`unsupported workflow capsule format: ${String(t.format)}`);if(t.format==="kodax.workflow"){let a=we(t);return{manifest:a.manifest,source:a.source,capsule:a,legacy:!1}}let n=t.source;if(typeof n!="string"||n.trim().length===0)throw new Error("generated workflow file source must be a non-empty string");let r=Z(t.manifest);return{manifest:r,source:n,capsule:B({minKodaxVersion:ee,manifest:r,source:n}),legacy:!0}}i(Jn,"parseGeneratedWorkflowFile");async function Fe(e){let t=Jn(await Q(e,"utf8"));return t.capsule??B({minKodaxVersion:ee,manifest:t.manifest,source:t.source})}i(Fe,"loadSavedWorkflowCapsule");async function At(e){if(e.endsWith(".workflow.json"))return ge(await Fe(e));let t=await import(Hn(e).href);return Gn(t)}i(At,"loadSavedWorkflow");function Oe(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}i(Oe,"deriveRequirements");function de(e,t){pe(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}i(de,"assertGeneratedCapsuleSource");async function Xn(e){let t=Ee(e.name),n=Z(e.manifest);de(n,e.source);let r=e.requires??Oe(n),a=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:n,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...r!==void 0?{requires:r}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}});await It(e.dir,{recursive:!0});let o=K(e.dir,`${t}.workflow.json`);return await Ae(o,`${JSON.stringify(a,null,2)}
17
17
  `,"utf8"),{name:t,path:o,source:"project",execution:"capability-generated"}}i(Xn,"saveGeneratedWorkflow");async function bt(e,t){await Ae(e,`${JSON.stringify(t,null,2)}
18
18
  `,"utf8")}i(bt,"writeCapsuleFile");async function Yn(e){try{return await Q(e,"utf8"),!0}catch{return!1}}i(Yn,"fileExists");async function fo(e){let t=(await te(e.dirs)).filter(d=>d.name===e.name).filter(d=>e.source===void 0||d.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be renamed");let r=Ee(e.newName),a=K(Pe(n.path),`${r}.workflow.json`);if(a!==n.path&&await Yn(a))throw new Error(`saved workflow already exists: ${r}`);let o=await Fe(n.path);de(o.manifest,o.source);let s=B({minKodaxVersion:o.minKodaxVersion,manifest:{...o.manifest,name:r},source:o.source,...o.intent!==void 0?{intent:o.intent}:{},...o.inputs!==void 0?{inputs:o.inputs}:{},...o.requires!==void 0?{requires:o.requires}:{},...o.provenance!==void 0?{provenance:o.provenance}:{}});return await Ae(a,`${JSON.stringify(s,null,2)}
19
19
  `,"utf8"),a!==n.path&&await Me(n.path),{name:r,path:a,source:n.source,execution:"capability-generated"}}i(fo,"renameSavedWorkflow");async function mo(e){let t=(await te(e.dirs)).filter(r=>r.name===e.name).filter(r=>e.source===void 0||r.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be deleted");return await Me(n.path),n}i(mo,"deleteSavedWorkflow");async function po(e){let t=Ee(e.name),n=(await te(e.dirs)).filter(v=>v.name===t).filter(v=>e.savedSource===void 0||v.source===e.savedSource);if(n.length===0)throw new Error(`saved workflow not found: ${t}`);if(n.length>1)throw new Error(`ambiguous saved workflow name: ${t}`);let r=n[0];if(!r.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be replaced");let a=Z({...e.manifest,name:t});de(a,e.source);let o=e.requires??Oe(a),s=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:a,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...o!==void 0?{requires:o}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}}),d=await Fe(r.path),g=new Date().toISOString().replace(/[:.]/g,"-"),h=K(Pe(r.path),".revisions",t),y=`${g}-${process.hrtime.bigint().toString(36)}`,p=K(h,`${t}-${y}.workflow.json`),b=K(Pe(r.path),`.${t}.${process.pid}.${Date.now().toString(36)}.tmp`);await It(h,{recursive:!0}),await bt(p,d);try{await bt(b,s),await Vn(b,r.path)}catch(v){try{await Me(b)}catch{}throw v}return{name:t,path:r.path,source:r.source,execution:"capability-generated",previousPath:p}}i(po,"replaceSavedWorkflow");function Zn(e){if(!We(e))return;let t=e.request;if(typeof t=="string"&&t.trim().length>0)return t;let n=e.question;if(typeof n=="string"&&n.trim().length>0)return n}i(Zn,"readOptionalOriginalRequest");function Et(e){return Qn(e)}i(Et,"buildCapsuleFromRun");async function Qn(e){let t=JSON.parse(await Q(K(e.runDir,"run.json"),"utf8"));if(!We(t))throw new Error("workflow run.json must be an object");let n=xt(t,"scriptSnapshotPath"),r=xt(t,"manifestSnapshotPath"),a=await Q(n,"utf8"),o=Z(JSON.parse(await Q(r,"utf8")));de(o,a);let s=typeof t.runId=="string"&&t.runId.length>0?t.runId:Bn(e.runDir),d=Zn(t.args),g=Oe(o),h=Ve(o,d!==void 0?{originalRequest:d}:{}),y={description:"Provide new workflow args matching the generated request shape.",..."args"in t?{examples:[t.args]}:{}};return B({minKodaxVersion:ee,manifest:o,source:a,intent:h,inputs:y,...g!==void 0?{requires:g}:{},provenance:{fromRunId:s,createdAt:new Date().toISOString(),kodaxVersion:Mt()}})}i(Qn,"readCapsuleFromRun");async function wo(e){let t=await Et(e);return{capsule:t,module:ge(t)}}i(wo,"loadGeneratedWorkflowFromRun");async function go(e){let t=await Et(e);return Xn({dir:e.targetDir,name:e.name,manifest:t.manifest,source:t.source,...t.intent!==void 0?{intent:t.intent}:{},...t.inputs!==void 0?{inputs:t.inputs}:{},...t.requires!==void 0?{requires:t.requires}:{},...t.provenance!==void 0?{provenance:t.provenance}:{},minKodaxVersion:t.minKodaxVersion})}i(go,"saveGeneratedWorkflowFromRun");function U(e,t,n,r){e.push({severity:t,requirement:n,message:r})}i(U,"addRequirementIssue");function Tt(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e.trim());if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}i(Tt,"parseSemver");function er(e,t){for(let n=0;n<3;n+=1){let r=e[n]-t[n];if(r!==0)return r}return 0}i(er,"compareSemver");function tr(e,t,n){let r=Tt(t),a=Tt(n);if(!r){U(e,"error","kodax:min-version",`workflow minKodaxVersion is not valid semver: ${t}`);return}if(!a){U(e,"warning","kodax:min-version",`cannot verify workflow minKodaxVersion ${t}; current version is unknown`);return}er(a,r)<0&&U(e,"error","kodax:min-version",`workflow requires KodaX >= ${t}, current version is ${n}`)}i(tr,"addMinVersionIssue");function Ie(e,t,n,r){if(!n)return;if(!r){for(let o of n)U(e,"warning",`${t}:${o}`,`workflow requires ${t}:${o}, but no ${t} inventory was provided`);return}let a=new Set(r);for(let o of n)a.has(o)||U(e,"error",`${t}:${o}`,`missing required workflow ${t}: ${o}`)}i(Ie,"addMissingItems");function ho(e,t={}){let n=we(e),r=[],a=n.requires;tr(r,n.minKodaxVersion,t.kodaxVersion??Mt()),a?.environment?.includes("git-repo")&&t.isGitRepo===!1&&U(r,"error","environment:git-repo","workflow requires a git repository"),a?.environment?.includes("worktree-capable")&&t.worktreeCapable===!1&&U(r,"error","environment:worktree-capable","workflow may request git worktree isolation");try{pe(n.source,{filename:`${n.manifest.name}.workflow.js`,requireAsyncRun:!0})}catch(o){let s=o instanceof Error?o.message:String(o);U(r,"error","workflow:source",s)}return Ie(r,"tools",a?.tools,t.availableTools),Ie(r,"mcp",a?.mcp,t.availableMcp),Ie(r,"skills",a?.skills,t.availableSkills),{ok:!r.some(o=>o.severity==="error"),issues:r}}i(ho,"preflightWorkflowCapsule");function rr(e){return{project:Wt(e,".kodax","workflows"),personal:Wt(nr(),".kodax","workflows")}}i(rr,"defaultSavedWorkflowDirs");async function or(e,t){let r=(await te(t)).find(a=>a.name===e);if(r)return At(r.path)}i(or,"resolveSavedByName");function Ft(e){let t=rr(e);return async n=>St(n)??await or(n,t)}i(Ft,"createNestedWorkflowResolver");import{existsSync as ir,mkdirSync as ar,readFileSync as sr,writeFileSync as Ot}from"node:fs";import{join as ne}from"node:path";var qt="results";function Ct(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}i(Ct,"safeKey");function $t(e,t){let n=ne(e,t);if(ir(n))try{return JSON.parse(sr(n,"utf8"))}catch{return}}i($t,"readResult");function _t(e,t={}){let n=ne(e,qt);ar(n,{recursive:!0});let r=t.readFrom?ne(t.readFrom,qt):void 0;return{get:i(a=>{let o=`${Ct(a)}.json`,s=$t(n,o);if(s!==void 0)return s;if(r===void 0)return;let d=$t(r,o);if(d!==void 0){try{Ot(ne(n,o),JSON.stringify(d),"utf8")}catch{}return d}},"get"),set:i((a,o)=>{try{Ot(ne(n,`${Ct(a)}.json`),JSON.stringify(o),"utf8")}catch{}},"set")}}i(_t,"createFsResultCache");import{mkdirSync as cr,appendFileSync as dr,writeFileSync as le}from"node:fs";import{join as G}from"node:path";function ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}i(ue,"record");function F(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0}i(F,"finiteNumber");function Nt(e){let t=new Map,n=new Set,r=[],a=[],o=new Set,s=[],d=[],g=0,h=0,y=0,p=0,b=0,v=0,W=0,m=0,T={},$=[];for(let C of e){let M=C.data??{};if(C.type==="agent_spawned"){let u=typeof M.taskId=="string"?M.taskId:void 0;u&&t.set(u,M),M.role==="primary-review"&&(v+=1);let w=typeof M.role=="string"?M.role:"agent",x=typeof M.requestedTier=="string"?M.requestedTier:"inherited",I=`${w}/${x}`;T[I]=(T[I]??0)+1;continue}if(C.type==="agent_completed"||C.type==="agent_unverified"||C.type==="agent_failed"){let u=typeof M.taskId=="string"?M.taskId:void 0;if(!u||n.has(u))continue;n.add(u);let w=ue(M.usage);!w||typeof w.totalTokens!="number"?typeof t.get(u)?.externalTarget=="string"?a.push(u):r.push(u):(g+=F(w.totalTokens),h+=F(w.inputTokens),y+=F(w.cacheReadTokens??w.cachedReadTokens),p+=F(w.outputTokens));let x=ue(M.digestUsage);b+=F(x?.totalTokens),h+=F(x?.inputTokens),p+=F(x?.outputTokens),y+=F(x?.cacheReadTokens??x?.cachedReadTokens),W+=F(M.iterations);continue}if(C.type==="agent_summary_updated"){let u=ue(M.usage),w=M.summaryKind;if((w==="digest"||w==="digest-failed")&&u){let x=F(u.totalTokens);g+=x,b+=x,h+=F(u.inputTokens),p+=F(u.outputTokens),y+=F(u.cacheReadTokens??u.cachedReadTokens)}continue}if(C.type!=="workflow_log")continue;let f=ue(M.data);if(f?.kind==="review_quality_gate"&&typeof f.contentHash=="string"){$.push({contentHash:f.contentHash,actionableFindings:F(f.actionableFindings),unresolvedFindings:F(f.unresolvedFindings),unqualifiedApprovalAllowed:f.unqualifiedApprovalAllowed===!0});continue}if(f?.kind!=="review_packet_read"||typeof f.contentHash!="string")continue;let l={contentHash:f.contentHash,...typeof f.reason=="string"?{reason:f.reason}:{}};f.role==="primary"?(o.has(f.contentHash)&&(m+=1),o.add(f.contentHash)):f.role==="verification"?s.push(l):f.role==="synthesis"&&d.push(l)}for(let C of t.keys())n.has(C)||r.push(C);let J=[...new Set(r)].sort();return{totalModelTokens:g,inputTokens:h,cacheReadTokens:y,outputTokens:p,digestTokens:b,agentStarts:t.size,childTurns:W,agentStartsByRoleTier:T,primaryReviewStarts:v,duplicatePrimaryPacketReads:m,verificationPacketReads:s,synthesisPacketReads:d,reviewWaves:v>0?1:0,fixWaves:0,rereviewWaves:0,qualityGateOutcomes:$,tokenCoverage:{ok:J.length===0,missingTaskIds:J},excludedExternalTaskIds:[...new Set(a)].sort()}}i(Nt,"buildWorkflowCostReport");function ur(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,120);return t.length>0?t:"artifact"}i(ur,"safeWorkflowArtifactName");function Dt(e,t={}){let n=t.now??(()=>Date.now()),r=G(e,"artifacts");cr(r,{recursive:!0});let a=G(e,"events.jsonl");return{runDir:e,onEvent:i(o=>{dr(a,`${JSON.stringify({...o,ts:n()})}