@xenosystem/agent-sdk 0.9.11 → 0.9.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 (102) hide show
  1. package/LICENSE +15 -15
  2. package/README.md +511 -511
  3. package/dist/agents/index.cjs +5 -5
  4. package/dist/agents/index.js +15 -15
  5. package/dist/agents/metafile-cjs.json +1 -1
  6. package/dist/agents/metafile-esm.json +1 -1
  7. package/dist/artifacts/index.cjs +1 -1
  8. package/dist/artifacts/index.js +1 -1
  9. package/dist/artifacts/metafile-cjs.json +1 -1
  10. package/dist/artifacts/metafile-esm.json +1 -1
  11. package/dist/automation/index.d.cts +1 -0
  12. package/dist/automation/index.d.ts +1 -0
  13. package/dist/automation/metafile-cjs.json +1 -1
  14. package/dist/automation/metafile-esm.json +1 -1
  15. package/dist/control-plane/index.cjs +1 -1
  16. package/dist/control-plane/index.js +1 -1
  17. package/dist/control-plane/metafile-cjs.json +1 -1
  18. package/dist/control-plane/metafile-esm.json +1 -1
  19. package/dist/control-room/metafile-cjs.json +1 -1
  20. package/dist/control-room/metafile-esm.json +1 -1
  21. package/dist/electron/index.cjs +107 -107
  22. package/dist/electron/index.d.cts +8 -0
  23. package/dist/electron/index.d.ts +8 -0
  24. package/dist/electron/index.js +103 -103
  25. package/dist/electron/metafile-cjs.json +1 -1
  26. package/dist/electron/metafile-esm.json +1 -1
  27. package/dist/governance/index.cjs +18 -18
  28. package/dist/governance/index.d.cts +1 -0
  29. package/dist/governance/index.d.ts +1 -0
  30. package/dist/governance/index.js +18 -18
  31. package/dist/governance/metafile-cjs.json +1 -1
  32. package/dist/governance/metafile-esm.json +1 -1
  33. package/dist/hooks/metafile-cjs.json +1 -1
  34. package/dist/hooks/metafile-esm.json +1 -1
  35. package/dist/hosted/index.cjs +1 -1
  36. package/dist/hosted/index.js +1 -1
  37. package/dist/hosted/metafile-cjs.json +1 -1
  38. package/dist/hosted/metafile-esm.json +1 -1
  39. package/dist/index.cjs +347 -329
  40. package/dist/index.d.cts +113 -2
  41. package/dist/index.d.ts +113 -2
  42. package/dist/index.js +329 -311
  43. package/dist/intelligence/metafile-cjs.json +1 -1
  44. package/dist/intelligence/metafile-esm.json +1 -1
  45. package/dist/mcp/index.d.cts +1 -0
  46. package/dist/mcp/index.d.ts +1 -0
  47. package/dist/mcp/metafile-cjs.json +1 -1
  48. package/dist/mcp/metafile-esm.json +1 -1
  49. package/dist/metafile-cjs.json +1 -1
  50. package/dist/metafile-esm.json +1 -1
  51. package/dist/oracle/metafile-cjs.json +1 -1
  52. package/dist/oracle/metafile-esm.json +1 -1
  53. package/dist/providers/metafile-cjs.json +1 -1
  54. package/dist/providers/metafile-esm.json +1 -1
  55. package/dist/recipes/metafile-cjs.json +1 -1
  56. package/dist/recipes/metafile-esm.json +1 -1
  57. package/dist/research/metafile-cjs.json +1 -1
  58. package/dist/research/metafile-esm.json +1 -1
  59. package/dist/session/index.cjs +2 -2
  60. package/dist/session/index.d.cts +8 -0
  61. package/dist/session/index.d.ts +8 -0
  62. package/dist/session/index.js +2 -2
  63. package/dist/session/metafile-cjs.json +1 -1
  64. package/dist/session/metafile-esm.json +1 -1
  65. package/dist/sharing/metafile-cjs.json +1 -1
  66. package/dist/sharing/metafile-esm.json +1 -1
  67. package/dist/skills/index.d.cts +1 -0
  68. package/dist/skills/index.d.ts +1 -0
  69. package/dist/skills/metafile-cjs.json +1 -1
  70. package/dist/skills/metafile-esm.json +1 -1
  71. package/dist/soul/metafile-cjs.json +1 -1
  72. package/dist/soul/metafile-esm.json +1 -1
  73. package/dist/terminal/metafile-cjs.json +1 -1
  74. package/dist/terminal/metafile-esm.json +1 -1
  75. package/dist/ui/index.d.cts +1 -0
  76. package/dist/ui/index.d.ts +1 -0
  77. package/dist/ui/metafile-cjs.json +1 -1
  78. package/dist/ui/metafile-esm.json +1 -1
  79. package/dist/utils/index.d.cts +1 -0
  80. package/dist/utils/index.d.ts +1 -0
  81. package/dist/utils/metafile-cjs.json +1 -1
  82. package/dist/utils/metafile-esm.json +1 -1
  83. package/native/mxc/LICENSE.microsoft-mxc-sdk.md +20 -20
  84. package/native/mxc/README.md +25 -25
  85. package/native/mxc/package.json +58 -58
  86. package/ownership/CLEAN_ROOM_CONTRIBUTOR_GUIDE.md +63 -63
  87. package/ownership/evidence/PROPRIETARY-COMMAND-1/implementation-record.md +77 -77
  88. package/ownership/evidence/PROPRIETARY-COMMAND-1/provenance-review.md +51 -51
  89. package/ownership/evidence/PROPRIETARY-MEDIA-1/implementation-record.md +131 -131
  90. package/ownership/evidence/PROPRIETARY-MEDIA-1/provenance-review.md +50 -50
  91. package/ownership/evidence/PROPRIETARY-PTY-1/implementation-record.md +86 -86
  92. package/ownership/evidence/PROPRIETARY-PTY-1/provenance-review.md +52 -52
  93. package/ownership/evidence/PROPRIETARY-RUNTIME-1/implementation-record.md +68 -68
  94. package/ownership/evidence/PROPRIETARY-RUNTIME-1/provenance-review.md +32 -32
  95. package/ownership/evidence/PROPRIETARY-TOOLCHAIN-1/implementation-record.md +53 -53
  96. package/ownership/evidence/PROPRIETARY-TOOLCHAIN-1/provenance-review.md +32 -32
  97. package/ownership/evidence/PROPRIETARY-UI-1/implementation-record.md +96 -96
  98. package/ownership/evidence/PROPRIETARY-UI-1/provenance-review.md +46 -46
  99. package/ownership/ownership-policy.schema.json +192 -192
  100. package/ownership/templates/clean-room-implementation-record.md +70 -70
  101. package/ownership/templates/provenance-review.md +51 -51
  102. package/package.json +1 -1
@@ -1,33 +1,33 @@
1
- "use strict";var C=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var oe=Object.prototype.hasOwnProperty;var ce=(t,e)=>{for(var n in e)C(t,n,{get:e[n],enumerable:!0})},le=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ae(e))!oe.call(t,r)&&r!==n&&C(t,r,{get:()=>e[r],enumerable:!(i=se(e,r))||i.enumerable});return t};var ue=t=>le(C({},"__esModule",{value:!0}),t);var Pt={};ce(Pt,{ExecutionGovernance:()=>p,InteractiveChatTurnGovernance:()=>A,InteractiveTurnGovernance:()=>h,buildContractLedgerGuidance:()=>k,buildProjectBudgetFinalizationGuidance:()=>G,buildProjectExecutionGuidance:()=>E,buildProjectExecutionProfile:()=>x,createBenchBashMiddleware:()=>S,createGovernanceExtensions:()=>It,isExplicitResearchPrompt:()=>_,isSimpleInformationalPrompt:()=>w,resolveInteractiveTurnMaxIterations:()=>ne,shouldEnableExecutionGovernance:()=>v});module.exports=ue(Pt);var de=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,me=[/\bwrite\s+(?:the\s+)?(?:output|result|answer|contents?|solution)\s+to\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\bsave\s+(?:it|them|your\s+solution|the\s+(?:output|result|answer|solution|model|file|artifact))?\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:create|place)\s+(?:a\s+file\s+(?:called|named)|the\s+file)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:must|should|needs?\s+to)\s+be\s+(?:saved|written|placed|stored)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\bfinal\s+(?:model|output|artifact|answer|solution)\s+(?:needs?\s+to|should|must)\s+be\s+saved\s+as\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:at|in)\s+(?:"|'|`)?((?:\/app|\/workspace|\/tmp|\.{1,2}\/)[^\s"'`]+)(?:"|'|`)?\s+(?:containing|with\s+the\s+(?:answer|result|solution))/i],he=/(?:"([^"\n]{4,240})"|'([^'\n]{4,240})'|`([^`\n]{4,240})`)/g,pe=/(?:^|\n)\s*(?:\$?\s*)?(uv run|python3?|pytest|npm|pnpm|yarn|cargo|make|cmake|ninja|gcc|g\+\+|clang|go|rustc|sqlite3|ffmpeg|openssl|qemu-system-[\w-]+|curl|ssh|git|docker|bash|sh)\b[^\n]{0,220}/gi,fe=/\b(?:at\s+least|at\s+most|less\s+than|more\s+than|greater\s+than|under|over|within|max(?:imum)?|min(?:imum)?|accuracy|score|valid\s+for|size|runtime|timeout|precision|recall|f1|rmse|mae)\b[^\n.;:]{0,120}\d+(?:\.\d+)?\s*(?:%|mb|gb|kb|bytes?|s|sec(?:onds?)?|ms|days?|years?|accuracy|score)?/gi,ge=[{name:"ML/model artifact",pattern:/\b(?:model|weights?|checkpoint|ckpt|onnx|torch|pytorch|tensorflow|keras|fasttext|embedding|inference|prediction|logits?|classif(?:y|ication)|train(?:ing)?|accuracy|gpt-?2|tokeni[sz]er)\b/i,checks:["validate on multiple representative samples or a holdout, not one smoke input","reject constant, hard-coded, or one-sample inference stubs unless the task explicitly proves they are valid","verify artifact size, invocation, preprocessing, label order, and output schema together"]},{name:"visual/video/geometry",pattern:/\b(?:image|video|frame|opencv|cv2|ffmpeg|ocr|render|pixel|sprite|gcode|g-code|path\s*tracing|ray\s*tracing|camera|toml|move\s+extraction)\b/i,checks:["derive answers from pixels, frames, geometry, or rendered previews instead of filenames or comments","use at least two independent views when possible, such as numeric analysis plus preview inspection","for exact tokens or flags, verify the final text byte-for-byte before finishing"]},{name:"compiler/emulator/build",pattern:/\b(?:compile|compiler|cross-?compile|gcc|clang|cargo|rustc|make|cmake|ninja|mips|riscv|x86|arm|kernel|qemu|emulator|interpreter|assembly|linker|windows\s+3\.11|doom)\b/i,checks:["split build, run, and verifier phases, each with bounded logs and explicit success criteria","keep the final runnable artifact or service state after the last positive check","if full builds are expensive, run narrow syntax/unit checks before the full verifier-shaped command"]},{name:"symbolic/search/optimization",pattern:/\b(?:regex|regular expression|solver|constraint|backtracking|search|codegolf|shortest|smallest|optimi[sz]e|fibonacci|circuit|sat|smt|brute\s*force)\b/i,checks:["build a small independent verifier or counterexample generator before optimizing","checkpoint the current best valid candidate to the required output path before long searches","treat near-threshold wins as failures unless repeated checks show a clear margin"]},{name:"data integrity/conversion",pattern:/\b(?:csv|tsv|parquet|jsonl?|dataset|dataframe|reshard|compress|decompress|wal|sqlite|database|token(?:s|i[sz]e)?)\b/i,checks:["compare row counts, ordering, schema, nulls, and exact byte or cell values where relevant","validate by reading the produced artifact back, not only by checking that files exist","preserve required final files after temporary validation cleanup"]},{name:"service/VM/network",pattern:/\b(?:server|service|daemon|webserver|http|https|localhost|port\s+\d+|ssh|sshd|qemu|vm|virtual\s+machine|container)\b/i,checks:["poll readiness and verify the exact final client command, including auth and content","leave required long-running services or VMs alive in the final state","an open port alone is not a pass; verify the protocol-level contract"]},{name:"security/sanitization",pattern:/\b(?:xss|sanitize|html|javascript|script|payload|exploit|decrypt|archive|hash|password|secret|certificate|openssl)\b/i,checks:["test both positive and negative/adversarial cases, including idempotence when preserving clean input matters","do not write guesses or placeholders into required answer files","verify final artifacts with format-specific tools where available"]},{name:"science/numeric/bio",pattern:/\b(?:dna|protein|genome|melting|tm\b|raman|spectrum|fit|curve|simulation|molecule|assembly)\b/i,checks:["measure the exact numeric constraints the prompt states and keep safety margin beyond thresholds","run validation on the final submitted artifact, not an intermediate candidate","if stochastic search is used, save the best validated candidate before continuing"]},{name:"binary/ELF/recovery",pattern:/\b(?:elf|binary|disassembl|objdump|readelf|segment|memory|recovery|reverse\s*engineer)\b/i,checks:["parse the file format generically and validate against header/segment metadata","confirm address formats, endian handling, and value types match the required output","test on a second generated or varied sample when possible"]}];function D(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function q(t){return t.length===0||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//")}function g(t,e){let n=[],i=new Set;for(let r of t){let s=r.trim();if(!(!s||i.has(s))&&(i.add(s),n.push(s),n.length>=e))break}return n}function be(t){let e=[];for(let n of me){let i=new RegExp(n.source,n.flags.includes("g")?n.flags:`${n.flags}g`),r;for(;(r=i.exec(t))!==null;){let s=r[1]?D(r[1]):"";q(s)||e.push(s)}}return g(e,8)}function ve(t,e){let n=new Set(e),i=t.match(de)??[];return g(i.map(r=>D(r)).filter(r=>!q(r)&&!n.has(r)),8)}function ye(t){let e=[],n;for(;(n=he.exec(t))!==null;){let i=(n[1]??n[2]??n[3]??"").trim();i&&(/^(?:\/|[A-Za-z]:\\|\.\.?\/)/.test(i)||/^(?:python|npm|uv|cargo|make|curl|ssh|git|docker)\b/i.test(i)||e.push(i.length>96?`${i.slice(0,93)}...`:i))}return g(e,6)}function we(t){let e=[],n;for(;(n=pe.exec(t))!==null;){let i=n[0].replace(/^\s*\$?\s*/,"").trim();i.length>0&&e.push(i.length>140?`${i.slice(0,137)}...`:i)}return g(e,6)}function ke(t){let e=[],n;for(;(n=fe.exec(t))!==null;)e.push(n[0].replace(/\s+/g," ").trim());return g(e,6)}function Re(t){return ge.filter(e=>e.pattern.test(t)).slice(0,5)}function O(t){return/\b(?:terminal-bench|benchmark|verifier|hidden tests?|run-tests\.sh|live benchmark task container|\/app)\b/i.test(t)}function k(t){let e=t?.trim()??"";if(!e)return"";let n=be(e),i=ve(e,n),r=ye(e),s=we(e),a=ke(e),o=Re(e);if(n.length===0&&i.length===0&&r.length===0&&s.length===0&&a.length===0&&o.length===0&&!O(e))return"";let c=["","","# Contract Ledger","- Before implementation, maintain a mental or written ledger of the required final artifacts, exact outputs, thresholds, and verifier-shaped commands.","- Update the ledger when new evidence appears. Do not finish until every ledger item has direct evidence from the final submitted state."];n.length>0&&c.push(`- Required output artifacts: ${n.join(", ")}`),i.length>0&&c.push(`- Mentioned input/reference paths: ${i.join(", ")}`),r.length>0&&c.push(`- Exact literal candidates to preserve byte-for-byte: ${r.join(" | ")}`),a.length>0&&c.push(`- Numeric or policy thresholds to measure directly: ${a.join(" | ")}`),s.length>0&&c.push(`- Prompt-provided command shapes to honor or emulate: ${s.join(" | ")}`),o.length>0&&c.push(`- Risk domains detected: ${o.map(d=>d.name).join(", ")}`),c.push("","# Adversarial Verification","- Treat file existence, one happy-path sample, a self-written smoke test, or a plausible-looking artifact as insufficient evidence.","- Build hidden-test-like checks: multiple samples, malformed/adversarial inputs, round trips, byte-level reads, schema checks, process-level invocation, or exact verifier commands as appropriate.","- Run checks against the final submitted artifact or final live service state, not only against an intermediate candidate.","- If validation is ambiguous, below threshold, near threshold, or only passes because of a narrow stub, keep working or explicitly mark the task incomplete instead of claiming success."),O(e)&&c.push("- In benchmark containers, do not declare SELF_CHECK_PASS until the required files or services survive final cleanup and at least one verifier-shaped check passes.");for(let d of o)c.push(`- ${d.name}: ${d.checks.join("; ")}.`);return c.join(`
1
+ "use strict";var C=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var oe=Object.prototype.hasOwnProperty;var ce=(t,e)=>{for(var n in e)C(t,n,{get:e[n],enumerable:!0})},le=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ae(e))!oe.call(t,r)&&r!==n&&C(t,r,{get:()=>e[r],enumerable:!(i=se(e,r))||i.enumerable});return t};var ue=t=>le(C({},"__esModule",{value:!0}),t);var Nt={};ce(Nt,{ExecutionGovernance:()=>p,InteractiveChatTurnGovernance:()=>A,InteractiveTurnGovernance:()=>h,buildContractLedgerGuidance:()=>k,buildProjectBudgetFinalizationGuidance:()=>G,buildProjectExecutionGuidance:()=>E,buildProjectExecutionProfile:()=>x,createBenchBashMiddleware:()=>S,createGovernanceExtensions:()=>Pt,isExplicitResearchPrompt:()=>_,isSimpleInformationalPrompt:()=>w,resolveInteractiveTurnMaxIterations:()=>ne,shouldEnableExecutionGovernance:()=>y});module.exports=ue(Nt);var de=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,me=[/\bwrite\s+(?:the\s+)?(?:output|result|answer|contents?|solution)\s+to\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\bsave\s+(?:it|them|your\s+solution|the\s+(?:output|result|answer|solution|model|file|artifact))?\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:create|place)\s+(?:a\s+file\s+(?:called|named)|the\s+file)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:must|should|needs?\s+to)\s+be\s+(?:saved|written|placed|stored)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\bfinal\s+(?:model|output|artifact|answer|solution)\s+(?:needs?\s+to|should|must)\s+be\s+saved\s+as\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:at|in)\s+(?:"|'|`)?((?:\/app|\/workspace|\/tmp|\.{1,2}\/)[^\s"'`]+)(?:"|'|`)?\s+(?:containing|with\s+the\s+(?:answer|result|solution))/i],he=/(?:"([^"\n]{4,240})"|'([^'\n]{4,240})'|`([^`\n]{4,240})`)/g,pe=/(?:^|\n)\s*(?:\$?\s*)?(uv run|python3?|pytest|npm|pnpm|yarn|cargo|make|cmake|ninja|gcc|g\+\+|clang|go|rustc|sqlite3|ffmpeg|openssl|qemu-system-[\w-]+|curl|ssh|git|docker|bash|sh)\b[^\n]{0,220}/gi,fe=/\b(?:at\s+least|at\s+most|less\s+than|more\s+than|greater\s+than|under|over|within|max(?:imum)?|min(?:imum)?|accuracy|score|valid\s+for|size|runtime|timeout|precision|recall|f1|rmse|mae)\b[^\n.;:]{0,120}\d+(?:\.\d+)?\s*(?:%|mb|gb|kb|bytes?|s|sec(?:onds?)?|ms|days?|years?|accuracy|score)?/gi,ge=[{name:"ML/model artifact",pattern:/\b(?:model|weights?|checkpoint|ckpt|onnx|torch|pytorch|tensorflow|keras|fasttext|embedding|inference|prediction|logits?|classif(?:y|ication)|train(?:ing)?|accuracy|gpt-?2|tokeni[sz]er)\b/i,checks:["validate on multiple representative samples or a holdout, not one smoke input","reject constant, hard-coded, or one-sample inference stubs unless the task explicitly proves they are valid","verify artifact size, invocation, preprocessing, label order, and output schema together"]},{name:"visual/video/geometry",pattern:/\b(?:image|video|frame|opencv|cv2|ffmpeg|ocr|render|pixel|sprite|gcode|g-code|path\s*tracing|ray\s*tracing|camera|toml|move\s+extraction)\b/i,checks:["derive answers from pixels, frames, geometry, or rendered previews instead of filenames or comments","use at least two independent views when possible, such as numeric analysis plus preview inspection","for exact tokens or flags, verify the final text byte-for-byte before finishing"]},{name:"compiler/emulator/build",pattern:/\b(?:compile|compiler|cross-?compile|gcc|clang|cargo|rustc|make|cmake|ninja|mips|riscv|x86|arm|kernel|qemu|emulator|interpreter|assembly|linker|windows\s+3\.11|doom)\b/i,checks:["split build, run, and verifier phases, each with bounded logs and explicit success criteria","keep the final runnable artifact or service state after the last positive check","if full builds are expensive, run narrow syntax/unit checks before the full verifier-shaped command"]},{name:"symbolic/search/optimization",pattern:/\b(?:regex|regular expression|solver|constraint|backtracking|search|codegolf|shortest|smallest|optimi[sz]e|fibonacci|circuit|sat|smt|brute\s*force)\b/i,checks:["build a small independent verifier or counterexample generator before optimizing","checkpoint the current best valid candidate to the required output path before long searches","treat near-threshold wins as failures unless repeated checks show a clear margin"]},{name:"data integrity/conversion",pattern:/\b(?:csv|tsv|parquet|jsonl?|dataset|dataframe|reshard|compress|decompress|wal|sqlite|database|token(?:s|i[sz]e)?)\b/i,checks:["compare row counts, ordering, schema, nulls, and exact byte or cell values where relevant","validate by reading the produced artifact back, not only by checking that files exist","preserve required final files after temporary validation cleanup"]},{name:"service/VM/network",pattern:/\b(?:server|service|daemon|webserver|http|https|localhost|port\s+\d+|ssh|sshd|qemu|vm|virtual\s+machine|container)\b/i,checks:["poll readiness and verify the exact final client command, including auth and content","leave required long-running services or VMs alive in the final state","an open port alone is not a pass; verify the protocol-level contract"]},{name:"security/sanitization",pattern:/\b(?:xss|sanitize|html|javascript|script|payload|exploit|decrypt|archive|hash|password|secret|certificate|openssl)\b/i,checks:["test both positive and negative/adversarial cases, including idempotence when preserving clean input matters","do not write guesses or placeholders into required answer files","verify final artifacts with format-specific tools where available"]},{name:"science/numeric/bio",pattern:/\b(?:dna|protein|genome|melting|tm\b|raman|spectrum|fit|curve|simulation|molecule|assembly)\b/i,checks:["measure the exact numeric constraints the prompt states and keep safety margin beyond thresholds","run validation on the final submitted artifact, not an intermediate candidate","if stochastic search is used, save the best validated candidate before continuing"]},{name:"binary/ELF/recovery",pattern:/\b(?:elf|binary|disassembl|objdump|readelf|segment|memory|recovery|reverse\s*engineer)\b/i,checks:["parse the file format generically and validate against header/segment metadata","confirm address formats, endian handling, and value types match the required output","test on a second generated or varied sample when possible"]}];function D(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function q(t){return t.length===0||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//")}function b(t,e){let n=[],i=new Set;for(let r of t){let s=r.trim();if(!(!s||i.has(s))&&(i.add(s),n.push(s),n.length>=e))break}return n}function be(t){let e=[];for(let n of me){let i=new RegExp(n.source,n.flags.includes("g")?n.flags:`${n.flags}g`),r;for(;(r=i.exec(t))!==null;){let s=r[1]?D(r[1]):"";q(s)||e.push(s)}}return b(e,8)}function ve(t,e){let n=new Set(e),i=t.match(de)??[];return b(i.map(r=>D(r)).filter(r=>!q(r)&&!n.has(r)),8)}function ye(t){let e=[],n;for(;(n=he.exec(t))!==null;){let i=(n[1]??n[2]??n[3]??"").trim();i&&(/^(?:\/|[A-Za-z]:\\|\.\.?\/)/.test(i)||/^(?:python|npm|uv|cargo|make|curl|ssh|git|docker)\b/i.test(i)||e.push(i.length>96?`${i.slice(0,93)}...`:i))}return b(e,6)}function we(t){let e=[],n;for(;(n=pe.exec(t))!==null;){let i=n[0].replace(/^\s*\$?\s*/,"").trim();i.length>0&&e.push(i.length>140?`${i.slice(0,137)}...`:i)}return b(e,6)}function ke(t){let e=[],n;for(;(n=fe.exec(t))!==null;)e.push(n[0].replace(/\s+/g," ").trim());return b(e,6)}function Re(t){return ge.filter(e=>e.pattern.test(t)).slice(0,5)}function O(t){return/\b(?:terminal-bench|benchmark|verifier|hidden tests?|run-tests\.sh|live benchmark task container|\/app)\b/i.test(t)}function k(t){let e=t?.trim()??"";if(!e)return"";let n=be(e),i=ve(e,n),r=ye(e),s=we(e),a=ke(e),o=Re(e);if(n.length===0&&i.length===0&&r.length===0&&s.length===0&&a.length===0&&o.length===0&&!O(e))return"";let c=["","","# Contract Ledger","- Before implementation, maintain a mental or written ledger of the required final artifacts, exact outputs, thresholds, and verifier-shaped commands.","- Update the ledger when new evidence appears. Do not finish until every ledger item has direct evidence from the final submitted state."];n.length>0&&c.push(`- Required output artifacts: ${n.join(", ")}`),i.length>0&&c.push(`- Mentioned input/reference paths: ${i.join(", ")}`),r.length>0&&c.push(`- Exact literal candidates to preserve byte-for-byte: ${r.join(" | ")}`),a.length>0&&c.push(`- Numeric or policy thresholds to measure directly: ${a.join(" | ")}`),s.length>0&&c.push(`- Prompt-provided command shapes to honor or emulate: ${s.join(" | ")}`),o.length>0&&c.push(`- Risk domains detected: ${o.map(d=>d.name).join(", ")}`),c.push("","# Adversarial Verification","- Treat file existence, one happy-path sample, a self-written smoke test, or a plausible-looking artifact as insufficient evidence.","- Build hidden-test-like checks: multiple samples, malformed/adversarial inputs, round trips, byte-level reads, schema checks, process-level invocation, or exact verifier commands as appropriate.","- Run checks against the final submitted artifact or final live service state, not only against an intermediate candidate.","- If validation is ambiguous, below threshold, near threshold, or only passes because of a narrow stub, keep working or explicitly mark the task incomplete instead of claiming success."),O(e)&&c.push("- In benchmark containers, do not declare SELF_CHECK_PASS until the required files or services survive final cleanup and at least one verifier-shaped check passes.");for(let d of o)c.push(`- ${d.name}: ${d.checks.join("; ")}.`);return c.join(`
2
2
  `)}var xe=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,Ee=[/\b(?:save|write|place|store)\s+(?:the\s+)?(?:output|result|answer|solution|model|artifact|file|contents?)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:save|write|place|store)\s+(?:the\s+)?final\s+(?:output|result|answer|solution|model|artifact|file)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:create|place)\s+(?:a\s+file\s+(?:called|named)|the\s+file)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:write|create|implement)\s+(?:a\s+)?(?:C|C\+\+|Python|Rust|Go|JavaScript|TypeScript|shell|bash)?\s*(?:source\s+)?(?:program|script|implementation|module|file|code)\s+(?:at|as|in|to)?\s*(?:"|'|`)?((?:\/|\.{1,2}[\\/]|[A-Za-z0-9_.-]+[\\/])[^\s"'`]+|[A-Za-z0-9_.-]+\.(?:c|cc|cpp|h|hpp|py|js|ts|tsx|sh|rs|go|java|rb|pl|php|json|xml|tex|sql|vim))(?:"|'|`)?/gi,/\b(?:must|should|needs?\s+to)\s+be\s+(?:saved|written|placed|stored)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\bfinal\s+(?:model|output|artifact|answer|solution)\s+(?:needs?\s+to|should|must)\s+be\s+saved\s+as\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:file|path)\s+(?:"|'|`)?((?:\/app|\/workspace|\/tmp|\.{1,2}\/)[^\s"'`]+)(?:"|'|`)?\s+(?:must|should|needs?\s+to|containing|with)\b/gi],Te=[{key:"ml_artifact",label:"ML/model artifact",trigger:/\b(?:model|weights?|checkpoint|ckpt|onnx|torch|pytorch|tensorflow|keras|fasttext|embedding|inference|prediction|logits?|classif(?:y|ication)|train(?:ing)?|accuracy|loss|gpt-?2|tokeni[sz]er|vocab|bpe)\b/i,verifierRequirements:["inspect model, weight, tokenizer, preprocessing, label-order, and entrypoint schema before wrapping it","validate multiple representative samples or known labels; one smoke input is not enough","when provided artifacts exist, prove dependency by loading/schema-checking or mutation/removal changing outputs","for distributed/tensor-parallel code, run the actual multiprocess/world-size verifier shape instead of only syntax or static checks"],finalAuditItems:["final model or wrapper loads from the submitted path","final invocation uses provided weights/tokenizers instead of constants","metric or known-output evidence is recorded against the final artifact"]},{key:"visual_artifact",label:"visual/video/geometry artifact",trigger:/\b(?:image|video|frame|opencv|cv2|ffmpeg|ocr|render|raster|pixel|sprite|gcode|g-code|path\s*tracing|ray\s*tracing|camera|toml|move\s+extraction|mask|segmentation|pdf|invoice|document)\b/i,verifierRequirements:["derive answers from rendered pixels, frame samples, geometry, OCR, or simulation rather than filenames/comments","use two independent views for exact text, coordinates, masks, or temporal outputs","read generated images, CSVs, PDFs, or media outputs back through the same shape the verifier will inspect"],finalAuditItems:["submitted visual/document/media artifact exists at the required path","second-pass content check agrees with the final output","temporary previews did not replace or remove the final deliverable"]},{key:"structured_data",label:"structured data or script output",trigger:/\b(?:csv|tsv|parquet|arrow|jsonl?|dataframe|table|schema|columns?|rows?|coords_[xy]|metadata|reshard|compress|decompress|output_path)\b/i,verifierRequirements:["run the submitted script or converter end-to-end, then read the generated artifact back","assert row count, column order, scalar/list field types, nulls, dtypes, and exact value preservation","for conversions, compare source and produced artifact with dataframe or byte-level equality where relevant"],finalAuditItems:["final generated artifact has the required schema and parseable fields","clean/reference inputs were not overwritten unless explicitly required","single-file deliverables contain only expected final content"]},{key:"performance",label:"performance or optimization",trigger:/\b(?:optimi[sz]e|faster|speed\s*up|runtime|latency|throughput|benchmark|profile|median|p95|under\s+\d+(?:\.\d+)?\s*(?:ms|s|sec|seconds?|min|minutes?)|accuracy|score)\b/i,verifierRequirements:["measure a baseline before optimizing and compare against the final candidate","use bounded warmed runs with medians or thresholds instead of one noisy timing","inspect relevant plans/profiles and reject changes that only preserve correctness while losing the target metric"],finalAuditItems:["best measured candidate is written to the required path","metric evidence has clear margin beyond the threshold","no long benchmark loop is still running in the final state"]},{key:"compiler_emulator",label:"compiler, emulator, or cross-architecture",trigger:/\b(?:compile|compiler|cross-?compile|gcc|clang|cargo|rustc|make|cmake|ninja|mips|riscv|x86|arm|kernel|qemu|emulator|interpreter|polyglot|doom|windows\s+3\.11|assembly|linker)\b/i,verifierRequirements:["identify the exact target toolchain and verifier command first","run a small compile/run smoke before expensive full builds","leave the final runnable artifact, VM, or emulator state after the last positive check"],finalAuditItems:["final binary/script/service starts with the verifier-shaped command","logs show the latest build/run result, not an old intermediate","background VM/emulator/service remains alive when the task requires post-run access"]},{key:"service_vm",label:"service, VM, network, or SSH",trigger:/\b(?:server|service|daemon|webserver|http|https|localhost|port\s+\d+|ssh|sshd|git\s+(?:server|clone|push)|grpc|protobuf|proto\b|rpc|request|response|client|qemu|vm|virtual\s+machine|container|socket|telnet|serial|monitor\s+socket|qmp|sendkey)\b/i,verifierRequirements:["separate setup, readiness polling, final client command, and cleanup into bounded phases","verify the exact user/verifier client command including auth, content, and protocol behavior","for gRPC/protobuf/RPC work, instantiate generated request messages with required fields and call every required RPC through a real client","for VM/QEMU work, verify monitor/QMP/serial control surfaces and expected framebuffer or service behavior, not screenshots alone","keep only required long-lived processes in the background and preserve logs"],finalAuditItems:["final service or VM is running if the verifier connects after completion","last positive client check happened after cleanup/negative tests","open port is backed by protocol-level success, not only socket readiness","protocol schemas, request fields, response fields, and VM control sockets match the verifier contract when applicable"]},{key:"search_symbolic",label:"search, symbolic, regex, or code-size",trigger:/\b(?:regex|regular expression|solver|constraint|backtracking|search|codegolf|shortest|smallest|fibonacci|circuit|sat|smt|brute\s*force|decompress|codec|round\s*trip)\b/i,verifierRequirements:["build a correctness oracle or counterexample generator before optimizing size or speed","checkpoint the best valid candidate to the required output before long searches","for regex/chess/legal-move tasks, compare against an independent oracle such as python-chess across provided PGN/FEN fixtures","cap search loops and pivot after repeated failures in the same direction"],finalAuditItems:["current best valid candidate is preserved at the submission path","randomized or adversarial fixtures ran against the final candidate","no known counterexample from the latest check remains unresolved"]},{key:"security_sanitization",label:"security, sanitization, archive, or certificate",trigger:/\b(?:xss|sanitize|html|javascript|script|payload|exploit|decrypt|archive|7z|zip|rar|hash|password|secret|credential|token|leak|git\s+repo|repository\s+cleanup|diff\s+scope|certificate|openssl|pem|tls)\b/i,verifierRequirements:["test harmful and clean/idempotent cases through the submitted entrypoint","use format-specific tooling before broad guessing for archives, hashes, and certificates","avoid regex-only sanitizers when parser or allowlist behavior is required","for repository secret cleanup, scan for remaining secrets and audit changed paths against the contaminated/allowed file set"],finalAuditItems:["clean inputs remain semantically unchanged when required","harmful/adversarial inputs are blocked by the final artifact","placeholder outputs such as UNKNOWN or TODO are absent","repository diff scope contains no unrelated clean-file modifications when the task asks for surgical cleanup"]},{key:"science_bio_numeric",label:"science, biosequence, or numeric fitting",trigger:/\b(?:dna|primer|protein|genome|melting|tm\b|oligotm|raman|spectrum|fit|curve|simulation|molecule|assembly|mjcf|robot)\b/i,verifierRequirements:["measure every stated numeric constraint using the specified calculator or an equivalent exact implementation","keep safety margin beyond hard thresholds and rerun validation on the final submitted artifact","for biological assembly, verify orientation, overhangs, circularity, translation, and sequence order end-to-end"],finalAuditItems:["final sequence/numeric file passes exact threshold calculations","no intermediate candidate is mistaken for the final artifact","round-trip or reconstruction checks cover the complete intended product"]},{key:"binary_recovery",label:"binary/ELF/recovery",trigger:/\b(?:elf|binary|disassembl|objdump|readelf|segment|memory|address|endianness|reverse\s*engineer)\b/i,verifierRequirements:["parse file-backed bytes and metadata, not only loader-expanded memory","validate address formats, endian handling, p_filesz/p_memsz boundaries, and exact JSON/value types","test on a second generated or varied sample when possible"],finalAuditItems:["final parser reads the required input file directly","output values match declared numeric/string formats","metadata and data-region boundary cases are covered"]},{key:"async_process",label:"async, signal, or process cleanup",trigger:/\b(?:async|asyncio|signal|sigterm|sigint|interrupt|cancel(?:lation)?|cleanup|terminate|shutdown|background\s+process|worker|taskgroup|semaphore)\b/i,verifierRequirements:["exercise the real interruption, signal, cancellation, or shutdown path through the submitted entrypoint","assert cleanup markers, drained finalizers, process termination, and exit behavior","include boundary cases around queued work or concurrency limits when mentioned"],finalAuditItems:["final entrypoint handles the same signal path the verifier will call","cleanup evidence comes from the submitted artifact, not only the validation harness","no orphaned process remains unless it is the required final service"]}];function $(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function U(t){return!!(!t||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//"))}function R(t,e){let n=[],i=new Set;for(let r of t){let s=r.trim();if(!(!s||i.has(s))&&(i.add(s),n.push(s),n.length>=e))break}return n}function Ae(t){let e=[];for(let n of Ee){let i;for(;(i=n.exec(t))!==null;){let r=$(i[1]??"");U(r)||e.push(r)}}return R(e,10)}function _e(t,e){let n=new Set(e),i=t.match(xe)??[];return R(i.map($).filter(r=>!U(r)&&!n.has(r)),10)}function Se(t){return Te.filter(e=>e.trigger.test(t)).slice(0,6)}function V(t){return/\b(?:terminal-bench|benchmark|hidden tests?|verifier|\/tests|test\.sh|run-tests\.sh|\/app)\b/i.test(t)}function Ce(t,e,n){return e.length>0||n.length>0||V(t)?!0:/\b(?:implement|fix|build|create|write|debug|optimi[sz]e|train|configure|recover|extract|convert|process|validate)\b/i.test(t)}function Ie(t,e){let n=t.some(r=>r.key==="ml_artifact"||r.key==="compiler_emulator"||r.key==="service_vm"||r.key==="search_symbolic"||r.key==="science_bio_numeric"),i=e||t.some(r=>r.key==="structured_data"||r.key==="visual_artifact"||r.key==="security_sanitization"||r.key==="binary_recovery"||r.key==="async_process");return n?[{name:"inspect",budgetPercent:15,objective:"extract the acceptance contract, toolchain, inputs, and verifier path before touching expensive work"},{name:"baseline",budgetPercent:15,objective:"create the smallest runnable baseline or measurement harness and write a checkpoint if an output path exists"},{name:"implement",budgetPercent:40,objective:"iterate on the candidate while keeping work bounded and evidence-driven"},{name:"validate",budgetPercent:20,objective:"run verifier-shaped checks against the final candidate and fix concrete failures only"},{name:"finalize",budgetPercent:10,objective:"restore final state, remove accidental temp artifacts, and preserve required outputs/services"}]:i?[{name:"inspect",budgetPercent:20,objective:"extract required outputs, fixtures, schema, and hidden-verifier assumptions"},{name:"baseline",budgetPercent:15,objective:"produce a narrow runnable baseline and a failing/passing local oracle"},{name:"implement",budgetPercent:35,objective:"implement the simplest general solution that satisfies the oracle"},{name:"validate",budgetPercent:20,objective:"read back artifacts and run adversarial, round-trip, or protocol checks"},{name:"finalize",budgetPercent:10,objective:"ensure the final filesystem/process state is exactly what the user or verifier will inspect"}]:[{name:"inspect",budgetPercent:20,objective:"understand the requested final state and available tests"},{name:"baseline",budgetPercent:10,objective:"make a small working baseline or reproduce the issue"},{name:"implement",budgetPercent:40,objective:"make the targeted change"},{name:"validate",budgetPercent:20,objective:"run the most relevant tests against the final state"},{name:"finalize",budgetPercent:10,objective:"clean temporary state and report only after validation"}]}function x(t){let e=t?.trim()??"",n=Ae(e),i=_e(e,n),r=Se(e),s=V(e),a=Ce(e,n,r),o=Ie(r,s),c=R([s?"check /tests, /test.sh, /run-tests.sh, README/instruction files, and prompt-provided commands early; if hidden, synthesize a contract-matched self-check":"look for existing tests or task-provided commands before writing custom checks",n.length>0?"write or preserve the best current candidate at each required output path before long-running work":"if a final artifact emerges, keep it in a stable path and validate that path","after any failed verifier/self-check, fix the first concrete failure and rerun the same check until a later passing signal supersedes it",...r.flatMap(m=>m.verifierRequirements)],12),d=R([...n.map(m=>`required output exists, is non-empty when applicable, and was read back: ${m}`),"latest validation ran after the last write to the submitted artifact","no known failed verifier, self-check, diff, build, or runtime signal remains unresolved","final filesystem/process state matches what the user or verifier will inspect after the agent exits",...r.flatMap(m=>m.finalAuditItems)],14);return{projectLike:a,hiddenVerifierLikely:s,requiredOutputs:n,referencedPaths:i,domains:r,phases:o,verifierRequirements:c,finalAuditItems:d}}function E(t){let e=x(t);if(!e.projectLike)return"";let n=["","","# Project Execution Board","- Treat non-trivial coding/terminal work as a project with phases, a live contract, a current best candidate, and explicit final-state proof.","- Do not optimize for appearing done. Optimize for the final filesystem, process, service, or artifact state a verifier/user will inspect.",`- Phase budget: ${e.phases.map(i=>`${i.name} ${i.budgetPercent}%`).join(" -> ")}.`];for(let i of e.phases)n.push(`- ${i.name}: ${i.objective}.`);return e.requiredOutputs.length>0&&n.push(`- Required outputs to preserve early: ${e.requiredOutputs.join(", ")}.`),e.referencedPaths.length>0&&n.push(`- Reference/input paths to avoid overwriting unless required: ${e.referencedPaths.join(", ")}.`),e.domains.length>0&&n.push(`- Domain kits active: ${e.domains.map(i=>i.label).join(", ")}.`),n.push("","# Verifier Synthesis",...e.verifierRequirements.map(i=>`- ${i}.`),"","# Final-State Auditor",...e.finalAuditItems.map(i=>`- ${i}.`)),n.join(`
3
3
  `)}function G(t){let e=x(t);if(!e.projectLike)return"";let n=e.domains.map(i=>i.label).join(", ");return["","[Project final-state audit]","You are now in validate/finalize mode, not exploration mode.",e.requiredOutputs.length>0?`Required output paths must already contain the best current candidate: ${e.requiredOutputs.join(", ")}.`:"If a final artifact/service exists, preserve the best current candidate before additional checks.",n?`Active domain risk kits: ${n}.`:"Use the general final-state audit.","Rerun only bounded verifier-shaped checks that target concrete unresolved failures.","Do not start a new long training/build/search/exploration loop unless it directly repairs the latest failing check.","Before the final answer, ensure the latest validation happened after the last artifact write and no known failing signal remains unresolved."].join(`
4
4
  `)}var T={official:6,project:5,user:4,self:3,smoke:2,syntax:1},W=/\b(?:pytest|py\.test|unittest|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest|run-tests?\.sh|test\.sh|verifier|verify|check)\b/i,Pe=/(?:^|\s)(?:\/tests\b|\/run-tests\.sh\b|\.\/run-tests?\.sh\b|\.\/test\.sh\b|test_outputs\.py\b|official\s+verifier|hidden\s+tests?|verifier\b)/i,P=/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?(?:PASS|FAIL|FAILED|ERROR)\b/i,Ne=/(?:^|\s)(?:cat\s+>|tee\b|cp\b|mv\b|rm\b|touch\b|mkdir\b|sed\b.*\s-i\b|patch\b|apply_patch\b|npm\s+install|pip\s+install)\b|[>]{1,2}|\b(?:writeFileSync|open\s*\([^)]*,\s*["']w|Path\([^)]*\)\.write_text)\b/i,z=[/\bFAILED\b/i,/\bFAILURES?\b/i,/\bAssertionError\b/i,/\bTraceback \(most recent call last\)/i,/\b(?:RuntimeError|ValueError|TypeError|SyntaxError|ModuleNotFoundError|ImportError)\b/i,/\b(?:mismatch|differs?|wrong output|does not match|not equal|not equivalent)\b/i,/\b(?:exit|status|return code|returncode)\s*[:=]?\s*[1-9]\d*\b/i,/\btimed?\s*out\b|\btimeout\b/i],Le=[/\b(?:all\s+tests?\s+passed|all\s+checks?\s+passed|verifier\s+passed|validation\s+passed)\b/i,/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?PASS\b/i,/\b(?:0\s+failed|no\s+failures?|passed)\b/i,/\b(?:SUCCESS|successful|verified)\b/i];function Me(t,e=500){return t.replace(/\r\n/g,`
5
- `).replace(/[ \t]+$/gm,"").trim().slice(0,e)}function Fe(t){return t.toLowerCase().replace(/\b0x[0-9a-f]+\b/g,"0x").replace(/\b\d+(?:\.\d+)?\b/g,"#").replace(/\s+/g," ").trim().slice(0,160)}function b(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function je(t,e,n){let i=b(e)??"";return/^Bash$/i.test(t)&&W.test(i)||/^TaskOutput$/i.test(t)&&(W.test(n)||P.test(n))?!0:P.test(n)}function Oe(t,e,n){let i=b(e)??"",r=`${i}
5
+ `).replace(/[ \t]+$/gm,"").trim().slice(0,e)}function Fe(t){return t.toLowerCase().replace(/\b0x[0-9a-f]+\b/g,"0x").replace(/\b\d+(?:\.\d+)?\b/g,"#").replace(/\s+/g," ").trim().slice(0,160)}function v(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function je(t,e,n){let i=v(e)??"";return/^Bash$/i.test(t)&&W.test(i)||/^TaskOutput$/i.test(t)&&(W.test(n)||P.test(n))?!0:P.test(n)}function Oe(t,e,n){let i=v(e)??"",r=`${i}
6
6
  ${n}`;return Pe.test(r)?"official":/\b(?:pytest|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest)\b/i.test(i)?"project":P.test(r)||/\bself[-_ ]?check\b/i.test(r)?"self":/\b(?:syntax|compile|lint|import)\b/i.test(r)?"syntax":/^Bash$/i.test(t)?"user":"smoke"}function De(t){let e,n,i=t.match(/(?:^|\s)(\d+)\s+failed\b/i),r=t.match(/(?:^|\s)(\d+)\s+passed\b/i);return i&&(e=Number.parseInt(i[1],10)),r&&(n=Number.parseInt(r[1],10)),{failed:e,passed:n}}function qe(t,e){let n=t.replace(/\r\n/g,`
7
7
  `).split(`
8
8
  `),i=[];for(let s=0;s<n.length;s+=1){let a=n[s]??"";if(/^(?:FAILED|ERROR)\s+[\w./:-]+/i.test(a.trim())||z.some(o=>o.test(a))){let o=n.slice(Math.max(0,s-1),Math.min(n.length,s+3)).join(`
9
9
  `);i.push(Me(o,260))}}let r=new Map;for(let s of i.slice(0,12)){let a=Fe(s);if(!a)continue;let o=r.get(a);if(o){o.count+=1,o.latestExcerpt=s,o.lastIteration=e;continue}r.set(a,{signature:a,title:s.split(`
10
- `).find(c=>c.trim().length>0)?.trim().slice(0,140)??"Validation failure",count:1,firstIteration:e,lastIteration:e,latestExcerpt:s})}return[...r.values()]}function $e(t,e){let n=De(e);return n.failed!==void 0&&n.failed>0?{outcome:"fail",failureCount:n.failed,...n.passed!==void 0?{passCount:n.passed}:{},summary:`${n.failed} pytest failure(s)${n.passed!==void 0?`, ${n.passed} passed`:""}`}:t.success===!1||z.some(i=>i.test(e))?{outcome:"fail",summary:t.error?`Command failed: ${t.error}`:"Validation output contains failure evidence"}:n.passed!==void 0&&n.passed>0?{outcome:"pass",passCount:n.passed,summary:`${n.passed} pytest test(s) passed`}:Le.some(i=>i.test(e))?{outcome:"pass",summary:"Validation output contains pass evidence"}:{outcome:"unknown",summary:t.success?"Validation-like command produced no clear pass/fail signal":"Command failed without parseable validation signal"}}function Ue(t,e,n){if(!n.success)return!1;if(/^(?:Write|Edit|NotebookEdit|MemoryWrite)$/i.test(t))return!0;let i=b(e);return/^Bash$/i.test(t)&&!!i&&Ne.test(i)}function I(t){return T[t.authority]>=T.project}function v(t){let e=t.taskPrompt??"";return t.benchmarkMode||(t.requiredOutputPaths??[]).length>0?!0:/\b(?:test|tests|pytest|verifier|benchmark|hidden\s+tests?|build|fix|implement|debug|\/app|run-tests?\.sh)\b/i.test(e)}var p=class{contract;signals=[];clusters=new Map;toolCalls=0;workspaceRevision=0;lastCompletionDecision=null;lastValidationIteration=null;lastEvaluatedIteration=null;constructor(e={}){let n=e.taskPrompt??"",i=[...e.requiredOutputPaths??[]],r=e.benchmarkMode===!0||i.length>0||/\b(?:test|tests|pytest|verifier|hidden\s+tests?|run-tests?\.sh|official|validate|validation)\b/i.test(n);this.contract={projectLike:v(e),benchmarkMode:e.benchmarkMode===!0,requiredOutputPaths:i,requiredValidation:r}}recordToolResult(e){if(this.toolCalls+=1,Ue(e.toolName,e.input,e.result)){this.workspaceRevision+=1;for(let a of this.signals)a.stale=!0}let n=`${e.result.output??""}
11
- ${e.result.error??""}`;if(!je(e.toolName,e.input,n))return[];let i=Oe(e.toolName,e.input,n),r=$e(e.result,n),s={id:`validation-${this.signals.length+1}`,iteration:e.iteration,toolName:e.toolName,...b(e.input)?{command:b(e.input)}:{},authority:i,outcome:r.outcome,stale:!1,workspaceRevision:this.workspaceRevision,summary:r.summary,...r.failureCount!==void 0?{failureCount:r.failureCount}:{},...r.passCount!==void 0?{passCount:r.passCount}:{},clusters:r.outcome==="fail"?qe(n,e.iteration):[]};this.signals.push(s),this.lastValidationIteration=e.iteration;for(let a of s.clusters){let o=this.clusters.get(a.signature);if(o){o.count+=a.count,o.lastIteration=a.lastIteration,o.latestExcerpt=a.latestExcerpt;continue}this.clusters.set(a.signature,{...a})}return[s]}evaluateCompletion(e){this.lastEvaluatedIteration=e.iteration;let n=this.getLatestUnresolvedFailure(),i=this.getLatestAuthoritativeSignal();if(this.contract.projectLike&&this.toolCalls===0)return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"no_tool_execution",message:["Do not finish yet. This is an execution task, but no tool evidence was recorded.","Inspect the relevant project state, make the required change, and run the strongest exposed validation before answering."].join(`
10
+ `).find(c=>c.trim().length>0)?.trim().slice(0,140)??"Validation failure",count:1,firstIteration:e,lastIteration:e,latestExcerpt:s})}return[...r.values()]}function $e(t,e){let n=De(e);return n.failed!==void 0&&n.failed>0?{outcome:"fail",failureCount:n.failed,...n.passed!==void 0?{passCount:n.passed}:{},summary:`${n.failed} pytest failure(s)${n.passed!==void 0?`, ${n.passed} passed`:""}`}:t.success===!1||z.some(i=>i.test(e))?{outcome:"fail",summary:t.error?`Command failed: ${t.error}`:"Validation output contains failure evidence"}:n.passed!==void 0&&n.passed>0?{outcome:"pass",passCount:n.passed,summary:`${n.passed} pytest test(s) passed`}:Le.some(i=>i.test(e))?{outcome:"pass",summary:"Validation output contains pass evidence"}:{outcome:"unknown",summary:t.success?"Validation-like command produced no clear pass/fail signal":"Command failed without parseable validation signal"}}function Ue(t,e,n){if(!n.success)return!1;if(/^(?:Write|Edit|NotebookEdit|MemoryWrite)$/i.test(t))return!0;let i=v(e);return/^Bash$/i.test(t)&&!!i&&Ne.test(i)}function I(t){return T[t.authority]>=T.project}function y(t){let e=t.taskPrompt??"";return t.benchmarkMode||(t.requiredOutputPaths??[]).length>0?!0:/\b(?:test|tests|pytest|verifier|benchmark|hidden\s+tests?|build|fix|implement|debug|\/app|run-tests?\.sh)\b/i.test(e)}var p=class{contract;signals=[];clusters=new Map;toolCalls=0;workspaceRevision=0;lastCompletionDecision=null;lastValidationIteration=null;lastEvaluatedIteration=null;constructor(e={}){let n=e.taskPrompt??"",i=[...e.requiredOutputPaths??[]],r=e.benchmarkMode===!0||i.length>0||/\b(?:test|tests|pytest|verifier|hidden\s+tests?|run-tests?\.sh|official|validate|validation)\b/i.test(n);this.contract={projectLike:y(e),benchmarkMode:e.benchmarkMode===!0,requiredOutputPaths:i,requiredValidation:r}}recordToolResult(e){if(this.toolCalls+=1,Ue(e.toolName,e.input,e.result)){this.workspaceRevision+=1;for(let a of this.signals)a.stale=!0}let n=`${e.result.output??""}
11
+ ${e.result.error??""}`;if(!je(e.toolName,e.input,n))return[];let i=Oe(e.toolName,e.input,n),r=$e(e.result,n),s={id:`validation-${this.signals.length+1}`,iteration:e.iteration,toolName:e.toolName,...v(e.input)?{command:v(e.input)}:{},authority:i,outcome:r.outcome,stale:!1,workspaceRevision:this.workspaceRevision,summary:r.summary,...r.failureCount!==void 0?{failureCount:r.failureCount}:{},...r.passCount!==void 0?{passCount:r.passCount}:{},clusters:r.outcome==="fail"?qe(n,e.iteration):[]};this.signals.push(s),this.lastValidationIteration=e.iteration;for(let a of s.clusters){let o=this.clusters.get(a.signature);if(o){o.count+=a.count,o.lastIteration=a.lastIteration,o.latestExcerpt=a.latestExcerpt;continue}this.clusters.set(a.signature,{...a})}return[s]}evaluateCompletion(e){this.lastEvaluatedIteration=e.iteration;let n=this.getLatestUnresolvedFailure(),i=this.getLatestAuthoritativeSignal();if(this.contract.projectLike&&this.toolCalls===0)return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"no_tool_execution",message:["Do not finish yet. This is an execution task, but no tool evidence was recorded.","Inspect the relevant project state, make the required change, and run the strongest exposed validation before answering."].join(`
12
12
  `),blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:i});if(n){let r=this.getRepeatedFailure(),s=["Do not finish yet. The latest authoritative validation signal is still failing.",`Latest failure: ${n.summary}.`,r?`Repeated failure signature detected (${r.count}x): ${r.title}`:"Use the concrete failure output, make the smallest targeted repair, then rerun the same verifier-shaped check.","A self-check pass or candidate note cannot supersede a later project/official failure."].join(`
13
13
  `);return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"authoritative_validation_failed",message:s,blocking:!0,unresolvedFailures:n.clusters,latestAuthoritativeSignal:i})}if(i?.outcome==="pass"&&!i.stale)return this.setDecision({action:"complete",finalStateVerified:!0,reason:"authoritative_validation_passed",message:"Latest authoritative validation passed after the current workspace revision.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:i});if(this.contract.requiredValidation&&e.stopReason!=="progress_checkpoint"){let r=this.getLatestSignal(),s=r?.outcome==="pass"&&!I(r),a=["Do not finish yet. This task requires authoritative validation evidence.",s?"The latest pass signal is only a self/smoke check; run the project test, verifier, or strongest exposed validation command.":"Run the project test, verifier, or strongest exposed validation command and fix concrete failures before answering."].join(`
14
- `);return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:s?"weak_validation_only":"missing_authoritative_validation",message:a,blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:i})}return this.setDecision({action:"complete",finalStateVerified:!1,reason:"no_governance_blocker",message:"No execution-governance blocker found.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:i})}getSummary(){return{contract:{...this.contract,requiredOutputPaths:[...this.contract.requiredOutputPaths]},validation:{latestSignal:this.cloneSignal(this.getLatestSignal()),latestAuthoritativeSignal:this.cloneSignal(this.getLatestAuthoritativeSignal()),latestUnresolvedFailure:this.cloneSignal(this.getLatestUnresolvedFailure()),signals:this.signals.slice(-20).map(e=>this.cloneSignal(e))},progress:{toolCalls:this.toolCalls,validationRuns:this.signals.length,workspaceRevision:this.workspaceRevision,repeatedFailureSignature:this.getRepeatedFailure()?.signature??null,repeatedFailureCount:this.getRepeatedFailure()?.count??0,iterationsSinceLastValidation:this.lastValidationIteration===null?null:Math.max(0,(this.lastEvaluatedIteration??this.lastValidationIteration)-this.lastValidationIteration)},completionDecision:this.lastCompletionDecision?{...this.lastCompletionDecision}:null}}getLatestSignal(){return this.signals.at(-1)??null}getLatestAuthoritativeSignal(){return[...this.signals].reverse().find(e=>I(e))??null}getLatestUnresolvedFailure(){let e=[...this.signals].reverse().find(i=>I(i)&&i.outcome==="fail"&&!i.stale);return e?this.signals.some(i=>i.iteration>e.iteration&&!i.stale&&i.outcome==="pass"&&T[i.authority]>=T[e.authority])?null:e:null}getRepeatedFailure(){let e=null;for(let n of this.clusters.values())n.count<2||(!e||n.count>e.count)&&(e=n);return e}setDecision(e){return this.lastCompletionDecision=e,e}cloneSignal(e){return e?{...e,clusters:e.clusters.map(n=>({...n}))}:null}};var Ve=new Set(["bash","elfanalyze","gitbranch","gitdiff","gitlog","gitstatus","glob","grep","ls","read","readimage"]),Ge=new Set(["applypatch","edit","notebookedit","write"]),We=/\?|\b(?:can|could|did|do|does|has|have|is|should|was|were|will|would)\b|\b(?:correct|right)\s*[.!?]*$/i,ze=/\b(?:audit|build|change|check|clone|configure|copy|create|delete|deploy|edit|find|fix|implement|inspect|install|locate|make|migrate|move|publish|refactor|release|remove|rename|research|run|save|scaffold|search|set|start|stop|test|update|verify|write)\b/i,Be=["audit","build","change","check","clone","configure","create","delete","deploy","implement","inspect","install","locate","migrate","publish","refactor","release","remove","rename","research","scaffold","search","start","update","verify","write"],He=/\b(?:browse|investigate|research|search)\b|\b(?:check|find|look)\s+(?:it\s+)?(?:up|online|on\s+the\s+web)\b/i,Xe=["browse","investigate","research","search"],Qe=/\b(?:Add-Content|Clear-Content|Copy-Item|git\s+(?:add|commit|merge|mv|push|rebase|reset|restore|rm|switch)|Move-Item|New-Item|npm\s+(?:install|publish|uninstall)|pnpm\s+(?:add|install|publish|remove)|Remove-Item|Rename-Item|Set-Content|Start-Process|yarn\s+(?:add|install|publish|remove))\b|(?:^|[^<])>{1,2}\s*[^&]/i,Ke=/\b(?:installed|install(?:ed)?|on\s+(?:my|this)\s+(?:machine|pc|computer|system)|cli|command(?:\s+line)?|executable|on\s+(?:the\s+)?path|version|where(?:\.exe)?|which|available)\b/i,Ye=/\b(?:Get-Command|where(?:\.exe)?|command\s+-v|which|type\s+-a?|--version|-v\b|--help|-h\b)\b/i,Ze=/\b(?:yes|installed|you\s+(?:have|do\s+have)|found|available|on\s+(?:your|the)\s+path|callable|working|responds?|verified|confirmed)\b/i,Je=/\b(?:cannot\s+confirm|can't\s+confirm|not\s+confirm(?:ed)?|not\s+proven|not\s+verified|uncertain|failed|fails|could\s+not\s+verify|not\s+installed|does\s+not\s+appear|isn't\s+available|not\s+available)\b/i,et=/\b(?:exit\s+code|exit\s+status|status|return\s+code|returncode)\s*[:= -]?\s*(?:-[1-9]\d*|[1-9]\d*)\b|\b(?:not\s+recognized|not\s+found|could\s+not\s+find|cannot\s+find|no\s+such\s+file|failed)\b/i,tt=/\b(?:created|generated|produced|saved|wrote|written|exported|converted|built|rendered|flattened|creat|generat|produs|salvat|scris|exportat|convertit|aplatizat)\b/i,nt=/\b(?:not|didn['’]?t|couldn['’]?t|cannot|failed\s+to|incomplete|missing|nu|n-am|nereu[sș]it)\b/i,it=/\b(?:pages?|page\s+count|dpi|ocr|text\s+layer|extractible\s+text|renders?|opens?|dimensions?|metadata|pagini|strat\s+(?:ocr|de\s+text)|text\s+extractibil|se\s+deschide|rezolu[tț]ie)\b/i,rt=/(?:^|[\\/])\.xeno[\\/](?:sessions|audit)[\\/]/i,st=/\b(?:official|docs?|documentation|source|reference|install(?:ation)?|supported|features?|commands?)\b/i,at=/\b(?:search\s+online|look\s+online|web\s+search|web\s+fetch|fetch\s+(?:the\s+)?(?:official\s+)?page|official|docs?|documentation|source|reference|summarize|url)\b/i,ot=/\b(?:HTTP\s+404|404\s+Not\s+Found|not\s+found|does\s+not\s+exist|gone|HTTP\s+410|410\s+Gone)\b/i,ct=/\b(?:curl|wget|Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b[\s\S]*https?:\/\/|\bpython(?:3|\.exe)?\b[\s\S]*\b(?:urllib\.request|requests\.get|http\.client)\b[\s\S]*https?:\/\/|\bnode(?:\.exe)?\b[\s\S]*\b(?:fetch|https\.get|axios)\b[\s\S]*https?:\/\//i,lt=/https?:\/\/[^\s)>\]]+/i;function y(t){return t.trim().replace(/\s+/g," ")}function ut(t,e){if(t===e)return!0;if(Math.abs(t.length-e.length)>1)return!1;if(t.length===e.length){let o=[];for(let c=0;c<t.length;c+=1)if(t[c]!==e[c]&&o.push(c),o.length>2)return!1;return o.length===1?!0:o.length===2&&o[1]===o[0]+1&&t[o[0]]===e[o[1]]&&t[o[1]]===e[o[0]]}let[n,i]=t.length<e.length?[t,e]:[e,t],r=0,s=0,a=!1;for(;r<n.length&&s<i.length;){if(n[r]===i[s]){r+=1,s+=1;continue}if(a)return!1;a=!0,s+=1}return!0}function te(t,e){return(t.toLowerCase().match(/[a-z]+/g)??[]).some(i=>i.length>=5&&e.some(r=>ut(i,r)))}function dt(t){return ze.test(t)||te(t,Be)}function _(t){return He.test(t)||te(t,Xe)}function F(t){return t.replace(/[\s_-]+/g,"").toLowerCase()}function N(t){return Array.isArray(t)?t.map(N):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,N(n)])):typeof t=="string"?y(t.replace(/\\/g,"/")):t}function B(t,e){return`${F(t)}:${JSON.stringify(N(e))}`}function H(t){return Ve.has(F(t))}function mt(t,e){let n=F(t);return Ge.has(n)?!0:n==="bash"&&Qe.test(L(e)??"")}function w(t){let e=y(t);return!e||e.length>320?!1:We.test(e)&&!dt(e)}function ne(t,e){let n=Math.max(1,Math.floor(e));return w(t)?Math.min(n,4):n}function ht(t){if(typeof t!="string")return null;let e=y(t).toLowerCase();return e.length>0?e:null}function X(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.hash="",e.pathname=e.pathname.replace(/\/+$/,"")||"/",e.toString().toLowerCase()}catch{let e=y(t).toLowerCase().replace(/#.*$/,"").replace(/\/+$/,"");return e.length>0?e:null}}function L(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function M(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(M):t&&typeof t=="object"?Object.values(t).flatMap(M):[]}function Q(t){return t.replace(/\\/g,"/").toLowerCase()}function K(t){return y([t.output,t.error].filter(Boolean).join(" ")).slice(0,240)}function Y(t){return t.success===!1||et.test([t.output,t.error].filter(Boolean).join(`
15
- `))}function Z(t){return/^Bash$/i.test(t)}function J(t){return/^WebSearch$/i.test(t)}function ee(t){return/^WebFetch$/i.test(t)}var h=class{taskPrompt;maxWebSearches;maxWebFetches;maxTotalWebResearchCalls;maxLocalInspectionCalls;simpleInformationalPrompt;explicitResearchPrompt;searchQueries=new Map;fetchedUrls=new Map;localInspectionRecords=new Map;localEvidence=[];webFetchEvidence=[];artifactEvidence=[];verificationRecords=[];pendingAwaitOperations=new Map;transcriptReadRanges=new Map;webSearches=0;webFetches=0;localInspectionCalls=0;mutationEpoch=0;constructor(e,n={}){this.taskPrompt=e,this.explicitResearchPrompt=_(e),this.maxWebSearches=Math.max(1,n.maxWebSearches??(this.explicitResearchPrompt?5:3)),this.maxWebFetches=Math.max(1,n.maxWebFetches??(this.explicitResearchPrompt?12:4)),this.maxTotalWebResearchCalls=Math.max(1,n.maxTotalWebResearchCalls??(this.explicitResearchPrompt?16:6)),this.simpleInformationalPrompt=w(e),this.maxLocalInspectionCalls=Math.max(1,n.maxLocalInspectionCalls??(this.simpleInformationalPrompt?4:Number.MAX_SAFE_INTEGER))}maybeBlockToolCall(e){let n=this.findOverlappingTranscriptRead(e.toolName,e.input);if(n)return this.blockedResult(["[Xeno continuation-state guard]",`This transcript range overlaps an earlier read in the current turn: ${n}`,"Use the structured operation/continuation checkpoint and the existing excerpt. Do not scan the growing session Markdown to rediscover current state."]);if(mt(e.toolName,e.input)){if(this.simpleInformationalPrompt)return this.blockedResult(["[Xeno interactive turn guard]","This is a short informational question, not a request to change files, configuration, packages, processes, or repository state.",`Blocked unrequested mutation through ${e.toolName}.`,"Answer the question from the evidence already available. Ask before making changes if a change would materially help."]);this.mutationEpoch+=1}if(H(e.toolName)){let i=`${this.mutationEpoch}:${B(e.toolName,e.input)}`,r=this.localInspectionRecords.get(i);if(r?.successful||(r?.attempts??0)>=2)return this.blockedResult(["[Xeno interactive turn guard]",r?.successful===!0?`This exact ${e.toolName} inspection already succeeded during the current turn.`:`This exact ${e.toolName} inspection has already failed twice during the current turn.`,"Do not repeat or cosmetically repackage the same inspection. Use the existing result, choose one materially different check, or answer now with the uncertainty that remains."]);if(this.localInspectionCalls>=this.maxLocalInspectionCalls)return this.blockedResult(["[Xeno interactive turn guard]",`The local inspection budget for this turn is exhausted (${this.localInspectionCalls}/${this.maxLocalInspectionCalls}).`,"Stop exploring. Give the shortest accurate answer supported by the evidence already gathered, and state one limitation if needed."]);this.localInspectionCalls+=1,this.localInspectionRecords.set(i,{attempts:(r?.attempts??0)+1,successful:r?.successful??!1})}if(Z(e.toolName)&&this.isWebResearchQuestion()){let i=L(e.input);if(i&&ct.test(i))return this.blockedResult(["[Xeno interactive research guard]","Do not use Bash, Python, PowerShell, curl, wget, or ad hoc scripts to fetch public web pages during a web-research turn.","Use WebSearch to discover sources and WebFetch to read exact URLs. WebFetch handles timeouts, redirects, readable extraction, source metadata, and discovered documentation links.",this.fetchedSourceSummary()])}if(J(e.toolName)){let i=ht(e.input.query),r=i?this.searchQueries.get(i)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Stop searching. Answer now from the fetched official source(s), naming the URL(s) used and clearly stating any remaining uncertainty."]);if(i&&r>0)return this.blockedResult(["[Xeno interactive research guard]",`The WebSearch query has already been run this turn: ${i}`,"Do not repeat equivalent searches. Use the existing search result, fetch one clearly relevant source, run a local verification command if the question is about this machine, or answer with the uncertainty that remains."]);if(this.webSearches>=this.maxWebSearches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-search budget is exhausted (${this.webSearches}/${this.maxWebSearches} searches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Prefer official documentation already found, run a local check if relevant, or give a bounded answer that states what is and is not verified."]);this.webSearches+=1,i&&this.searchQueries.set(i,r+1)}if(ee(e.toolName)){let i=X(e.input.url),r=i?this.fetchedUrls.get(i)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Enough official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Do not guess more nearby documentation URLs. Answer from the fetched source(s), cite the URL(s), and mention if a specific detail was not present."]);if(i&&r>0)return this.blockedResult(["[Xeno interactive research guard]",`This URL has already been fetched this turn: ${i}`,"Do not fetch the same page again. Use the existing content, fetch a more precise official source, run a local verification command if relevant, or answer with the uncertainty that remains."]);if(this.webFetches>=this.maxWebFetches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-fetch budget is exhausted (${this.webFetches}/${this.maxWebFetches} fetches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Use the best source already gathered, run a local check if relevant, or answer with a clear limitation."]);this.webFetches+=1,i&&this.fetchedUrls.set(i,r+1)}return null}recordToolResult(e){let n=e.result.operation;n?.completionPolicy==="await"&&(n.terminal?this.pendingAwaitOperations.delete(n.operationId):this.pendingAwaitOperations.set(n.operationId,n.taskId??n.operationId));for(let s of e.result.evidence??n?.evidence??[]){let a=this.artifactEvidence.findIndex(c=>c.operationId===s.operationId&&c.path===s.path),o={iteration:e.iteration,path:s.path,status:s.status,operationId:s.operationId};a>=0?this.artifactEvidence[a]=o:this.artifactEvidence.push(o)}if(pt(e.toolName)&&this.verificationRecords.push({iteration:e.iteration,toolName:e.toolName,inputValues:M(e.input),success:e.result.success===!0&&!Y(e.result)}),H(e.toolName)){let s=`${this.mutationEpoch}:${B(e.toolName,e.input)}`,a=this.localInspectionRecords.get(s);a&&(a.successful=a.successful||e.result.success===!0)}if(J(e.toolName))return;if(ee(e.toolName)){let s=X(e.input.url);s&&this.webFetchEvidence.push({iteration:e.iteration,url:s,success:e.result.success===!0,summary:K(e.result)});return}if(!Z(e.toolName)||!this.isLocalSetupQuestion())return;let i=L(e.input);if(!i||!Ye.test(i))return;let r=Y(e.result);this.localEvidence.push({iteration:e.iteration,command:i,success:e.result.success===!0&&!r,summary:K(e.result)})}evaluateCompletion(e){if(this.pendingAwaitOperations.size>0)return{blocking:!0,message:["[Xeno pending-operation guard]",`Awaited operation(s) are still nonterminal: ${Array.from(this.pendingAwaitOperations.values()).join(", ")}.`,"Suspend this turn without a final answer. The runtime will resume the objective exactly once when the operation becomes terminal."].join(`
16
- `)};let n=this.evaluateArtifactClaims(e.finalText);if(n)return n;if(this.isWebResearchQuestion()){let a=this.evaluateWebResearchCompletion(e.finalText);if(a)return a}if(!this.isLocalSetupQuestion())return null;let i=[...this.localEvidence].reverse().find(a=>!a.success);if(!i||this.localEvidence.some(a=>a.iteration>=i.iteration&&a.success))return null;let s=e.finalText.trim();return!s||!Ze.test(s)||Je.test(s)?null:{blocking:!0,message:["[Xeno evidence correction]","Do not claim the local tool/app/CLI is installed or working yet.",`The latest local verification command failed: ${i.command}`,i.summary?`Failure evidence: ${i.summary}`:null,"Next step: either run one robust local verification command that directly proves the claim, or answer that the launcher/path may exist but the CLI status is not confirmed.","Do not use web documentation as proof of what is installed on this machine."].filter(Boolean).join(`
17
- `)}}evaluateWebResearchCompletion(e){let n=e.trim();if(!n)return null;let i=this.successfulWebFetches(),r=i.map(o=>o.url),s=lt.test(n),a=r.some(o=>n.toLowerCase().includes(o.toLowerCase()));return i.length>0&&(!s||!a)?{blocking:!0,message:["[Xeno source-citation correction]","The answer uses web/documentation evidence but does not clearly cite the fetched source URL(s).",this.fetchedSourceSummary(),"Rewrite the final answer with a short Sources section using Markdown links like `Sources: [Title](url)`, then the requested sections. Do not run more tools unless a required detail is still missing."].join(`
18
- `)}:null}isLocalSetupQuestion(){return Ke.test(this.taskPrompt)}totalWebResearchCalls(){return this.webSearches+this.webFetches}isOfficialResearchQuestion(){return st.test(this.taskPrompt)}isWebResearchQuestion(){return this.explicitResearchPrompt||at.test(this.taskPrompt)}successfulWebFetches(){return this.webFetchEvidence.filter(e=>e.success)}failedSpeculativeWebFetches(){return this.webFetchEvidence.filter(e=>!e.success&&ot.test(e.summary))}shouldStopOfficialResearch(){if(this.explicitResearchPrompt||!this.isOfficialResearchQuestion())return!1;let e=this.successfulWebFetches();return e.length>=this.minimumOfficialEvidenceFetches()?!0:e.length>=1&&this.failedSpeculativeWebFetches().length>=1}minimumOfficialEvidenceFetches(){let e=this.taskPrompt.toLowerCase(),n=/\binstall(?:ation)?|update|upgrade|version|verify\b/.test(e),i=/\binteractive|usage|using|agent\s+commands?|session|resume|flags?|shortcuts?\b/.test(e),r=/\bslash|reference|commands?\s+list|all\s+commands?\b/.test(e);return n&&i||r?Math.min(4,this.maxWebFetches):2}fetchedSourceSummary(){let e=this.successfulWebFetches().map(n=>n.url);return e.length===0?"No successful web fetch is recorded yet.":`Fetched source(s): ${e.join(", ")}`}blockedResult(e){return{success:!1,output:e.join(`
19
- `),error:"Interactive turn guard blocked redundant, excessive, or unrequested tool use"}}evaluateArtifactClaims(e){let n=e.trim();if(!tt.test(n)||nt.test(n))return null;let i=this.artifactEvidence.filter(a=>a.status==="verified");if(i.length===0){let a=this.artifactEvidence.filter(o=>o.status==="failed");return{blocking:!0,message:["[Xeno artifact-evidence guard]","Do not claim that an artifact was created, saved, converted, or written without current verified artifact evidence.",a.length>0?`The latest postcondition evidence failed for: ${a.map(o=>o.path??o.operationId).join(", ")}.`:"No successful artifact postcondition is recorded in this turn.","Inspect the target, verify it is the expected file, and only then give the completion answer."].join(`
20
- `)}}if(!it.test(n))return null;let r=Math.max(...i.map(a=>a.iteration));return this.verificationRecords.some(a=>a.success&&a.iteration>=r&&i.some(o=>!o.path||a.inputValues.some(c=>Q(c).includes(Q(o.path)))))?null:{blocking:!0,message:["[Xeno semantic-evidence guard]","File existence does not prove semantic claims such as page count, OCR absence, dimensions, metadata, or successful rendering.","Run one bounded verifier against the generated artifact and then report only the properties that verifier established."].join(`
21
- `)}}findOverlappingTranscriptRead(e,n){if(!/^Read$/i.test(e))return null;let i=typeof n.file_path=="string"?n.file_path:"";if(!rt.test(i))return null;let r=Math.max(0,Number.isFinite(n.offset)?Math.floor(Number(n.offset)):0),s=Math.max(1,Number.isFinite(n.limit)?Math.floor(Number(n.limit)):2e3),a=r+s,o=i.toLowerCase(),c=this.transcriptReadRanges.get(o)??[],d=c.find(m=>r<m.end&&a>m.start);return d?`${i}:${r}-${a} overlaps ${d.start}-${d.end}`:(c.push({start:r,end:a}),this.transcriptReadRanges.set(o,c),null)}};function pt(t){return/^(?:Bash|Read|ReadImage|ElfAnalyze|NotebookRead)$/i.test(t)}var A=class{active=null;activePrompt=null;promptSection={name:"interactive-chat-answer-budget",order:20,provide:()=>this.activePrompt?_(this.activePrompt)?[`
14
+ `);return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:s?"weak_validation_only":"missing_authoritative_validation",message:a,blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:i})}return this.setDecision({action:"complete",finalStateVerified:!1,reason:"no_governance_blocker",message:"No execution-governance blocker found.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:i})}getSummary(){return{contract:{...this.contract,requiredOutputPaths:[...this.contract.requiredOutputPaths]},validation:{latestSignal:this.cloneSignal(this.getLatestSignal()),latestAuthoritativeSignal:this.cloneSignal(this.getLatestAuthoritativeSignal()),latestUnresolvedFailure:this.cloneSignal(this.getLatestUnresolvedFailure()),signals:this.signals.slice(-20).map(e=>this.cloneSignal(e))},progress:{toolCalls:this.toolCalls,validationRuns:this.signals.length,workspaceRevision:this.workspaceRevision,repeatedFailureSignature:this.getRepeatedFailure()?.signature??null,repeatedFailureCount:this.getRepeatedFailure()?.count??0,iterationsSinceLastValidation:this.lastValidationIteration===null?null:Math.max(0,(this.lastEvaluatedIteration??this.lastValidationIteration)-this.lastValidationIteration)},completionDecision:this.lastCompletionDecision?{...this.lastCompletionDecision}:null}}getLatestSignal(){return this.signals.at(-1)??null}getLatestAuthoritativeSignal(){return[...this.signals].reverse().find(e=>I(e))??null}getLatestUnresolvedFailure(){let e=[...this.signals].reverse().find(i=>I(i)&&i.outcome==="fail"&&!i.stale);return e?this.signals.some(i=>i.iteration>e.iteration&&!i.stale&&i.outcome==="pass"&&T[i.authority]>=T[e.authority])?null:e:null}getRepeatedFailure(){let e=null;for(let n of this.clusters.values())n.count<2||(!e||n.count>e.count)&&(e=n);return e}setDecision(e){return this.lastCompletionDecision=e,e}cloneSignal(e){return e?{...e,clusters:e.clusters.map(n=>({...n}))}:null}};var Ve=new Set(["bash","elfanalyze","gitbranch","gitdiff","gitlog","gitstatus","glob","grep","ls","read","readimage"]),Ge=new Set(["applypatch","edit","notebookedit","write"]),We=/\?|\b(?:can|could|did|do|does|has|have|is|should|was|were|will|would)\b|\b(?:correct|right)\s*[.!?]*$/i,ze=/\b(?:audit|build|change|check|clone|configure|copy|create|delete|deploy|edit|find|fix|implement|inspect|install|locate|make|migrate|move|publish|refactor|release|remove|rename|research|run|save|scaffold|search|set|start|stop|test|update|verify|write)\b/i,Be=/^(?:ok(?:ay)?[\s,!.:-]*)?(?:then\s+)?(?:(?:let(?:'|’)s|lets)\s+)?(?:continue|do\s+it|fix\s+it|get\s+started|go\s+ahead|implement\s+it|make\s+it|proceed|procede|ship\s+it|start)(?:\s+(?:now|please))?[\s.!?]*$/i,He=["audit","build","change","check","clone","configure","create","delete","deploy","implement","inspect","install","locate","migrate","publish","refactor","release","remove","rename","research","scaffold","search","start","update","verify","write"],Xe=/\b(?:browse|investigate|research|search)\b|\b(?:check|find|look)\s+(?:it\s+)?(?:up|online|on\s+the\s+web)\b/i,Qe=["browse","investigate","research","search"],Ke=/\b(?:Add-Content|Clear-Content|Copy-Item|git\s+(?:add|commit|merge|mv|push|rebase|reset|restore|rm|switch)|Move-Item|New-Item|npm\s+(?:install|publish|uninstall)|pnpm\s+(?:add|install|publish|remove)|Remove-Item|Rename-Item|Set-Content|Start-Process|yarn\s+(?:add|install|publish|remove))\b|(?:^|[^<])>{1,2}\s*[^&]/i,Ye=/\b(?:installed|install(?:ed)?|on\s+(?:my|this)\s+(?:machine|pc|computer|system)|cli|command(?:\s+line)?|executable|on\s+(?:the\s+)?path|version|where(?:\.exe)?|which|available)\b/i,Ze=/\b(?:Get-Command|where(?:\.exe)?|command\s+-v|which|type\s+-a?|--version|-v\b|--help|-h\b)\b/i,Je=/\b(?:yes|installed|you\s+(?:have|do\s+have)|found|available|on\s+(?:your|the)\s+path|callable|working|responds?|verified|confirmed)\b/i,et=/\b(?:cannot\s+confirm|can't\s+confirm|not\s+confirm(?:ed)?|not\s+proven|not\s+verified|uncertain|failed|fails|could\s+not\s+verify|not\s+installed|does\s+not\s+appear|isn't\s+available|not\s+available)\b/i,tt=/\b(?:exit\s+code|exit\s+status|status|return\s+code|returncode)\s*[:= -]?\s*(?:-[1-9]\d*|[1-9]\d*)\b|\b(?:not\s+recognized|not\s+found|could\s+not\s+find|cannot\s+find|no\s+such\s+file|failed)\b/i,nt=/\b(?:created|generated|produced|saved|wrote|written|exported|converted|built|rendered|flattened|creat|generat|produs|salvat|scris|exportat|convertit|aplatizat)\b/i,it=/\b(?:not|didn['’]?t|couldn['’]?t|cannot|failed\s+to|incomplete|missing|nu|n-am|nereu[sÈ™]it)\b/i,rt=/\b(?:pages?|page\s+count|dpi|ocr|text\s+layer|extractible\s+text|renders?|opens?|dimensions?|metadata|pagini|strat\s+(?:ocr|de\s+text)|text\s+extractibil|se\s+deschide|rezolu[tÈ›]ie)\b/i,st=/(?:^|[\\/])\.xeno[\\/](?:sessions|audit)[\\/]/i,at=/\b(?:official|docs?|documentation|source|reference|install(?:ation)?|supported|features?|commands?)\b/i,ot=/\b(?:search\s+online|look\s+online|web\s+search|web\s+fetch|fetch\s+(?:the\s+)?(?:official\s+)?page|official|docs?|documentation|source|reference|summarize|url)\b/i,ct=/\b(?:HTTP\s+404|404\s+Not\s+Found|not\s+found|does\s+not\s+exist|gone|HTTP\s+410|410\s+Gone)\b/i,lt=/\b(?:curl|wget|Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b[\s\S]*https?:\/\/|\bpython(?:3|\.exe)?\b[\s\S]*\b(?:urllib\.request|requests\.get|http\.client)\b[\s\S]*https?:\/\/|\bnode(?:\.exe)?\b[\s\S]*\b(?:fetch|https\.get|axios)\b[\s\S]*https?:\/\//i,ut=/https?:\/\/[^\s)>\]]+/i;function f(t){return t.trim().replace(/\s+/g," ")}function dt(t,e){if(t===e)return!0;if(Math.abs(t.length-e.length)>1)return!1;if(t.length===e.length){let o=[];for(let c=0;c<t.length;c+=1)if(t[c]!==e[c]&&o.push(c),o.length>2)return!1;return o.length===1?!0:o.length===2&&o[1]===o[0]+1&&t[o[0]]===e[o[1]]&&t[o[1]]===e[o[0]]}let[n,i]=t.length<e.length?[t,e]:[e,t],r=0,s=0,a=!1;for(;r<n.length&&s<i.length;){if(n[r]===i[s]){r+=1,s+=1;continue}if(a)return!1;a=!0,s+=1}return!0}function te(t,e){return(t.toLowerCase().match(/[a-z]+/g)??[]).some(i=>i.length>=5&&e.some(r=>dt(i,r)))}function mt(t){return Be.test(f(t))||ze.test(t)||te(t,He)}function _(t){return Xe.test(t)||te(t,Qe)}function F(t){return t.replace(/[\s_-]+/g,"").toLowerCase()}function N(t){return Array.isArray(t)?t.map(N):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,N(n)])):typeof t=="string"?f(t.replace(/\\/g,"/")):t}function B(t,e){return`${F(t)}:${JSON.stringify(N(e))}`}function H(t){return Ve.has(F(t))}function ht(t,e){let n=F(t);return Ge.has(n)?!0:n==="bash"&&Ke.test(L(e)??"")}function w(t){let e=f(t);return!e||e.length>320?!1:We.test(e)&&!mt(e)}function ne(t,e){let n=Math.max(1,Math.floor(e));return w(t)?Math.min(n,15):n}function pt(t){if(typeof t!="string")return null;let e=f(t).toLowerCase();return e.length>0?e:null}function X(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.hash="",e.pathname=e.pathname.replace(/\/+$/,"")||"/",e.toString().toLowerCase()}catch{let e=f(t).toLowerCase().replace(/#.*$/,"").replace(/\/+$/,"");return e.length>0?e:null}}function L(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function M(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(M):t&&typeof t=="object"?Object.values(t).flatMap(M):[]}function Q(t){return t.replace(/\\/g,"/").toLowerCase()}function K(t){return f([t.output,t.error].filter(Boolean).join(" ")).slice(0,240)}function Y(t){return t.success===!1||tt.test([t.output,t.error].filter(Boolean).join(`
15
+ `))}function Z(t){return/^Bash$/i.test(t)}function J(t){return/^WebSearch$/i.test(t)}function ee(t){return/^WebFetch$/i.test(t)}var h=class{taskPrompt;maxWebSearches;maxWebFetches;maxTotalWebResearchCalls;maxLocalInspectionCalls;simpleInformationalPrompt;explicitResearchPrompt;searchQueries=new Map;fetchedUrls=new Map;localInspectionRecords=new Map;localEvidence=[];webFetchEvidence=[];artifactEvidence=[];verificationRecords=[];pendingAwaitOperations=new Map;transcriptReadRanges=new Map;webSearches=0;webFetches=0;localInspectionCalls=0;mutationEpoch=0;constructor(e,n={}){this.taskPrompt=e,this.explicitResearchPrompt=_(e),this.maxWebSearches=Math.max(1,n.maxWebSearches??(this.explicitResearchPrompt?5:3)),this.maxWebFetches=Math.max(1,n.maxWebFetches??(this.explicitResearchPrompt?12:4)),this.maxTotalWebResearchCalls=Math.max(1,n.maxTotalWebResearchCalls??(this.explicitResearchPrompt?16:6)),this.simpleInformationalPrompt=w(e),this.maxLocalInspectionCalls=Math.max(1,n.maxLocalInspectionCalls??(this.simpleInformationalPrompt?12:Number.MAX_SAFE_INTEGER))}maybeBlockToolCall(e){let n=this.findOverlappingTranscriptRead(e.toolName,e.input);if(n)return this.blockedResult(["[Xeno continuation-state guard]",`This transcript range overlaps an earlier read in the current turn: ${n}`,"Use the structured operation/continuation checkpoint and the existing excerpt. Do not scan the growing session Markdown to rediscover current state."]);if(ht(e.toolName,e.input)){if(this.simpleInformationalPrompt)return this.blockedResult(["[Xeno interactive turn guard]","This is a short informational question, not a request to change files, configuration, packages, processes, or repository state.",`Blocked unrequested mutation through ${e.toolName}.`,"Answer the question from the evidence already available. Ask before making changes if a change would materially help."]);this.mutationEpoch+=1}if(H(e.toolName)){let i=`${this.mutationEpoch}:${B(e.toolName,e.input)}`,r=this.localInspectionRecords.get(i);if(r?.successful||(r?.attempts??0)>=2)return this.blockedResult(["[Xeno interactive turn guard]",r?.successful===!0?`This exact ${e.toolName} inspection already succeeded during the current turn.`:`This exact ${e.toolName} inspection has already failed twice during the current turn.`,"Do not repeat or cosmetically repackage the same inspection. Use the existing result, choose one materially different check, or answer now with the uncertainty that remains."]);if(this.localInspectionCalls>=this.maxLocalInspectionCalls)return this.blockedResult(["[Xeno interactive turn guard]",`The local inspection budget for this turn is exhausted (${this.localInspectionCalls}/${this.maxLocalInspectionCalls}).`,"Stop exploring. Give the shortest accurate answer supported by the evidence already gathered, and state one limitation if needed."]);this.localInspectionCalls+=1,this.localInspectionRecords.set(i,{attempts:(r?.attempts??0)+1,successful:r?.successful??!1})}if(Z(e.toolName)&&this.isWebResearchQuestion()){let i=L(e.input);if(i&&lt.test(i))return this.blockedResult(["[Xeno interactive research guard]","Do not use Bash, Python, PowerShell, curl, wget, or ad hoc scripts to fetch public web pages during a web-research turn.","Use WebSearch to discover sources and WebFetch to read exact URLs. WebFetch handles timeouts, redirects, readable extraction, source metadata, and discovered documentation links.",this.fetchedSourceSummary()])}if(J(e.toolName)){let i=pt(e.input.query),r=i?this.searchQueries.get(i)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Stop searching. Answer now from the fetched official source(s), naming the URL(s) used and clearly stating any remaining uncertainty."]);if(i&&r>0)return this.blockedResult(["[Xeno interactive research guard]",`The WebSearch query has already been run this turn: ${i}`,"Do not repeat equivalent searches. Use the existing search result, fetch one clearly relevant source, run a local verification command if the question is about this machine, or answer with the uncertainty that remains."]);if(this.webSearches>=this.maxWebSearches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-search budget is exhausted (${this.webSearches}/${this.maxWebSearches} searches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Prefer official documentation already found, run a local check if relevant, or give a bounded answer that states what is and is not verified."]);this.webSearches+=1,i&&this.searchQueries.set(i,r+1)}if(ee(e.toolName)){let i=X(e.input.url),r=i?this.fetchedUrls.get(i)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Enough official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Do not guess more nearby documentation URLs. Answer from the fetched source(s), cite the URL(s), and mention if a specific detail was not present."]);if(i&&r>0)return this.blockedResult(["[Xeno interactive research guard]",`This URL has already been fetched this turn: ${i}`,"Do not fetch the same page again. Use the existing content, fetch a more precise official source, run a local verification command if relevant, or answer with the uncertainty that remains."]);if(this.webFetches>=this.maxWebFetches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-fetch budget is exhausted (${this.webFetches}/${this.maxWebFetches} fetches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Use the best source already gathered, run a local check if relevant, or answer with a clear limitation."]);this.webFetches+=1,i&&this.fetchedUrls.set(i,r+1)}return null}recordToolResult(e){let n=e.result.operation;n?.completionPolicy==="await"&&(n.terminal?this.pendingAwaitOperations.delete(n.operationId):this.pendingAwaitOperations.set(n.operationId,n.taskId??n.operationId));for(let s of e.result.evidence??n?.evidence??[]){let a=this.artifactEvidence.findIndex(c=>c.operationId===s.operationId&&c.path===s.path),o={iteration:e.iteration,path:s.path,status:s.status,operationId:s.operationId};a>=0?this.artifactEvidence[a]=o:this.artifactEvidence.push(o)}if(ft(e.toolName)&&this.verificationRecords.push({iteration:e.iteration,toolName:e.toolName,inputValues:M(e.input),success:e.result.success===!0&&!Y(e.result)}),H(e.toolName)){let s=`${this.mutationEpoch}:${B(e.toolName,e.input)}`,a=this.localInspectionRecords.get(s);a&&(a.successful=a.successful||e.result.success===!0)}if(J(e.toolName))return;if(ee(e.toolName)){let s=X(e.input.url);s&&this.webFetchEvidence.push({iteration:e.iteration,url:s,success:e.result.success===!0,summary:K(e.result)});return}if(!Z(e.toolName)||!this.isLocalSetupQuestion())return;let i=L(e.input);if(!i||!Ze.test(i))return;let r=Y(e.result);this.localEvidence.push({iteration:e.iteration,command:i,success:e.result.success===!0&&!r,summary:K(e.result)})}evaluateCompletion(e){if(this.pendingAwaitOperations.size>0)return{blocking:!0,message:["[Xeno pending-operation guard]",`Awaited operation(s) are still nonterminal: ${Array.from(this.pendingAwaitOperations.values()).join(", ")}.`,"Suspend this turn without a final answer. The runtime will resume the objective exactly once when the operation becomes terminal."].join(`
16
+ `)};let n=this.evaluateArtifactClaims(e.finalText);if(n)return n;if(this.isWebResearchQuestion()){let a=this.evaluateWebResearchCompletion(e.finalText);if(a)return a}if(!this.isLocalSetupQuestion())return null;let i=[...this.localEvidence].reverse().find(a=>!a.success);if(!i||this.localEvidence.some(a=>a.iteration>=i.iteration&&a.success))return null;let s=e.finalText.trim();return!s||!Je.test(s)||et.test(s)?null:{blocking:!0,message:["[Xeno evidence correction]","Do not claim the local tool/app/CLI is installed or working yet.",`The latest local verification command failed: ${i.command}`,i.summary?`Failure evidence: ${i.summary}`:null,"Next step: either run one robust local verification command that directly proves the claim, or answer that the launcher/path may exist but the CLI status is not confirmed.","Do not use web documentation as proof of what is installed on this machine."].filter(Boolean).join(`
17
+ `)}}evaluateWebResearchCompletion(e){let n=e.trim();if(!n)return null;let i=this.successfulWebFetches(),r=i.map(o=>o.url),s=ut.test(n),a=r.some(o=>n.toLowerCase().includes(o.toLowerCase()));return i.length>0&&(!s||!a)?{blocking:!0,message:["[Xeno source-citation correction]","The answer uses web/documentation evidence but does not clearly cite the fetched source URL(s).",this.fetchedSourceSummary(),"Rewrite the final answer with a short Sources section using Markdown links like `Sources: [Title](url)`, then the requested sections. Do not run more tools unless a required detail is still missing."].join(`
18
+ `)}:null}isLocalSetupQuestion(){return Ye.test(this.taskPrompt)}totalWebResearchCalls(){return this.webSearches+this.webFetches}isOfficialResearchQuestion(){return at.test(this.taskPrompt)}isWebResearchQuestion(){return this.explicitResearchPrompt||ot.test(this.taskPrompt)}successfulWebFetches(){return this.webFetchEvidence.filter(e=>e.success)}failedSpeculativeWebFetches(){return this.webFetchEvidence.filter(e=>!e.success&&ct.test(e.summary))}shouldStopOfficialResearch(){if(this.explicitResearchPrompt||!this.isOfficialResearchQuestion())return!1;let e=this.successfulWebFetches();return e.length>=this.minimumOfficialEvidenceFetches()?!0:e.length>=1&&this.failedSpeculativeWebFetches().length>=1}minimumOfficialEvidenceFetches(){let e=this.taskPrompt.toLowerCase(),n=/\binstall(?:ation)?|update|upgrade|version|verify\b/.test(e),i=/\binteractive|usage|using|agent\s+commands?|session|resume|flags?|shortcuts?\b/.test(e),r=/\bslash|reference|commands?\s+list|all\s+commands?\b/.test(e);return n&&i||r?Math.min(4,this.maxWebFetches):2}fetchedSourceSummary(){let e=this.successfulWebFetches().map(n=>n.url);return e.length===0?"No successful web fetch is recorded yet.":`Fetched source(s): ${e.join(", ")}`}blockedResult(e){return{success:!1,output:e.join(`
19
+ `),error:"Interactive turn guard blocked redundant, excessive, or unrequested tool use"}}evaluateArtifactClaims(e){let n=e.trim();if(!nt.test(n)||it.test(n))return null;let i=this.artifactEvidence.filter(a=>a.status==="verified");if(i.length===0){let a=this.artifactEvidence.filter(o=>o.status==="failed");return{blocking:!0,message:["[Xeno artifact-evidence guard]","Do not claim that an artifact was created, saved, converted, or written without current verified artifact evidence.",a.length>0?`The latest postcondition evidence failed for: ${a.map(o=>o.path??o.operationId).join(", ")}.`:"No successful artifact postcondition is recorded in this turn.","Inspect the target, verify it is the expected file, and only then give the completion answer."].join(`
20
+ `)}}if(!rt.test(n))return null;let r=Math.max(...i.map(a=>a.iteration));return this.verificationRecords.some(a=>a.success&&a.iteration>=r&&i.some(o=>!o.path||a.inputValues.some(c=>Q(c).includes(Q(o.path)))))?null:{blocking:!0,message:["[Xeno semantic-evidence guard]","File existence does not prove semantic claims such as page count, OCR absence, dimensions, metadata, or successful rendering.","Run one bounded verifier against the generated artifact and then report only the properties that verifier established."].join(`
21
+ `)}}findOverlappingTranscriptRead(e,n){if(!/^Read$/i.test(e))return null;let i=typeof n.file_path=="string"?n.file_path:"";if(!st.test(i))return null;let r=Math.max(0,Number.isFinite(n.offset)?Math.floor(Number(n.offset)):0),s=Math.max(1,Number.isFinite(n.limit)?Math.floor(Number(n.limit)):2e3),a=r+s,o=i.toLowerCase(),c=this.transcriptReadRanges.get(o)??[],d=c.find(m=>r<m.end&&a>m.start);return d?`${i}:${r}-${a} overlaps ${d.start}-${d.end}`:(c.push({start:r,end:a}),this.transcriptReadRanges.set(o,c),null)}};function ft(t){return/^(?:Bash|Read|ReadImage|ElfAnalyze|NotebookRead)$/i.test(t)}var A=class{active=null;activePrompt=null;promptSection={name:"interactive-chat-answer-budget",order:20,provide:()=>this.activePrompt?_(this.activePrompt)?[`
22
22
 
23
23
  <interactive_research_budget>`,"The user explicitly requested research. Gather enough primary evidence to answer the requested scope; do not treat this as a four-fetch quick lookup.","Start broad once, then fetch distinct targeted sources. For a public repository, prefer repository metadata, one recursive tree, and only the files needed for the answer.","Do not fetch duplicate representations of the same content or guess files already disproved by the repository tree.","Synthesize the answer once the evidence is sufficient. Tool limits preserve a separate tool-free final-answer turn.","</interactive_research_budget>"].join(`
24
24
  `):w(this.activePrompt)?[`
25
25
 
26
26
  <interactive_answer_budget>`,"This turn is a short informational question, not an implementation request.","Answer directly when the current context already contains the answer.","If local verification is genuinely needed, use one broad lookup and at most one targeted read, then answer.","Do not modify files, configuration, packages, processes, or repository state. Do not convert the question into an installation or workflow task.","</interactive_answer_budget>"].join(`
27
- `):null:null};toolMiddleware=async(e,n)=>{let i=this.active;if(!i)return n();let r=i.maybeBlockToolCall({toolName:e.toolName,input:e.input,iteration:e.iteration});if(r)return r;let s=await n();return i.recordToolResult({toolName:e.toolName,input:e.input,result:s,iteration:e.iteration}),s};completionGuard={name:"interactive-chat-turn-governance",order:10,evaluate:e=>{let n=this.active?.evaluateCompletion({finalText:e.finalText,iteration:e.iteration,stopReason:e.stopReason});return n?{allow:!1,guidance:n.message}:{allow:!0}}};beginTurn(e){this.activePrompt=e,this.active=new h(e)}endTurn(){this.active=null,this.activePrompt=null}};var ie=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,ft=new RegExp(String.raw`${ie}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i"),gt=new RegExp(`${ie}(?:timeout\\s+\\S+\\s+)?(?:sudo\\s+)?(?:env\\s+(?:\\S+=\\S+\\s+)*)?(?:make(?:\\s|$)|cmake\\s+--build\\b|ninja\\b|cargo\\s+build\\b|go\\s+build\\b)`,"i"),bt=/\b(?:make|ninja|cmake\s+--build)\b[\s\S]*?(?:^|\s)-j\s*(?:\$\(?nproc\)?|[5-9]\b|\d{2,}\b)/i,vt=900,yt=/\b(?:cifar(?:-?10)?|mnist|imagenet|yelp|fasttext|wikitext|c4|common\s*crawl|glue|squad|train(?:ing)?[_ -]?data|test[_ -]?data|lmdb)\b/i,wt=/\b(?:synthetic|fake|dummy|placeholder|random(?:\.|_|ness|\b)|randint|randn|np\.random|os\.urandom|bytearray|generate(?:d|s)?\s+(?:data|dataset|samples?|images?|records?)|make_img|SYNTHETIC[_ -]?DATA)\b/i,kt=/\b(?:>\s*|tee\s+|open\s*\(|write(?:_text|_bytes)?\s*\(|to_csv\s*\(|np\.save|torch\.save|pickle\.dump|lmdb|create[_ -]?(?:dataset|data)|mkdir(?:\s+-p)?|rm\s+-rf)\b/i,Rt=/\btimeout\s+(\d+)([smhd]?)/i;function xt(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function Et(t){return/^Bash$/i.test(t)}function Tt(t){let e=t.match(Rt);if(!e)return null;let n=Number(e[1]);if(!Number.isFinite(n))return null;let i=e[2]?.toLowerCase();return i==="h"?n*3600:i==="m"?n*60:i==="d"?n*86400:n}function At(t){if(!gt.test(t))return null;if(bt.test(t))return["[xeno guidance]","This finite source build uses an unbounded or oversized parallelism setting such as -j$(nproc).","In benchmark containers this often slows the build down or causes timeout/memory failure instead of making progress.","Rerun the build with conservative parallelism such as -j2 or -j4, keep logs visible, and continue from the existing partial build artifacts."].join(`
28
- `);let e=Tt(t);return e!==null&&e<vt?["[xeno guidance]",`This required finite build is wrapped in a shell timeout of ${e}s.`,"Do not use a too-short shell timeout around source builds where partial output is not the final artifact.","Use the Bash tool timeout instead, run with conservative parallelism such as -j2 or -j4, and preserve final budget for verifier/training only after the build succeeds."].join(`
29
- `):null}function _t(t){return!yt.test(t)||!wt.test(t)||!kt.test(t)?null:["[xeno guidance]","This command appears to synthesize or overwrite a named/provided training dataset.","Do not replace CIFAR, MNIST, Yelp, C4, LMDB, or other task datasets with random, synthetic, dummy, or placeholder data to recover from a crash.","Fix the real data path instead: repair the download/extraction/conversion/dependency issue, remove corrupted partial outputs, and rerun only the failed stage with bounded resources."].join(`
30
- `)}function St(t){return ft.test(t)}function Ct(){return{success:!1,output:["[Xeno benchmark Bash guard]",'Blocked a shell-eval-download command (eval "$(curl \xE2\u20AC\xA6)" / eval "$(wget \xE2\u20AC\xA6)").',"Piping remote content straight into a shell evaluator is unsafe and non-reproducible.","Download the artifact to a file with WebFetch or curl/wget, inspect it, then run the verified script explicitly."].join(`
31
- `),error:"Benchmark Bash guard blocked a shell-eval-download command"}}function S(t={}){let e=t.benchmarkMode===!0;return async(n,i)=>{if(!Et(n.toolName))return i();let r=xt(n.input);if(!r)return i();if(St(r))return Ct();if(e){let s=At(r);s&&n.addGuidance(s);let a=_t(r);a&&n.addGuidance(a)}return i()}}var re=`
27
+ `):null:null};toolMiddleware=async(e,n)=>{let i=this.active;if(!i)return n();let r=i.maybeBlockToolCall({toolName:e.toolName,input:e.input,iteration:e.iteration});if(r)return r;let s=await n();return i.recordToolResult({toolName:e.toolName,input:e.input,result:s,iteration:e.iteration}),s};completionGuard={name:"interactive-chat-turn-governance",order:10,evaluate:e=>{let n=this.active?.evaluateCompletion({finalText:e.finalText,iteration:e.iteration,stopReason:e.stopReason});return n?{allow:!1,guidance:n.message}:{allow:!0}}};beginTurn(e){this.activePrompt=e,this.active=new h(e)}endTurn(){this.active=null,this.activePrompt=null}};var ie=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,gt=new RegExp(String.raw`${ie}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i"),bt=new RegExp(`${ie}(?:timeout\\s+\\S+\\s+)?(?:sudo\\s+)?(?:env\\s+(?:\\S+=\\S+\\s+)*)?(?:make(?:\\s|$)|cmake\\s+--build\\b|ninja\\b|cargo\\s+build\\b|go\\s+build\\b)`,"i"),vt=/\b(?:make|ninja|cmake\s+--build)\b[\s\S]*?(?:^|\s)-j\s*(?:\$\(?nproc\)?|[5-9]\b|\d{2,}\b)/i,yt=900,wt=/\b(?:cifar(?:-?10)?|mnist|imagenet|yelp|fasttext|wikitext|c4|common\s*crawl|glue|squad|train(?:ing)?[_ -]?data|test[_ -]?data|lmdb)\b/i,kt=/\b(?:synthetic|fake|dummy|placeholder|random(?:\.|_|ness|\b)|randint|randn|np\.random|os\.urandom|bytearray|generate(?:d|s)?\s+(?:data|dataset|samples?|images?|records?)|make_img|SYNTHETIC[_ -]?DATA)\b/i,Rt=/\b(?:>\s*|tee\s+|open\s*\(|write(?:_text|_bytes)?\s*\(|to_csv\s*\(|np\.save|torch\.save|pickle\.dump|lmdb|create[_ -]?(?:dataset|data)|mkdir(?:\s+-p)?|rm\s+-rf)\b/i,xt=/\btimeout\s+(\d+)([smhd]?)/i;function Et(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function Tt(t){return/^Bash$/i.test(t)}function At(t){let e=t.match(xt);if(!e)return null;let n=Number(e[1]);if(!Number.isFinite(n))return null;let i=e[2]?.toLowerCase();return i==="h"?n*3600:i==="m"?n*60:i==="d"?n*86400:n}function _t(t){if(!bt.test(t))return null;if(vt.test(t))return["[xeno guidance]","This finite source build uses an unbounded or oversized parallelism setting such as -j$(nproc).","In benchmark containers this often slows the build down or causes timeout/memory failure instead of making progress.","Rerun the build with conservative parallelism such as -j2 or -j4, keep logs visible, and continue from the existing partial build artifacts."].join(`
28
+ `);let e=At(t);return e!==null&&e<yt?["[xeno guidance]",`This required finite build is wrapped in a shell timeout of ${e}s.`,"Do not use a too-short shell timeout around source builds where partial output is not the final artifact.","Use the Bash tool timeout instead, run with conservative parallelism such as -j2 or -j4, and preserve final budget for verifier/training only after the build succeeds."].join(`
29
+ `):null}function St(t){return!wt.test(t)||!kt.test(t)||!Rt.test(t)?null:["[xeno guidance]","This command appears to synthesize or overwrite a named/provided training dataset.","Do not replace CIFAR, MNIST, Yelp, C4, LMDB, or other task datasets with random, synthetic, dummy, or placeholder data to recover from a crash.","Fix the real data path instead: repair the download/extraction/conversion/dependency issue, remove corrupted partial outputs, and rerun only the failed stage with bounded resources."].join(`
30
+ `)}function Ct(t){return gt.test(t)}function It(){return{success:!1,output:["[Xeno benchmark Bash guard]",'Blocked a shell-eval-download command (eval "$(curl \xE2\u20AC\xA6)" / eval "$(wget \xE2\u20AC\xA6)").',"Piping remote content straight into a shell evaluator is unsafe and non-reproducible.","Download the artifact to a file with WebFetch or curl/wget, inspect it, then run the verified script explicitly."].join(`
31
+ `),error:"Benchmark Bash guard blocked a shell-eval-download command"}}function S(t={}){let e=t.benchmarkMode===!0;return async(n,i)=>{if(!Tt(n.toolName))return i();let r=Et(n.input);if(!r)return i();if(Ct(r))return It();if(e){let s=_t(r);s&&n.addGuidance(s);let a=St(r);a&&n.addGuidance(a)}return i()}}var re=`
32
32
 
33
- `;function It(t){let e=t.taskPrompt??"",n=t.benchmarkMode===!0,i=t.requiredOutputPaths??[],r=t.interactiveTurnGovernance===!1?null:new h(e,t.interactiveTurnGovernance??{}),a=(t.executionGovernance===!1?!1:t.executionGovernance===!0||v({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}))?new p({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}):null,o=a?.getSummary()??null,c=[];(r||a)&&c.push(async(l,u)=>{if(r){let j=r.maybeBlockToolCall({toolName:l.toolName,input:l.input,iteration:l.iteration});if(j)return j}let f=await u();return r&&r.recordToolResult({toolName:l.toolName,input:l.input,result:f,iteration:l.iteration}),a&&(a.recordToolResult({toolName:l.toolName,input:l.input,result:f,iteration:l.iteration}),o=a.getSummary(),t.onExecutionGovernanceUpdate?.(o)),f}),c.push(S({benchmarkMode:n}));let d=[];r&&d.push({name:"interactive-turn-governance",order:10,evaluate(l){let u=r.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason});return u?{allow:!1,guidance:u.message}:{allow:!0}}}),a&&d.push({name:"execution-governance",order:20,evaluate(l){let u=a.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason,messages:l.messages,maxIterations:l.maxIterations});if(o=a.getSummary(),t.onExecutionGovernanceUpdate?.(o),u.action==="complete"||!u.blocking)return{allow:!0};let f=u.action==="incomplete";return{allow:!1,guidance:u.message,stop:f}}});let m=[];return t.promptGuidance!==!1&&(m.push({name:"contract-ledger",order:100,provide(l){let u=k(l.taskPrompt??e);return u?`${re}${u.replace(/^\n+/,"")}`:null}}),m.push({name:"project-execution",order:110,provide(l){let u=E(l.taskPrompt??e);return u?`${re}${u.replace(/^\n+/,"")}`:null}})),{toolMiddleware:c,promptSections:m,completionGuards:d,getExecutionGovernanceSummary:()=>o}}0&&(module.exports={ExecutionGovernance,InteractiveChatTurnGovernance,InteractiveTurnGovernance,buildContractLedgerGuidance,buildProjectBudgetFinalizationGuidance,buildProjectExecutionGuidance,buildProjectExecutionProfile,createBenchBashMiddleware,createGovernanceExtensions,isExplicitResearchPrompt,isSimpleInformationalPrompt,resolveInteractiveTurnMaxIterations,shouldEnableExecutionGovernance});
33
+ `;function Pt(t){let e=t.taskPrompt??"",n=t.benchmarkMode===!0,i=t.requiredOutputPaths??[],r=t.interactiveTurnGovernance===!1?null:new h(e,t.interactiveTurnGovernance??{}),a=(t.executionGovernance===!1?!1:t.executionGovernance===!0||y({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}))?new p({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}):null,o=a?.getSummary()??null,c=[];(r||a)&&c.push(async(l,u)=>{if(r){let j=r.maybeBlockToolCall({toolName:l.toolName,input:l.input,iteration:l.iteration});if(j)return j}let g=await u();return r&&r.recordToolResult({toolName:l.toolName,input:l.input,result:g,iteration:l.iteration}),a&&(a.recordToolResult({toolName:l.toolName,input:l.input,result:g,iteration:l.iteration}),o=a.getSummary(),t.onExecutionGovernanceUpdate?.(o)),g}),c.push(S({benchmarkMode:n}));let d=[];r&&d.push({name:"interactive-turn-governance",order:10,evaluate(l){let u=r.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason});return u?{allow:!1,guidance:u.message}:{allow:!0}}}),a&&d.push({name:"execution-governance",order:20,evaluate(l){let u=a.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason,messages:l.messages,maxIterations:l.maxIterations});if(o=a.getSummary(),t.onExecutionGovernanceUpdate?.(o),u.action==="complete"||!u.blocking)return{allow:!0};let g=u.action==="incomplete";return{allow:!1,guidance:u.message,stop:g}}});let m=[];return t.promptGuidance!==!1&&(m.push({name:"contract-ledger",order:100,provide(l){let u=k(l.taskPrompt??e);return u?`${re}${u.replace(/^\n+/,"")}`:null}}),m.push({name:"project-execution",order:110,provide(l){let u=E(l.taskPrompt??e);return u?`${re}${u.replace(/^\n+/,"")}`:null}})),{toolMiddleware:c,promptSections:m,completionGuards:d,getExecutionGovernanceSummary:()=>o}}0&&(module.exports={ExecutionGovernance,InteractiveChatTurnGovernance,InteractiveTurnGovernance,buildContractLedgerGuidance,buildProjectBudgetFinalizationGuidance,buildProjectExecutionGuidance,buildProjectExecutionProfile,createBenchBashMiddleware,createGovernanceExtensions,isExplicitResearchPrompt,isSimpleInformationalPrompt,resolveInteractiveTurnMaxIterations,shouldEnableExecutionGovernance});
@@ -44,6 +44,7 @@ interface ToolOperationSnapshot {
44
44
  promotable: boolean;
45
45
  processId?: string;
46
46
  taskId?: string;
47
+ displayName?: string;
47
48
  pid?: number;
48
49
  commandFingerprint?: string;
49
50
  outputPath?: string;
@@ -44,6 +44,7 @@ interface ToolOperationSnapshot {
44
44
  promotable: boolean;
45
45
  processId?: string;
46
46
  taskId?: string;
47
+ displayName?: string;
47
48
  pid?: number;
48
49
  commandFingerprint?: string;
49
50
  outputPath?: string;