@rpamis/comet 0.4.0-beta.19 → 0.4.0-beta.20

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 (71) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +3 -0
  3. package/assets/manifest.json +1 -1
  4. package/assets/skills/comet/scripts/comet-hook-router.mjs +10 -10
  5. package/assets/skills/comet-archive/SKILL.md +0 -1
  6. package/assets/skills/comet-archive/agents/openai.yaml +1 -1
  7. package/assets/skills/comet-build/SKILL.md +0 -1
  8. package/assets/skills/comet-build/agents/openai.yaml +1 -1
  9. package/assets/skills/comet-design/SKILL.md +0 -1
  10. package/assets/skills/comet-design/agents/openai.yaml +1 -1
  11. package/assets/skills/comet-hotfix/SKILL.md +0 -1
  12. package/assets/skills/comet-hotfix/agents/openai.yaml +1 -1
  13. package/assets/skills/comet-native/SKILL.md +1 -1
  14. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +56 -56
  15. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +77 -77
  16. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +11 -11
  17. package/assets/skills/comet-native/scripts/comet-native-init.mjs +3 -3
  18. package/assets/skills/comet-native/scripts/comet-native-new.mjs +55 -55
  19. package/assets/skills/comet-native/scripts/comet-native-next.mjs +54 -54
  20. package/assets/skills/comet-native/scripts/comet-native-root.mjs +6 -6
  21. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +91 -91
  22. package/assets/skills/comet-native/scripts/comet-native-select.mjs +63 -63
  23. package/assets/skills/comet-native/scripts/comet-native-show.mjs +45 -45
  24. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +42 -42
  25. package/assets/skills/comet-native/scripts/comet-native-status.mjs +67 -67
  26. package/assets/skills/comet-open/SKILL.md +0 -1
  27. package/assets/skills/comet-open/agents/openai.yaml +1 -1
  28. package/assets/skills/comet-tweak/SKILL.md +0 -1
  29. package/assets/skills/comet-tweak/agents/openai.yaml +1 -1
  30. package/assets/skills/comet-verify/SKILL.md +0 -1
  31. package/assets/skills/comet-verify/agents/openai.yaml +1 -1
  32. package/assets/skills-zh/comet-archive/SKILL.md +0 -1
  33. package/assets/skills-zh/comet-archive/agents/openai.yaml +1 -1
  34. package/assets/skills-zh/comet-build/SKILL.md +0 -1
  35. package/assets/skills-zh/comet-build/agents/openai.yaml +1 -1
  36. package/assets/skills-zh/comet-design/SKILL.md +0 -1
  37. package/assets/skills-zh/comet-design/agents/openai.yaml +1 -1
  38. package/assets/skills-zh/comet-hotfix/SKILL.md +0 -1
  39. package/assets/skills-zh/comet-hotfix/agents/openai.yaml +1 -1
  40. package/assets/skills-zh/comet-native/SKILL.md +1 -1
  41. package/assets/skills-zh/comet-open/SKILL.md +0 -1
  42. package/assets/skills-zh/comet-open/agents/openai.yaml +1 -1
  43. package/assets/skills-zh/comet-tweak/SKILL.md +0 -1
  44. package/assets/skills-zh/comet-tweak/agents/openai.yaml +1 -1
  45. package/assets/skills-zh/comet-verify/SKILL.md +0 -1
  46. package/assets/skills-zh/comet-verify/agents/openai.yaml +1 -1
  47. package/dist/app/commands/doctor.d.ts.map +1 -1
  48. package/dist/app/commands/doctor.js +43 -24
  49. package/dist/app/commands/doctor.js.map +1 -1
  50. package/dist/app/commands/init.d.ts.map +1 -1
  51. package/dist/app/commands/init.js +32 -18
  52. package/dist/app/commands/init.js.map +1 -1
  53. package/dist/domains/comet-native/native-change.d.ts +0 -1
  54. package/dist/domains/comet-native/native-change.d.ts.map +1 -1
  55. package/dist/domains/comet-native/native-change.js +2 -2
  56. package/dist/domains/comet-native/native-change.js.map +1 -1
  57. package/dist/domains/comet-native/native-cli-help.js +1 -1
  58. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  59. package/dist/domains/comet-native/native-next-command.js +3 -3
  60. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  61. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  62. package/dist/domains/comet-native/native-portable-continuation.js +23 -0
  63. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  64. package/dist/domains/comet-native/native-portable-runtime.js +1 -1
  65. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
  66. package/dist/domains/dashboard/web/index.html +14 -14
  67. package/dist/domains/integrations/codegraph.d.ts +24 -2
  68. package/dist/domains/integrations/codegraph.d.ts.map +1 -1
  69. package/dist/domains/integrations/codegraph.js +307 -1
  70. package/dist/domains/integrations/codegraph.js.map +1 -1
  71. package/package.json +1 -1
@@ -166,22 +166,22 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
166
166
  `),i=t.at(-1)==="";if(i&&t.pop(),t.length>Wr)throw new Error(`Native transaction event log exceeds ${Wr} events`);let r=[];for(let n=0;n<t.length;n+=1){let a=n+1,o=t[n],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&n===t.length-1;try{r.push(Hv(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&Ov(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function ru(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
167
167
  `)}
168
168
  `}function Bv(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Ne.join(e.transactionsDir,t)}function zr(e,t){let i=Bv(e,t);return{directory:i,journal:Ne.join(i,"transaction.json"),events:Ne.join(i,"events.jsonl"),staged:Ne.join(i,"staged"),backups:Ne.join(i,"backups")}}async function Ze(e,t){let i=zr(e,t);return await Promise.all(Object.values(i).map(r=>$(e.runtimeDir,r))),i}async function nu(e,t,i={}){let r=await Ze(e,t);try{await Vr.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await J({root:e.runtimeDir,file:r.events,maxBytes:Tv,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=eu.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=Dv(a),s=ru(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function Yl(e,t,i){let r=await nu(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function co(e,t,i,r){let n=await Ze(e,t),a=await nu(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await z(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>Yl(e,t,a)}),o;if(a.events.length>=Wr)throw new Error(`Native transaction event log ${t} exceeds ${Wr} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return iu(s,s.sequence),await Vr.mkdir(n.directory,{recursive:!0}),await z(n.events,ru([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>Yl(e,t,a)}),s}async function au(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=so(t);let i=await Ze(e,t.id);await Vr.mkdir(i.staged,{recursive:!0}),await Vr.mkdir(i.backups,{recursive:!0}),await Y(i.journal,t,{containedRoot:e.runtimeDir}),await co(e,t.id,"prepared")}async function wi(e,t,i={}){let r=await Ze(e,t),n=await J({root:e.runtimeDir,file:r.journal,maxBytes:_v,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(eu.decode(n.bytes)),o=so(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Lv(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=so({...t,status:i});return await Y((await Ze(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function lo(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await co(e,t.id,i),i==="commit"?Lv(e,t,"committed"):t}import{createHash as Pg}from"node:crypto";import{promises as Zr}from"node:fs";import Me from"node:path";import{execFileSync as Mv}from"child_process";import Gr from"path";function Jr(e,t){return Mv("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Fv(e,t){let i=Gr.normalize(e),r=Gr.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Be(e){try{let t=Gr.resolve(Jr(e,["rev-parse","--show-toplevel"])),r=Jr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Gr.resolve(r.slice(9)):t,a=null;try{a=Jr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Fv(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function uo(e,t){try{let i=Jr(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as zv}from"node:crypto";import{promises as se}from"node:fs";import Q from"node:path";import{TextDecoder as Jv}from"node:util";var qv=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Vv=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Wv(e){return e.toLowerCase().startsWith(".env")}function yi(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>Wv(r))?"environment-file":i.some(r=>Vv.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>qv.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var Kr=1024*1024;function fo(e,t){let i=Q.relative(e,t);return i===""||!Q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Q.sep}`)}function Gv(e){let t=Q.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Q.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=yi(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function Uv(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Kv(e,t){return T({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ur(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return de(i,r)?T(i,r):T(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ou(e){let t=await se.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await se.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Yv(e,t){let i=Q.resolve(e),r=Q.resolve(t);if(!fo(i,r))throw new Error("Native artifact path is outside its root");let n=[await ou(i)],a=i;for(let o of Q.relative(i,r).split(Q.sep).filter(Boolean)){a=Q.join(a,o);let s=await ou(a);if(!fo(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function su(e){for(let t of e){let i=await se.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Kv(t,i)||await se.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function me(e){let t=Gv(e.ref),i=e.maxBytes===null?null:Uv(e.maxBytes??Kr),r=Q.resolve(e.root,...t.split("/")),n=await Yv(e.root,Q.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await se.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await se.realpath(r);if(!fo(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await se.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),se.lstat(r),se.realpath(r)]);if(await su(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Ur(a,c)||!Ur(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let b=i===null?p.length:i+1-f,k=await s.read(p,0,Math.min(p.length,b),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),se.lstat(r),se.realpath(r)]);if(await su(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Ur(c,v)||!Ur(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(d,f),y;try{y=new Jv("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:b})}return{ref:t,size:f,hash:e.includeHash===!1?null:zv("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var fu=Et(ft(),1);import{createHash as Xv}from"crypto";function Z(e){return Xv("sha256").update(e).digest("hex")}var Zb={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var ek=8*1024*1024;var tk=64*1024,ik=64*1024;var rk={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},nk={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var ak=(1n<<256n)-1n;var ng=Et(ft(),1);var bk=4*1024*1024;var ag=null;function og(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function cu(e,t){return(...i)=>{let r=ag;if(r===null)return t(...i);let n=og(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var Rk=cu("hookWritePolicy",async e=>(await Ua(e))?.hook??{allow_paths:[]});var yS=256*1024;var IS={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};var hu=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],aE=new Set(hu),hg=new Set([...hu,"minimum_runtime_version","revision"]),oE=new Set([...hg,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]);var Yr=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Ni=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Xr=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},sE=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
169
- `);var cE=256*1024;import{createHash as pg}from"crypto";function ce(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function mg(e,t){t.has(e)&&ce("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||ce("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&ce("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ce("symbol properties are not supported"),`[${e.map(r=>mo(r,t)).join(",")}]`}finally{t.delete(e)}}function vg(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&ce("only plain objects are supported"),t.has(e)&&ce("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ce("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&ce("accessor properties are not supported"),`${JSON.stringify(o)}:${mo(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function mo(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||ce("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?mg(e,t):vg(e,t);case"bigint":case"function":case"symbol":case"undefined":return ce(`${typeof e} values are not supported`)}return ce("unsupported value type")}function vo(e){return mo(e,new Set)}function ee(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return pg("sha256").update(`${e}
170
- ${vo(t)}`).digest("hex")}var mE=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),pu=Object.freeze({maxCriteria:1024});var mu=Et(ft(),1);var yu="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",DE=new RegExp(`^portable-archive-(${yu})\\.json$`,"u"),BE=new RegExp(`^portable-migration-(${yu})\\.json$`,"u");var bi=/^[a-f0-9]{64}$/u,Nu=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Rg=16*1024,wo=process.platform;function Su(e,t){let i=Me.relative(e,t);return Me.isAbsolute(i)||i===".."||i.startsWith(`..${Me.sep}`)?null:i.replaceAll("\\","/")||"."}function Eu(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Pu(e,t){if(e.length===0||Eu(e)||e.includes("\\")||Me.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Me.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function yo(e,t){return Pg("sha256").update(`${e}
169
+ `);import{createHash as pg}from"crypto";function ce(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function mg(e,t){t.has(e)&&ce("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||ce("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&ce("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ce("symbol properties are not supported"),`[${e.map(r=>mo(r,t)).join(",")}]`}finally{t.delete(e)}}function vg(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&ce("only plain objects are supported"),t.has(e)&&ce("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ce("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&ce("accessor properties are not supported"),`${JSON.stringify(o)}:${mo(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function mo(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||ce("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?mg(e,t):vg(e,t);case"bigint":case"function":case"symbol":case"undefined":return ce(`${typeof e} values are not supported`)}return ce("unsupported value type")}function vo(e){return mo(e,new Set)}function ee(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return pg("sha256").update(`${e}
170
+ ${vo(t)}`).digest("hex")}var pE=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),pu=Object.freeze({maxCriteria:1024});var mu=Et(ft(),1);var yu="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",HE=new RegExp(`^portable-archive-(${yu})\\.json$`,"u"),DE=new RegExp(`^portable-migration-(${yu})\\.json$`,"u");var bi=/^[a-f0-9]{64}$/u,Nu=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Rg=16*1024,wo=process.platform;function Su(e,t){let i=Me.relative(e,t);return Me.isAbsolute(i)||i===".."||i.startsWith(`..${Me.sep}`)?null:i.replaceAll("\\","/")||"."}function Eu(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Pu(e,t){if(e.length===0||Eu(e)||e.includes("\\")||Me.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Me.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function yo(e,t){return Pg("sha256").update(`${e}
171
171
  ${t}`).digest("hex")}async function bu(e,t){let i=await Zr.realpath(t),r=await Zr.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=wo==="win32"?Me.normalize(i).toLowerCase():i;return yo(e,`${n}
172
172
  ${r.dev}
173
173
  ${r.ino}
174
174
  ${r.birthtimeMs}`)}async function ku(e,t){let i=await Zr.realpath(t),r=await Zr.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=wo==="win32"?Me.normalize(i).toLowerCase():i;return yo(e,n)}function xg(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function go(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Eu(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Ru(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(go(e.changeBranch,"Native workspace change branch"),go(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function Cg(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Nu.test(t.baseCommit)||typeof t.targetCommit!="string"||!Nu.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");go(t.targetBranch,"Native workspace Git target branch")}function en(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!bi.test(String(t.projectRootId))||!bi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");xg(t.capturedAt),Pu(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!bi.test(String(t.projectRootPathId))||a&&!bi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!bi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Cg(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(Ru(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function xu(e,t){return Me.join(he(e,t),"workspace.json")}function Ag(e,t){let i=xu(e,t),r=ae(e,i),n=Su(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Pu(n,"Native workspace file ref")}}async function _g(e,t){try{let i=Ag(e,t),r=await me({root:i.root,ref:i.ref,maxBytes:Rg});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Cu(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Su(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Be(e.paths.projectRoot),r=i.isGitWorktree?uo(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:uo(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([bu("comet.native.workspace-project-root.v2",e.paths.projectRoot),bu("comet.native.workspace-native-root.v2",e.paths.nativeRoot),ku("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),ku("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&Ru(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:yo("comet.native.workspace-session.v2",`${s}
175
175
  ${c}
176
- ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return en(p),p}async function ho(e){let t=await Cu(e),i=xu(e.paths,e.name),r=ae(e.paths,i);return await $(r,i),await Y(i,t,{containedRoot:r}),t}async function kt(e,t){let i=await _g(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(en(i),i)}async function Qr(e){en(e.identity);let t=await Cu({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),wo==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function po(e){if(en(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Qr(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Be(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}var bo=64*1024*1024,pP=256*1024,Iu=16*1024*1024;async function U(e){try{return await Fe.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $g(e){let t;try{t=await Fe.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t){if(!i.isDirectory()||i.isSymbolicLink())continue;let r;try{r=await wi(e,i.name)}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction ${i.name} has no journal; run doctor before moving`,{cause:n}):n}if(r.status!=="committed"&&r.status!=="rolled-back")throw new Error(`Native transaction ${r.id} is unfinished; recover it before moving`)}}async function Og(e,t){for(let i of await Fe.readdir(e.locksDir,{withFileTypes:!0})){let r=I.join(e.locksDir,i.name);if(I.resolve(r)!==I.resolve(t)&&(i.isFile()||i.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${r}`)}}async function Hg(e){let t;try{t=await Fe.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await kt(e,i.name);if(r){await ho({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function Dg(e){let t;try{t=await Fe.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name)))if(!(!i.isDirectory()||i.isSymbolicLink()))try{let r=await kt(e,i.name);if(r?.schema==="comet.native.workspace.v3"){let n=await po({paths:e,identity:r});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(r){let n=await Qr({paths:e,identity:r});if(n.state!=="aligned")throw new Error(`legacy workspace ownership is ${n.state}`)}}catch(r){throw new Error(`Native workspace identity for ${i.name} must be aligned and repaired before moving the root`,{cause:r})}}async function Si(e,t){let i=[];async function r(n){let a=await Qe({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=I.join(n,s.name);if(t.excludedFiles?.has(I.resolve(c))){await a.verify();continue}let l=await Fe.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:I.relative(e,c).split(I.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await J({root:e,file:c,maxBytes:bo,label:`Native root file ${I.relative(e,c)}`});i.push({ref:I.relative(e,c).split(I.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function Bg(e,t,i,r){await pi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await Qe({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=I.join(a,l.name);if(I.resolve(u)===I.resolve(i)){await s.verify();continue}let d=await Fe.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=I.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await pi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await mi({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:bo,label:`Native root move file ${I.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function tn(e,t,i,r){let n=await Si(e,{rejectSymlinks:!0,excludedFiles:i?new Set([I.resolve(i)]):void 0}),a=await Si(t,{rejectSymlinks:!0,excludedFiles:r?new Set([I.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function Lg(e,t){return I.join(e.artifactRoot,`.comet-native-move-${t}`)}function Mg(e,t){return I.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function Fg(e){return`${e}.removing`}function ju(e,t,i){return I.join(zr(e,t).directory,`root-move-cleanup-${i}.json`)}function qg(e){return JSON.stringify(e,null,2)+`
177
- `}function Vg(e){return Ig("sha256").update(e).digest("hex")}function Wg(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||I.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function zg(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(Wg);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=I.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function Jg(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=qg(t);if(Buffer.byteLength(i,"utf8")>Iu)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await z(ju(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),Vg(i)}async function Gg(e){let t=await J({root:e.paths.runtimeDir,file:ju(e.paths,e.id,e.cleanup.kind),maxBytes:Iu,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return zg(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function No(e){let t=await Si(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function Au(e){return e.ref.split("/").length}async function Ug(e){let i=[...await No({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>Au(a)-Au(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=I.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await no({root:e.projectRoot,file:a,maxBytes:bo,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await ao({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await No({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await ao({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function rn(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function Kg(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function _u(e){let t=rn(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await He(e.projectRoot,t),t}async function ki(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=rn(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await He(e.projectRoot,i),i}async function Tu(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await U(e.target),a=await U(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await Jg({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Si(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await ki({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await Gg({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await U(e.target),a=await U(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await Ul({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return ki({projectRoot:e.projectRoot,config:t,id:e.id})}return await No({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await ki({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await ki({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await Ug({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),ki({projectRoot:e.projectRoot,config:t,id:e.id})}async function Yg(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await U(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=Fg(e.staging);t=await Tu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Si(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([I.resolve(e.lockFile)])}),await Bg(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await tn(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await _u({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await U(e.destinationPaths.nativeRoot)){if(await U(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await tn(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await U(e.staging))throw new Error("Native move staging tree is missing");await tn(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Fe.rename(e.staging,e.destinationPaths.nativeRoot)}t=await _u({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await U(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=Mg(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await U(e.sourcePaths.nativeRoot)&&await tn(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Tu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await Hg(e.destinationPaths);let n=await wi(e.destinationPaths,e.pending.id);await lo(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await He(e.projectRoot,o),o}async function $u(e){let t=await oe(e.projectRoot)??Ol("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let i=ui(e.toArtifactRoot);if(i===t.native.artifact_root)throw new Error(`Native artifact root is already ${i}`);let r=await fe(e.projectRoot,t.native.artifact_root),n=await fe(e.projectRoot,i);if(F(r.nativeRoot,n.nativeRoot)||F(n.nativeRoot,r.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await U(r.nativeRoot))throw new Error(`Native source root does not exist: ${r.nativeRoot}`);if(await $g(r),await U(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await di(r,"root-move",`move root to ${i}`),o=jg(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:i,stage:"copying"},c=Kg({id:o,paths:r,now:e.now??new Date}),l=Lg(n,o);try{if(await Og(r,a.file),await Dg(r),await U(l))throw new Error(`Native move staging path is occupied: ${l}`);return await He(e.projectRoot,rn(t,s)),await au(r,c),await e.hooks?.afterRootMoveStage?.("copying",c),await Yg({projectRoot:e.projectRoot,config:rn(t,s),pending:s,sourcePaths:r,destinationPaths:n,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:r.nativeRoot,toNativeRoot:n.nativeRoot,transactionId:o}}finally{await fi(a)}}import xi from"path";import{realpathSync as Vw}from"fs";var Qg=["Outcome","Scope","Non-goals","Acceptance examples"],_P=[...Qg,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var Zg=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Ou=1024*1024;var Du="scoped-text-safety",ew=1,tw=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var iw="comet.native.checker-policy.v1";var GP=ee(iw,{policy:Du,version:ew,limits:tw,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var rw=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],UP=new Set(rw);var ow=Ou,dR=3*ow;var Bu={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},cw=Z("comet-native-runtime:v3:scope-reopen"),BR=[{skillVersion:"3",skillHash:Z("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Z("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Z("comet-native-runtime:v1")}];var Mu=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],wx=new Set(Mu),mw=new Set([...Mu,"minimum_runtime_version","revision"]),yx=new Set([...mw,"operation"]),Nx=512*1024,vw=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),bx=new Set([...vw,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var Px={maxAcceptanceCriteria:pu.maxCriteria};var _x={maxSpecs:64,maxFileBytes:Kr,maxTotalBytes:4*1024*1024};import{execFile as xw}from"node:child_process";import{promisify as Cw}from"node:util";var Ix=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var Vx={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var uC=512*1024;var Ri=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var jC=64*1024;var $C=3600*1e3;var OC=Cw(xw);var nn=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};var NA={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var AA=16*1024*1024,_A=256*1024,TA=16*1024;var HA=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var LA=16*1024;var Hw=Et(ft(),1);var FA=8*1024*1024;var TT=16*1024;var NI=16*1024*1024,an=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},on=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var sn=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Vu=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],So=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Vu,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction; parent changes also expose children and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker]
178
- comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
176
+ ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return en(p),p}async function ho(e){let t=await Cu(e),i=xu(e.paths,e.name),r=ae(e.paths,i);return await $(r,i),await Y(i,t,{containedRoot:r}),t}async function kt(e,t){let i=await _g(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(en(i),i)}async function Qr(e){en(e.identity);let t=await Cu({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),wo==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function po(e){if(en(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Qr(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Be(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}var bo=64*1024*1024,hP=256*1024,Iu=16*1024*1024;async function U(e){try{return await Fe.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $g(e){let t;try{t=await Fe.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t){if(!i.isDirectory()||i.isSymbolicLink())continue;let r;try{r=await wi(e,i.name)}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction ${i.name} has no journal; run doctor before moving`,{cause:n}):n}if(r.status!=="committed"&&r.status!=="rolled-back")throw new Error(`Native transaction ${r.id} is unfinished; recover it before moving`)}}async function Og(e,t){for(let i of await Fe.readdir(e.locksDir,{withFileTypes:!0})){let r=I.join(e.locksDir,i.name);if(I.resolve(r)!==I.resolve(t)&&(i.isFile()||i.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${r}`)}}async function Hg(e){let t;try{t=await Fe.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await kt(e,i.name);if(r){await ho({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function Dg(e){let t;try{t=await Fe.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name)))if(!(!i.isDirectory()||i.isSymbolicLink()))try{let r=await kt(e,i.name);if(r?.schema==="comet.native.workspace.v3"){let n=await po({paths:e,identity:r});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(r){let n=await Qr({paths:e,identity:r});if(n.state!=="aligned")throw new Error(`legacy workspace ownership is ${n.state}`)}}catch(r){throw new Error(`Native workspace identity for ${i.name} must be aligned and repaired before moving the root`,{cause:r})}}async function Si(e,t){let i=[];async function r(n){let a=await Qe({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=I.join(n,s.name);if(t.excludedFiles?.has(I.resolve(c))){await a.verify();continue}let l=await Fe.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:I.relative(e,c).split(I.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await J({root:e,file:c,maxBytes:bo,label:`Native root file ${I.relative(e,c)}`});i.push({ref:I.relative(e,c).split(I.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function Bg(e,t,i,r){await pi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await Qe({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=I.join(a,l.name);if(I.resolve(u)===I.resolve(i)){await s.verify();continue}let d=await Fe.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=I.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await pi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await mi({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:bo,label:`Native root move file ${I.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function tn(e,t,i,r){let n=await Si(e,{rejectSymlinks:!0,excludedFiles:i?new Set([I.resolve(i)]):void 0}),a=await Si(t,{rejectSymlinks:!0,excludedFiles:r?new Set([I.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function Lg(e,t){return I.join(e.artifactRoot,`.comet-native-move-${t}`)}function Mg(e,t){return I.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function Fg(e){return`${e}.removing`}function ju(e,t,i){return I.join(zr(e,t).directory,`root-move-cleanup-${i}.json`)}function qg(e){return JSON.stringify(e,null,2)+`
177
+ `}function Vg(e){return Ig("sha256").update(e).digest("hex")}function Wg(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||I.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function zg(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(Wg);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=I.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function Jg(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=qg(t);if(Buffer.byteLength(i,"utf8")>Iu)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await z(ju(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),Vg(i)}async function Gg(e){let t=await J({root:e.paths.runtimeDir,file:ju(e.paths,e.id,e.cleanup.kind),maxBytes:Iu,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return zg(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function No(e){let t=await Si(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function Au(e){return e.ref.split("/").length}async function Ug(e){let i=[...await No({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>Au(a)-Au(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=I.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await no({root:e.projectRoot,file:a,maxBytes:bo,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await ao({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await No({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await ao({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function rn(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function Kg(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function _u(e){let t=rn(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await He(e.projectRoot,t),t}async function ki(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=rn(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await He(e.projectRoot,i),i}async function Tu(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await U(e.target),a=await U(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await Jg({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Si(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await ki({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await Gg({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await U(e.target),a=await U(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await Ul({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return ki({projectRoot:e.projectRoot,config:t,id:e.id})}return await No({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await ki({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await ki({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await Ug({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),ki({projectRoot:e.projectRoot,config:t,id:e.id})}async function Yg(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await U(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=Fg(e.staging);t=await Tu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Si(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([I.resolve(e.lockFile)])}),await Bg(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await tn(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await _u({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await U(e.destinationPaths.nativeRoot)){if(await U(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await tn(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await U(e.staging))throw new Error("Native move staging tree is missing");await tn(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Fe.rename(e.staging,e.destinationPaths.nativeRoot)}t=await _u({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await U(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=Mg(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await U(e.sourcePaths.nativeRoot)&&await tn(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Tu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await Hg(e.destinationPaths);let n=await wi(e.destinationPaths,e.pending.id);await lo(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await He(e.projectRoot,o),o}async function $u(e){let t=await oe(e.projectRoot)??Ol("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let i=ui(e.toArtifactRoot);if(i===t.native.artifact_root)throw new Error(`Native artifact root is already ${i}`);let r=await fe(e.projectRoot,t.native.artifact_root),n=await fe(e.projectRoot,i);if(F(r.nativeRoot,n.nativeRoot)||F(n.nativeRoot,r.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await U(r.nativeRoot))throw new Error(`Native source root does not exist: ${r.nativeRoot}`);if(await $g(r),await U(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await di(r,"root-move",`move root to ${i}`),o=jg(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:i,stage:"copying"},c=Kg({id:o,paths:r,now:e.now??new Date}),l=Lg(n,o);try{if(await Og(r,a.file),await Dg(r),await U(l))throw new Error(`Native move staging path is occupied: ${l}`);return await He(e.projectRoot,rn(t,s)),await au(r,c),await e.hooks?.afterRootMoveStage?.("copying",c),await Yg({projectRoot:e.projectRoot,config:rn(t,s),pending:s,sourcePaths:r,destinationPaths:n,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:r.nativeRoot,toNativeRoot:n.nativeRoot,transactionId:o}}finally{await fi(a)}}import xi from"path";import{realpathSync as Vw}from"fs";var Qg=["Outcome","Scope","Non-goals","Acceptance examples"],AP=[...Qg,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var Zg=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Ou=1024*1024;var Du="scoped-text-safety",ew=1,tw=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var iw="comet.native.checker-policy.v1";var JP=ee(iw,{policy:Du,version:ew,limits:tw,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var rw=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],GP=new Set(rw);var ow=Ou,uR=3*ow;var Bu={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},cw=Z("comet-native-runtime:v3:scope-reopen"),DR=[{skillVersion:"3",skillHash:Z("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Z("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Z("comet-native-runtime:v1")}];var Mu=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],gx=new Set(Mu),mw=new Set([...Mu,"minimum_runtime_version","revision"]),wx=new Set([...mw,"operation"]),yx=512*1024,vw=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Nx=new Set([...vw,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var Ex={maxAcceptanceCriteria:pu.maxCriteria};var Ax={maxSpecs:64,maxFileBytes:Kr,maxTotalBytes:4*1024*1024};import{execFile as xw}from"node:child_process";import{promisify as Cw}from"node:util";var Tx=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var qx={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var lC=512*1024;var Ri=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var IC=64*1024;var jC=3600*1e3;var $C=Cw(xw);var nn=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};var yA={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var CA=16*1024*1024,AA=256*1024,_A=16*1024;var OA=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var BA=16*1024;var Hw=Et(ft(),1);var MA=8*1024*1024;var _T=16*1024;var yI=16*1024*1024,an=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},on=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var sn=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Vu=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],So=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Vu,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction; parent changes also expose children and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker]
178
+ comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
179
179
  comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function ko(e,t){return`${e}:
180
180
  ${t.map(i=>` ${i}`).join(`
181
181
  `)}`}function Mw(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return So[i]||t.length>1&&So[t[0]]?.subcommands?i:t[0]}function Fw(e=[]){let t=Mw(e),i=So[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",ko("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...Vu];return n&&n.length>0&&r.push("",ko("Options",n)),r.push("",`Output:
182
182
  ${i.output}`),i.examples&&r.push("",ko("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
183
183
  `)}
184
- `}}var qw=Fw().usage;var GI=10*1024*1024,ve=class extends Error{};function zu(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new ve(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Ju(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new ve(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new ve(`${t} requires a value`);return e.splice(r,2),n}function Po(e){if(e.length>0)throw new ve(`Unexpected argument: ${e[0]}`)}function Ro(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new ve(`${t} is required`);return i}function Eo(e,t){let i=xi.normalize(Wu(e)),r=xi.normalize(Wu(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Wu(e){let t=xi.resolve(e);try{return Vw.native(t)}catch{return t}}function Ww(e){let t=xi.resolve(e),i=Be(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Be(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Eo(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Eo(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Eo(process.cwd(),i.currentWorktreeRoot)?xi.resolve(process.cwd()):i.currentWorktreeRoot}async function Gu(e){return e?Ww(e):eo(process.cwd())}function xo(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
184
+ `}}var qw=Fw().usage;var JI=10*1024*1024,ve=class extends Error{};function zu(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new ve(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Ju(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new ve(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new ve(`${t} requires a value`);return e.splice(r,2),n}function Po(e){if(e.length>0)throw new ve(`Unexpected argument: ${e[0]}`)}function Ro(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new ve(`${t} is required`);return i}function Eo(e,t){let i=xi.normalize(Wu(e)),r=xi.normalize(Wu(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Wu(e){let t=xi.resolve(e);try{return Vw.native(t)}catch{return t}}function Ww(e){let t=xi.resolve(e),i=Be(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Be(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Eo(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Eo(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Eo(process.cwd(),i.currentWorktreeRoot)?xi.resolve(process.cwd()):i.currentWorktreeRoot}async function Gu(e){return e?Ww(e):eo(process.cwd())}function xo(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
185
185
  `}}function Uu(e,t){if(t instanceof ve)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof an)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof on)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Yr)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Ni)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof sn)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Xr)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof nn)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Ri)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Ku(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
186
186
  `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Yu(e,t){let i=Ro(e,"root subcommand");if(i==="show"){Po(e);let r=await oe(t);if(!r)throw new Error(".comet/config.yaml was not found");let n=await fe(t,r.native.artifact_root);return xo("root show",{projectRoot:t,artifactRoot:r.native.artifact_root,language:r.native.language,nativeRoot:n.nativeRoot,pendingRootMove:r.native.pending_root_move??null})}if(i==="move"){let r=Ro(e,"artifact root");Po(e);let n=await $u({projectRoot:t,toArtifactRoot:r});return xo("root move",n,`Moved Comet Native to ${n.toNativeRoot}
187
187
  `)}throw new ve(`Unknown root command: ${i}`)}function zw(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`