@xenosystem/agent-sdk 0.8.12

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 (175) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +511 -0
  3. package/dist/agents/index.cjs +17 -0
  4. package/dist/agents/index.d.cts +244 -0
  5. package/dist/agents/index.d.ts +244 -0
  6. package/dist/agents/index.js +17 -0
  7. package/dist/agents/metafile-cjs.json +1 -0
  8. package/dist/agents/metafile-esm.json +1 -0
  9. package/dist/artifacts/browser.cjs +1 -0
  10. package/dist/artifacts/browser.d.cts +8 -0
  11. package/dist/artifacts/browser.d.ts +8 -0
  12. package/dist/artifacts/browser.js +1 -0
  13. package/dist/artifacts/diff-artifact-C2tQZWcs.d.cts +354 -0
  14. package/dist/artifacts/diff-artifact-C2tQZWcs.d.ts +354 -0
  15. package/dist/artifacts/index.cjs +10 -0
  16. package/dist/artifacts/index.d.cts +588 -0
  17. package/dist/artifacts/index.d.ts +588 -0
  18. package/dist/artifacts/index.js +10 -0
  19. package/dist/artifacts/metafile-cjs.json +1 -0
  20. package/dist/artifacts/metafile-esm.json +1 -0
  21. package/dist/automation/index.cjs +438 -0
  22. package/dist/automation/index.d.cts +878 -0
  23. package/dist/automation/index.d.ts +878 -0
  24. package/dist/automation/index.js +438 -0
  25. package/dist/automation/metafile-cjs.json +1 -0
  26. package/dist/automation/metafile-esm.json +1 -0
  27. package/dist/control-plane/index.cjs +7 -0
  28. package/dist/control-plane/index.d.cts +403 -0
  29. package/dist/control-plane/index.d.ts +403 -0
  30. package/dist/control-plane/index.js +7 -0
  31. package/dist/control-plane/metafile-cjs.json +1 -0
  32. package/dist/control-plane/metafile-esm.json +1 -0
  33. package/dist/control-room/index.cjs +1 -0
  34. package/dist/control-room/index.d.cts +216 -0
  35. package/dist/control-room/index.d.ts +216 -0
  36. package/dist/control-room/index.js +1 -0
  37. package/dist/control-room/metafile-cjs.json +1 -0
  38. package/dist/control-room/metafile-esm.json +1 -0
  39. package/dist/electron/index.cjs +1476 -0
  40. package/dist/electron/index.d.cts +1583 -0
  41. package/dist/electron/index.d.ts +1583 -0
  42. package/dist/electron/index.js +1476 -0
  43. package/dist/electron/metafile-cjs.json +1 -0
  44. package/dist/electron/metafile-esm.json +1 -0
  45. package/dist/governance/index.cjs +33 -0
  46. package/dist/governance/index.d.cts +397 -0
  47. package/dist/governance/index.d.ts +397 -0
  48. package/dist/governance/index.js +33 -0
  49. package/dist/governance/metafile-cjs.json +1 -0
  50. package/dist/governance/metafile-esm.json +1 -0
  51. package/dist/hooks/index.cjs +9 -0
  52. package/dist/hooks/index.d.cts +198 -0
  53. package/dist/hooks/index.d.ts +198 -0
  54. package/dist/hooks/index.js +9 -0
  55. package/dist/hooks/metafile-cjs.json +1 -0
  56. package/dist/hooks/metafile-esm.json +1 -0
  57. package/dist/hosted/index.cjs +1 -0
  58. package/dist/hosted/index.d.cts +490 -0
  59. package/dist/hosted/index.d.ts +490 -0
  60. package/dist/hosted/index.js +1 -0
  61. package/dist/hosted/metafile-cjs.json +1 -0
  62. package/dist/hosted/metafile-esm.json +1 -0
  63. package/dist/index.cjs +2161 -0
  64. package/dist/index.d.cts +12259 -0
  65. package/dist/index.d.ts +12259 -0
  66. package/dist/index.js +2161 -0
  67. package/dist/intelligence/index.cjs +10 -0
  68. package/dist/intelligence/index.d.cts +220 -0
  69. package/dist/intelligence/index.d.ts +220 -0
  70. package/dist/intelligence/index.js +10 -0
  71. package/dist/intelligence/metafile-cjs.json +1 -0
  72. package/dist/intelligence/metafile-esm.json +1 -0
  73. package/dist/mcp/index.cjs +28 -0
  74. package/dist/mcp/index.d.cts +960 -0
  75. package/dist/mcp/index.d.ts +960 -0
  76. package/dist/mcp/index.js +28 -0
  77. package/dist/mcp/metafile-cjs.json +1 -0
  78. package/dist/mcp/metafile-esm.json +1 -0
  79. package/dist/metafile-cjs.json +1 -0
  80. package/dist/metafile-esm.json +1 -0
  81. package/dist/oracle/index.cjs +1 -0
  82. package/dist/oracle/index.d.cts +310 -0
  83. package/dist/oracle/index.d.ts +310 -0
  84. package/dist/oracle/index.js +1 -0
  85. package/dist/oracle/metafile-cjs.json +1 -0
  86. package/dist/oracle/metafile-esm.json +1 -0
  87. package/dist/providers/index.cjs +11 -0
  88. package/dist/providers/index.d.cts +462 -0
  89. package/dist/providers/index.d.ts +462 -0
  90. package/dist/providers/index.js +11 -0
  91. package/dist/providers/metafile-cjs.json +1 -0
  92. package/dist/providers/metafile-esm.json +1 -0
  93. package/dist/recipes/index.cjs +2 -0
  94. package/dist/recipes/index.d.cts +86 -0
  95. package/dist/recipes/index.d.ts +86 -0
  96. package/dist/recipes/index.js +2 -0
  97. package/dist/recipes/metafile-cjs.json +1 -0
  98. package/dist/recipes/metafile-esm.json +1 -0
  99. package/dist/research/index.cjs +3 -0
  100. package/dist/research/index.d.cts +285 -0
  101. package/dist/research/index.d.ts +285 -0
  102. package/dist/research/index.js +3 -0
  103. package/dist/research/metafile-cjs.json +1 -0
  104. package/dist/research/metafile-esm.json +1 -0
  105. package/dist/session/index.cjs +56 -0
  106. package/dist/session/index.d.cts +523 -0
  107. package/dist/session/index.d.ts +523 -0
  108. package/dist/session/index.js +56 -0
  109. package/dist/session/metafile-cjs.json +1 -0
  110. package/dist/session/metafile-esm.json +1 -0
  111. package/dist/sharing/index.cjs +4 -0
  112. package/dist/sharing/index.d.cts +272 -0
  113. package/dist/sharing/index.d.ts +272 -0
  114. package/dist/sharing/index.js +4 -0
  115. package/dist/sharing/metafile-cjs.json +1 -0
  116. package/dist/sharing/metafile-esm.json +1 -0
  117. package/dist/skills/index.cjs +6 -0
  118. package/dist/skills/index.d.cts +277 -0
  119. package/dist/skills/index.d.ts +277 -0
  120. package/dist/skills/index.js +6 -0
  121. package/dist/skills/metafile-cjs.json +1 -0
  122. package/dist/skills/metafile-esm.json +1 -0
  123. package/dist/soul/index.cjs +32 -0
  124. package/dist/soul/index.d.cts +138 -0
  125. package/dist/soul/index.d.ts +138 -0
  126. package/dist/soul/index.js +32 -0
  127. package/dist/soul/metafile-cjs.json +1 -0
  128. package/dist/soul/metafile-esm.json +1 -0
  129. package/dist/terminal/index.cjs +4 -0
  130. package/dist/terminal/index.d.cts +55 -0
  131. package/dist/terminal/index.d.ts +55 -0
  132. package/dist/terminal/index.js +4 -0
  133. package/dist/terminal/metafile-cjs.json +1 -0
  134. package/dist/terminal/metafile-esm.json +1 -0
  135. package/dist/ui/index.cjs +35 -0
  136. package/dist/ui/index.d.cts +298 -0
  137. package/dist/ui/index.d.ts +298 -0
  138. package/dist/ui/index.js +35 -0
  139. package/dist/ui/metafile-cjs.json +1 -0
  140. package/dist/ui/metafile-esm.json +1 -0
  141. package/dist/utils/index.cjs +23 -0
  142. package/dist/utils/index.d.cts +245 -0
  143. package/dist/utils/index.d.ts +245 -0
  144. package/dist/utils/index.js +23 -0
  145. package/dist/utils/metafile-cjs.json +1 -0
  146. package/dist/utils/metafile-esm.json +1 -0
  147. package/native/mxc/LICENSE.microsoft-mxc-sdk.md +21 -0
  148. package/native/mxc/README.md +25 -0
  149. package/native/mxc/bin/arm64/lxc-exec +0 -0
  150. package/native/mxc/bin/arm64/mxc-exec-mac +0 -0
  151. package/native/mxc/bin/arm64/wxc-exec.exe +0 -0
  152. package/native/mxc/bin/arm64/wxc-host-prep.exe +0 -0
  153. package/native/mxc/bin/x64/lxc-exec +0 -0
  154. package/native/mxc/bin/x64/wxc-exec.exe +0 -0
  155. package/native/mxc/bin/x64/wxc-host-prep.exe +0 -0
  156. package/native/mxc/package.json +58 -0
  157. package/ownership/CLEAN_ROOM_CONTRIBUTOR_GUIDE.md +63 -0
  158. package/ownership/audit.mjs +727 -0
  159. package/ownership/evidence/PROPRIETARY-COMMAND-1/implementation-record.md +77 -0
  160. package/ownership/evidence/PROPRIETARY-COMMAND-1/provenance-review.md +51 -0
  161. package/ownership/evidence/PROPRIETARY-MEDIA-1/implementation-record.md +131 -0
  162. package/ownership/evidence/PROPRIETARY-MEDIA-1/provenance-review.md +50 -0
  163. package/ownership/evidence/PROPRIETARY-PTY-1/implementation-record.md +86 -0
  164. package/ownership/evidence/PROPRIETARY-PTY-1/provenance-review.md +52 -0
  165. package/ownership/evidence/PROPRIETARY-RUNTIME-1/implementation-record.md +68 -0
  166. package/ownership/evidence/PROPRIETARY-RUNTIME-1/provenance-review.md +32 -0
  167. package/ownership/evidence/PROPRIETARY-TOOLCHAIN-1/implementation-record.md +53 -0
  168. package/ownership/evidence/PROPRIETARY-TOOLCHAIN-1/provenance-review.md +32 -0
  169. package/ownership/evidence/PROPRIETARY-UI-1/implementation-record.md +96 -0
  170. package/ownership/evidence/PROPRIETARY-UI-1/provenance-review.md +46 -0
  171. package/ownership/ownership-policy.json +232 -0
  172. package/ownership/ownership-policy.schema.json +192 -0
  173. package/ownership/templates/clean-room-implementation-record.md +70 -0
  174. package/ownership/templates/provenance-review.md +51 -0
  175. package/package.json +209 -0
@@ -0,0 +1,10 @@
1
+ "use strict";var _e=Object.defineProperty;var Gt=Object.getOwnPropertyDescriptor;var Kt=Object.getOwnPropertyNames;var Yt=Object.prototype.hasOwnProperty;var Zt=(e,t)=>{for(var i in t)_e(e,i,{get:t[i],enumerable:!0})},Qt=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Kt(t))!Yt.call(e,o)&&o!==i&&_e(e,o,{get:()=>t[o],enumerable:!(n=Gt(t,o))||n.enumerable});return e};var ei=e=>Qt(_e({},"__esModule",{value:!0}),e);var In={};Zt(In,{FileXenoArtifactRepository:()=>Pe,InMemoryXenoArtifactRepository:()=>J,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION:()=>Le,XENO_ARTIFACT_SCHEMA_VERSION:()=>h,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION:()=>pe,XENO_REVIEW_REPORT_SCHEMA_VERSION:()=>Ye,XENO_SPEC_EXECUTION_SCHEMA_VERSION:()=>oe,XENO_SPEC_SCHEMA_VERSION:()=>z,XenoArtifactRepositoryError:()=>u,XenoArtifactReviewService:()=>B,XenoArtifactStateTransitionError:()=>ue,XenoArtifactValidationError:()=>L,XenoDiffParseError:()=>E,XenoEvidenceGraphBuilder:()=>Ce,XenoEvidenceGraphValidationError:()=>he,XenoMultiAgentReviewCoordinator:()=>Ke,XenoReviewValidationError:()=>R,XenoSpecLifecycleService:()=>Be,XenoSpecValidationError:()=>w,assertValidXenoArtifact:()=>I,assertValidXenoEvidenceGraph:()=>q,assertValidXenoReviewPack:()=>Ze,assertValidXenoReviewReport:()=>ae,assertValidXenoReviewTarget:()=>Qe,assertValidXenoSpecDocument:()=>Xe,assertValidXenoSpecExecution:()=>Ge,assertXenoArtifactStateTransition:()=>ee,buildXenoArtifactReviewAnchor:()=>Je,canTransitionXenoArtifactState:()=>pt,canonicalizeArtifactJson:()=>b,defaultXenoReviewPack:()=>Yi,detectXenoSpecDrift:()=>Bi,legacyAgentArtifactToXenoArtifact:()=>fn,normalizeRepositoryRelativePath:()=>Tt,parseUnifiedDiff:()=>He,sha256ArtifactBytes:()=>k,sha256ArtifactJson:()=>x,summarizeXenoArtifactReview:()=>me,toolEvidenceToXenoArtifact:()=>un,turnDiffSummaryToXenoArtifact:()=>mn,unifiedDiffToXenoArtifact:()=>je,validateXenoArtifact:()=>ft,validateXenoArtifactReviewEvent:()=>le,validateXenoEvidenceGraph:()=>lt,validateXenoSpecDocument:()=>Nt,xenoArtifactToDiffDocument:()=>qe,xenoArtifactToLegacyAgentArtifact:()=>pn,xenoArtifactToReviewReport:()=>Qi,xenoArtifactToSpecDocument:()=>ze,xenoArtifactToSpecExecution:()=>$t,xenoArtifactToToolEvidence:()=>ln,xenoArtifactToTurnDiffSummary:()=>vn,xenoReviewReportToArtifact:()=>Zi,xenoReviewReportToGitHubComments:()=>en,xenoSpecArtifactIds:()=>U,xenoSpecExecutionToArtifact:()=>We,xenoSpecToArtifactBundle:()=>Ue});module.exports=ei(In);var h=1,pe=1;var xe=require("node:buffer");var at=require("node:crypto");function k(e){return{algorithm:"sha256",value:(0,at.createHash)("sha256").update(e).digest("hex")}}function b(e){return JSON.stringify(ke(e,new Set))}function x(e){return k(b(e))}function ke(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let n=e.map(o=>ke(o,t));return t.delete(e),n}let i={};for(let n of Object.keys(e).sort((o,r)=>o.localeCompare(r))){let o=e[n];if(o===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);i[n]=ke(o,t)}return t.delete(e),i}var L=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,i){super(t),this.name="XenoArtifactValidationError",this.issues=i.map(n=>({...n}))}},ue=class extends Error{constructor(i,n){super(`Artifact state cannot transition from ${i} to ${n}`);this.fromState=i;this.toState=n;this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},ti={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},ii=/^[a-z0-9][a-z0-9._/-]{0,127}$/,ni="[\\u0000-\\u001f\\u007f]",ri=new RegExp(ni),ct=/^[a-f0-9]{64}$/,oi=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,si=new Set(["draft","pending_review","approved","rejected","superseded","archived"]),ai=new Set(["public","internal","confidential","restricted"]),ci=new Set(["agent","tool","user","system","integration"]),di=new Set(["plan","requirements","design","task-graph","patch","diff","file","document","diagram","screenshot","recording","browser-snapshot","test-report","review-report","security-report","performance-report","release-report","sbom","provenance","attestation"]),fi=new Set(["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"]),pi=new Set(["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"]);function p(e,t,i,n){e.push({path:t,code:i,message:n})}function l(e,t,i,n=1024){return typeof e!="string"||e.trim().length===0?(p(i,t,"required_string","Value must be a non-empty string"),!1):(e.length>n&&p(i,t,"string_too_long",`Value must not exceed ${n} characters`),ri.test(e)&&p(i,t,"control_character","Value must not contain control characters"),!0)}function Z(e,t,i){e!==void 0&&(!Number.isFinite(Date.parse(e))||!e.includes("T"))&&p(i,t,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function F(e,t,i,n){if(typeof e!="string"||!e.startsWith(t))return;let o=e.slice(t.length);ii.test(o)||p(n,i,"invalid_custom_name",`Custom name after ${t} is invalid`)}function dt(e,t,i){if(!e||typeof e!="object"){p(i,t,"missing_actor","Actor is required");return}l(e.kind,`${t}.kind`,i,64),ci.has(e.kind)||p(i,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),l(e.id,`${t}.id`,i,512),e?.displayName!==void 0&&l(e.displayName,`${t}.displayName`,i,512),e?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.profileFingerprint)&&p(i,`${t}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function Te(e,t,i){if(!e||typeof e!="object"){p(i,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":l(e.path,`${t}.path`,i,4096);break;case"source-line":l(e.path,`${t}.path`,i,4096),(!Number.isInteger(e.startLine)||e.startLine<1)&&p(i,`${t}.startLine`,"invalid_line","startLine must be a positive integer"),e.endLine!==void 0&&(!Number.isInteger(e.endLine)||e.endLine<e.startLine)&&p(i,`${t}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":l(e.path,`${t}.path`,i,4096),l(e.hunkId,`${t}.hunkId`,i,512);break;case"symbol":l(e.path,`${t}.path`,i,4096),l(e.symbol,`${t}.symbol`,i,1024);break;case"dom-node":l(e.pageId,`${t}.pageId`,i,512),!e.selector&&!e.accessibilityId&&!e.snapshotArtifactId&&p(i,t,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":l(e.recordingArtifactId,`${t}.recordingArtifactId`,i,512),(!Number.isFinite(e.startMs)||e.startMs<0)&&p(i,`${t}.startMs`,"invalid_time","startMs must be a non-negative finite number"),e.endMs!==void 0&&(!Number.isFinite(e.endMs)||e.endMs<e.startMs)&&p(i,`${t}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":l(e.mediaArtifactId,`${t}.mediaArtifactId`,i,512),[e.x,e.y,e.width,e.height].every(Number.isFinite)?(e.width<=0||e.height<=0)&&p(i,t,"invalid_region_size","Region width and height must be positive"):p(i,t,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":l(e.artifactId,`${t}.artifactId`,i,512);break;default:typeof e.kind!="string"||!e.kind.startsWith("custom:")?p(i,`${t}.kind`,"unknown_anchor","Anchor kind is not supported"):F(e.kind,"custom:",`${t}.kind`,i)}}function Q(e,t,i,n){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||p(i,t,"non_finite_number","JSON numbers must be finite");return}if(typeof e!="object"){p(i,t,"non_json_value","Value must be JSON-serializable");return}if(n.has(e)){p(i,t,"cyclic_value","Value must not contain cycles");return}if(n.add(e),Array.isArray(e))e.forEach((o,r)=>Q(o,`${t}[${r}]`,i,n));else for(let[o,r]of Object.entries(e))r===void 0?p(i,`${t}.${o}`,"undefined_value","Undefined is not valid JSON"):Q(r,`${t}.${o}`,i,n);n.delete(e)}}function ft(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_artifact",message:"Artifact must be an object"}];if(e.schemaVersion!==1&&p(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(e.artifactId,"artifactId",t,512),(!Number.isInteger(e.revision)||e.revision<1)&&p(t,"revision","invalid_revision","revision must be a positive integer"),l(e.kind,"kind",t,160),typeof e.kind=="string"&&!di.has(e.kind)&&!e.kind.startsWith("custom:")&&p(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),F(e.kind,"custom:","kind",t),l(e.title,"title",t,1024),e.description!==void 0&&l(e.description,"description",t,32768),l(e.state,"state",t,64),si.has(e.state)||p(t,"state","unknown_state","Artifact state is not supported"),l(e.createdAt,"createdAt",t,128),Z(e.createdAt,"createdAt",t),Z(e.updatedAt,"updatedAt",t),e.updatedAt&&Number.isFinite(Date.parse(e.createdAt))&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&p(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt"),l(e.mediaType,"mediaType",t,255),l(e.sensitivity,"sensitivity",t,64),ai.has(e.sensitivity)||p(t,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),e.identity)for(let[n,o]of Object.entries(e.identity))o!==void 0&&l(o,`identity.${n}`,t,512);if(!e.content||typeof e.content!="object")p(t,"content","missing_content","content descriptor is required");else{!e.content.hash||typeof e.content.hash!="object"?p(t,"content.hash","missing_hash","content hash is required"):(l(e.content.hash.algorithm,"content.hash.algorithm",t,128),F(e.content.hash.algorithm,"custom:","content.hash.algorithm",t),typeof e.content.hash.algorithm=="string"&&e.content.hash.algorithm!=="sha256"&&!e.content.hash.algorithm.startsWith("custom:")&&p(t,"content.hash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported"),l(e.content.hash.value,"content.hash.value",t,512),e.content.hash.algorithm==="sha256"&&!ct.test(e.content.hash.value)&&p(t,"content.hash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters")),(!Number.isSafeInteger(e.content.sizeBytes)||e.content.sizeBytes<0)&&p(t,"content.sizeBytes","invalid_size","sizeBytes must be a non-negative safe integer");let n=e.content.storage;if(!n||typeof n!="object")p(t,"content.storage","missing_storage","storage reference is required");else if(n.type==="inline")if(n.text===void 0==(n.base64===void 0))p(t,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;n.text!==void 0?o=xe.Buffer.from(n.text,"utf8"):n.base64!==void 0&&(oi.test(n.base64)?o=xe.Buffer.from(n.base64,"base64"):p(t,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),o&&e.content.sizeBytes!==o.byteLength&&p(t,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),o&&e.content.hash.algorithm==="sha256"&&k(o).value!==e.content.hash.value&&p(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else n.type==="file"?l(n.path,"content.storage.path",t,4096):n.type==="blob"?l(n.uri,"content.storage.uri",t,8192):n.type==="git"?(l(n.commit,"content.storage.commit",t,512),l(n.path,"content.storage.path",t,4096)):n.type==="url"?(l(n.url,"content.storage.url",t,8192),Z(n.expiresAt,"content.storage.expiresAt",t)):n.type==="external"?(l(n.provider,"content.storage.provider",t,255),l(n.locator,"content.storage.locator",t,8192)):p(t,"content.storage.type","unknown_storage","Storage type is not supported");e.content.encoding!==void 0&&(typeof e.content.encoding!="string"||e.content.encoding!=="utf8"&&e.content.encoding!=="base64"&&e.content.encoding!=="binary"&&!e.content.encoding.startsWith("custom:"))&&p(t,"content.encoding","unknown_encoding","Content encoding is not supported"),F(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?p(t,"provenance","missing_provenance","provenance is required"):(dt(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((n,o)=>l(n,`provenance.capabilityLeaseIds[${o}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((n,o)=>l(n,`provenance.sourceArtifactIds[${o}]`,t,512)),e.provenance.attributes&&Q(e.provenance.attributes,"provenance.attributes",t,new Set));let i=new Set;return e.relationships?.forEach((n,o)=>{let r=`relationships[${o}]`;l(n.relation,`${r}.relation`,t,160),typeof n.relation=="string"&&!pi.has(n.relation)&&!n.relation.startsWith("custom:")&&p(t,`${r}.relation`,"unknown_relationship","Relationship type is not supported"),F(n.relation,"custom:",`${r}.relation`,t),l(n.target?.type,`${r}.target.type`,t,160),typeof n.target?.type=="string"&&!fi.has(n.target.type)&&!n.target.type.startsWith("custom:")&&p(t,`${r}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),F(n.target?.type,"custom:",`${r}.target.type`,t),l(n.target?.id,`${r}.target.id`,t,512);let a=`${n.relation}:${n.target?.type}:${n.target?.id}:${n.target?.revision??""}`;i.has(a)&&p(t,r,"duplicate_relationship","Duplicate relationship"),i.add(a),n.attributes&&Q(n.attributes,`${r}.attributes`,t,new Set)}),e.anchors?.forEach((n,o)=>Te(n,`anchors[${o}]`,t)),e.revision===1&&e.predecessorRevision!==void 0&&p(t,"predecessorRevision","unexpected_predecessor","First revision cannot have a predecessor"),e.revision>1&&(!Number.isInteger(e.predecessorRevision)||(e.predecessorRevision??0)>=e.revision)&&p(t,"predecessorRevision","invalid_predecessor","Later revisions require an earlier predecessor revision"),Z(e.retention?.retainUntil,"retention.retainUntil",t),e.retention?.legalHold!==void 0&&typeof e.retention.legalHold!="boolean"&&p(t,"retention.legalHold","invalid_boolean","legalHold must be a boolean"),e.extensions&&Q(e.extensions,"extensions",t,new Set),t}function I(e){let t=ft(e);if(t.length>0)throw new L("XENO artifact validation failed",t)}function pt(e,t){return ti[e].includes(t)}function ee(e,t){if(!pt(e,t))throw new ue(e,t)}function le(e,t){let i=[];return e.schemaVersion!==1&&p(i,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(e.eventId,"eventId",i,512),l(e.artifactId,"artifactId",i,512),(!Number.isInteger(e.artifactRevision)||e.artifactRevision<1)&&p(i,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(e.sequence)||e.sequence<1)&&p(i,"sequence","invalid_sequence","sequence must be a positive integer"),l(e.recordedAt,"recordedAt",i,128),Z(e.recordedAt,"recordedAt",i),dt(e.actor,"actor",i),!e.artifactHash||typeof e.artifactHash!="object"?p(i,"artifactHash","missing_hash","Artifact hash is required"):(l(e.artifactHash.algorithm,"artifactHash.algorithm",i,128),F(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",i),l(e.artifactHash.value,"artifactHash.value",i,512),e.artifactHash.algorithm==="sha256"&&!ct.test(e.artifactHash.value)&&p(i,"artifactHash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters"),typeof e.artifactHash.algorithm=="string"&&e.artifactHash.algorithm!=="sha256"&&!e.artifactHash.algorithm.startsWith("custom:")&&p(i,"artifactHash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported")),["review-requested","comment-added","comment-resolved","comment-reopened","decision-recorded","review-withdrawn"].includes(e.type)||p(i,"type","unknown_review_event","Review event type is not supported"),e.type==="comment-added"?(l(e.commentId,"commentId",i,512),l(e.body,"body",i,65536),e.anchor&&Te(e.anchor,"anchor",i)):e.type==="comment-resolved"||e.type==="comment-reopened"?l(e.commentId,"commentId",i,512):e.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(e.decision)||p(i,"decision","unknown_review_decision","Review decision is not supported"),e.scope&&Te(e.scope,"scope",i)),t&&(e.artifactId!==t.artifactId&&p(i,"artifactId","artifact_mismatch","Review event targets a different artifact"),e.artifactRevision!==t.revision&&p(i,"artifactRevision","revision_mismatch","Review event targets a different revision"),e.artifactHash&&(e.artifactHash.algorithm!==t.content.hash.algorithm||e.artifactHash.value!==t.content.hash.value)&&p(i,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),i}function me(e){let t="not_requested",i,n,o,r=0,a=new Set,c=new Set;for(let s of[...e].sort((d,f)=>d.sequence-f.sequence))o=s.recordedAt,s.type==="review-requested"?t="pending":s.type==="review-withdrawn"?t="withdrawn":s.type==="comment-added"?(a.add(s.commentId),c.delete(s.commentId),t==="not_requested"&&(t="pending")):s.type==="comment-resolved"?c.add(s.commentId):s.type==="comment-reopened"?c.delete(s.commentId):s.type==="decision-recorded"&&(s.scope?r+=1:(i=s.decision,n=s.eventId,t=s.decision));return{status:t,totalComments:a.size,unresolvedComments:[...a].filter(s=>!c.has(s)).length,...i?{latestDecision:i}:{},...n?{latestDecisionEventId:n}:{},...r>0?{scopedDecisionCount:r}:{},...o?{lastReviewedAt:o}:{}}}var he=class extends Error{code="EVIDENCE_GRAPH_INVALID";issues;constructor(t){super("XENO evidence graph validation failed"),this.name="XenoEvidenceGraphValidationError",this.issues=t.map(i=>({...i}))}},ui=new Set(["depends_on","decomposes","supersedes"]),li=/^[a-z0-9][a-z0-9._/-]{0,127}$/,mi=new Set(["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"]),vi=new Set(["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"]);function y(e,t,i,n){e.push({path:t,code:i,message:n})}function te(e){return e.includes("T")&&Number.isFinite(Date.parse(e))}function ut(e,t){return e.startsWith("custom:")?li.test(e.slice(7)):t.has(e)}function lt(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_graph",message:"Evidence graph must be an object"}];e.schemaVersion!==1&&y(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),(typeof e.graphId!="string"||e.graphId.trim().length===0)&&y(t,"graphId","required_string","graphId must be a non-empty string"),(!Number.isInteger(e.version)||e.version<1)&&y(t,"version","invalid_version","version must be a positive integer"),te(e.createdAt)||y(t,"createdAt","invalid_timestamp","createdAt must be an ISO 8601 timestamp"),te(e.updatedAt)||y(t,"updatedAt","invalid_timestamp","updatedAt must be an ISO 8601 timestamp"),te(e.createdAt)&&te(e.updatedAt)&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&y(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt");let i=new Map;Array.isArray(e.nodes)||y(t,"nodes","invalid_nodes","nodes must be an array"),(Array.isArray(e.nodes)?e.nodes:[]).forEach((f,g)=>{let X=`nodes[${g}]`;typeof f.id!="string"||f.id.trim().length===0?y(t,`${X}.id`,"required_string","Node ID must be a non-empty string"):i.has(f.id)?y(t,`${X}.id`,"duplicate_node",`Node ID ${f.id} is duplicated`):i.set(f.id,f),(typeof f.type!="string"||!ut(f.type,mi))&&y(t,`${X}.type`,"invalid_node_type","Node type is invalid"),f.artifactRevision!==void 0&&(!Number.isInteger(f.artifactRevision)||f.artifactRevision<1)&&y(t,`${X}.artifactRevision`,"invalid_revision","artifactRevision must be a positive integer")});let n=new Set,o=new Set;Array.isArray(e.edges)||y(t,"edges","invalid_edges","edges must be an array"),(Array.isArray(e.edges)?e.edges:[]).forEach((f,g)=>{let X=`edges[${g}]`;typeof f.id!="string"||f.id.trim().length===0?y(t,`${X}.id`,"required_string","Edge ID must be a non-empty string"):n.has(f.id)&&y(t,`${X}.id`,"duplicate_edge",`Edge ID ${f.id} is duplicated`),n.add(f.id),(typeof f.type!="string"||!ut(f.type,vi))&&y(t,`${X}.type`,"invalid_edge_type","Edge type is invalid");let D=`${f.type}:${f.from}:${f.to}`;o.has(D)&&y(t,X,"duplicate_edge_identity","Equivalent evidence edge is duplicated"),o.add(D),i.has(f.from)||y(t,`${X}.from`,"dangling_reference",`Source node ${f.from} does not exist`),i.has(f.to)||y(t,`${X}.to`,"dangling_reference",`Target node ${f.to} does not exist`),f.from===f.to&&y(t,X,"self_edge","Evidence edges cannot point to the same node"),te(f.createdAt)||y(t,`${X}.createdAt`,"invalid_timestamp","createdAt must be an ISO 8601 timestamp")});let r=(Array.isArray(e.edges)?e.edges:[]).filter(f=>ui.has(f.type)),a=new Map;for(let f of r){let g=a.get(f.from)??[];g.push(f.to),a.set(f.from,g)}let c=new Set,s=new Set,d=f=>{if(c.has(f))return!0;if(s.has(f))return!1;c.add(f);for(let g of a.get(f)??[])if(d(g))return!0;return c.delete(f),s.add(f),!1};for(let f of i.keys())if(d(f)){y(t,"edges","cyclic_graph","Dependency, decomposition, and supersession edges must be acyclic");break}return t}function q(e){let t=lt(e);if(t.length>0)throw new he(t)}var Ce=class{now;graph;constructor(t){if("schemaVersion"in t)q(t),this.now=()=>new Date().toISOString(),this.graph=ve(t);else{this.now=t.now??(()=>new Date().toISOString());let i=this.now();this.graph={schemaVersion:1,graphId:t.graphId,version:1,createdAt:i,updatedAt:i,nodes:[],edges:[]},q(this.graph)}}addNode(t){let i=ve(this.graph);return i.nodes.push(mt(t)),this.touch(i),q(i),this.graph=i,this}addEdge(t){let i=ve(this.graph);return i.edges.push(vt(t)),this.touch(i),q(i),this.graph=i,this}build(){return q(this.graph),ve(this.graph)}touch(t){t.version+=1,t.updatedAt=this.now()}};function mt(e){return{...e,...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function vt(e){return{...e,...e.producer?{producer:{...e.producer}}:{},...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function ve(e){return{...e,nodes:e.nodes.map(mt),edges:e.edges.map(vt)}}var u=class extends Error{constructor(i,n,o,r){super(n,r);this.code=i;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},J=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(t={}){this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(i=>(this.idCounter+=1,`${i}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),t.initialState&&this.hydrate(t.initialState)}exportState(){let t=[...this.records.values()].flatMap(i=>[...i.values()]).sort(ht).map(i=>({artifact:ie(i.artifact),recordVersion:i.recordVersion,lifecycleEvents:structuredClone(i.lifecycleEvents),reviewEvents:structuredClone(i.reviewEvents)}));return{schemaVersion:1,records:t}}async create(t){if(I(t),this.assertInitialState(t),t.revision!==1)throw new u("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:t.artifactId,revision:t.revision});if(this.records.has(t.artifactId))throw new u("ARTIFACT_ALREADY_EXISTS",`Artifact ${t.artifactId} already exists`,{artifactId:t.artifactId});let i=ie(t),n=this.createLifecycleEvent({artifact:i,sequence:1,actor:i.provenance.producer,fromState:null,toState:i.state,reason:"artifact-created"}),o={artifact:i,recordVersion:1,lifecycleEvents:[n],reviewEvents:[]};return this.records.set(i.artifactId,new Map([[i.revision,o]])),this.currentRevisions.set(i.artifactId,i.revision),M(o)}async createRevision(t,i={}){I(t),this.assertInitialState(t);let n=this.getMutable(t.artifactId);this.assertVersion(n,i.expectedRecordVersion);let o=n.artifact.revision+1;if(t.revision!==o||t.predecessorRevision!==n.artifact.revision)throw new u("ARTIFACT_REVISION_INVALID",`Revision ${t.revision} does not follow current revision ${n.artifact.revision}`,{artifactId:t.artifactId,currentRevision:n.artifact.revision,requestedRevision:t.revision});if(gi(t,n.artifact))throw new u("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:t.artifactId,revision:t.revision});if(n.artifact.state==="archived")throw new u("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:t.artifactId,revision:n.artifact.revision});if(n.artifact.state!=="superseded"){ee(n.artifact.state,"superseded");let s=this.now(),d=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:i.actor??t.provenance.producer,fromState:n.artifact.state,toState:"superseded",reason:i.reason??`superseded-by-revision-${t.revision}`,recordedAt:s});n.artifact.state="superseded",n.artifact.updatedAt=s,n.lifecycleEvents.push(d),n.recordVersion+=1}let r=ie(t),a=this.createLifecycleEvent({artifact:r,sequence:1,actor:i.actor??r.provenance.producer,fromState:null,toState:r.state,reason:i.reason??`revision-created-from-${n.artifact.revision}`}),c={artifact:r,recordVersion:1,lifecycleEvents:[a],reviewEvents:[]};return this.records.get(r.artifactId)?.set(r.revision,c),this.currentRevisions.set(r.artifactId,r.revision),M(c)}async get(t,i){let n=this.records.get(t);if(!n)return;let o=i??this.currentRevisions.get(t);if(o===void 0)return;let r=n.get(o);return r?M(r):void 0}async require(t,i){let n=await this.get(t,i);if(!n)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${i===void 0?"":` revision ${i}`} was not found`,{artifactId:t,...i===void 0?{}:{revision:i}});return n}async list(t={}){let i=[];for(let[n,o]of this.records)if(!(t.artifactIds&&!t.artifactIds.includes(n)))if(t.includeSuperseded)i.push(...o.values());else{let r=this.currentRevisions.get(n);if(r!==void 0){let a=o.get(r);a&&i.push(a)}}return i.filter(n=>yi(n.artifact,t)).sort(ht).map(M)}async listRevisions(t){let i=this.records.get(t);return i?[...i.values()].sort((n,o)=>n.artifact.revision-o.artifact.revision).map(M):[]}async transition(t){let i=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(i,t.expectedRecordVersion),ee(i.artifact.state,t.toState),t.toState==="approved"||t.toState==="rejected"){let a=t.reviewEventId?i.reviewEvents.find(s=>s.eventId===t.reviewEventId&&s.type==="decision-recorded"):void 0,c=me(i.reviewEvents);if(!a||a.decision!==t.toState||c.latestDecisionEventId!==a.eventId)throw new u("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${t.toState} requires a matching decision event`,{artifactId:t.artifactId,revision:i.artifact.revision});if(t.toState==="approved"&&c.unresolvedComments>0)throw new u("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${c.unresolvedComments} unresolved review comment(s)`,{artifactId:t.artifactId,revision:i.artifact.revision,unresolvedComments:c.unresolvedComments})}let n=this.now(),o=i.artifact.state,r=this.createLifecycleEvent({artifact:i.artifact,sequence:i.lifecycleEvents.length+1,actor:t.actor,fromState:o,toState:t.toState,reason:t.reason,reviewEventId:t.reviewEventId,recordedAt:n});return i.artifact.state=t.toState,i.artifact.updatedAt=n,i.lifecycleEvents.push(r),i.recordVersion+=1,M(i)}async appendReviewEvent(t){let i=t.event,n=this.getMutable(i.artifactId,i.artifactRevision);if(this.assertVersion(n,t.expectedRecordVersion),n.artifact.state==="archived"||n.artifact.state==="superseded")throw new u("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${n.artifact.state} artifact revision`,{artifactId:i.artifactId,revision:i.artifactRevision});if(this.assertReviewCommentState(n,i),(i.type==="review-requested"||i.type==="review-withdrawn"||i.type==="decision-recorded")&&n.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`${i.type} requires an artifact in pending_review state`,{artifactId:i.artifactId,revision:i.artifactRevision});let o={...structuredClone(i),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:n.reviewEvents.length+1,recordedAt:this.now()},r=le(o,n.artifact);if(r.length>0)throw new L("XENO artifact review event validation failed",r);return n.reviewEvents.push(o),n.recordVersion+=1,M(n)}getMutable(t,i){let n=this.records.get(t),o=i??this.currentRevisions.get(t),r=o===void 0?void 0:n?.get(o);if(!r)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${i===void 0?"":` revision ${i}`} was not found`,{artifactId:t,...i===void 0?{}:{revision:i}});return r}assertVersion(t,i){if(i!==void 0&&i!==t.recordVersion)throw new u("ARTIFACT_CONFLICT",`Expected record version ${i}, found ${t.recordVersion}`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision,expectedRecordVersion:i,actualRecordVersion:t.recordVersion})}assertInitialState(t){if(t.state!=="draft"&&t.state!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:t.artifactId,revision:t.revision})}assertReviewCommentState(t,i){if(i.type==="comment-added"){if(t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===i.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${i.commentId} already exists`);if(i.parentCommentId&&!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===i.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Parent comment ${i.parentCommentId} does not exist`);return}if(i.type!=="comment-resolved"&&i.type!=="comment-reopened")return;if(!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===i.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${i.commentId} does not exist`);let o=Ai(t.reviewEvents,i.commentId);if(i.type==="comment-resolved"&&o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${i.commentId} is already resolved`);if(i.type==="comment-reopened"&&!o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${i.commentId} is not resolved`)}createLifecycleEvent(t){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:t.artifact.artifactId,revision:t.artifact.revision,sequence:t.sequence,recordedAt:t.recordedAt??this.now(),actor:{...t.actor},fromState:t.fromState,toState:t.toState,...t.reason?{reason:t.reason}:{},...t.reviewEventId?{reviewEventId:t.reviewEventId}:{}}}nextEventId(t){let i=this.idFactory(t);if(typeof i!="string"||i.trim().length===0||this.eventIds.has(i))throw new u("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${t} ID`);return this.eventIds.add(i),i}hydrate(t){if(t.schemaVersion!==1||!Array.isArray(t.records))throw new u("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let i=[...t.records].sort((n,o)=>n.artifact.artifactId.localeCompare(o.artifact.artifactId)||n.artifact.revision-o.artifact.revision);for(let n of i){let o=hi(n,this.eventIds),r=this.records.get(o.artifact.artifactId);if(r||(r=new Map,this.records.set(o.artifact.artifactId,r)),r.has(o.artifact.revision))throw new u("ARTIFACT_REVISION_INVALID",`Duplicate persisted revision ${o.artifact.artifactId}:${o.artifact.revision}`);r.set(o.artifact.revision,o),this.currentRevisions.set(o.artifact.artifactId,o.artifact.revision)}for(let[n,o]of this.records){let r=[...o.values()].sort((a,c)=>a.artifact.revision-c.artifact.revision);for(let a=0;a<r.length;a+=1){let c=r[a],s=a+1;if(c.artifact.revision!==s)throw new u("ARTIFACT_REVISION_INVALID",`Persisted artifact ${n} is missing revision ${s}`);if(a===0&&c.artifact.predecessorRevision!==void 0)throw new u("ARTIFACT_REVISION_INVALID",`Initial revision for ${n} cannot declare a predecessor`);if(a>0&&c.artifact.predecessorRevision!==s-1)throw new u("ARTIFACT_REVISION_INVALID",`Persisted revision ${n}:${s} has an invalid predecessor`);if(a<r.length-1&&c.artifact.state!=="superseded")throw new u("ARTIFACT_REVISION_INVALID",`Non-current revision ${n}:${s} must be superseded`)}}}};function hi(e,t){if(I(e.artifact),!Number.isInteger(e.recordVersion)||e.recordVersion<1)throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact recordVersion must be a positive integer",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(!Array.isArray(e.lifecycleEvents)||e.lifecycleEvents.length===0||!Array.isArray(e.reviewEvents))throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact records require lifecycle and review event arrays",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let i=e.lifecycleEvents.length+e.reviewEvents.length;if(e.recordVersion!==i)throw new u("ARTIFACT_REVISION_INVALID",`Persisted record version ${e.recordVersion} does not match ${i} mutations`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let n=null;for(let r=0;r<e.lifecycleEvents.length;r+=1){let a=e.lifecycleEvents[r];if(a.schemaVersion!==1||a.artifactId!==e.artifact.artifactId||a.revision!==e.artifact.revision||a.sequence!==r+1||a.fromState!==n||typeof a.eventId!="string"||a.eventId.length===0||t.has(a.eventId)||!Number.isFinite(Date.parse(a.recordedAt)))throw new u("ARTIFACT_REVISION_INVALID",`Persisted lifecycle event ${r+1} is invalid`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});if(n===null){if(a.toState!=="draft"&&a.toState!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:e.artifact.artifactId,revision:e.artifact.revision})}else ee(n,a.toState);t.add(a.eventId),n=a.toState}if(n!==e.artifact.state)throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact state does not match its lifecycle tail",{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let o=new Map;for(let r=0;r<e.reviewEvents.length;r+=1){let a=e.reviewEvents[r];if(a.sequence!==r+1||t.has(a.eventId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted review event ${r+1} has an invalid sequence or duplicate ID`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let c=le(a,e.artifact);if(c.length>0)throw new L("Persisted XENO artifact review event validation failed",c);if(a.type==="comment-added"){if(o.has(a.commentId)||a.parentCommentId!==void 0&&!o.has(a.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted comment ${a.commentId} has an invalid identity or parent`);o.set(a.commentId,!1)}else if(a.type==="comment-resolved"||a.type==="comment-reopened"){let s=o.get(a.commentId);if(s===void 0||a.type==="comment-resolved"&&s||a.type==="comment-reopened"&&!s)throw new u("ARTIFACT_REVIEW_INVALID",`Persisted comment transition for ${a.commentId} is invalid`);o.set(a.commentId,a.type==="comment-resolved")}t.add(a.eventId)}return{artifact:ie(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function gi(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function yi(e,t){return!(t.kinds&&!t.kinds.includes(e.kind)||t.states&&!t.states.includes(e.state)||t.runId&&e.identity?.runId!==t.runId||t.sessionId&&e.identity?.sessionId!==t.sessionId||t.turnId&&e.identity?.turnId!==t.turnId||t.taskId&&e.identity?.taskId!==t.taskId||t.workspaceId&&e.identity?.workspaceId!==t.workspaceId||t.repositoryId&&e.identity?.repositoryId!==t.repositoryId||t.producerId&&e.provenance.producer.id!==t.producerId||t.sensitivity&&!t.sensitivity.includes(e.sensitivity))}function ht(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function Ai(e,t){let i=!1;for(let n of e)(n.type==="comment-resolved"||n.type==="comment-reopened")&&n.commentId===t&&(i=n.type==="comment-resolved");return{resolved:i}}function ie(e){return structuredClone(e)}function M(e){return{artifact:ie(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:me(e.reviewEvents)}}var Fe=require("node:crypto"),S=require("node:fs/promises"),N=require("node:path");var $=require("node:fs"),Ne=require("node:os"),yt=require("node:path");function Ii(){return new Date().toISOString()}function wi(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function At(e){try{return JSON.parse((0,$.readFileSync)(e,"utf8"))}catch{return null}}function Ri(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Xi(e){return e.hostname!==(0,Ne.hostname)()?!0:Ri(e.pid)}function gt(e,t){(0,$.mkdirSync)((0,yt.dirname)(e),{recursive:!0}),(0,$.writeFileSync)(e,JSON.stringify(t,null,2)+`
2
+ `,{encoding:"utf8",flag:"wx"})}function Ei(e,t){let i=At(e);i?.pid!==t.pid||i.hostname!==t.hostname||(0,$.rmSync)(e,{force:!0})}function It(e,t,i){let n=Ii(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,Ne.hostname)(),processStartedAt:wi(),version:i,acquiredAt:n,updatedAt:n};try{gt(e,o)}catch(r){if(r.code!=="EEXIST")throw r;let c=At(e);if(c&&Xi(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);(0,$.rmSync)(e,{force:!0}),gt(e,o)}return{record:o,release:()=>{Ei(e,o)}}}var wt="0.8.11";var Le=1,bi="repository.v1.json",Si=5e3,_i=20,ki=64*1024*1024,Pe=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(t){if(!t||typeof t.directory!="string"||t.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let i=t.snapshotFileName??bi;if((0,N.basename)(i)!==i||!/^[A-Za-z0-9_.-]+$/.test(i))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,N.resolve)(t.directory),this.snapshotPath=(0,N.join)(this.directory,i),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=$e(t.lockTimeoutMs,Si,100,6e4,"lockTimeoutMs"),this.lockRetryMs=$e(t.lockRetryMs,_i,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=$e(t.maxSnapshotBytes,ki,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(i=>i.create(t))}async createRevision(t,i){return this.mutate(n=>n.createRevision(t,i))}async get(t,i){return(await this.load()).repository.get(t,i)}async require(t,i){return(await this.load()).repository.require(t,i)}async list(t){return(await this.load()).repository.list(t)}async listRevisions(t){return(await this.load()).repository.listRevisions(t)}async transition(t){return this.mutate(i=>i.transition(t))}async appendReviewEvent(t){return this.mutate(i=>i.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let i=await this.acquireLock();try{let n=await this.load(),o=await t(n.repository);return await this.persist(n),o}finally{i.release()}})}async enqueueMutation(t){let i=this.mutationTail.then(t,t);return this.mutationTail=i.then(()=>{},()=>{}),i}async acquireLock(){let t=Date.now(),i;for(;Date.now()-t<=this.lockTimeoutMs;)try{return It(this.lockPath,`artifact-repository:${(0,N.basename)(this.snapshotPath)}`,wt)}catch(n){if(!(n instanceof Error)||!/already locked by PID/.test(n.message))throw n;i=n,await $i(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:i})}async load(){let t,i,n=!1;try{i=await this.readSnapshot(this.snapshotPath,!1)}catch(r){t=ge(r)}if(!i&&(t||await Ni(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:t?.message??"primary snapshot missing"}),i=r,n=!0)}catch(r){throw t?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([t,ge(r)])}):r}if(!i&&t)throw t;let o=i?.state??{schemaVersion:1,records:[]};return{repository:new J({now:this.now,idFactory:r=>`${r}_${(0,Fe.randomUUID)()}`,initialState:o}),generation:i?.generation??0,createdAt:i?.createdAt??this.now(),hasSnapshot:i!==void 0,recoveredFromBackup:n,...i?{sourceSnapshot:i}:{}}}async persist(t){let i=this.now(),o={...{schemaVersion:Le,generation:t.generation,createdAt:t.createdAt,updatedAt:i,state:t.repository.exportState()},generation:t.generation+1},r=Ti(o),a=`${JSON.stringify(r,null,2)}
3
+ `;if(Buffer.byteLength(a,"utf8")>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await(0,S.mkdir)(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await Rt(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
4
+ `),await Rt(this.snapshotPath,a)}async readSnapshot(t,i){let n;try{n=await(0,S.stat)(t)}catch(o){if(!i&&De(o,"ENOENT")||i&&De(o,"ENOENT"))return;throw Oe("Unable to inspect artifact repository snapshot",t,o)}if(!n.isFile()||n.size>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:t,sizeBytes:n.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await(0,S.readFile)(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return xi(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof u?o:Oe("Unable to parse artifact repository snapshot",t,o,!0)}}};function xi(e,t){if(!Ve(e)||e.schemaVersion!==Le||!Number.isInteger(e.generation)||e.generation<0||typeof e.createdAt!="string"||!Number.isFinite(Date.parse(e.createdAt))||typeof e.updatedAt!="string"||!Number.isFinite(Date.parse(e.updatedAt))||!Ve(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!Ve(e.checksum)||e.checksum.algorithm!=="sha256"||typeof e.checksum.value!="string")throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:t});let i=e,n=Ci(i),o=Xt(n);if(i.checksum.value!==o)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new J({initialState:i.state}),structuredClone(i)}function Ti(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:Xt(e)}}}function Ci(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function Xt(e){return k(JSON.stringify(e)).value}async function Rt(e,t){await(0,S.mkdir)((0,N.dirname)(e),{recursive:!0,mode:448});let i=`${e}.tmp.${process.pid}.${(0,Fe.randomUUID)()}`,n;try{n=await(0,S.open)(i,"wx",384),await n.writeFile(t,{encoding:"utf8"}),await n.sync(),await n.close(),n=void 0,await(0,S.rename)(i,e);try{let o=await(0,S.open)((0,N.dirname)(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{n&&await n.close().catch(()=>{}),await(0,S.unlink)(i).catch(()=>{})}}function $e(e,t,i,n,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<i||e>n)throw new TypeError(`${o} must be an integer between ${i} and ${n}`);return e}function Ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function De(e,t){return e instanceof Error&&e.code===t}async function Ni(e){try{return(await(0,S.stat)(e)).isFile()}catch(t){if(De(t,"ENOENT"))return!1;throw Oe("Unable to inspect artifact repository backup",e,t)}}function ge(e){return e instanceof Error?e:new Error(String(e))}function Oe(e,t,i,n=!1){return new u(n?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${ge(i).message}`,{snapshotPath:t},{cause:ge(i)})}function $i(e){return new Promise(t=>setTimeout(t,e))}var Me=require("node:buffer");var Vi=16*1024*1024,Pi=5e3,Di=1e5,Oi=1e6,Fi=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,E=class extends Error{constructor(i,n){super(n===void 0?i:`${i} at diff line ${n}`);this.line=n;this.name="XenoDiffParseError"}line;code="XENO_DIFF_INVALID"};function He(e,t={}){if(typeof e!="string")throw new TypeError("Unified diff must be a string");let i=ye(t.maxBytes,Vi,1024,256*1024*1024,"maxBytes"),n=ye(t.maxFiles,Pi,1,1e5,"maxFiles"),o=ye(t.maxHunks,Di,1,1e6,"maxHunks"),r=ye(t.maxLines,Oi,1,5e6,"maxLines");if(Me.Buffer.byteLength(e,"utf8")>i)throw new E(`Unified diff exceeds ${i} bytes`);let a=e.replace(/\r\n/g,`
5
+ `).replace(/\r/g,`
6
+ `),c=a.length===0?[]:a.split(`
7
+ `);if(c.length>r)throw new E(`Unified diff exceeds ${r} lines`);let s=[],d,f=0,g=(v,m)=>{if(d&&Et(d,s),s.length>=n)throw new E(`Unified diff exceeds ${n} files`);return d={oldPath:v,newPath:m,status:"modified",binary:!1,headerLines:[],hunks:[]},d};for(let v=0;v<c.length;v+=1){let m=c[v];if(m.startsWith("diff --git ")){let[_,G]=Li(m.slice(11),v+1);g(_,G).headerLines.push(m);continue}if(m.startsWith("--- ")){(!d||d.hunks.length>0)&&(d=g()),d.oldPath=bt(m.slice(4)),d.headerLines.push(m);continue}if(m.startsWith("+++ ")){d||(d=g()),d.newPath=bt(m.slice(4)),d.headerLines.push(m);continue}if(m.startsWith("@@ ")){if(!d)throw new E("Hunk appears before a file header",v+1);if(f>=o)throw new E(`Unified diff exceeds ${o} hunks`,v+1);let _=Fi.exec(m);if(!_)throw new E("Malformed unified diff hunk header",v+1);let G=Number(_[1]),de=_[2]===void 0?1:Number(_[2]),Se=Number(_[3]),fe=_[4]===void 0?1:Number(_[4]),P=[],K=G,Y=Se,it=0,nt=0,O=v+1;for(;O<c.length;O+=1){let A=c[O],zt=K-G===de,Wt=Y-Se===fe;if(zt&&Wt&&A.length===0||A.startsWith("diff --git ")||A.startsWith("@@ ")||A.startsWith("--- ")&&c[O+1]?.startsWith("+++ "))break;if(A.startsWith("+"))P.push({kind:"addition",text:A.slice(1),newLine:Y}),Y+=1,it+=1;else if(A.startsWith("-"))P.push({kind:"deletion",text:A.slice(1),oldLine:K}),K+=1,nt+=1;else if(A.startsWith(" "))P.push({kind:"context",text:A.slice(1),oldLine:K,newLine:Y}),K+=1,Y+=1;else if(A==="\")P.push({kind:"no-newline",text:A});else{if(A.length===0&&O===c.length-1)break;throw new E("Unexpected line inside unified diff hunk",O+1)}}let rt=P.filter(A=>A.kind==="context"||A.kind==="deletion").length,ot=P.filter(A=>A.kind==="context"||A.kind==="addition").length;if(rt!==de||ot!==fe)throw new E(`Hunk line counts do not match header (expected -${de}/+${fe}, observed -${rt}/+${ot})`,v+1);let st=m,Ut=k(JSON.stringify({oldPath:d.oldPath??null,newPath:d.newPath??null,header:st,lines:P})).value.slice(0,32);d.hunks.push({hunkId:Ut,header:st,..._[5]?{section:_[5]}:{},oldStart:G,oldLines:de,newStart:Se,newLines:fe,additions:it,deletions:nt,lines:P}),f+=1,v=O-1;continue}if(!d){if(m.trim().length===0)continue;throw new E("Content appears before the first diff file header",v+1)}d.headerLines.push(m),m.startsWith("new file mode ")?d.status="added":m.startsWith("deleted file mode ")?d.status="deleted":m.startsWith("rename from ")?(d.status="renamed",d.oldPath=H(m.slice(12))):m.startsWith("rename to ")?(d.status="renamed",d.newPath=H(m.slice(10))):m.startsWith("copy from ")?(d.status="copied",d.oldPath=H(m.slice(10))):m.startsWith("copy to ")?(d.status="copied",d.newPath=H(m.slice(8))):(m.startsWith("Binary files ")||m==="GIT binary patch")&&(d.binary=!0,d.status="binary")}d&&Et(d,s);let X=s.reduce((v,m)=>v+m.additions,0),D=s.reduce((v,m)=>v+m.deletions,0);return{schemaVersion:1,mode:t.mode??"working-tree",...t.repositoryId?{repositoryId:t.repositoryId}:{},...t.baseRef?{baseRef:t.baseRef}:{},...t.headRef?{headRef:t.headRef}:{},files:s,additions:X,deletions:D,rawDiff:a}}function je(e,t){let i=He(e,{mode:t.mode,repositoryId:t.repositoryId,baseRef:t.baseRef,headRef:t.headRef}),n=i,o=b(n),r=[t.identity?.runId,t.identity?.turnId,t.identity?.taskId,t.repositoryId,t.mode].filter(Boolean).join(":"),a=t.kind??"diff",c=t.artifactId??`${a}_${k(`${r}:${i.rawDiff}`).value.slice(0,24)}`,s=t.revision??1,d={schemaVersion:1,artifactId:c,revision:s,kind:a,title:t.title??`${ji(i.mode)} diff (${i.files.length} files)`,...t.description?{description:t.description}:{},state:"pending_review",createdAt:t.createdAt??new Date().toISOString(),mediaType:`application/vnd.xeno.${a}+json`,sensitivity:t.sensitivity??"internal",...t.identity?{identity:structuredClone(t.identity)}:{},content:{hash:x(n),sizeBytes:Me.Buffer.byteLength(o,"utf8"),encoding:"utf8",storage:{type:"inline",text:o},redactedPreview:`${i.files.length} files, +${i.additions}/-${i.deletions}`},provenance:{producer:{...t.producer}},anchors:i.files.flatMap(f=>[{kind:"file",path:f.displayPath,...t.repositoryId?{repositoryId:t.repositoryId}:{}},...f.hunks.map(g=>({kind:"diff-hunk",path:f.displayPath,hunkId:g.hunkId,artifactId:c,revision:s}))]),...s>1?{predecessorRevision:t.predecessorRevision??s-1}:{},...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.diff.mode":i.mode,"xeno.diff.files":i.files.length,"xeno.diff.additions":i.additions,"xeno.diff.deletions":i.deletions}};return I(d),d}function qe(e){if(I(e),e.kind!=="diff"&&e.kind!=="patch")throw new TypeError("Artifact is not a diff or patch");if(e.content.storage.type!=="inline"||typeof e.content.storage.text!="string")throw new TypeError("Diff artifact content is not available inline");let t;try{t=JSON.parse(e.content.storage.text)}catch(n){throw new E(`Diff artifact JSON is malformed: ${qi(n).message}`)}if(!Hi(t))throw new E("Diff artifact document is invalid");let i=He(t.rawDiff,{mode:t.mode,repositoryId:t.repositoryId,baseRef:t.baseRef,headRef:t.headRef});if(b(i)!==b(t))throw new E("Diff artifact document does not match its raw diff");return i}function Et(e,t){if(!e.oldPath&&!e.newPath)throw new E("Diff file has no path");e.oldPath||(e.status="added"),e.newPath||(e.status="deleted"),e.binary&&(e.status="binary");let i=e.hunks.reduce((o,r)=>o+r.additions,0),n=e.hunks.reduce((o,r)=>o+r.deletions,0);t.push({...e.oldPath?{oldPath:e.oldPath}:{},...e.newPath?{newPath:e.newPath}:{},displayPath:e.newPath??e.oldPath,status:e.status,additions:i,deletions:n,binary:e.binary,headerLines:[...e.headerLines],hunks:structuredClone(e.hunks)})}function Li(e,t){let i=Mi(e);if(i.length!==2)throw new E("Malformed diff --git path pair",t);return[H(i[0]),H(i[1])]}function Mi(e){let t=[],i=0;for(;i<e.length;){for(;e[i]===" ";)i+=1;if(i>=e.length)break;if(e[i]==='"'){let n='"';i+=1;let o=!1;for(;i<e.length;){let r=e[i];if(n+=r,i+=1,!o&&r==='"')break;o=!o&&r==="\\",r!=="\\"&&(o=!1)}t.push(_t(n))}else{let n=e.indexOf(" ",i);if(n===-1){t.push(e.slice(i));break}t.push(e.slice(i,n)),i=n+1}}return t}function _t(e){return!e.startsWith('"')||!e.endsWith('"')?e:e.slice(1,-1).replace(/\\([\\"tnr]|[0-7]{1,3})/g,(i,n)=>n==="t"?" ":n==="n"?`
8
+ `:n==="r"?"\r":n==="\\"?"\\":n==='"'?'"':String.fromCharCode(Number.parseInt(n,8)))}function bt(e){let t=e.split(" ",1)[0].trim();if(t!=="/dev/null")return H(_t(t))}function H(e){let t=e.replace(/\\/g,"/");return t.startsWith("a/")||t.startsWith("b/")?t.slice(2):t}function Hi(e){return!St(e)||e.schemaVersion!==1||!["working-tree","staged","turn","commit","preview"].includes(String(e.mode))||!Array.isArray(e.files)||!Number.isSafeInteger(e.additions)||!Number.isSafeInteger(e.deletions)||typeof e.rawDiff!="string"?!1:e.files.every(t=>St(t)&&typeof t.displayPath=="string"&&Array.isArray(t.headerLines)&&Array.isArray(t.hunks))}function St(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ye(e,t,i,n,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<i||e>n)throw new TypeError(`${o} must be an integer between ${i} and ${n}`);return e}function ji(e){return e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" ")}function qi(e){return e instanceof Error?e:new Error(String(e))}var xt=require("node:crypto");var B=class{repository;actor;idFactory;constructor(t){if(!t?.repository)throw new TypeError("Artifact repository is required");if(!t.actor?.kind||!t.actor.id?.trim())throw new TypeError("Review actor is required");this.repository=t.repository,this.actor=structuredClone(t.actor),this.idFactory=t.idFactory??(()=>`comment_${(0,xt.randomUUID)()}`)}async addComment(t){let i=Ie(t.body,"Review comment body",65536),n=await this.repository.require(t.artifactId,t.revision),o=Je(n,t),r=Ae(this.idFactory(),"Comment ID"),a=Ji(t.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:"comment-added",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,commentId:r,body:i,...o?{anchor:o}:{},...a?{parentCommentId:a}:{}}})}async setCommentResolution(t){let i=Ae(t.commentId,"Review comment ID"),n=kt(t.reason,"Resolution reason",16*1024),o=await this.repository.require(t.artifactId,t.revision);return this.repository.appendReviewEvent({expectedRecordVersion:o.recordVersion,event:{type:t.resolved?"comment-resolved":"comment-reopened",artifactId:o.artifact.artifactId,artifactRevision:o.artifact.revision,artifactHash:o.artifact.content.hash,actor:this.actor,commentId:i,...n?{reason:n}:{}}})}async decide(t){let i=await this.repository.require(t.artifactId,t.revision);if(i.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${i.artifact.state}`);let n=Je(i,t),o=kt(t.rationale,"Decision rationale",64*1024),r=await this.repository.appendReviewEvent({expectedRecordVersion:i.recordVersion,event:{type:"decision-recorded",artifactId:i.artifact.artifactId,artifactRevision:i.artifact.revision,artifactHash:i.artifact.content.hash,actor:this.actor,decision:t.decision,...o?{rationale:o}:{},...n?{scope:n}:{}}});if(n||t.decision==="changes_requested")return r;let a=r.reviewEvents.at(-1);if(!a||a.type!=="decision-recorded")throw new u("ARTIFACT_REVIEW_INVALID","Artifact decision event was not recorded");return this.repository.transition({artifactId:r.artifact.artifactId,revision:r.artifact.revision,expectedRecordVersion:r.recordVersion,toState:t.decision,actor:this.actor,reviewEventId:a.eventId,...o?{reason:o}:{}})}};function Je(e,t){if((t.line!==void 0||t.hunkId!==void 0)&&!t.file)throw V("Line and hunk anchors require a file");if(t.line!==void 0&&t.hunkId!==void 0)throw V("Line and hunk anchors cannot be combined");if(!t.file)return;let i=Tt(t.file);if(t.line!==void 0&&(!Number.isInteger(t.line)||t.line<1))throw V("Review line must be a positive integer");if(e.artifact.kind==="diff"||e.artifact.kind==="patch"){let o=qe(e.artifact).files.find(r=>r.displayPath===i);if(!o)throw V(`File ${i} is not present in this artifact`);if(t.hunkId&&!o.hunks.some(r=>r.hunkId===t.hunkId))throw V(`Hunk ${t.hunkId} is not present in ${i}`)}return t.hunkId?{kind:"diff-hunk",path:i,hunkId:Ae(t.hunkId,"Hunk ID"),artifactId:e.artifact.artifactId,revision:e.artifact.revision}:t.line!==void 0?{kind:"source-line",path:i,startLine:t.line}:{kind:"file",path:i}}function Tt(e){let t=Ie(e,"Artifact review file",4096).replace(/\\/g,"/").replace(/^\.\//,"");if(t.startsWith("../")||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").some(i=>i===".."||i.length===0))throw V("Artifact review file anchors must be repository-relative paths");return t}function Ie(e,t,i){let n=typeof e=="string"?e.trim():"";if(!n)throw V(`${t} cannot be empty`);if(n.length>i)throw V(`${t} exceeds ${i} characters`);return n}function kt(e,t,i){if(e!==void 0)return Ie(e,t,i)}function Ae(e,t){let i=Ie(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(i))throw V(`${t} contains unsupported characters`);return i}function Ji(e,t){return e===void 0?void 0:Ae(e,t)}function V(e){return new u("ARTIFACT_REVIEW_INVALID",e)}var Ct=require("node:crypto");var z="xeno.spec.v1",oe="xeno.spec-execution.v1",w=class extends Error{constructor(i){super(`XENO spec is invalid: ${i.join("; ")}`);this.issues=i;this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},Be=class{repository;now;idFactory;constructor(t){if(!t?.repository)throw new TypeError("Artifact repository is required");this.repository=t.repository,this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(()=>(0,Ct.randomUUID)())}async create(t,i){if(t.revision!==1||t.predecessorRevision!==void 0)throw new w(["A new spec must begin at revision 1 without a predecessor"]);let n=Ue(t,i);return await this.repository.create(n.requirements),await this.repository.create(n.design),await this.repository.create(n.taskGraph),await this.repository.create(n.plan),n}async revise(t,i){let n=U(t.specId),o=await this.repository.require(n.plan);if(t.revision!==o.artifact.revision+1||t.predecessorRevision!==o.artifact.revision)throw new w([`Revision ${t.revision} must follow approved or reviewed revision ${o.artifact.revision}`]);let r=Ue(t,i);return await this.repository.createRevision(r.requirements,{actor:i.producer,reason:"spec-revised"}),await this.repository.createRevision(r.design,{actor:i.producer,reason:"spec-revised"}),await this.repository.createRevision(r.taskGraph,{actor:i.producer,reason:"spec-revised"}),await this.repository.createRevision(r.plan,{actor:i.producer,reason:"spec-revised"}),r}async approve(t,i,n){return new B({repository:this.repository,actor:i}).decide({artifactId:U(t).plan,decision:"approved",...n?{rationale:n}:{}})}async reject(t,i,n){return new B({repository:this.repository,actor:i}).decide({artifactId:U(t).plan,decision:"rejected",rationale:n})}async startExecution(t,i){let n=await this.repository.require(U(t).plan);if(n.artifact.state!=="approved")throw new w([`Spec ${t} must be approved before execution`]);let o=ze(n.artifact),r=this.now(),a={schemaVersion:oe,executionId:`spec_execution_${this.idFactory()}`,specId:o.specId,specRevision:o.revision,planArtifactId:n.artifact.artifactId,planHash:{...n.artifact.content.hash},state:"ready",createdAt:r,updatedAt:r,observedPaths:[],tasks:o.tasks.map(c=>({taskId:c.id,status:"pending",evidence:[],acceptanceEvidence:Object.fromEntries(c.acceptanceCriterionIds.map(s=>[s,[]]))}))};return this.repository.create(We(a,{producer:i,identity:n.artifact.identity,sensitivity:n.artifact.sensitivity,accessPolicyId:n.artifact.accessPolicyId}))}async updateExecution(t,i,n){let o=await this.repository.require(t),r=$t(o.artifact),a=await this.repository.require(r.planArtifactId,r.specRevision);if(a.artifact.state!=="approved"||!se(a.artifact.content.hash,r.planHash))throw new w(["Execution is no longer bound to the approved plan revision"]);let c=i(structuredClone(r));c.schemaVersion=oe,c.executionId=r.executionId,c.specId=r.specId,c.specRevision=r.specRevision,c.planArtifactId=r.planArtifactId,c.planHash={...r.planHash},c.createdAt=r.createdAt,c.updatedAt=this.now(),Ge(c,ze(a.artifact));let s=We(c,{producer:n,identity:o.artifact.identity,sensitivity:o.artifact.sensitivity,accessPolicyId:o.artifact.accessPolicyId},o.artifact.revision+1,o.artifact.revision);return this.repository.createRevision(s,{actor:n,reason:"spec-execution-updated"})}};function U(e){let t=zi(e,"specId");return{plan:`spec_${t}_plan`,requirements:`spec_${t}_requirements`,design:`spec_${t}_design`,taskGraph:`spec_${t}_task_graph`}}function Nt(e){let t=[];e?.schemaVersion!==z&&t.push(`schemaVersion must be ${z}`),re(e?.specId,"specId",t),(!Number.isInteger(e?.revision)||e.revision<1)&&t.push("revision must be a positive integer"),T(e?.title,"title",t),T(e?.problem,"problem",t),Re(e?.createdAt,"createdAt",t),Re(e?.updatedAt,"updatedAt",t),e?.predecessorRevision!==void 0&&(!Number.isInteger(e.predecessorRevision)||e.predecessorRevision!==e.revision-1)&&t.push("predecessorRevision must be the immediately preceding revision");let i=we(e?.requirements,"requirement",t),n=we(e?.tasks,"task",t),o=new Set,r=[...Array.isArray(e?.acceptanceCriteria)?e.acceptanceCriteria:[],...Array.isArray(e?.requirements)?e.requirements.flatMap(s=>Array.isArray(s.acceptanceCriteria)?s.acceptanceCriteria:[]):[]];for(let s of r){re(s?.id,"acceptance criterion id",t),T(s?.text,`acceptance criterion ${s?.id??"?"}`,t),o.has(s?.id)&&t.push(`Duplicate acceptance criterion: ${s?.id}`),o.add(s?.id);for(let d of s?.requiredEvidenceKinds??[])re(d,"required evidence kind",t)}for(let s of e?.requirements??[])T(s?.text,`requirement ${s?.id??"?"}`,t),["must","should","could"].includes(s?.priority)||t.push(`Requirement ${s?.id??"?"} has invalid priority`),(!Array.isArray(s?.acceptanceCriteria)||s.acceptanceCriteria.length===0)&&t.push(`Requirement ${s?.id??"?"} needs at least one acceptance criterion`);T(e?.design?.summary,"design summary",t);let a=we(e?.design?.decisions,"design decision",t),c=we(e?.design?.risks,"risk",t);for(let s of e?.design?.decisions??[]){T(s?.decision,`design decision ${s?.id??"?"}`,t),T(s?.rationale,`design rationale ${s?.id??"?"}`,t);for(let d of s?.requirementIds??[])i.has(d)||t.push(`Design decision ${s.id} references unknown requirement ${d}`)}for(let s of e?.design?.risks??[])T(s?.description,`risk ${s?.id??"?"}`,t),T(s?.mitigation,`risk mitigation ${s?.id??"?"}`,t),["low","medium","high","critical"].includes(s?.impact)||t.push(`Risk ${s?.id??"?"} has invalid impact`);for(let s of e?.tasks??[]){T(s?.title,`task title ${s?.id??"?"}`,t),T(s?.description,`task description ${s?.id??"?"}`,t);for(let d of s?.dependsOn??[])n.has(d)||t.push(`Task ${s.id} depends on unknown task ${d}`),d===s.id&&t.push(`Task ${s.id} cannot depend on itself`);for(let d of s?.requirementIds??[])i.has(d)||t.push(`Task ${s.id} references unknown requirement ${d}`);for(let d of s?.acceptanceCriterionIds??[])o.has(d)||t.push(`Task ${s.id} references unknown acceptance criterion ${d}`);for(let d of s?.expectedPaths??[])Pt(d)||t.push(`Task ${s.id} has unsafe expected path ${d}`)}return Wi(e?.tasks??[])&&t.push("Task dependency graph contains a cycle"),[...new Set(t)]}function Xe(e){let t=Nt(e);if(t.length>0)throw new w(t)}function Ue(e,t){Xe(e);let i=U(e.specId),n=e.revision,o={...t,createdAt:e.updatedAt,state:"draft"},r=ne({artifactId:i.requirements,revision:n,predecessorRevision:e.predecessorRevision,kind:"requirements",title:`${e.title} - requirements`,value:{schemaVersion:z,specId:e.specId,revision:n,problem:e.problem,requirements:e.requirements,acceptanceCriteria:e.acceptanceCriteria},context:o}),a=ne({artifactId:i.design,revision:n,predecessorRevision:e.predecessorRevision,kind:"design",title:`${e.title} - design`,value:{schemaVersion:z,specId:e.specId,revision:n,design:e.design,...e.sourceBaseline?{sourceBaseline:e.sourceBaseline}:{}},context:o}),c=ne({artifactId:i.taskGraph,revision:n,predecessorRevision:e.predecessorRevision,kind:"task-graph",title:`${e.title} - task graph`,value:{schemaVersion:z,specId:e.specId,revision:n,tasks:e.tasks},context:o}),s=[r,a,c].map(f=>({relation:"decomposes",target:{type:"artifact",id:f.artifactId,revision:f.revision}})),d=ne({artifactId:i.plan,revision:n,predecessorRevision:e.predecessorRevision,kind:"plan",title:e.title,description:e.problem,value:e,context:{...t,createdAt:e.updatedAt,state:"pending_review"},relationships:s,extensions:{"xeno.spec.id":e.specId,"xeno.spec.revision":e.revision,"xeno.spec.requirements_hash":r.content.hash.value,"xeno.spec.design_hash":a.content.hash.value,"xeno.spec.task_graph_hash":c.content.hash.value}});return{document:structuredClone(e),plan:d,requirements:r,design:a,taskGraph:c}}function ze(e){if(e.kind!=="plan"||e.mediaType!=="application/vnd.xeno.spec+json")throw new w([`Artifact ${e.artifactId} is not a XENO spec plan`]);let t=Vt(e);if(Xe(t),t.revision!==e.revision)throw new w(["Spec and artifact revisions differ"]);if(!se(x(t),e.content.hash))throw new w(["Spec artifact content hash is invalid"]);return structuredClone(t)}function We(e,t,i=1,n){let o=structuredClone(e);return ne({artifactId:e.executionId,revision:i,predecessorRevision:n,kind:"custom:xeno.spec-execution",title:`Execution of ${e.specId} revision ${e.specRevision}`,description:`Execution state: ${e.state}`,value:o,context:{...t,createdAt:e.updatedAt,state:e.state==="completed"?"pending_review":"draft"},relationships:[{relation:"implements",target:{type:"artifact",id:e.planArtifactId,revision:e.specRevision}}],extensions:{"xeno.spec.execution_state":e.state,"xeno.spec.plan_hash":e.planHash.value}})}function $t(e){if(e.kind!=="custom:xeno.spec-execution")throw new w([`Artifact ${e.artifactId} is not a spec execution`]);let t=Vt(e);if(t.schemaVersion!==oe||t.executionId!==e.artifactId)throw new w(["Spec execution identity or schema is invalid"]);if(!se(x(t),e.content.hash))throw new w(["Spec execution content hash is invalid"]);return structuredClone(t)}function Ge(e,t){let i=[];e.schemaVersion!==oe&&i.push("Execution schema is invalid"),(e.specId!==t.specId||e.specRevision!==t.revision)&&i.push("Execution is bound to the wrong spec revision");let n=new Map(t.tasks.map(r=>[r.id,r])),o=new Set;for(let r of e.tasks){o.has(r.taskId)&&i.push(`Duplicate execution task ${r.taskId}`),o.add(r.taskId);let a=n.get(r.taskId);if(!a){i.push(`Unknown execution task ${r.taskId}`);continue}for(let c of a.acceptanceCriterionIds)Array.isArray(r.acceptanceEvidence?.[c])||i.push(`Task ${r.taskId} is missing acceptance evidence slot ${c}`)}for(let r of n.keys())o.has(r)||i.push(`Execution is missing task ${r}`);for(let r of e.observedPaths)Gi(r)||i.push(`Unsafe observed path ${r}`);if(Re(e.createdAt,"execution createdAt",i),Re(e.updatedAt,"execution updatedAt",i),i.length>0)throw new w([...new Set(i)])}function Bi(e,t,i,n,o=new Date().toISOString()){Xe(e),Ge(i,e);let r=[];(!se(t,n)||!se(i.planHash,n))&&r.push({code:"PLAN_HASH_MISMATCH",severity:"error",message:"Execution is not bound to the approved plan content hash"});let a=new Map(e.tasks.map(d=>[d.id,d])),c=new Map(i.tasks.map(d=>[d.taskId,d]));for(let d of i.tasks){let f=a.get(d.taskId);if(!f){r.push({code:"UNKNOWN_TASK",severity:"error",taskId:d.taskId,message:`Unknown task ${d.taskId}`});continue}if(d.status==="completed"){d.evidence.length===0&&r.push({code:"MISSING_TASK_EVIDENCE",severity:"error",taskId:f.id,message:`Completed task ${f.id} has no evidence`});for(let g of f.dependsOn??[])c.get(g)?.status!=="completed"&&r.push({code:"DEPENDENCY_INCOMPLETE",severity:"error",taskId:f.id,message:`Task ${f.id} completed before dependency ${g}`});for(let g of f.acceptanceCriterionIds)(d.acceptanceEvidence[g]??[]).length===0&&r.push({code:"MISSING_ACCEPTANCE_EVIDENCE",severity:"error",taskId:f.id,criterionId:g,message:`Completed task ${f.id} has no evidence for ${g}`})}}let s=e.tasks.flatMap(d=>d.expectedPaths??[]);for(let d of i.observedPaths)s.some(f=>Ki(d,f))||r.push({code:"UNKNOWN_PATH",severity:"warning",path:d,message:`Observed path ${d} is outside the approved task plan`});return{schemaVersion:"xeno.spec-drift.v1",specId:e.specId,specRevision:e.revision,executionId:i.executionId,checkedAt:o,drifted:r.length>0,findings:r}}function ne(e){let t=e.value,i=b(t);return{schemaVersion:1,artifactId:e.artifactId,revision:e.revision,kind:e.kind,title:e.title,...e.description?{description:e.description}:{},state:e.context.state,createdAt:e.context.createdAt??new Date().toISOString(),mediaType:Ui(e.kind),sensitivity:e.context.sensitivity??"internal",...e.context.identity?{identity:structuredClone(e.context.identity)}:{},content:{hash:x(t),sizeBytes:Buffer.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i},redactedPreview:e.title},provenance:{producer:structuredClone(e.context.producer)},...e.relationships?.length?{relationships:structuredClone(e.relationships)}:{},...e.predecessorRevision!==void 0?{predecessorRevision:e.predecessorRevision}:{},...e.context.accessPolicyId?{accessPolicyId:e.context.accessPolicyId}:{},...e.extensions?{extensions:structuredClone(e.extensions)}:{}}}function Ui(e){return e==="plan"?"application/vnd.xeno.spec+json":e==="custom:xeno.spec-execution"?"application/vnd.xeno.spec-execution+json":`application/vnd.xeno.spec-${e}+json`}function Vt(e){let t=e.content.storage;if(t.type!=="inline"||typeof t.text!="string")throw new w(["Spec artifacts require inline JSON content"]);try{return JSON.parse(t.text)}catch(i){throw new w([`Spec artifact JSON is invalid: ${i instanceof Error?i.message:String(i)}`])}}function we(e,t,i){let n=new Set;(!Array.isArray(e)||e.length===0)&&i.push(`${t} list cannot be empty`);for(let o of e??[])re(o?.id,`${t} id`,i),n.has(o?.id??"")&&i.push(`Duplicate ${t}: ${o?.id}`),o?.id&&n.add(o.id);return n}function re(e,t,i){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(e))&&i.push(`${t} must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}`)}function T(e,t,i){(typeof e!="string"||e.trim().length===0||e.length>64*1024)&&i.push(`${t} must be non-empty and no longer than 65536 characters`)}function Re(e,t,i){(typeof e!="string"||!e.includes("T")||!Number.isFinite(Date.parse(e)))&&i.push(`${t} must be an ISO 8601 timestamp`)}function zi(e,t){let i=[];if(re(e,t,i),i.length>0)throw new w(i);return e}function Wi(e){let t=new Map(e.map(r=>[r.id,r])),i=new Set,n=new Set,o=r=>{if(i.has(r))return!0;if(n.has(r))return!1;i.add(r);for(let a of t.get(r)?.dependsOn??[])if(o(a))return!0;return i.delete(r),n.add(r),!1};return e.some(r=>o(r.id))}function Pt(e){let t=e.replace(/\\/gu,"/");return t.length>0&&t.length<=4096&&!t.startsWith("/")&&!/^[A-Za-z]:/u.test(t)&&!t.split("/").includes("..")}function Gi(e){return Pt(e)&&!e.includes("*")}function Ki(e,t){let i=e.replace(/\\/gu,"/"),n=t.replace(/\\/gu,"/");if(n.endsWith("/**")){let o=n.slice(0,-3).replace(/\/$/u,"");return i===o||i.startsWith(`${o}/`)}if(n.endsWith("/*")){let o=n.slice(0,-2).replace(/\/$/u,""),r=i.startsWith(`${o}/`)?i.slice(o.length+1):"";return r.length>0&&!r.includes("/")}return i===n}function se(e,t){return e.algorithm===t.algorithm&&e.value===t.value}var Dt=require("node:crypto");var Ye="xeno.review-report.v1",R=class extends Error{constructor(i){super(`XENO review is invalid: ${i.join("; ")}`);this.issues=i;this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},Ke=class{reviewer;verifier;now;idFactory;constructor(t){if(typeof t?.reviewer!="function")throw new TypeError("Review agent executor is required");this.reviewer=t.reviewer,this.verifier=t.verifier,this.now=t.now??(()=>new Date().toISOString()),this.idFactory=t.idFactory??(i=>`${i}_${(0,Dt.randomUUID)()}`)}async run(t){Ze(t.pack),Qe(t.target),Ee(t.runId,"runId");let i=this.now(),n=await Promise.all(t.pack.dimensions.map(async(s,d)=>{let f=await this.reviewer({...t,dimension:s,reviewerSlot:d});return rn(f,s,t.pack.maxFindings),structuredClone(f)})),o=n.flatMap(s=>s.findings.map(d=>({finding:d,reviewerAgentId:s.reviewerAgentId})));if(o.length>t.pack.maxFindings)throw new R([`Reviewers returned ${o.length} findings, exceeding maxFindings ${t.pack.maxFindings}`]);let r=tn(o,this.idFactory);for(let s of r){let d=this.verifier?await Promise.all(Array.from({length:t.pack.verifierCount},async(v,m)=>{let _=await this.verifier({...t,finding:structuredClone(s),verifierSlot:m});return on(_),structuredClone(_)})):[];s.verifications=sn(d),s.evidence=Ft([...s.evidence,...s.verifications.flatMap(v=>v.evidence)]);let f=new Set(s.verifications.filter(v=>v.outcome==="reproduced").map(v=>v.verifierAgentId)).size,g=s.verifications.length>0&&s.verifications.every(v=>v.outcome==="rejected"),X=new Set(s.evidence.map(v=>v.producerId)).size;f>=t.pack.minimumVerifierReproductions?(s.state="verified",s.verificationBasis="verifier"):t.pack.allowIndependentEvidenceVerification&&X>=t.pack.minimumIndependentEvidenceProducers?(s.state="verified",s.verificationBasis="independent-evidence"):g?(s.state="rejected",s.verificationBasis="verifier"):(s.state="unverified",s.verificationBasis="none");let D=s.verifications.map(v=>v.confidence).filter(v=>v!==void 0);D.length>0&&(s.confidence=Jt(Math.min(s.confidence,...D)))}r.sort(an);let a=this.now(),c={schemaVersion:Ye,reportId:Ee(this.idFactory("report"),"reportId"),runId:t.runId,pack:structuredClone(t.pack),target:structuredClone(t.target),startedAt:i,completedAt:a,reviewers:n.map(s=>({agentId:s.reviewerAgentId,dimension:s.dimension,findingCount:s.findings.length})),findings:r,summary:Ht(r)};return ae(c),c}};function Yi(e="xeno-production-review"){return{schemaVersion:"xeno.review-pack.v1",packId:e,version:"1.0.0",dimensions:["correctness","security","performance","api","tests","documentation"],verifierCount:1,minimumVerifierReproductions:1,allowIndependentEvidenceVerification:!1,minimumIndependentEvidenceProducers:2,maxFindings:256}}function Ze(e){let t=[];e?.schemaVersion!=="xeno.review-pack.v1"&&t.push("Review pack schemaVersion must be xeno.review-pack.v1"),C(e?.packId,"packId",t),(typeof e?.version!="string"||!/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/u.test(e.version))&&t.push("Review pack version must be semantic version text"),(!Array.isArray(e?.dimensions)||e.dimensions.length===0)&&t.push("Review pack needs at least one dimension"),new Set(e?.dimensions??[]).size!==(e?.dimensions??[]).length&&t.push("Review pack dimensions must be unique");for(let i of e?.dimensions??[])qt(i)||t.push(`Invalid review dimension ${i}`);if((!Number.isInteger(e?.verifierCount)||e.verifierCount<0||e.verifierCount>8)&&t.push("verifierCount must be 0 through 8"),(!Number.isInteger(e?.minimumVerifierReproductions)||e.minimumVerifierReproductions<1||e.minimumVerifierReproductions>Math.max(1,e.verifierCount))&&t.push("minimumVerifierReproductions must be positive and no greater than verifierCount"),(!Number.isInteger(e?.minimumIndependentEvidenceProducers)||e.minimumIndependentEvidenceProducers<2)&&t.push("minimumIndependentEvidenceProducers must be at least 2"),(!Number.isInteger(e?.maxFindings)||e.maxFindings<1||e.maxFindings>2048)&&t.push("maxFindings must be 1 through 2048"),t.length>0)throw new R(t)}function Qe(e){let t=[];if(C(e?.artifactId,"target artifactId",t),(!Number.isInteger(e?.revision)||e.revision<1)&&t.push("Target revision must be positive"),j(e?.title,"target title",t),(e?.contentHash?.algorithm!=="sha256"||!/^[a-f0-9]{64}$/u.test(e?.contentHash?.value??""))&&t.push("Target contentHash must be lowercase sha256"),t.length>0)throw new R(t)}function ae(e){let t=[];e?.schemaVersion!==Ye&&t.push("Review report schemaVersion is invalid"),C(e?.reportId,"reportId",t),C(e?.runId,"runId",t),be(e?.startedAt,"startedAt",t),be(e?.completedAt,"completedAt",t),Date.parse(e?.completedAt)<Date.parse(e?.startedAt)&&t.push("completedAt cannot precede startedAt");try{Ze(e.pack)}catch(r){t.push(r instanceof Error?r.message:String(r))}try{Qe(e.target)}catch(r){t.push(r instanceof Error?r.message:String(r))}let i=new Set,n=new Set;for(let r of e?.findings??[])C(r?.findingId,"findingId",t),i.has(r.findingId)&&t.push(`Duplicate findingId ${r.findingId}`),i.add(r.findingId),/^[a-f0-9]{64}$/u.test(r?.fingerprint??"")||t.push(`Finding ${r.findingId} has invalid fingerprint`),n.has(r.fingerprint)&&t.push(`Duplicate finding fingerprint ${r.fingerprint}`),n.add(r.fingerprint),j(r?.title,`finding ${r.findingId} title`,t),j(r?.summary,`finding ${r.findingId} summary`,t),jt(r?.severity)||t.push(`Finding ${r.findingId} has invalid severity`),(!Number.isFinite(r?.confidence)||r.confidence<0||r.confidence>1)&&t.push(`Finding ${r.findingId} has invalid confidence`),r?.state==="verified"&&r.verificationBasis==="none"&&t.push(`Finding ${r.findingId} cannot be verified without a basis`),r?.state!=="verified"&&r.verificationBasis==="independent-evidence"&&t.push(`Finding ${r.findingId} has inconsistent evidence verification`);let o=Ht(e?.findings??[]);if((o.total!==e?.summary?.total||o.verified!==e?.summary?.verified||o.unverified!==e?.summary?.unverified||o.rejected!==e?.summary?.rejected||Object.keys(o.bySeverity).some(r=>o.bySeverity[r]!==e?.summary?.bySeverity?.[r]))&&t.push("Review report summary is inconsistent"),t.length>0)throw new R([...new Set(t)])}function Zi(e,t){ae(e);let i=e,n=b(i),o=t.artifactId??`review_${k(`${e.runId}:${e.target.artifactId}:${e.target.contentHash.value}`).value.slice(0,24)}`,r={schemaVersion:1,artifactId:o,revision:1,kind:"review-report",title:`Review of ${e.target.title}`,description:`${e.summary.verified} verified, ${e.summary.unverified} unverified, ${e.summary.rejected} rejected findings`,state:"pending_review",createdAt:t.createdAt??e.completedAt,mediaType:"application/vnd.xeno.review-report+json",sensitivity:t.sensitivity??"internal",...t.identity?{identity:structuredClone(t.identity)}:{},content:{hash:x(i),sizeBytes:Buffer.byteLength(n,"utf8"),encoding:"utf8",storage:{type:"inline",text:n},redactedPreview:`${e.summary.total} findings; ${e.summary.verified} verified`},provenance:{producer:structuredClone(t.producer),sourceArtifactIds:[e.target.artifactId],attributes:{reviewPackId:e.pack.packId,reviewPackVersion:e.pack.version}},relationships:[{relation:"reviews",target:{type:"artifact",id:e.target.artifactId,revision:e.target.revision}}],anchors:Lt(e.findings.flatMap(a=>a.anchors)),...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.review.pack":e.pack.packId,"xeno.review.verified":e.summary.verified,"xeno.review.unverified":e.summary.unverified,"xeno.review.rejected":e.summary.rejected}};return I(r),r}function Qi(e){if(e.kind!=="review-report"||e.mediaType!=="application/vnd.xeno.review-report+json")throw new R([`Artifact ${e.artifactId} is not a XENO review report`]);if(e.content.storage.type!=="inline"||typeof e.content.storage.text!="string")throw new R(["Review report requires inline JSON content"]);let t;try{t=JSON.parse(e.content.storage.text)}catch(i){throw new R([`Review report JSON is invalid: ${i instanceof Error?i.message:String(i)}`])}if(ae(t),!dn(x(t),e.content.hash))throw new R(["Review report content hash is invalid"]);return structuredClone(t)}function en(e,t={}){ae(e);let i=[];for(let n of e.findings){if(t.verifiedOnly!==!1&&n.state!=="verified")continue;let o=n.anchors.find(r=>r.kind==="source-line"||r.kind==="file"||r.kind==="diff-hunk");!o||!("path"in o)||i.push({findingId:n.findingId,path:o.path,...o.kind==="source-line"?{line:o.startLine}:{},severity:n.severity,verified:n.state==="verified",body:[`**${n.severity.toUpperCase()} - ${n.title}**`,"",n.summary,"",`Evidence: ${n.evidence.map(r=>r.summary).join("; ")||"none"}`,n.remediation?`Suggested remediation: ${n.remediation}`:"",`XENO finding: ${n.findingId} (${n.state}, confidence ${n.confidence.toFixed(2)})`].filter(Boolean).join(`
9
+ `)})}return i}function tn(e,t){let i=new Map;for(let n of e){Ot(n.finding),Ee(n.reviewerAgentId,"reviewerAgentId");let o=nn(n.finding),r=i.get(o)??[];r.push(structuredClone(n)),i.set(o,r)}return[...i.entries()].map(([n,o])=>{let r=[...o].sort((c,s)=>W(s.finding.severity)-W(c.finding.severity))[0],a=Ft(o.flatMap(c=>c.finding.evidence));return{findingId:Ee(t("finding"),"findingId"),fingerprint:n,ruleIds:[...new Set(o.flatMap(c=>c.finding.ruleId?[c.finding.ruleId]:[]))].sort(),dimensions:[...new Set(o.map(c=>c.finding.dimension))].sort(),reviewerAgentIds:[...new Set(o.map(c=>c.reviewerAgentId))].sort(),title:r.finding.title,summary:r.finding.summary,severity:o.reduce((c,s)=>W(s.finding.severity)>W(c)?s.finding.severity:c,r.finding.severity),confidence:Jt(Math.max(...o.map(c=>c.finding.confidence))),state:"unverified",verificationBasis:"none",anchors:Lt(o.flatMap(c=>c.finding.anchors)),evidence:a,verifications:[],...r.finding.remediation?{remediation:r.finding.remediation}:{},duplicateProposalCount:o.length}})}function nn(e){let t=e.anchors.map(Mt).sort();return x({ruleId:e.ruleId??"",title:cn(e.title),anchors:t}).value}function rn(e,t,i){let n=[];C(e?.reviewerAgentId,"reviewerAgentId",n),e?.dimension!==t&&n.push(`Reviewer returned dimension ${e?.dimension} for requested ${t}`),be(e?.completedAt,"reviewer completedAt",n),(!Array.isArray(e?.findings)||e.findings.length>i)&&n.push("Reviewer finding list is invalid or exceeds maxFindings");for(let o of e?.findings??[]){try{Ot(o)}catch(r){n.push(r instanceof Error?r.message:String(r))}o.dimension!==t&&n.push(`Finding dimension ${o.dimension} differs from reviewer dimension ${t}`)}if(n.length>0)throw new R([...new Set(n)])}function Ot(e){let t=[];qt(e?.dimension)||t.push(`Invalid finding dimension ${e?.dimension}`),j(e?.title,"finding title",t),j(e?.summary,"finding summary",t),jt(e?.severity)||t.push(`Invalid finding severity ${e?.severity}`),(!Number.isFinite(e?.confidence)||e.confidence<0||e.confidence>1)&&t.push("Finding confidence must be 0 through 1"),(!Array.isArray(e?.anchors)||e.anchors.length===0)&&t.push("Finding needs at least one source or artifact anchor"),Array.isArray(e?.evidence)||t.push("Finding evidence must be an array");for(let i of e?.evidence??[])et(i,t);if(e?.ruleId!==void 0&&C(e.ruleId,"ruleId",t),t.length>0)throw new R([...new Set(t)])}function on(e){let t=[];C(e?.verifierAgentId,"verifierAgentId",t),["reproduced","rejected","inconclusive"].includes(e?.outcome)||t.push("Verifier outcome is invalid"),j(e?.rationale,"verifier rationale",t),be(e?.completedAt,"verifier completedAt",t),Array.isArray(e?.evidence)||t.push("Verifier evidence must be an array");for(let i of e?.evidence??[])et(i,t);if(e?.outcome==="reproduced"&&(e?.evidence?.length??0)===0&&t.push("A reproduced finding requires verifier evidence"),e?.confidence!==void 0&&(!Number.isFinite(e.confidence)||e.confidence<0||e.confidence>1)&&t.push("Verifier confidence must be 0 through 1"),t.length>0)throw new R([...new Set(t)])}function et(e,t){C(e?.evidenceId,"evidenceId",t),C(e?.producerId,"evidence producerId",t),j(e?.summary,"evidence summary",t),(typeof e?.kind!="string"||!(/^(?:source|test|trace|artifact|reproduction|benchmark)$/u.test(e.kind)||/^custom:[a-z0-9][a-z0-9._/-]{0,127}$/u.test(e.kind)))&&t.push(`Invalid evidence kind ${e?.kind}`)}function Ft(e){let t=new Map;for(let i of e){let n=[];if(et(i,n),n.length>0)throw new R(n);let o=t.get(i.evidenceId);if(o&&b(o)!==b(i))throw new R([`Conflicting evidence ID ${i.evidenceId}`]);t.set(i.evidenceId,structuredClone(i))}return[...t.values()].sort((i,n)=>i.evidenceId.localeCompare(n.evidenceId))}function sn(e){let t=new Map;for(let i of e){if(t.has(i.verifierAgentId))throw new R([`Verifier ${i.verifierAgentId} returned more than one result for a finding`]);t.set(i.verifierAgentId,structuredClone(i))}return[...t.values()].sort((i,n)=>i.verifierAgentId.localeCompare(n.verifierAgentId))}function Lt(e){let t=new Map;for(let i of e)t.set(Mt(i),structuredClone(i));return[...t.entries()].sort(([i],[n])=>i.localeCompare(n)).map(([,i])=>i)}function Mt(e){return b(e)}function Ht(e){let t={info:0,low:0,medium:0,high:0,critical:0};for(let i of e)t[i.severity]+=1;return{total:e.length,verified:e.filter(i=>i.state==="verified").length,unverified:e.filter(i=>i.state==="unverified").length,rejected:e.filter(i=>i.state==="rejected").length,bySeverity:t}}function an(e,t){return W(t.severity)-W(e.severity)||+(t.state==="verified")-+(e.state==="verified")||e.fingerprint.localeCompare(t.fingerprint)}function W(e){return{info:0,low:1,medium:2,high:3,critical:4}[e]}function jt(e){return typeof e=="string"&&["info","low","medium","high","critical"].includes(e)}function qt(e){return typeof e=="string"&&(["correctness","security","performance","api","tests","documentation"].includes(e)||/^custom:[a-z0-9][a-z0-9._/-]{0,127}$/u.test(e))}function cn(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function Jt(e){return Math.max(0,Math.min(1,Number(e.toFixed(6))))}function C(e,t,i){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u.test(e))&&i.push(`${t} has an invalid identifier`)}function Ee(e,t){let i=[];if(C(e,t,i),i.length>0)throw new R(i);return e}function j(e,t,i){(typeof e!="string"||e.trim().length===0||e.length>64*1024)&&i.push(`${t} must be non-empty and no longer than 65536 characters`)}function be(e,t,i){(typeof e!="string"||!e.includes("T")||!Number.isFinite(Date.parse(e)))&&i.push(`${t} must be an ISO 8601 timestamp`)}function dn(e,t){return e.algorithm===t.algorithm&&e.value===t.value}var ce=require("node:buffer");function fn(e,t){let i=t.contentEncoding??"utf8",n=i==="base64"?ce.Buffer.from(e.content,"base64"):ce.Buffer.from(e.content,"utf8"),o=[t.identity?.runId,t.identity?.taskId,t.identity?.turnId].filter(Boolean).join(":"),r=k(`${o}:${e.name}:${e.mimeType??""}:${e.content}`).value.slice(0,24),a={schemaVersion:1,artifactId:t.artifactId??`legacy_agent_artifact_${r}`,revision:t.revision??1,kind:t.kind??hn(e),title:e.name,state:t.state??"draft",createdAt:t.createdAt??new Date().toISOString(),mediaType:e.mimeType??"text/plain",sensitivity:t.sensitivity??"internal",...t.identity?{identity:structuredClone(t.identity)}:{},content:{hash:k(n),sizeBytes:n.byteLength,encoding:i,storage:i==="base64"?{type:"inline",base64:e.content}:{type:"inline",text:e.content}},provenance:{producer:{...t.producer}},...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.legacy.agentArtifact":{name:e.name,...e.mimeType?{mimeType:e.mimeType}:{},content:e.content,encoding:i}}};return I(a),a}function pn(e){I(e);let t=e.extensions?.["xeno.legacy.agentArtifact"];if(tt(t)&&typeof t.name=="string"&&typeof t.content=="string")return{name:t.name,...typeof t.mimeType=="string"?{mimeType:t.mimeType}:{},content:t.content};if(e.content.storage.type!=="inline")throw new TypeError("Only inline XENO artifacts can be converted to legacy AgentArtifact values");return{name:e.title,mimeType:e.mediaType,content:e.content.storage.text??e.content.storage.base64??""}}function un(e,t){let i=Bt(e),n=b(i),o={schemaVersion:1,artifactId:t.artifactId??e.id,revision:t.revision??1,kind:gn(e),title:e.path?`Evidence for ${e.path}`:`Tool evidence ${e.id}`,state:t.state??"draft",createdAt:t.createdAt??e.observedAt,mediaType:"application/vnd.xeno.tool-evidence+json",sensitivity:t.sensitivity??"internal",...t.identity?{identity:structuredClone(t.identity)}:{},content:{hash:x(i),sizeBytes:ce.Buffer.byteLength(n,"utf8"),encoding:"utf8",storage:{type:"inline",text:n}},provenance:{producer:{...t.producer},operationId:e.operationId,attributes:{legacyEvidenceId:e.id,legacyEvidenceKind:e.kind,legacyEvidenceStatus:e.status}},...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.legacy.toolEvidence":i}};return I(o),o}function ln(e){I(e);let t=e.extensions?.["xeno.legacy.toolEvidence"];if(yn(t))return structuredClone(t);throw new TypeError("XENO artifact does not contain lossless legacy ToolEvidence data")}function mn(e,t){let i=Bt(e),n=e.files.map(a=>a.patch).filter(a=>!!a);if(e.files.length>0&&n.length===e.files.length&&n.every(a=>a.startsWith("diff --git ")))try{let a=je(n.join(`
10
+ `),{artifactId:t.artifactId??`turn_diff_${e.turnId}`,revision:t.revision??1,createdAt:t.createdAt??e.completedAt,title:`Turn ${e.turnId} changes`,producer:t.producer,identity:{...t.identity?structuredClone(t.identity):{},turnId:t.identity?.turnId??e.turnId},sensitivity:t.sensitivity??"internal",...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},mode:"turn"}),c={...a,state:t.state??a.state,extensions:{...a.extensions??{},"xeno.legacy.turnDiffSummary":i}};return I(c),c}catch{}let o=b(i),r={schemaVersion:1,artifactId:t.artifactId??`turn_diff_${e.turnId}`,revision:t.revision??1,kind:"diff",title:`Turn ${e.turnId} changes`,state:t.state??"pending_review",createdAt:t.createdAt??e.completedAt,mediaType:"application/vnd.xeno.turn-diff+json",sensitivity:t.sensitivity??"internal",identity:{...t.identity?structuredClone(t.identity):{},turnId:t.identity?.turnId??e.turnId},content:{hash:x(i),sizeBytes:ce.Buffer.byteLength(o,"utf8"),encoding:"utf8",storage:{type:"inline",text:o}},provenance:{producer:{...t.producer}},anchors:e.files.map(a=>({kind:"custom:source-file",data:{path:a.path}})),...t.accessPolicyId?{accessPolicyId:t.accessPolicyId}:{},extensions:{"xeno.legacy.turnDiffSummary":i}};return I(r),r}function vn(e){I(e);let t=e.extensions?.["xeno.legacy.turnDiffSummary"];if(An(t))return structuredClone(t);throw new TypeError("XENO artifact does not contain lossless TurnDiffSummary data")}function hn(e){let t=e.name.toLowerCase(),i=e.mimeType?.toLowerCase()??"";return t.endsWith(".patch")||i.includes("patch")?"patch":t.endsWith(".diff")||i.includes("diff")?"diff":i.startsWith("image/")?"screenshot":i.startsWith("video/")?"recording":i.includes("json")&&t.includes("report")?"test-report":"file"}function gn(e){return e.kind==="artifact"?e.path?"file":"custom:tool-artifact-evidence":e.kind==="verification"?"test-report":"custom:tool-process-evidence"}function Bt(e){return JSON.parse(JSON.stringify(e))}function tt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yn(e){return tt(e)?typeof e.id=="string"&&(e.kind==="artifact"||e.kind==="process"||e.kind==="verification")&&(e.status==="pending"||e.status==="verified"||e.status==="failed")&&typeof e.observedAt=="string"&&typeof e.operationId=="string":!1}function An(e){return tt(e)?typeof e.turnId=="string"&&typeof e.startedAt=="string"&&typeof e.completedAt=="string"&&Array.isArray(e.files):!1}0&&(module.exports={FileXenoArtifactRepository,InMemoryXenoArtifactRepository,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION,XENO_ARTIFACT_SCHEMA_VERSION,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION,XENO_REVIEW_REPORT_SCHEMA_VERSION,XENO_SPEC_EXECUTION_SCHEMA_VERSION,XENO_SPEC_SCHEMA_VERSION,XenoArtifactRepositoryError,XenoArtifactReviewService,XenoArtifactStateTransitionError,XenoArtifactValidationError,XenoDiffParseError,XenoEvidenceGraphBuilder,XenoEvidenceGraphValidationError,XenoMultiAgentReviewCoordinator,XenoReviewValidationError,XenoSpecLifecycleService,XenoSpecValidationError,assertValidXenoArtifact,assertValidXenoEvidenceGraph,assertValidXenoReviewPack,assertValidXenoReviewReport,assertValidXenoReviewTarget,assertValidXenoSpecDocument,assertValidXenoSpecExecution,assertXenoArtifactStateTransition,buildXenoArtifactReviewAnchor,canTransitionXenoArtifactState,canonicalizeArtifactJson,defaultXenoReviewPack,detectXenoSpecDrift,legacyAgentArtifactToXenoArtifact,normalizeRepositoryRelativePath,parseUnifiedDiff,sha256ArtifactBytes,sha256ArtifactJson,summarizeXenoArtifactReview,toolEvidenceToXenoArtifact,turnDiffSummaryToXenoArtifact,unifiedDiffToXenoArtifact,validateXenoArtifact,validateXenoArtifactReviewEvent,validateXenoEvidenceGraph,validateXenoSpecDocument,xenoArtifactToDiffDocument,xenoArtifactToLegacyAgentArtifact,xenoArtifactToReviewReport,xenoArtifactToSpecDocument,xenoArtifactToSpecExecution,xenoArtifactToToolEvidence,xenoArtifactToTurnDiffSummary,xenoReviewReportToArtifact,xenoReviewReportToGitHubComments,xenoSpecArtifactIds,xenoSpecExecutionToArtifact,xenoSpecToArtifactBundle});