@xenosystem/agent-sdk 0.9.27 → 0.9.28

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 (58) hide show
  1. package/THIRD_PARTY_NOTICES.md +89 -0
  2. package/dist/artifacts/index.cjs +6 -6
  3. package/dist/artifacts/index.js +6 -6
  4. package/dist/artifacts/metafile-cjs.json +1 -1
  5. package/dist/artifacts/metafile-esm.json +1 -1
  6. package/dist/automation/index.cjs +1 -1
  7. package/dist/automation/index.js +1 -1
  8. package/dist/automation/metafile-cjs.json +1 -1
  9. package/dist/automation/metafile-esm.json +1 -1
  10. package/dist/control-plane/index.cjs +7 -7
  11. package/dist/control-plane/index.js +7 -7
  12. package/dist/control-plane/metafile-cjs.json +1 -1
  13. package/dist/control-plane/metafile-esm.json +1 -1
  14. package/dist/control-room/index.cjs +1 -1
  15. package/dist/control-room/index.d.cts +2 -1
  16. package/dist/control-room/index.d.ts +2 -1
  17. package/dist/control-room/index.js +1 -1
  18. package/dist/control-room/metafile-cjs.json +1 -1
  19. package/dist/control-room/metafile-esm.json +1 -1
  20. package/dist/coordination/index.cjs +2 -2
  21. package/dist/coordination/index.d.cts +70 -4
  22. package/dist/coordination/index.d.ts +70 -4
  23. package/dist/coordination/index.js +2 -2
  24. package/dist/coordination/metafile-cjs.json +1 -1
  25. package/dist/coordination/metafile-esm.json +1 -1
  26. package/dist/electron/index.cjs +151 -151
  27. package/dist/electron/index.d.cts +81 -0
  28. package/dist/electron/index.d.ts +81 -0
  29. package/dist/electron/index.js +153 -153
  30. package/dist/electron/metafile-cjs.json +1 -1
  31. package/dist/electron/metafile-esm.json +1 -1
  32. package/dist/hosted/metafile-cjs.json +1 -1
  33. package/dist/hosted/metafile-esm.json +1 -1
  34. package/dist/index.cjs +334 -334
  35. package/dist/index.d.cts +541 -364
  36. package/dist/index.d.ts +541 -364
  37. package/dist/index.js +331 -331
  38. package/dist/metafile-cjs.json +1 -1
  39. package/dist/metafile-esm.json +1 -1
  40. package/dist/providers/index.cjs +10 -10
  41. package/dist/providers/index.d.cts +15 -1
  42. package/dist/providers/index.d.ts +15 -1
  43. package/dist/providers/index.js +10 -10
  44. package/dist/providers/metafile-cjs.json +1 -1
  45. package/dist/providers/metafile-esm.json +1 -1
  46. package/dist/recipes/index.cjs +1 -1
  47. package/dist/recipes/index.js +2 -2
  48. package/dist/recipes/metafile-cjs.json +1 -1
  49. package/dist/recipes/metafile-esm.json +1 -1
  50. package/dist/research/metafile-cjs.json +1 -1
  51. package/dist/research/metafile-esm.json +1 -1
  52. package/dist/session/index.cjs +24 -24
  53. package/dist/session/index.d.cts +49 -1
  54. package/dist/session/index.d.ts +49 -1
  55. package/dist/session/index.js +24 -24
  56. package/dist/session/metafile-cjs.json +1 -1
  57. package/dist/session/metafile-esm.json +1 -1
  58. package/package.json +2 -1
@@ -0,0 +1,89 @@
1
+ # Third-Party Notices
2
+
3
+ This index accompanies the XENO Agent SDK npm distribution. Runtime dependency
4
+ versions below are the versions resolved for this candidate; separately installed
5
+ packages also carry their own notices. Consumers must preserve those notices when
6
+ redistributing dependencies.
7
+
8
+ The component list was reconciled with the candidate package and its dependency
9
+ SBOM. Microsoft assets are vendored under `native/mxc`; their original licence
10
+ also remains beside them. Inclusion here does not resolve the separate MXC binary
11
+ licence-metadata findings or constitute a release approval.
12
+
13
+ ## @primno/dpapi@2.0.1
14
+
15
+ Licence text from `node_modules/@primno/dpapi/LICENSE`:
16
+
17
+ MIT License
18
+
19
+ Copyright (c) 2023 Xavier Monin
20
+
21
+ Permission is hereby granted, free of charge, to any person obtaining a copy
22
+ of this software and associated documentation files (the "Software"), to deal
23
+ in the Software without restriction, including without limitation the rights
24
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
25
+ copies of the Software, and to permit persons to whom the Software is
26
+ furnished to do so, subject to the following conditions:
27
+
28
+ The above copyright notice and this permission notice shall be included in all
29
+ copies or substantial portions of the Software.
30
+
31
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
34
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
36
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
37
+ SOFTWARE.
38
+
39
+ ## node-gyp-build@4.8.4
40
+
41
+ Licence text from `node_modules/node-gyp-build/LICENSE`:
42
+
43
+ The MIT License (MIT)
44
+
45
+ Copyright (c) 2017 Mathias Buus
46
+
47
+ Permission is hereby granted, free of charge, to any person obtaining a copy
48
+ of this software and associated documentation files (the "Software"), to deal
49
+ in the Software without restriction, including without limitation the rights
50
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
51
+ copies of the Software, and to permit persons to whom the Software is
52
+ furnished to do so, subject to the following conditions:
53
+
54
+ The above copyright notice and this permission notice shall be included in
55
+ all copies or substantial portions of the Software.
56
+
57
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
58
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
59
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
60
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
61
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
62
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
63
+ THE SOFTWARE.
64
+
65
+ ## @microsoft/mxc-sdk@0.7.0
66
+
67
+ Licence text from `native/mxc/LICENSE.microsoft-mxc-sdk.md`:
68
+
69
+ MIT License
70
+
71
+ Copyright (c) Microsoft Corporation.
72
+
73
+ Permission is hereby granted, free of charge, to any person obtaining a copy
74
+ of this software and associated documentation files (the "Software"), to deal
75
+ in the Software without restriction, including without limitation the rights
76
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
77
+ copies of the Software, and to permit persons to whom the Software is
78
+ furnished to do so, subject to the following conditions:
79
+
80
+ The above copyright notice and this permission notice shall be included in all
81
+ copies or substantial portions of the Software.
82
+
83
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
84
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
85
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
86
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
87
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
88
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
89
+ SOFTWARE
@@ -1,10 +1,10 @@
1
- "use strict";var xe=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var an=Object.getOwnPropertyNames;var cn=Object.prototype.hasOwnProperty;var dn=(e,t)=>{for(var n in t)xe(e,n,{get:t[n],enumerable:!0})},fn=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of an(t))!cn.call(e,o)&&o!==n&&xe(e,o,{get:()=>t[o],enumerable:!(i=sn(t,o))||i.enumerable});return e};var pn=e=>fn(xe({},"__esModule",{value:!0}),e);var ki={};dn(ki,{FileXenoArtifactRepository:()=>qe,InMemoryXenoArtifactRepository:()=>B,XENO_ARTIFACT_ACTOR_KINDS:()=>Pe,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION:()=>We,XENO_ARTIFACT_SCHEMA_VERSION:()=>h,XENO_ARTIFACT_SENSITIVITIES:()=>Ve,XENO_ARTIFACT_STATES:()=>Ne,XENO_BUILTIN_ARTIFACT_KINDS:()=>Ce,XENO_EVIDENCE_EDGE_TYPES:()=>ee,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION:()=>me,XENO_EVIDENCE_NODE_TYPES:()=>Q,XENO_REVIEW_DIMENSIONS:()=>Bt,XENO_REVIEW_EVIDENCE_KINDS:()=>Ut,XENO_REVIEW_REPORT_SCHEMA_VERSION:()=>ot,XENO_SPEC_EXECUTION_SCHEMA_VERSION:()=>ce,XENO_SPEC_SCHEMA_VERSION:()=>z,XenoArtifactRepositoryError:()=>u,XenoArtifactReviewService:()=>U,XenoArtifactStateTransitionError:()=>ve,XenoArtifactValidationError:()=>M,XenoDiffParseError:()=>X,XenoEvidenceGraphBuilder:()=>Le,XenoEvidenceGraphValidationError:()=>ye,XenoMultiAgentReviewCoordinator:()=>rt,XenoReviewValidationError:()=>E,XenoSpecLifecycleService:()=>Qe,XenoSpecValidationError:()=>w,assertValidXenoArtifact:()=>I,assertValidXenoEvidenceGraph:()=>J,assertValidXenoReviewPack:()=>st,assertValidXenoReviewReport:()=>fe,assertValidXenoReviewTarget:()=>at,assertValidXenoSpecDocument:()=>be,assertValidXenoSpecExecution:()=>it,assertXenoArtifactStateTransition:()=>ie,buildXenoArtifactReviewAnchor:()=>Ze,canTransitionXenoArtifactState:()=>yt,canonicalizeArtifactJson:()=>S,defaultXenoReviewPack:()=>ai,detectXenoSpecDrift:()=>ti,legacyAgentArtifactToXenoArtifact:()=>yi,normalizeRepositoryRelativePath:()=>Ft,parseUnifiedDiff:()=>Ke,sha256ArtifactBytes:()=>T,sha256ArtifactJson:()=>k,summarizeXenoArtifactReview:()=>ge,toolEvidenceToXenoArtifact:()=>wi,turnDiffSummaryToXenoArtifact:()=>Ri,unifiedDiffToXenoArtifact:()=>Ge,validateXenoArtifact:()=>At,validateXenoArtifactReviewEvent:()=>he,validateXenoEvidenceGraph:()=>wt,validateXenoSpecDocument:()=>Mt,xenoArtifactToDiffDocument:()=>Ye,xenoArtifactToLegacyAgentArtifact:()=>Ii,xenoArtifactToReviewReport:()=>di,xenoArtifactToSpecDocument:()=>tt,xenoArtifactToSpecExecution:()=>Ht,xenoArtifactToToolEvidence:()=>Ei,xenoArtifactToTurnDiffSummary:()=>Xi,xenoReviewReportToArtifact:()=>ci,xenoReviewReportToGitHubComments:()=>fi,xenoSpecArtifactIds:()=>W,xenoSpecExecutionToArtifact:()=>nt,xenoSpecToArtifactBundle:()=>et});module.exports=pn(ki);var h=1,me=1,Ce=["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"],Ne=["draft","pending_review","approved","rejected","superseded","archived"],Ve=["public","internal","confidential","restricted"],Pe=["agent","tool","user","system","integration"],Q=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],ee=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var De=require("node:buffer");var vt=require("node:crypto");function T(e){return{algorithm:"sha256",value:(0,vt.createHash)("sha256").update(e).digest("hex")}}function S(e){return JSON.stringify($e(e,new Set))}function k(e){return T(S(e))}function $e(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 i=e.map(o=>$e(o,t));return t.delete(e),i}let n={};for(let i of Object.keys(e).sort((o,r)=>o.localeCompare(r))){let o=e[i];if(o===void 0)throw new TypeError(`Artifact JSON property ${i} is undefined`);n[i]=$e(o,t)}return t.delete(e),n}var un=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Oe="custom:";function F(e,t=Oe){return e.startsWith(t)?un.test(e.slice(t.length)):!1}var M=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,n){super(t),this.name="XenoArtifactValidationError",this.issues=n.map(i=>({...i}))}},ve=class extends Error{constructor(n,i){super(`Artifact state cannot transition from ${n} to ${i}`);this.fromState=n;this.toState=i;this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},ln={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},mn="[\\u0000-\\u001f\\u007f]",vn=new RegExp(mn),ht=/^[a-f0-9]{64}$/,hn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,gn=new Set(Ne),An=new Set(Ve),yn=new Set(Pe),In=new Set(Ce),wn=new Set(Q),En=new Set(ee);function p(e,t,n,i){e.push({path:t,code:n,message:i})}function l(e,t,n,i=1024){return typeof e!="string"||e.trim().length===0?(p(n,t,"required_string","Value must be a non-empty string"),!1):(e.length>i&&p(n,t,"string_too_long",`Value must not exceed ${i} characters`),vn.test(e)&&p(n,t,"control_character","Value must not contain control characters"),!0)}function te(e,t,n){e!==void 0&&(!Number.isFinite(Date.parse(e))||!e.includes("T"))&&p(n,t,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function L(e,t,n,i){typeof e=="string"&&e.startsWith(t)&&(F(e,t)||p(i,n,"invalid_custom_name",`Custom name after ${t} is invalid`))}function gt(e,t,n){if(!e||typeof e!="object"){p(n,t,"missing_actor","Actor is required");return}l(e.kind,`${t}.kind`,n,64),yn.has(e.kind)||p(n,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),l(e.id,`${t}.id`,n,512),e?.displayName!==void 0&&l(e.displayName,`${t}.displayName`,n,512),e?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.profileFingerprint)&&p(n,`${t}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function Fe(e,t,n){if(!e||typeof e!="object"){p(n,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":l(e.path,`${t}.path`,n,4096);break;case"source-line":l(e.path,`${t}.path`,n,4096),(!Number.isInteger(e.startLine)||e.startLine<1)&&p(n,`${t}.startLine`,"invalid_line","startLine must be a positive integer"),e.endLine!==void 0&&(!Number.isInteger(e.endLine)||e.endLine<e.startLine)&&p(n,`${t}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":l(e.path,`${t}.path`,n,4096),l(e.hunkId,`${t}.hunkId`,n,512);break;case"symbol":l(e.path,`${t}.path`,n,4096),l(e.symbol,`${t}.symbol`,n,1024);break;case"dom-node":l(e.pageId,`${t}.pageId`,n,512),!e.selector&&!e.accessibilityId&&!e.snapshotArtifactId&&p(n,t,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":l(e.recordingArtifactId,`${t}.recordingArtifactId`,n,512),(!Number.isFinite(e.startMs)||e.startMs<0)&&p(n,`${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(n,`${t}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":l(e.mediaArtifactId,`${t}.mediaArtifactId`,n,512),[e.x,e.y,e.width,e.height].every(Number.isFinite)?(e.width<=0||e.height<=0)&&p(n,t,"invalid_region_size","Region width and height must be positive"):p(n,t,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":l(e.artifactId,`${t}.artifactId`,n,512);break;default:typeof e.kind!="string"||!e.kind.startsWith("custom:")?p(n,`${t}.kind`,"unknown_anchor","Anchor kind is not supported"):L(e.kind,"custom:",`${t}.kind`,n)}}function ne(e,t,n,i){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||p(n,t,"non_finite_number","JSON numbers must be finite");return}if(typeof e!="object"){p(n,t,"non_json_value","Value must be JSON-serializable");return}if(i.has(e)){p(n,t,"cyclic_value","Value must not contain cycles");return}if(i.add(e),Array.isArray(e))e.forEach((o,r)=>ne(o,`${t}[${r}]`,n,i));else for(let[o,r]of Object.entries(e))r===void 0?p(n,`${t}.${o}`,"undefined_value","Undefined is not valid JSON"):ne(r,`${t}.${o}`,n,i);i.delete(e)}}function At(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"&&!In.has(e.kind)&&!e.kind.startsWith("custom:")&&p(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),L(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),gn.has(e.state)||p(t,"state","unknown_state","Artifact state is not supported"),l(e.createdAt,"createdAt",t,128),te(e.createdAt,"createdAt",t),te(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),An.has(e.sensitivity)||p(t,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),e.identity)for(let[i,o]of Object.entries(e.identity))o!==void 0&&l(o,`identity.${i}`,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),L(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"&&!ht.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 i=e.content.storage;if(!i||typeof i!="object")p(t,"content.storage","missing_storage","storage reference is required");else if(i.type==="inline")if(i.text===void 0==(i.base64===void 0))p(t,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;i.text!==void 0?o=De.Buffer.from(i.text,"utf8"):i.base64!==void 0&&(hn.test(i.base64)?o=De.Buffer.from(i.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"&&T(o).value!==e.content.hash.value&&p(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else i.type==="file"?l(i.path,"content.storage.path",t,4096):i.type==="blob"?l(i.uri,"content.storage.uri",t,8192):i.type==="git"?(l(i.commit,"content.storage.commit",t,512),l(i.path,"content.storage.path",t,4096)):i.type==="url"?(l(i.url,"content.storage.url",t,8192),te(i.expiresAt,"content.storage.expiresAt",t)):i.type==="external"?(l(i.provider,"content.storage.provider",t,255),l(i.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"),L(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?p(t,"provenance","missing_provenance","provenance is required"):(gt(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((i,o)=>l(i,`provenance.capabilityLeaseIds[${o}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((i,o)=>l(i,`provenance.sourceArtifactIds[${o}]`,t,512)),e.provenance.attributes&&ne(e.provenance.attributes,"provenance.attributes",t,new Set));let n=new Set;return e.relationships?.forEach((i,o)=>{let r=`relationships[${o}]`;l(i.relation,`${r}.relation`,t,160),typeof i.relation=="string"&&!En.has(i.relation)&&!i.relation.startsWith("custom:")&&p(t,`${r}.relation`,"unknown_relationship","Relationship type is not supported"),L(i.relation,"custom:",`${r}.relation`,t),l(i.target?.type,`${r}.target.type`,t,160),typeof i.target?.type=="string"&&!wn.has(i.target.type)&&!i.target.type.startsWith("custom:")&&p(t,`${r}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),L(i.target?.type,"custom:",`${r}.target.type`,t),l(i.target?.id,`${r}.target.id`,t,512);let a=`${i.relation}:${i.target?.type}:${i.target?.id}:${i.target?.revision??""}`;n.has(a)&&p(t,r,"duplicate_relationship","Duplicate relationship"),n.add(a),i.attributes&&ne(i.attributes,`${r}.attributes`,t,new Set)}),e.anchors?.forEach((i,o)=>Fe(i,`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"),te(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&&ne(e.extensions,"extensions",t,new Set),t}function I(e){let t=At(e);if(t.length>0)throw new M("XENO artifact validation failed",t)}function yt(e,t){return ln[e].includes(t)}function ie(e,t){if(!yt(e,t))throw new ve(e,t)}function he(e,t){let n=[];return e.schemaVersion!==1&&p(n,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(e.eventId,"eventId",n,512),l(e.artifactId,"artifactId",n,512),(!Number.isInteger(e.artifactRevision)||e.artifactRevision<1)&&p(n,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(e.sequence)||e.sequence<1)&&p(n,"sequence","invalid_sequence","sequence must be a positive integer"),l(e.recordedAt,"recordedAt",n,128),te(e.recordedAt,"recordedAt",n),gt(e.actor,"actor",n),!e.artifactHash||typeof e.artifactHash!="object"?p(n,"artifactHash","missing_hash","Artifact hash is required"):(l(e.artifactHash.algorithm,"artifactHash.algorithm",n,128),L(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",n),l(e.artifactHash.value,"artifactHash.value",n,512),e.artifactHash.algorithm==="sha256"&&!ht.test(e.artifactHash.value)&&p(n,"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(n,"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(n,"type","unknown_review_event","Review event type is not supported"),e.type==="comment-added"?(l(e.commentId,"commentId",n,512),l(e.body,"body",n,65536),e.anchor&&Fe(e.anchor,"anchor",n)):e.type==="comment-resolved"||e.type==="comment-reopened"?l(e.commentId,"commentId",n,512):e.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(e.decision)||p(n,"decision","unknown_review_decision","Review decision is not supported"),e.scope&&Fe(e.scope,"scope",n)),t&&(e.artifactId!==t.artifactId&&p(n,"artifactId","artifact_mismatch","Review event targets a different artifact"),e.artifactRevision!==t.revision&&p(n,"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(n,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),n}function ge(e){let t="not_requested",n,i,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:(n=s.decision,i=s.eventId,t=s.decision));return{status:t,totalComments:a.size,unresolvedComments:[...a].filter(s=>!c.has(s)).length,...n?{latestDecision:n}:{},...i?{latestDecisionEventId:i}:{},...r>0?{scopedDecisionCount:r}:{},...o?{lastReviewedAt:o}:{}}}var ye=class extends Error{code="EVIDENCE_GRAPH_INVALID";issues;constructor(t){super("XENO evidence graph validation failed"),this.name="XenoEvidenceGraphValidationError",this.issues=t.map(n=>({...n}))}},Rn=new Set(["depends_on","decomposes","supersedes"]),Xn=new Set(Q),Sn=new Set(ee);function A(e,t,n,i){e.push({path:t,code:n,message:i})}function re(e){return e.includes("T")&&Number.isFinite(Date.parse(e))}function It(e,t){return e.startsWith(Oe)?F(e):t.has(e)}function wt(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_graph",message:"Evidence graph must be an object"}];e.schemaVersion!==1&&A(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),(typeof e.graphId!="string"||e.graphId.trim().length===0)&&A(t,"graphId","required_string","graphId must be a non-empty string"),(!Number.isInteger(e.version)||e.version<1)&&A(t,"version","invalid_version","version must be a positive integer"),re(e.createdAt)||A(t,"createdAt","invalid_timestamp","createdAt must be an ISO 8601 timestamp"),re(e.updatedAt)||A(t,"updatedAt","invalid_timestamp","updatedAt must be an ISO 8601 timestamp"),re(e.createdAt)&&re(e.updatedAt)&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&A(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt");let n=new Map;Array.isArray(e.nodes)||A(t,"nodes","invalid_nodes","nodes must be an array"),(Array.isArray(e.nodes)?e.nodes:[]).forEach((f,g)=>{let R=`nodes[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(t,`${R}.id`,"required_string","Node ID must be a non-empty string"):n.has(f.id)?A(t,`${R}.id`,"duplicate_node",`Node ID ${f.id} is duplicated`):n.set(f.id,f),(typeof f.type!="string"||!It(f.type,Xn))&&A(t,`${R}.type`,"invalid_node_type","Node type is invalid"),f.artifactRevision!==void 0&&(!Number.isInteger(f.artifactRevision)||f.artifactRevision<1)&&A(t,`${R}.artifactRevision`,"invalid_revision","artifactRevision must be a positive integer")});let i=new Set,o=new Set;Array.isArray(e.edges)||A(t,"edges","invalid_edges","edges must be an array"),(Array.isArray(e.edges)?e.edges:[]).forEach((f,g)=>{let R=`edges[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(t,`${R}.id`,"required_string","Edge ID must be a non-empty string"):i.has(f.id)&&A(t,`${R}.id`,"duplicate_edge",`Edge ID ${f.id} is duplicated`),i.add(f.id),(typeof f.type!="string"||!It(f.type,Sn))&&A(t,`${R}.type`,"invalid_edge_type","Edge type is invalid");let O=`${f.type}:${f.from}:${f.to}`;o.has(O)&&A(t,R,"duplicate_edge_identity","Equivalent evidence edge is duplicated"),o.add(O),n.has(f.from)||A(t,`${R}.from`,"dangling_reference",`Source node ${f.from} does not exist`),n.has(f.to)||A(t,`${R}.to`,"dangling_reference",`Target node ${f.to} does not exist`),f.from===f.to&&A(t,R,"self_edge","Evidence edges cannot point to the same node"),re(f.createdAt)||A(t,`${R}.createdAt`,"invalid_timestamp","createdAt must be an ISO 8601 timestamp")});let r=(Array.isArray(e.edges)?e.edges:[]).filter(f=>Rn.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 n.keys())if(d(f)){A(t,"edges","cyclic_graph","Dependency, decomposition, and supersession edges must be acyclic");break}return t}function J(e){let t=wt(e);if(t.length>0)throw new ye(t)}var Le=class{now;graph;constructor(t){if("schemaVersion"in t)J(t),this.now=()=>new Date().toISOString(),this.graph=Ae(t);else{this.now=t.now??(()=>new Date().toISOString());let n=this.now();this.graph={schemaVersion:1,graphId:t.graphId,version:1,createdAt:n,updatedAt:n,nodes:[],edges:[]},J(this.graph)}}addNode(t){let n=Ae(this.graph);return n.nodes.push(Et(t)),this.touch(n),J(n),this.graph=n,this}addEdge(t){let n=Ae(this.graph);return n.edges.push(Rt(t)),this.touch(n),J(n),this.graph=n,this}build(){return J(this.graph),Ae(this.graph)}touch(t){t.version+=1,t.updatedAt=this.now()}};function Et(e){return{...e,...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function Rt(e){return{...e,...e.producer?{producer:{...e.producer}}:{},...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function Ae(e){return{...e,nodes:e.nodes.map(Et),edges:e.edges.map(Rt)}}var u=class extends Error{constructor(n,i,o,r){super(i,r);this.code=n;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},B=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??(n=>(this.idCounter+=1,`${n}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),t.initialState&&this.hydrate(t.initialState)}exportState(){let t=[...this.records.values()].flatMap(n=>[...n.values()]).sort(Xt).map(n=>({artifact:oe(n.artifact),recordVersion:n.recordVersion,lifecycleEvents:structuredClone(n.lifecycleEvents),reviewEvents:structuredClone(n.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 n=oe(t),i=this.createLifecycleEvent({artifact:n,sequence:1,actor:n.provenance.producer,fromState:null,toState:n.state,reason:"artifact-created"}),o={artifact:n,recordVersion:1,lifecycleEvents:[i],reviewEvents:[]};return this.records.set(n.artifactId,new Map([[n.revision,o]])),this.currentRevisions.set(n.artifactId,n.revision),H(o)}async createRevision(t,n={}){I(t),this.assertInitialState(t);let i=this.getMutable(t.artifactId);this.assertVersion(i,n.expectedRecordVersion);let o=i.artifact.revision+1;if(t.revision!==o||t.predecessorRevision!==i.artifact.revision)throw new u("ARTIFACT_REVISION_INVALID",`Revision ${t.revision} does not follow current revision ${i.artifact.revision}`,{artifactId:t.artifactId,currentRevision:i.artifact.revision,requestedRevision:t.revision});if(_n(t,i.artifact))throw new u("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:t.artifactId,revision:t.revision});if(i.artifact.state==="archived")throw new u("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:t.artifactId,revision:i.artifact.revision});if(i.artifact.state!=="superseded"){ie(i.artifact.state,"superseded");let s=this.now(),d=this.createLifecycleEvent({artifact:i.artifact,sequence:i.lifecycleEvents.length+1,actor:n.actor??t.provenance.producer,fromState:i.artifact.state,toState:"superseded",reason:n.reason??`superseded-by-revision-${t.revision}`,recordedAt:s});i.artifact.state="superseded",i.artifact.updatedAt=s,i.lifecycleEvents.push(d),i.recordVersion+=1}let r=oe(t),a=this.createLifecycleEvent({artifact:r,sequence:1,actor:n.actor??r.provenance.producer,fromState:null,toState:r.state,reason:n.reason??`revision-created-from-${i.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),H(c)}async get(t,n){let i=this.records.get(t);if(!i)return;let o=n??this.currentRevisions.get(t);if(o===void 0)return;let r=i.get(o);return r?H(r):void 0}async require(t,n){let i=await this.get(t,n);if(!i)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:t,...n===void 0?{}:{revision:n}});return i}async list(t={}){let n=[];for(let[i,o]of this.records)if(!(t.artifactIds&&!t.artifactIds.includes(i)))if(t.includeSuperseded)n.push(...o.values());else{let r=this.currentRevisions.get(i);if(r!==void 0){let a=o.get(r);a&&n.push(a)}}return n.filter(i=>Tn(i.artifact,t)).sort(Xt).map(H)}async listRevisions(t){let n=this.records.get(t);return n?[...n.values()].sort((i,o)=>i.artifact.revision-o.artifact.revision).map(H):[]}async transition(t){let n=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(n,t.expectedRecordVersion),ie(n.artifact.state,t.toState),t.toState==="approved"||t.toState==="rejected"){let a=t.reviewEventId?n.reviewEvents.find(s=>s.eventId===t.reviewEventId&&s.type==="decision-recorded"):void 0,c=ge(n.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:n.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:n.artifact.revision,unresolvedComments:c.unresolvedComments})}let i=this.now(),o=n.artifact.state,r=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor,fromState:o,toState:t.toState,reason:t.reason,reviewEventId:t.reviewEventId,recordedAt:i});return n.artifact.state=t.toState,n.artifact.updatedAt=i,n.lifecycleEvents.push(r),n.recordVersion+=1,H(n)}async appendReviewEvent(t){let n=t.event,i=this.getMutable(n.artifactId,n.artifactRevision);if(this.assertVersion(i,t.expectedRecordVersion),i.artifact.state==="archived"||i.artifact.state==="superseded")throw new u("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${i.artifact.state} artifact revision`,{artifactId:n.artifactId,revision:n.artifactRevision});if(this.assertReviewCommentState(i,n),(n.type==="review-requested"||n.type==="review-withdrawn"||n.type==="decision-recorded")&&i.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`${n.type} requires an artifact in pending_review state`,{artifactId:n.artifactId,revision:n.artifactRevision});let o={...structuredClone(n),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:i.reviewEvents.length+1,recordedAt:this.now()},r=he(o,i.artifact);if(r.length>0)throw new M("XENO artifact review event validation failed",r);return i.reviewEvents.push(o),i.recordVersion+=1,H(i)}getMutable(t,n){let i=this.records.get(t),o=n??this.currentRevisions.get(t),r=o===void 0?void 0:i?.get(o);if(!r)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:t,...n===void 0?{}:{revision:n}});return r}assertVersion(t,n){if(n!==void 0&&n!==t.recordVersion)throw new u("ARTIFACT_CONFLICT",`Expected record version ${n}, found ${t.recordVersion}`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision,expectedRecordVersion:n,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,n){if(n.type==="comment-added"){if(t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} already exists`);if(n.parentCommentId&&!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Parent comment ${n.parentCommentId} does not exist`);return}if(n.type!=="comment-resolved"&&n.type!=="comment-reopened")return;if(!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} does not exist`);let o=kn(t.reviewEvents,n.commentId);if(n.type==="comment-resolved"&&o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} is already resolved`);if(n.type==="comment-reopened"&&!o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.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 n=this.idFactory(t);if(typeof n!="string"||n.trim().length===0||this.eventIds.has(n))throw new u("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${t} ID`);return this.eventIds.add(n),n}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 n=[...t.records].sort((i,o)=>i.artifact.artifactId.localeCompare(o.artifact.artifactId)||i.artifact.revision-o.artifact.revision);for(let i of n){let o=bn(i,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[i,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 ${i} is missing revision ${s}`);if(a===0&&c.artifact.predecessorRevision!==void 0)throw new u("ARTIFACT_REVISION_INVALID",`Initial revision for ${i} cannot declare a predecessor`);if(a>0&&c.artifact.predecessorRevision!==s-1)throw new u("ARTIFACT_REVISION_INVALID",`Persisted revision ${i}:${s} has an invalid predecessor`);if(a<r.length-1&&c.artifact.state!=="superseded")throw new u("ARTIFACT_REVISION_INVALID",`Non-current revision ${i}:${s} must be superseded`)}}}};function bn(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 n=e.lifecycleEvents.length+e.reviewEvents.length;if(e.recordVersion!==n)throw new u("ARTIFACT_REVISION_INVALID",`Persisted record version ${e.recordVersion} does not match ${n} mutations`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let i=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!==i||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(i===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 ie(i,a.toState);t.add(a.eventId),i=a.toState}if(i!==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=he(a,e.artifact);if(c.length>0)throw new M("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:oe(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function _n(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function Tn(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 Xt(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function kn(e,t){let n=!1;for(let i of e)(i.type==="comment-resolved"||i.type==="comment-reopened")&&i.commentId===t&&(n=i.type==="comment-resolved");return{resolved:n}}function oe(e){return structuredClone(e)}function H(e){return{artifact:oe(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:ge(e.reviewEvents)}}var Ue=require("node:crypto"),b=require("node:fs/promises"),N=require("node:path");var V=require("node:fs"),Me=require("node:os"),bt=require("node:path");function xn(){return new Date().toISOString()}function Cn(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function _t(e){try{return JSON.parse((0,V.readFileSync)(e,"utf8"))}catch{return null}}function Nn(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Vn(e){return e.hostname!==(0,Me.hostname)()?!0:Nn(e.pid)}function St(e,t){(0,V.mkdirSync)((0,bt.dirname)(e),{recursive:!0}),(0,V.writeFileSync)(e,JSON.stringify(t,null,2)+`
2
- `,{encoding:"utf8",flag:"wx"})}function Pn(e,t){let n=_t(e);n?.pid!==t.pid||n.hostname!==t.hostname||(0,V.rmSync)(e,{force:!0})}function Tt(e,t,n){let i=xn(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,Me.hostname)(),processStartedAt:Cn(),version:n,acquiredAt:i,updatedAt:i};try{St(e,o)}catch(r){if(r.code!=="EEXIST")throw r;let c=_t(e);if(c&&Vn(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);(0,V.rmSync)(e,{force:!0}),St(e,o)}return{record:o,release:()=>{Pn(e,o)}}}var kt="0.9.26";var We=1,$n="repository.v1.json",On=5e3,Dn=20,Fn=64*1024*1024,qe=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 n=t.snapshotFileName??$n;if((0,N.basename)(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))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,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=He(t.lockTimeoutMs,On,100,6e4,"lockTimeoutMs"),this.lockRetryMs=He(t.lockRetryMs,Dn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=He(t.maxSnapshotBytes,Fn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(n=>n.create(t))}async createRevision(t,n){return this.mutate(i=>i.createRevision(t,n))}async get(t,n){return(await this.load()).repository.get(t,n)}async require(t,n){return(await this.load()).repository.require(t,n)}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(n=>n.transition(t))}async appendReviewEvent(t){return this.mutate(n=>n.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await t(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(t){let n=this.mutationTail.then(t,t);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let t=Date.now(),n;for(;Date.now()-t<=this.lockTimeoutMs;)try{return Tt(this.lockPath,`artifact-repository:${(0,N.basename)(this.snapshotPath)}`,kt)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await qn(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let t,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){t=Ie(r)}if(!n&&(t||await jn(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"}),n=r,i=!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,Ie(r)])}):r}if(!n&&t)throw t;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new B({now:this.now,idFactory:r=>`${r}_${(0,Ue.randomUUID)()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(t){let n=this.now(),o={...{schemaVersion:We,generation:t.generation,createdAt:t.createdAt,updatedAt:n,state:t.repository.exportState()},generation:t.generation+1},r=Mn(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,b.mkdir)(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await xt(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
4
- `),await xt(this.snapshotPath,a)}async readSnapshot(t,n){let i;try{i=await(0,b.stat)(t)}catch(o){if(!n&&Je(o,"ENOENT")||n&&Je(o,"ENOENT"))return;throw Be("Unable to inspect artifact repository snapshot",t,o)}if(!i.isFile()||i.size>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:t,sizeBytes:i.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await(0,b.readFile)(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return Ln(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof u?o:Be("Unable to parse artifact repository snapshot",t,o,!0)}}};function Ln(e,t){if(!je(e)||e.schemaVersion!==We||!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))||!je(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!je(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 n=e,i=Hn(n),o=Ct(i);if(n.checksum.value!==o)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new B({initialState:n.state}),structuredClone(n)}function Mn(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:Ct(e)}}}function Hn(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function Ct(e){return T(JSON.stringify(e)).value}async function xt(e,t){await(0,b.mkdir)((0,N.dirname)(e),{recursive:!0,mode:448});let n=`${e}.tmp.${process.pid}.${(0,Ue.randomUUID)()}`,i;try{i=await(0,b.open)(n,"wx",384),await i.writeFile(t,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,await(0,b.rename)(n,e);try{let o=await(0,b.open)((0,N.dirname)(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{i&&await i.close().catch(()=>{}),await(0,b.unlink)(n).catch(()=>{})}}function He(e,t,n,i,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<n||e>i)throw new TypeError(`${o} must be an integer between ${n} and ${i}`);return e}function je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Je(e,t){return e instanceof Error&&e.code===t}async function jn(e){try{return(await(0,b.stat)(e)).isFile()}catch(t){if(Je(t,"ENOENT"))return!1;throw Be("Unable to inspect artifact repository backup",e,t)}}function Ie(e){return e instanceof Error?e:new Error(String(e))}function Be(e,t,n,i=!1){return new u(i?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${Ie(n).message}`,{snapshotPath:t},{cause:Ie(n)})}function qn(e){return new Promise(t=>setTimeout(t,e))}var ze=require("node:buffer");var Jn=16*1024*1024,Bn=5e3,Un=1e5,Wn=1e6,zn=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,X=class extends Error{constructor(n,i){super(i===void 0?n:`${n} at diff line ${i}`);this.line=i;this.name="XenoDiffParseError"}line;code="XENO_DIFF_INVALID"};function Ke(e,t={}){if(typeof e!="string")throw new TypeError("Unified diff must be a string");let n=we(t.maxBytes,Jn,1024,256*1024*1024,"maxBytes"),i=we(t.maxFiles,Bn,1,1e5,"maxFiles"),o=we(t.maxHunks,Un,1,1e6,"maxHunks"),r=we(t.maxLines,Wn,1,5e6,"maxLines");if(ze.Buffer.byteLength(e,"utf8")>n)throw new X(`Unified diff exceeds ${n} bytes`);let a=e.replace(/\r\n/g,`
1
+ "use strict";var Ce=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var an=Object.getOwnPropertyNames;var cn=Object.prototype.hasOwnProperty;var dn=(e,t)=>{for(var n in t)Ce(e,n,{get:t[n],enumerable:!0})},fn=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of an(t))!cn.call(e,o)&&o!==n&&Ce(e,o,{get:()=>t[o],enumerable:!(i=sn(t,o))||i.enumerable});return e};var pn=e=>fn(Ce({},"__esModule",{value:!0}),e);var ki={};dn(ki,{FileXenoArtifactRepository:()=>qe,InMemoryXenoArtifactRepository:()=>B,XENO_ARTIFACT_ACTOR_KINDS:()=>Pe,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION:()=>We,XENO_ARTIFACT_SCHEMA_VERSION:()=>h,XENO_ARTIFACT_SENSITIVITIES:()=>Ve,XENO_ARTIFACT_STATES:()=>Ne,XENO_BUILTIN_ARTIFACT_KINDS:()=>xe,XENO_EVIDENCE_EDGE_TYPES:()=>ee,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION:()=>me,XENO_EVIDENCE_NODE_TYPES:()=>Q,XENO_REVIEW_DIMENSIONS:()=>Bt,XENO_REVIEW_EVIDENCE_KINDS:()=>Ut,XENO_REVIEW_REPORT_SCHEMA_VERSION:()=>ot,XENO_SPEC_EXECUTION_SCHEMA_VERSION:()=>ce,XENO_SPEC_SCHEMA_VERSION:()=>z,XenoArtifactRepositoryError:()=>u,XenoArtifactReviewService:()=>U,XenoArtifactStateTransitionError:()=>ve,XenoArtifactValidationError:()=>M,XenoDiffParseError:()=>X,XenoEvidenceGraphBuilder:()=>Le,XenoEvidenceGraphValidationError:()=>ye,XenoMultiAgentReviewCoordinator:()=>rt,XenoReviewValidationError:()=>E,XenoSpecLifecycleService:()=>Qe,XenoSpecValidationError:()=>w,assertValidXenoArtifact:()=>I,assertValidXenoEvidenceGraph:()=>J,assertValidXenoReviewPack:()=>st,assertValidXenoReviewReport:()=>fe,assertValidXenoReviewTarget:()=>at,assertValidXenoSpecDocument:()=>be,assertValidXenoSpecExecution:()=>it,assertXenoArtifactStateTransition:()=>ie,buildXenoArtifactReviewAnchor:()=>Ze,canTransitionXenoArtifactState:()=>yt,canonicalizeArtifactJson:()=>S,defaultXenoReviewPack:()=>ai,detectXenoSpecDrift:()=>ti,legacyAgentArtifactToXenoArtifact:()=>yi,normalizeRepositoryRelativePath:()=>Ft,parseUnifiedDiff:()=>Ke,sha256ArtifactBytes:()=>T,sha256ArtifactJson:()=>k,summarizeXenoArtifactReview:()=>ge,toolEvidenceToXenoArtifact:()=>wi,turnDiffSummaryToXenoArtifact:()=>Ri,unifiedDiffToXenoArtifact:()=>Ge,validateXenoArtifact:()=>At,validateXenoArtifactReviewEvent:()=>he,validateXenoEvidenceGraph:()=>wt,validateXenoSpecDocument:()=>Mt,xenoArtifactToDiffDocument:()=>Ye,xenoArtifactToLegacyAgentArtifact:()=>Ii,xenoArtifactToReviewReport:()=>di,xenoArtifactToSpecDocument:()=>tt,xenoArtifactToSpecExecution:()=>Ht,xenoArtifactToToolEvidence:()=>Ei,xenoArtifactToTurnDiffSummary:()=>Xi,xenoReviewReportToArtifact:()=>ci,xenoReviewReportToGitHubComments:()=>fi,xenoSpecArtifactIds:()=>W,xenoSpecExecutionToArtifact:()=>nt,xenoSpecToArtifactBundle:()=>et});module.exports=pn(ki);var h=1,me=1,xe=["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"],Ne=["draft","pending_review","approved","rejected","superseded","archived"],Ve=["public","internal","confidential","restricted"],Pe=["agent","tool","user","system","integration"],Q=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],ee=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var De=require("node:buffer");var vt=require("node:crypto");function T(e){return{algorithm:"sha256",value:(0,vt.createHash)("sha256").update(e).digest("hex")}}function S(e){return JSON.stringify($e(e,new Set))}function k(e){return T(S(e))}function $e(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 i=e.map(o=>$e(o,t));return t.delete(e),i}let n={};for(let i of Object.keys(e).sort((o,r)=>o.localeCompare(r))){let o=e[i];if(o===void 0)throw new TypeError(`Artifact JSON property ${i} is undefined`);n[i]=$e(o,t)}return t.delete(e),n}var un=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Oe="custom:";function F(e,t=Oe){return e.startsWith(t)?un.test(e.slice(t.length)):!1}var M=class extends Error{code="ARTIFACT_INVALID";issues;constructor(t,n){super(t),this.name="XenoArtifactValidationError",this.issues=n.map(i=>({...i}))}},ve=class extends Error{constructor(n,i){super(`Artifact state cannot transition from ${n} to ${i}`);this.fromState=n;this.toState=i;this.name="XenoArtifactStateTransitionError"}fromState;toState;code="ARTIFACT_STATE_TRANSITION_INVALID"},ln={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},mn="[\\u0000-\\u001f\\u007f]",vn=new RegExp(mn),ht=/^[a-f0-9]{64}$/,hn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,gn=new Set(Ne),An=new Set(Ve),yn=new Set(Pe),In=new Set(xe),wn=new Set(Q),En=new Set(ee);function p(e,t,n,i){e.push({path:t,code:n,message:i})}function l(e,t,n,i=1024){return typeof e!="string"||e.trim().length===0?(p(n,t,"required_string","Value must be a non-empty string"),!1):(e.length>i&&p(n,t,"string_too_long",`Value must not exceed ${i} characters`),vn.test(e)&&p(n,t,"control_character","Value must not contain control characters"),!0)}function te(e,t,n){e!==void 0&&(!Number.isFinite(Date.parse(e))||!e.includes("T"))&&p(n,t,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function L(e,t,n,i){typeof e=="string"&&e.startsWith(t)&&(F(e,t)||p(i,n,"invalid_custom_name",`Custom name after ${t} is invalid`))}function gt(e,t,n){if(!e||typeof e!="object"){p(n,t,"missing_actor","Actor is required");return}l(e.kind,`${t}.kind`,n,64),yn.has(e.kind)||p(n,`${t}.kind`,"unknown_actor_kind","Actor kind is not supported"),l(e.id,`${t}.id`,n,512),e?.displayName!==void 0&&l(e.displayName,`${t}.displayName`,n,512),e?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(e.profileFingerprint)&&p(n,`${t}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function Fe(e,t,n){if(!e||typeof e!="object"){p(n,t,"invalid_anchor","Anchor must be an object");return}switch(e.kind){case"file":l(e.path,`${t}.path`,n,4096);break;case"source-line":l(e.path,`${t}.path`,n,4096),(!Number.isInteger(e.startLine)||e.startLine<1)&&p(n,`${t}.startLine`,"invalid_line","startLine must be a positive integer"),e.endLine!==void 0&&(!Number.isInteger(e.endLine)||e.endLine<e.startLine)&&p(n,`${t}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":l(e.path,`${t}.path`,n,4096),l(e.hunkId,`${t}.hunkId`,n,512);break;case"symbol":l(e.path,`${t}.path`,n,4096),l(e.symbol,`${t}.symbol`,n,1024);break;case"dom-node":l(e.pageId,`${t}.pageId`,n,512),!e.selector&&!e.accessibilityId&&!e.snapshotArtifactId&&p(n,t,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":l(e.recordingArtifactId,`${t}.recordingArtifactId`,n,512),(!Number.isFinite(e.startMs)||e.startMs<0)&&p(n,`${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(n,`${t}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":l(e.mediaArtifactId,`${t}.mediaArtifactId`,n,512),[e.x,e.y,e.width,e.height].every(Number.isFinite)?(e.width<=0||e.height<=0)&&p(n,t,"invalid_region_size","Region width and height must be positive"):p(n,t,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":l(e.artifactId,`${t}.artifactId`,n,512);break;default:typeof e.kind!="string"||!e.kind.startsWith("custom:")?p(n,`${t}.kind`,"unknown_anchor","Anchor kind is not supported"):L(e.kind,"custom:",`${t}.kind`,n)}}function ne(e,t,n,i){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||p(n,t,"non_finite_number","JSON numbers must be finite");return}if(typeof e!="object"){p(n,t,"non_json_value","Value must be JSON-serializable");return}if(i.has(e)){p(n,t,"cyclic_value","Value must not contain cycles");return}if(i.add(e),Array.isArray(e))e.forEach((o,r)=>ne(o,`${t}[${r}]`,n,i));else for(let[o,r]of Object.entries(e))r===void 0?p(n,`${t}.${o}`,"undefined_value","Undefined is not valid JSON"):ne(r,`${t}.${o}`,n,i);i.delete(e)}}function At(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"&&!In.has(e.kind)&&!e.kind.startsWith("custom:")&&p(t,"kind","unknown_artifact_kind","Artifact kind is not supported"),L(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),gn.has(e.state)||p(t,"state","unknown_state","Artifact state is not supported"),l(e.createdAt,"createdAt",t,128),te(e.createdAt,"createdAt",t),te(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),An.has(e.sensitivity)||p(t,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),e.identity)for(let[i,o]of Object.entries(e.identity))o!==void 0&&l(o,`identity.${i}`,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),L(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"&&!ht.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 i=e.content.storage;if(!i||typeof i!="object")p(t,"content.storage","missing_storage","storage reference is required");else if(i.type==="inline")if(i.text===void 0==(i.base64===void 0))p(t,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;i.text!==void 0?o=De.Buffer.from(i.text,"utf8"):i.base64!==void 0&&(hn.test(i.base64)?o=De.Buffer.from(i.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"&&T(o).value!==e.content.hash.value&&p(t,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else i.type==="file"?l(i.path,"content.storage.path",t,4096):i.type==="blob"?l(i.uri,"content.storage.uri",t,8192):i.type==="git"?(l(i.commit,"content.storage.commit",t,512),l(i.path,"content.storage.path",t,4096)):i.type==="url"?(l(i.url,"content.storage.url",t,8192),te(i.expiresAt,"content.storage.expiresAt",t)):i.type==="external"?(l(i.provider,"content.storage.provider",t,255),l(i.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"),L(e.content.encoding,"custom:","content.encoding",t)}!e.provenance||typeof e.provenance!="object"?p(t,"provenance","missing_provenance","provenance is required"):(gt(e.provenance.producer,"provenance.producer",t),e.provenance.capabilityLeaseIds?.forEach((i,o)=>l(i,`provenance.capabilityLeaseIds[${o}]`,t,512)),e.provenance.sourceArtifactIds?.forEach((i,o)=>l(i,`provenance.sourceArtifactIds[${o}]`,t,512)),e.provenance.attributes&&ne(e.provenance.attributes,"provenance.attributes",t,new Set));let n=new Set;return e.relationships?.forEach((i,o)=>{let r=`relationships[${o}]`;l(i.relation,`${r}.relation`,t,160),typeof i.relation=="string"&&!En.has(i.relation)&&!i.relation.startsWith("custom:")&&p(t,`${r}.relation`,"unknown_relationship","Relationship type is not supported"),L(i.relation,"custom:",`${r}.relation`,t),l(i.target?.type,`${r}.target.type`,t,160),typeof i.target?.type=="string"&&!wn.has(i.target.type)&&!i.target.type.startsWith("custom:")&&p(t,`${r}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),L(i.target?.type,"custom:",`${r}.target.type`,t),l(i.target?.id,`${r}.target.id`,t,512);let a=`${i.relation}:${i.target?.type}:${i.target?.id}:${i.target?.revision??""}`;n.has(a)&&p(t,r,"duplicate_relationship","Duplicate relationship"),n.add(a),i.attributes&&ne(i.attributes,`${r}.attributes`,t,new Set)}),e.anchors?.forEach((i,o)=>Fe(i,`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"),te(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&&ne(e.extensions,"extensions",t,new Set),t}function I(e){let t=At(e);if(t.length>0)throw new M("XENO artifact validation failed",t)}function yt(e,t){return ln[e].includes(t)}function ie(e,t){if(!yt(e,t))throw new ve(e,t)}function he(e,t){let n=[];return e.schemaVersion!==1&&p(n,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(e.eventId,"eventId",n,512),l(e.artifactId,"artifactId",n,512),(!Number.isInteger(e.artifactRevision)||e.artifactRevision<1)&&p(n,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(e.sequence)||e.sequence<1)&&p(n,"sequence","invalid_sequence","sequence must be a positive integer"),l(e.recordedAt,"recordedAt",n,128),te(e.recordedAt,"recordedAt",n),gt(e.actor,"actor",n),!e.artifactHash||typeof e.artifactHash!="object"?p(n,"artifactHash","missing_hash","Artifact hash is required"):(l(e.artifactHash.algorithm,"artifactHash.algorithm",n,128),L(e.artifactHash.algorithm,"custom:","artifactHash.algorithm",n),l(e.artifactHash.value,"artifactHash.value",n,512),e.artifactHash.algorithm==="sha256"&&!ht.test(e.artifactHash.value)&&p(n,"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(n,"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(n,"type","unknown_review_event","Review event type is not supported"),e.type==="comment-added"?(l(e.commentId,"commentId",n,512),l(e.body,"body",n,65536),e.anchor&&Fe(e.anchor,"anchor",n)):e.type==="comment-resolved"||e.type==="comment-reopened"?l(e.commentId,"commentId",n,512):e.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(e.decision)||p(n,"decision","unknown_review_decision","Review decision is not supported"),e.scope&&Fe(e.scope,"scope",n)),t&&(e.artifactId!==t.artifactId&&p(n,"artifactId","artifact_mismatch","Review event targets a different artifact"),e.artifactRevision!==t.revision&&p(n,"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(n,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),n}function ge(e){let t="not_requested",n,i,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:(n=s.decision,i=s.eventId,t=s.decision));return{status:t,totalComments:a.size,unresolvedComments:[...a].filter(s=>!c.has(s)).length,...n?{latestDecision:n}:{},...i?{latestDecisionEventId:i}:{},...r>0?{scopedDecisionCount:r}:{},...o?{lastReviewedAt:o}:{}}}var ye=class extends Error{code="EVIDENCE_GRAPH_INVALID";issues;constructor(t){super("XENO evidence graph validation failed"),this.name="XenoEvidenceGraphValidationError",this.issues=t.map(n=>({...n}))}},Rn=new Set(["depends_on","decomposes","supersedes"]),Xn=new Set(Q),Sn=new Set(ee);function A(e,t,n,i){e.push({path:t,code:n,message:i})}function re(e){return e.includes("T")&&Number.isFinite(Date.parse(e))}function It(e,t){return e.startsWith(Oe)?F(e):t.has(e)}function wt(e){let t=[];if(!e||typeof e!="object")return[{path:"$",code:"invalid_graph",message:"Evidence graph must be an object"}];e.schemaVersion!==1&&A(t,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),(typeof e.graphId!="string"||e.graphId.trim().length===0)&&A(t,"graphId","required_string","graphId must be a non-empty string"),(!Number.isInteger(e.version)||e.version<1)&&A(t,"version","invalid_version","version must be a positive integer"),re(e.createdAt)||A(t,"createdAt","invalid_timestamp","createdAt must be an ISO 8601 timestamp"),re(e.updatedAt)||A(t,"updatedAt","invalid_timestamp","updatedAt must be an ISO 8601 timestamp"),re(e.createdAt)&&re(e.updatedAt)&&Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&A(t,"updatedAt","timestamp_order","updatedAt must not precede createdAt");let n=new Map;Array.isArray(e.nodes)||A(t,"nodes","invalid_nodes","nodes must be an array"),(Array.isArray(e.nodes)?e.nodes:[]).forEach((f,g)=>{let R=`nodes[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(t,`${R}.id`,"required_string","Node ID must be a non-empty string"):n.has(f.id)?A(t,`${R}.id`,"duplicate_node",`Node ID ${f.id} is duplicated`):n.set(f.id,f),(typeof f.type!="string"||!It(f.type,Xn))&&A(t,`${R}.type`,"invalid_node_type","Node type is invalid"),f.artifactRevision!==void 0&&(!Number.isInteger(f.artifactRevision)||f.artifactRevision<1)&&A(t,`${R}.artifactRevision`,"invalid_revision","artifactRevision must be a positive integer")});let i=new Set,o=new Set;Array.isArray(e.edges)||A(t,"edges","invalid_edges","edges must be an array"),(Array.isArray(e.edges)?e.edges:[]).forEach((f,g)=>{let R=`edges[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(t,`${R}.id`,"required_string","Edge ID must be a non-empty string"):i.has(f.id)&&A(t,`${R}.id`,"duplicate_edge",`Edge ID ${f.id} is duplicated`),i.add(f.id),(typeof f.type!="string"||!It(f.type,Sn))&&A(t,`${R}.type`,"invalid_edge_type","Edge type is invalid");let O=`${f.type}:${f.from}:${f.to}`;o.has(O)&&A(t,R,"duplicate_edge_identity","Equivalent evidence edge is duplicated"),o.add(O),n.has(f.from)||A(t,`${R}.from`,"dangling_reference",`Source node ${f.from} does not exist`),n.has(f.to)||A(t,`${R}.to`,"dangling_reference",`Target node ${f.to} does not exist`),f.from===f.to&&A(t,R,"self_edge","Evidence edges cannot point to the same node"),re(f.createdAt)||A(t,`${R}.createdAt`,"invalid_timestamp","createdAt must be an ISO 8601 timestamp")});let r=(Array.isArray(e.edges)?e.edges:[]).filter(f=>Rn.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 n.keys())if(d(f)){A(t,"edges","cyclic_graph","Dependency, decomposition, and supersession edges must be acyclic");break}return t}function J(e){let t=wt(e);if(t.length>0)throw new ye(t)}var Le=class{now;graph;constructor(t){if("schemaVersion"in t)J(t),this.now=()=>new Date().toISOString(),this.graph=Ae(t);else{this.now=t.now??(()=>new Date().toISOString());let n=this.now();this.graph={schemaVersion:1,graphId:t.graphId,version:1,createdAt:n,updatedAt:n,nodes:[],edges:[]},J(this.graph)}}addNode(t){let n=Ae(this.graph);return n.nodes.push(Et(t)),this.touch(n),J(n),this.graph=n,this}addEdge(t){let n=Ae(this.graph);return n.edges.push(Rt(t)),this.touch(n),J(n),this.graph=n,this}build(){return J(this.graph),Ae(this.graph)}touch(t){t.version+=1,t.updatedAt=this.now()}};function Et(e){return{...e,...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function Rt(e){return{...e,...e.producer?{producer:{...e.producer}}:{},...e.attributes?{attributes:structuredClone(e.attributes)}:{}}}function Ae(e){return{...e,nodes:e.nodes.map(Et),edges:e.edges.map(Rt)}}var u=class extends Error{constructor(n,i,o,r){super(i,r);this.code=n;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},B=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??(n=>(this.idCounter+=1,`${n}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),t.initialState&&this.hydrate(t.initialState)}exportState(){let t=[...this.records.values()].flatMap(n=>[...n.values()]).sort(Xt).map(n=>({artifact:oe(n.artifact),recordVersion:n.recordVersion,lifecycleEvents:structuredClone(n.lifecycleEvents),reviewEvents:structuredClone(n.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 n=oe(t),i=this.createLifecycleEvent({artifact:n,sequence:1,actor:n.provenance.producer,fromState:null,toState:n.state,reason:"artifact-created"}),o={artifact:n,recordVersion:1,lifecycleEvents:[i],reviewEvents:[]};return this.records.set(n.artifactId,new Map([[n.revision,o]])),this.currentRevisions.set(n.artifactId,n.revision),H(o)}async createRevision(t,n={}){I(t),this.assertInitialState(t);let i=this.getMutable(t.artifactId);this.assertVersion(i,n.expectedRecordVersion);let o=i.artifact.revision+1;if(t.revision!==o||t.predecessorRevision!==i.artifact.revision)throw new u("ARTIFACT_REVISION_INVALID",`Revision ${t.revision} does not follow current revision ${i.artifact.revision}`,{artifactId:t.artifactId,currentRevision:i.artifact.revision,requestedRevision:t.revision});if(_n(t,i.artifact))throw new u("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:t.artifactId,revision:t.revision});if(i.artifact.state==="archived")throw new u("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:t.artifactId,revision:i.artifact.revision});if(i.artifact.state!=="superseded"){ie(i.artifact.state,"superseded");let s=this.now(),d=this.createLifecycleEvent({artifact:i.artifact,sequence:i.lifecycleEvents.length+1,actor:n.actor??t.provenance.producer,fromState:i.artifact.state,toState:"superseded",reason:n.reason??`superseded-by-revision-${t.revision}`,recordedAt:s});i.artifact.state="superseded",i.artifact.updatedAt=s,i.lifecycleEvents.push(d),i.recordVersion+=1}let r=oe(t),a=this.createLifecycleEvent({artifact:r,sequence:1,actor:n.actor??r.provenance.producer,fromState:null,toState:r.state,reason:n.reason??`revision-created-from-${i.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),H(c)}async get(t,n){let i=this.records.get(t);if(!i)return;let o=n??this.currentRevisions.get(t);if(o===void 0)return;let r=i.get(o);return r?H(r):void 0}async require(t,n){let i=await this.get(t,n);if(!i)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:t,...n===void 0?{}:{revision:n}});return i}async list(t={}){let n=[];for(let[i,o]of this.records)if(!(t.artifactIds&&!t.artifactIds.includes(i)))if(t.includeSuperseded)n.push(...o.values());else{let r=this.currentRevisions.get(i);if(r!==void 0){let a=o.get(r);a&&n.push(a)}}return n.filter(i=>Tn(i.artifact,t)).sort(Xt).map(H)}async listRevisions(t){let n=this.records.get(t);return n?[...n.values()].sort((i,o)=>i.artifact.revision-o.artifact.revision).map(H):[]}async transition(t){let n=this.getMutable(t.artifactId,t.revision);if(this.assertVersion(n,t.expectedRecordVersion),ie(n.artifact.state,t.toState),t.toState==="approved"||t.toState==="rejected"){let a=t.reviewEventId?n.reviewEvents.find(s=>s.eventId===t.reviewEventId&&s.type==="decision-recorded"):void 0,c=ge(n.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:n.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:n.artifact.revision,unresolvedComments:c.unresolvedComments})}let i=this.now(),o=n.artifact.state,r=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:t.actor,fromState:o,toState:t.toState,reason:t.reason,reviewEventId:t.reviewEventId,recordedAt:i});return n.artifact.state=t.toState,n.artifact.updatedAt=i,n.lifecycleEvents.push(r),n.recordVersion+=1,H(n)}async appendReviewEvent(t){let n=t.event,i=this.getMutable(n.artifactId,n.artifactRevision);if(this.assertVersion(i,t.expectedRecordVersion),i.artifact.state==="archived"||i.artifact.state==="superseded")throw new u("ARTIFACT_REVIEW_INVALID",`Cannot append review events to a ${i.artifact.state} artifact revision`,{artifactId:n.artifactId,revision:n.artifactRevision});if(this.assertReviewCommentState(i,n),(n.type==="review-requested"||n.type==="review-withdrawn"||n.type==="decision-recorded")&&i.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`${n.type} requires an artifact in pending_review state`,{artifactId:n.artifactId,revision:n.artifactRevision});let o={...structuredClone(n),schemaVersion:1,eventId:this.nextEventId("review_event"),sequence:i.reviewEvents.length+1,recordedAt:this.now()},r=he(o,i.artifact);if(r.length>0)throw new M("XENO artifact review event validation failed",r);return i.reviewEvents.push(o),i.recordVersion+=1,H(i)}getMutable(t,n){let i=this.records.get(t),o=n??this.currentRevisions.get(t),r=o===void 0?void 0:i?.get(o);if(!r)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${t}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:t,...n===void 0?{}:{revision:n}});return r}assertVersion(t,n){if(n!==void 0&&n!==t.recordVersion)throw new u("ARTIFACT_CONFLICT",`Expected record version ${n}, found ${t.recordVersion}`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision,expectedRecordVersion:n,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,n){if(n.type==="comment-added"){if(t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} already exists`);if(n.parentCommentId&&!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Parent comment ${n.parentCommentId} does not exist`);return}if(n.type!=="comment-resolved"&&n.type!=="comment-reopened")return;if(!t.reviewEvents.some(r=>r.type==="comment-added"&&r.commentId===n.commentId))throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} does not exist`);let o=kn(t.reviewEvents,n.commentId);if(n.type==="comment-resolved"&&o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.commentId} is already resolved`);if(n.type==="comment-reopened"&&!o.resolved)throw new u("ARTIFACT_REVIEW_INVALID",`Comment ${n.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 n=this.idFactory(t);if(typeof n!="string"||n.trim().length===0||this.eventIds.has(n))throw new u("ARTIFACT_CONFLICT",`Event ID factory produced an invalid or duplicate ${t} ID`);return this.eventIds.add(n),n}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 n=[...t.records].sort((i,o)=>i.artifact.artifactId.localeCompare(o.artifact.artifactId)||i.artifact.revision-o.artifact.revision);for(let i of n){let o=bn(i,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[i,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 ${i} is missing revision ${s}`);if(a===0&&c.artifact.predecessorRevision!==void 0)throw new u("ARTIFACT_REVISION_INVALID",`Initial revision for ${i} cannot declare a predecessor`);if(a>0&&c.artifact.predecessorRevision!==s-1)throw new u("ARTIFACT_REVISION_INVALID",`Persisted revision ${i}:${s} has an invalid predecessor`);if(a<r.length-1&&c.artifact.state!=="superseded")throw new u("ARTIFACT_REVISION_INVALID",`Non-current revision ${i}:${s} must be superseded`)}}}};function bn(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 n=e.lifecycleEvents.length+e.reviewEvents.length;if(e.recordVersion!==n)throw new u("ARTIFACT_REVISION_INVALID",`Persisted record version ${e.recordVersion} does not match ${n} mutations`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision});let i=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!==i||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(i===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 ie(i,a.toState);t.add(a.eventId),i=a.toState}if(i!==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=he(a,e.artifact);if(c.length>0)throw new M("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:oe(e.artifact),recordVersion:e.recordVersion,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents)}}function _n(e,t){return e.content.hash.algorithm===t.content.hash.algorithm&&e.content.hash.value===t.content.hash.value}function Tn(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 Xt(e,t){return e.artifact.createdAt.localeCompare(t.artifact.createdAt)||e.artifact.artifactId.localeCompare(t.artifact.artifactId)||e.artifact.revision-t.artifact.revision}function kn(e,t){let n=!1;for(let i of e)(i.type==="comment-resolved"||i.type==="comment-reopened")&&i.commentId===t&&(n=i.type==="comment-resolved");return{resolved:n}}function oe(e){return structuredClone(e)}function H(e){return{artifact:oe(e.artifact),recordVersion:e.recordVersion,etag:`${e.artifact.artifactId}:${e.artifact.revision}:${e.recordVersion}`,lifecycleEvents:structuredClone(e.lifecycleEvents),reviewEvents:structuredClone(e.reviewEvents),reviewSummary:ge(e.reviewEvents)}}var Ue=require("node:crypto"),b=require("node:fs/promises"),N=require("node:path");var V=require("node:fs"),Me=require("node:os"),bt=require("node:path");function Cn(){return new Date().toISOString()}function xn(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function _t(e){try{return JSON.parse((0,V.readFileSync)(e,"utf8"))}catch{return null}}function Nn(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Vn(e){return e.hostname!==(0,Me.hostname)()?!0:Nn(e.pid)}function St(e,t){(0,V.mkdirSync)((0,bt.dirname)(e),{recursive:!0}),(0,V.writeFileSync)(e,JSON.stringify(t,null,2)+`
2
+ `,{encoding:"utf8",flag:"wx"})}function Pn(e,t){let n=_t(e);n?.pid!==t.pid||n.hostname!==t.hostname||(0,V.rmSync)(e,{force:!0})}function Tt(e,t,n){let i=Cn(),o={schemaVersion:1,name:t,pid:process.pid,hostname:(0,Me.hostname)(),processStartedAt:xn(),version:n,acquiredAt:i,updatedAt:i};try{St(e,o)}catch(r){if(r.code!=="EEXIST")throw r;let c=_t(e);if(c&&Vn(c))throw new Error(`${t} is already locked by PID ${c.pid} on ${c.hostname}.`);(0,V.rmSync)(e,{force:!0}),St(e,o)}return{record:o,release:()=>{Pn(e,o)}}}var kt="0.9.28";var We=1,$n="repository.v1.json",On=5e3,Dn=20,Fn=64*1024*1024,qe=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 n=t.snapshotFileName??$n;if((0,N.basename)(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))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,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=t.now??(()=>new Date().toISOString()),this.lockTimeoutMs=He(t.lockTimeoutMs,On,100,6e4,"lockTimeoutMs"),this.lockRetryMs=He(t.lockRetryMs,Dn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=He(t.maxSnapshotBytes,Fn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=t.onRecovery}async create(t){return this.mutate(n=>n.create(t))}async createRevision(t,n){return this.mutate(i=>i.createRevision(t,n))}async get(t,n){return(await this.load()).repository.get(t,n)}async require(t,n){return(await this.load()).repository.require(t,n)}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(n=>n.transition(t))}async appendReviewEvent(t){return this.mutate(n=>n.appendReviewEvent(t))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(t){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await t(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(t){let n=this.mutationTail.then(t,t);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let t=Date.now(),n;for(;Date.now()-t<=this.lockTimeoutMs;)try{return Tt(this.lockPath,`artifact-repository:${(0,N.basename)(this.snapshotPath)}`,kt)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await qn(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let t,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){t=Ie(r)}if(!n&&(t||await jn(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"}),n=r,i=!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,Ie(r)])}):r}if(!n&&t)throw t;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new B({now:this.now,idFactory:r=>`${r}_${(0,Ue.randomUUID)()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(t){let n=this.now(),o={...{schemaVersion:We,generation:t.generation,createdAt:t.createdAt,updatedAt:n,state:t.repository.exportState()},generation:t.generation+1},r=Mn(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,b.mkdir)(this.directory,{recursive:!0,mode:448}),t.hasSnapshot&&!t.recoveredFromBackup&&t.sourceSnapshot&&await Ct(this.backupPath,`${JSON.stringify(t.sourceSnapshot,null,2)}
4
+ `),await Ct(this.snapshotPath,a)}async readSnapshot(t,n){let i;try{i=await(0,b.stat)(t)}catch(o){if(!n&&Je(o,"ENOENT")||n&&Je(o,"ENOENT"))return;throw Be("Unable to inspect artifact repository snapshot",t,o)}if(!i.isFile()||i.size>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:t,sizeBytes:i.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await(0,b.readFile)(t);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return Ln(JSON.parse(o.toString("utf8")),t)}catch(o){throw o instanceof u?o:Be("Unable to parse artifact repository snapshot",t,o,!0)}}};function Ln(e,t){if(!je(e)||e.schemaVersion!==We||!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))||!je(e.state)||e.state.schemaVersion!==1||!Array.isArray(e.state.records)||!je(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 n=e,i=Hn(n),o=xt(i);if(n.checksum.value!==o)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:t});return new B({initialState:n.state}),structuredClone(n)}function Mn(e){return{...structuredClone(e),checksum:{algorithm:"sha256",value:xt(e)}}}function Hn(e){return{schemaVersion:e.schemaVersion,generation:e.generation,createdAt:e.createdAt,updatedAt:e.updatedAt,state:e.state}}function xt(e){return T(JSON.stringify(e)).value}async function Ct(e,t){await(0,b.mkdir)((0,N.dirname)(e),{recursive:!0,mode:448});let n=`${e}.tmp.${process.pid}.${(0,Ue.randomUUID)()}`,i;try{i=await(0,b.open)(n,"wx",384),await i.writeFile(t,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,await(0,b.rename)(n,e);try{let o=await(0,b.open)((0,N.dirname)(e),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{i&&await i.close().catch(()=>{}),await(0,b.unlink)(n).catch(()=>{})}}function He(e,t,n,i,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<n||e>i)throw new TypeError(`${o} must be an integer between ${n} and ${i}`);return e}function je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Je(e,t){return e instanceof Error&&e.code===t}async function jn(e){try{return(await(0,b.stat)(e)).isFile()}catch(t){if(Je(t,"ENOENT"))return!1;throw Be("Unable to inspect artifact repository backup",e,t)}}function Ie(e){return e instanceof Error?e:new Error(String(e))}function Be(e,t,n,i=!1){return new u(i?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${e}: ${Ie(n).message}`,{snapshotPath:t},{cause:Ie(n)})}function qn(e){return new Promise(t=>setTimeout(t,e))}var ze=require("node:buffer");var Jn=16*1024*1024,Bn=5e3,Un=1e5,Wn=1e6,zn=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,X=class extends Error{constructor(n,i){super(i===void 0?n:`${n} at diff line ${i}`);this.line=i;this.name="XenoDiffParseError"}line;code="XENO_DIFF_INVALID"};function Ke(e,t={}){if(typeof e!="string")throw new TypeError("Unified diff must be a string");let n=we(t.maxBytes,Jn,1024,256*1024*1024,"maxBytes"),i=we(t.maxFiles,Bn,1,1e5,"maxFiles"),o=we(t.maxHunks,Un,1,1e6,"maxHunks"),r=we(t.maxLines,Wn,1,5e6,"maxLines");if(ze.Buffer.byteLength(e,"utf8")>n)throw new X(`Unified diff exceeds ${n} bytes`);let a=e.replace(/\r\n/g,`
5
5
  `).replace(/\r/g,`
6
6
  `),c=a.length===0?[]:a.split(`
7
7
  `);if(c.length>r)throw new X(`Unified diff exceeds ${r} lines`);let s=[],d,f=0,g=(v,m)=>{if(d&&Nt(d,s),s.length>=i)throw new X(`Unified diff exceeds ${i} 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]=Kn(m.slice(11),v+1);g(_,G).headerLines.push(m);continue}if(m.startsWith("--- ")){(!d||d.hunks.length>0)&&(d=g()),d.oldPath=Vt(m.slice(4)),d.headerLines.push(m);continue}if(m.startsWith("+++ ")){d||(d=g()),d.newPath=Vt(m.slice(4)),d.headerLines.push(m);continue}if(m.startsWith("@@ ")){if(!d)throw new X("Hunk appears before a file header",v+1);if(f>=o)throw new X(`Unified diff exceeds ${o} hunks`,v+1);let _=zn.exec(m);if(!_)throw new X("Malformed unified diff hunk header",v+1);let G=Number(_[1]),ue=_[2]===void 0?1:Number(_[2]),ke=Number(_[3]),le=_[4]===void 0?1:Number(_[4]),$=[],Y=G,Z=ke,ft=0,pt=0,D=v+1;for(;D<c.length;D+=1){let y=c[D],rn=Y-G===ue,on=Z-ke===le;if(rn&&on&&y.length===0||y.startsWith("diff --git ")||y.startsWith("@@ ")||y.startsWith("--- ")&&c[D+1]?.startsWith("+++ "))break;if(y.startsWith("+"))$.push({kind:"addition",text:y.slice(1),newLine:Z}),Z+=1,ft+=1;else if(y.startsWith("-"))$.push({kind:"deletion",text:y.slice(1),oldLine:Y}),Y+=1,pt+=1;else if(y.startsWith(" "))$.push({kind:"context",text:y.slice(1),oldLine:Y,newLine:Z}),Y+=1,Z+=1;else if(y==="\")$.push({kind:"no-newline",text:y});else{if(y.length===0&&D===c.length-1)break;throw new X("Unexpected line inside unified diff hunk",D+1)}}let ut=$.filter(y=>y.kind==="context"||y.kind==="deletion").length,lt=$.filter(y=>y.kind==="context"||y.kind==="addition").length;if(ut!==ue||lt!==le)throw new X(`Hunk line counts do not match header (expected -${ue}/+${le}, observed -${ut}/+${lt})`,v+1);let mt=m,nn=T(JSON.stringify({oldPath:d.oldPath??null,newPath:d.newPath??null,header:mt,lines:$})).value.slice(0,32);d.hunks.push({hunkId:nn,header:mt,..._[5]?{section:_[5]}:{},oldStart:G,oldLines:ue,newStart:ke,newLines:le,additions:ft,deletions:pt,lines:$}),f+=1,v=D-1;continue}if(!d){if(m.trim().length===0)continue;throw new X("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=j(m.slice(12))):m.startsWith("rename to ")?(d.status="renamed",d.newPath=j(m.slice(10))):m.startsWith("copy from ")?(d.status="copied",d.oldPath=j(m.slice(10))):m.startsWith("copy to ")?(d.status="copied",d.newPath=j(m.slice(8))):(m.startsWith("Binary files ")||m==="GIT binary patch")&&(d.binary=!0,d.status="binary")}d&&Nt(d,s);let R=s.reduce((v,m)=>v+m.additions,0),O=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:R,deletions:O,rawDiff:a}}function Ge(e,t){let n=Ke(e,{mode:t.mode,repositoryId:t.repositoryId,baseRef:t.baseRef,headRef:t.headRef}),i=n,o=S(i),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}_${T(`${r}:${n.rawDiff}`).value.slice(0,24)}`,s=t.revision??1,d={schemaVersion:1,artifactId:c,revision:s,kind:a,title:t.title??`${Zn(n.mode)} diff (${n.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:k(i),sizeBytes:ze.Buffer.byteLength(o,"utf8"),encoding:"utf8",storage:{type:"inline",text:o},redactedPreview:`${n.files.length} files, +${n.additions}/-${n.deletions}`},provenance:{producer:{...t.producer}},anchors:n.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":n.mode,"xeno.diff.files":n.files.length,"xeno.diff.additions":n.additions,"xeno.diff.deletions":n.deletions}};return I(d),d}function Ye(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(i){throw new X(`Diff artifact JSON is malformed: ${Qn(i).message}`)}if(!Yn(t))throw new X("Diff artifact document is invalid");let n=Ke(t.rawDiff,{mode:t.mode,repositoryId:t.repositoryId,baseRef:t.baseRef,headRef:t.headRef});if(S(n)!==S(t))throw new X("Diff artifact document does not match its raw diff");return n}function Nt(e,t){if(!e.oldPath&&!e.newPath)throw new X("Diff file has no path");e.oldPath||(e.status="added"),e.newPath||(e.status="deleted"),e.binary&&(e.status="binary");let n=e.hunks.reduce((o,r)=>o+r.additions,0),i=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:n,deletions:i,binary:e.binary,headerLines:[...e.headerLines],hunks:structuredClone(e.hunks)})}function Kn(e,t){let n=Gn(e);if(n.length!==2)throw new X("Malformed diff --git path pair",t);return[j(n[0]),j(n[1])]}function Gn(e){let t=[],n=0;for(;n<e.length;){for(;e[n]===" ";)n+=1;if(n>=e.length)break;if(e[n]==='"'){let i='"';n+=1;let o=!1;for(;n<e.length;){let r=e[n];if(i+=r,n+=1,!o&&r==='"')break;o=!o&&r==="\\",r!=="\\"&&(o=!1)}t.push($t(i))}else{let i=e.indexOf(" ",n);if(i===-1){t.push(e.slice(n));break}t.push(e.slice(n,i)),n=i+1}}return t}function $t(e){return!e.startsWith('"')||!e.endsWith('"')?e:e.slice(1,-1).replace(/\\([\\"tnr]|[0-7]{1,3})/g,(n,i)=>i==="t"?" ":i==="n"?`
8
- `:i==="r"?"\r":i==="\\"?"\\":i==='"'?'"':String.fromCharCode(Number.parseInt(i,8)))}function Vt(e){let t=e.split(" ",1)[0].trim();if(t!=="/dev/null")return j($t(t))}function j(e){let t=e.replace(/\\/g,"/");return t.startsWith("a/")||t.startsWith("b/")?t.slice(2):t}function Yn(e){return!Pt(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=>Pt(t)&&typeof t.displayPath=="string"&&Array.isArray(t.headerLines)&&Array.isArray(t.hunks))}function Pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function we(e,t,n,i,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<n||e>i)throw new TypeError(`${o} must be an integer between ${n} and ${i}`);return e}function Zn(e){return e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" ")}function Qn(e){return e instanceof Error?e:new Error(String(e))}var Dt=require("node:crypto");var U=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,Dt.randomUUID)()}`)}async addComment(t){let n=Re(t.body,"Review comment body",65536),i=await this.repository.require(t.artifactId,t.revision),o=Ze(i,t),r=Ee(this.idFactory(),"Comment ID"),a=ei(t.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:i.recordVersion,event:{type:"comment-added",artifactId:i.artifact.artifactId,artifactRevision:i.artifact.revision,artifactHash:i.artifact.content.hash,actor:this.actor,commentId:r,body:n,...o?{anchor:o}:{},...a?{parentCommentId:a}:{}}})}async setCommentResolution(t){let n=Ee(t.commentId,"Review comment ID"),i=Ot(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:n,...i?{reason:i}:{}}})}async decide(t){let n=await this.repository.require(t.artifactId,t.revision);if(n.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${n.artifact.state}`);let i=Ze(n,t),o=Ot(t.rationale,"Decision rationale",64*1024),r=await this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:"decision-recorded",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,decision:t.decision,...o?{rationale:o}:{},...i?{scope:i}:{}}});if(i||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 Ze(e,t){if((t.line!==void 0||t.hunkId!==void 0)&&!t.file)throw P("Line and hunk anchors require a file");if(t.line!==void 0&&t.hunkId!==void 0)throw P("Line and hunk anchors cannot be combined");if(!t.file)return;let n=Ft(t.file);if(t.line!==void 0&&(!Number.isInteger(t.line)||t.line<1))throw P("Review line must be a positive integer");if(e.artifact.kind==="diff"||e.artifact.kind==="patch"){let o=Ye(e.artifact).files.find(r=>r.displayPath===n);if(!o)throw P(`File ${n} is not present in this artifact`);if(t.hunkId&&!o.hunks.some(r=>r.hunkId===t.hunkId))throw P(`Hunk ${t.hunkId} is not present in ${n}`)}return t.hunkId?{kind:"diff-hunk",path:n,hunkId:Ee(t.hunkId,"Hunk ID"),artifactId:e.artifact.artifactId,revision:e.artifact.revision}:t.line!==void 0?{kind:"source-line",path:n,startLine:t.line}:{kind:"file",path:n}}function Ft(e){let t=Re(e,"Artifact review file",4096).replace(/\\/g,"/").replace(/^\.\//,"");if(t.startsWith("../")||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").some(n=>n===".."||n.length===0))throw P("Artifact review file anchors must be repository-relative paths");return t}function Re(e,t,n){let i=typeof e=="string"?e.trim():"";if(!i)throw P(`${t} cannot be empty`);if(i.length>n)throw P(`${t} exceeds ${n} characters`);return i}function Ot(e,t,n){if(e!==void 0)return Re(e,t,n)}function Ee(e,t){let n=Re(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(n))throw P(`${t} contains unsupported characters`);return n}function ei(e,t){return e===void 0?void 0:Ee(e,t)}function P(e){return new u("ARTIFACT_REVIEW_INVALID",e)}var Lt=require("node:crypto");var z="xeno.spec.v1",ce="xeno.spec-execution.v1",w=class extends Error{constructor(n){super(`XENO spec is invalid: ${n.join("; ")}`);this.issues=n;this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},Qe=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,Lt.randomUUID)())}async create(t,n){if(t.revision!==1||t.predecessorRevision!==void 0)throw new w(["A new spec must begin at revision 1 without a predecessor"]);let i=et(t,n);return await this.repository.create(i.requirements),await this.repository.create(i.design),await this.repository.create(i.taskGraph),await this.repository.create(i.plan),i}async revise(t,n){let i=W(t.specId),o=await this.repository.require(i.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=et(t,n);return await this.repository.createRevision(r.requirements,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.design,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.taskGraph,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.plan,{actor:n.producer,reason:"spec-revised"}),r}async approve(t,n,i){return new U({repository:this.repository,actor:n}).decide({artifactId:W(t).plan,decision:"approved",...i?{rationale:i}:{}})}async reject(t,n,i){return new U({repository:this.repository,actor:n}).decide({artifactId:W(t).plan,decision:"rejected",rationale:i})}async startExecution(t,n){let i=await this.repository.require(W(t).plan);if(i.artifact.state!=="approved")throw new w([`Spec ${t} must be approved before execution`]);let o=tt(i.artifact),r=this.now(),a={schemaVersion:ce,executionId:`spec_execution_${this.idFactory()}`,specId:o.specId,specRevision:o.revision,planArtifactId:i.artifact.artifactId,planHash:{...i.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(nt(a,{producer:n,identity:i.artifact.identity,sensitivity:i.artifact.sensitivity,accessPolicyId:i.artifact.accessPolicyId}))}async updateExecution(t,n,i){let o=await this.repository.require(t),r=Ht(o.artifact),a=await this.repository.require(r.planArtifactId,r.specRevision);if(a.artifact.state!=="approved"||!de(a.artifact.content.hash,r.planHash))throw new w(["Execution is no longer bound to the approved plan revision"]);let c=n(structuredClone(r));c.schemaVersion=ce,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(),it(c,tt(a.artifact));let s=nt(c,{producer:i,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:i,reason:"spec-execution-updated"})}};function W(e){let t=ii(e,"specId");return{plan:`spec_${t}_plan`,requirements:`spec_${t}_requirements`,design:`spec_${t}_design`,taskGraph:`spec_${t}_task_graph`}}function Mt(e){let t=[];e?.schemaVersion!==z&&t.push(`schemaVersion must be ${z}`),ae(e?.specId,"specId",t),(!Number.isInteger(e?.revision)||e.revision<1)&&t.push("revision must be a positive integer"),x(e?.title,"title",t),x(e?.problem,"problem",t),Se(e?.createdAt,"createdAt",t),Se(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 n=Xe(e?.requirements,"requirement",t),i=Xe(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){ae(s?.id,"acceptance criterion id",t),x(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??[])ae(d,"required evidence kind",t)}for(let s of e?.requirements??[])x(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`);x(e?.design?.summary,"design summary",t);let a=Xe(e?.design?.decisions,"design decision",t),c=Xe(e?.design?.risks,"risk",t);for(let s of e?.design?.decisions??[]){x(s?.decision,`design decision ${s?.id??"?"}`,t),x(s?.rationale,`design rationale ${s?.id??"?"}`,t);for(let d of s?.requirementIds??[])n.has(d)||t.push(`Design decision ${s.id} references unknown requirement ${d}`)}for(let s of e?.design?.risks??[])x(s?.description,`risk ${s?.id??"?"}`,t),x(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??[]){x(s?.title,`task title ${s?.id??"?"}`,t),x(s?.description,`task description ${s?.id??"?"}`,t);for(let d of s?.dependsOn??[])i.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??[])n.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??[])qt(d)||t.push(`Task ${s.id} has unsafe expected path ${d}`)}return ri(e?.tasks??[])&&t.push("Task dependency graph contains a cycle"),[...new Set(t)]}function be(e){let t=Mt(e);if(t.length>0)throw new w(t)}function et(e,t){be(e);let n=W(e.specId),i=e.revision,o={...t,createdAt:e.updatedAt,state:"draft"},r=se({artifactId:n.requirements,revision:i,predecessorRevision:e.predecessorRevision,kind:"requirements",title:`${e.title} - requirements`,value:{schemaVersion:z,specId:e.specId,revision:i,problem:e.problem,requirements:e.requirements,acceptanceCriteria:e.acceptanceCriteria},context:o}),a=se({artifactId:n.design,revision:i,predecessorRevision:e.predecessorRevision,kind:"design",title:`${e.title} - design`,value:{schemaVersion:z,specId:e.specId,revision:i,design:e.design,...e.sourceBaseline?{sourceBaseline:e.sourceBaseline}:{}},context:o}),c=se({artifactId:n.taskGraph,revision:i,predecessorRevision:e.predecessorRevision,kind:"task-graph",title:`${e.title} - task graph`,value:{schemaVersion:z,specId:e.specId,revision:i,tasks:e.tasks},context:o}),s=[r,a,c].map(f=>({relation:"decomposes",target:{type:"artifact",id:f.artifactId,revision:f.revision}})),d=se({artifactId:n.plan,revision:i,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 tt(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=jt(e);if(be(t),t.revision!==e.revision)throw new w(["Spec and artifact revisions differ"]);if(!de(k(t),e.content.hash))throw new w(["Spec artifact content hash is invalid"]);return structuredClone(t)}function nt(e,t,n=1,i){let o=structuredClone(e);return se({artifactId:e.executionId,revision:n,predecessorRevision:i,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 Ht(e){if(e.kind!=="custom:xeno.spec-execution")throw new w([`Artifact ${e.artifactId} is not a spec execution`]);let t=jt(e);if(t.schemaVersion!==ce||t.executionId!==e.artifactId)throw new w(["Spec execution identity or schema is invalid"]);if(!de(k(t),e.content.hash))throw new w(["Spec execution content hash is invalid"]);return structuredClone(t)}function it(e,t){let n=[];e.schemaVersion!==ce&&n.push("Execution schema is invalid"),(e.specId!==t.specId||e.specRevision!==t.revision)&&n.push("Execution is bound to the wrong spec revision");let i=new Map(t.tasks.map(r=>[r.id,r])),o=new Set;for(let r of e.tasks){o.has(r.taskId)&&n.push(`Duplicate execution task ${r.taskId}`),o.add(r.taskId);let a=i.get(r.taskId);if(!a){n.push(`Unknown execution task ${r.taskId}`);continue}for(let c of a.acceptanceCriterionIds)Array.isArray(r.acceptanceEvidence?.[c])||n.push(`Task ${r.taskId} is missing acceptance evidence slot ${c}`)}for(let r of i.keys())o.has(r)||n.push(`Execution is missing task ${r}`);for(let r of e.observedPaths)oi(r)||n.push(`Unsafe observed path ${r}`);if(Se(e.createdAt,"execution createdAt",n),Se(e.updatedAt,"execution updatedAt",n),n.length>0)throw new w([...new Set(n)])}function ti(e,t,n,i,o=new Date().toISOString()){be(e),it(n,e);let r=[];(!de(t,i)||!de(n.planHash,i))&&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(n.tasks.map(d=>[d.taskId,d]));for(let d of n.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 n.observedPaths)s.some(f=>si(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:n.executionId,checkedAt:o,drifted:r.length>0,findings:r}}function se(e){let t=e.value,n=S(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:ni(e.kind),sensitivity:e.context.sensitivity??"internal",...e.context.identity?{identity:structuredClone(e.context.identity)}:{},content:{hash:k(t),sizeBytes:Buffer.byteLength(n,"utf8"),encoding:"utf8",storage:{type:"inline",text:n},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 ni(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 jt(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(n){throw new w([`Spec artifact JSON is invalid: ${n instanceof Error?n.message:String(n)}`])}}function Xe(e,t,n){let i=new Set;(!Array.isArray(e)||e.length===0)&&n.push(`${t} list cannot be empty`);for(let o of e??[])ae(o?.id,`${t} id`,n),i.has(o?.id??"")&&n.push(`Duplicate ${t}: ${o?.id}`),o?.id&&i.add(o.id);return i}function ae(e,t,n){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(e))&&n.push(`${t} must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}`)}function x(e,t,n){(typeof e!="string"||e.trim().length===0||e.length>64*1024)&&n.push(`${t} must be non-empty and no longer than 65536 characters`)}function Se(e,t,n){(typeof e!="string"||!e.includes("T")||!Number.isFinite(Date.parse(e)))&&n.push(`${t} must be an ISO 8601 timestamp`)}function ii(e,t){let n=[];if(ae(e,t,n),n.length>0)throw new w(n);return e}function ri(e){let t=new Map(e.map(r=>[r.id,r])),n=new Set,i=new Set,o=r=>{if(n.has(r))return!0;if(i.has(r))return!1;n.add(r);for(let a of t.get(r)?.dependsOn??[])if(o(a))return!0;return n.delete(r),i.add(r),!1};return e.some(r=>o(r.id))}function qt(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 oi(e){return qt(e)&&!e.includes("*")}function si(e,t){let n=e.replace(/\\/gu,"/"),i=t.replace(/\\/gu,"/");if(i.endsWith("/**")){let o=i.slice(0,-3).replace(/\/$/u,"");return n===o||n.startsWith(`${o}/`)}if(i.endsWith("/*")){let o=i.slice(0,-2).replace(/\/$/u,""),r=n.startsWith(`${o}/`)?n.slice(o.length+1):"";return r.length>0&&!r.includes("/")}return n===i}function de(e,t){return e.algorithm===t.algorithm&&e.value===t.value}var Jt=require("node:crypto");var ot="xeno.review-report.v1",Bt=["correctness","security","performance","api","tests","documentation"],Ut=["source","test","trace","artifact","reproduction","benchmark"],E=class extends Error{constructor(n){super(`XENO review is invalid: ${n.join("; ")}`);this.issues=n;this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},rt=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??(n=>`${n}_${(0,Jt.randomUUID)()}`)}async run(t){st(t.pack),at(t.target),_e(t.runId,"runId");let n=this.now(),i=await Promise.all(t.pack.dimensions.map(async(s,d)=>{let f=await this.reviewer({...t,dimension:s,reviewerSlot:d});return li(f,s,t.pack.maxFindings),structuredClone(f)})),o=i.flatMap(s=>s.findings.map(d=>({finding:d,reviewerAgentId:s.reviewerAgentId})));if(o.length>t.pack.maxFindings)throw new E([`Reviewers returned ${o.length} findings, exceeding maxFindings ${t.pack.maxFindings}`]);let r=pi(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 mi(_),structuredClone(_)})):[];s.verifications=vi(d),s.evidence=zt([...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"),R=new Set(s.evidence.map(v=>v.producerId)).size;f>=t.pack.minimumVerifierReproductions?(s.state="verified",s.verificationBasis="verifier"):t.pack.allowIndependentEvidenceVerification&&R>=t.pack.minimumIndependentEvidenceProducers?(s.state="verified",s.verificationBasis="independent-evidence"):g?(s.state="rejected",s.verificationBasis="verifier"):(s.state="unverified",s.verificationBasis="none");let O=s.verifications.map(v=>v.confidence).filter(v=>v!==void 0);O.length>0&&(s.confidence=en(Math.min(s.confidence,...O)))}r.sort(hi);let a=this.now(),c={schemaVersion:ot,reportId:_e(this.idFactory("report"),"reportId"),runId:t.runId,pack:structuredClone(t.pack),target:structuredClone(t.target),startedAt:n,completedAt:a,reviewers:i.map(s=>({agentId:s.reviewerAgentId,dimension:s.dimension,findingCount:s.findings.length})),findings:r,summary:Yt(r)};return fe(c),c}};function ai(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 st(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 n of e?.dimensions??[])Qt(n)||t.push(`Invalid review dimension ${n}`);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 E(t)}function at(e){let t=[];if(C(e?.artifactId,"target artifactId",t),(!Number.isInteger(e?.revision)||e.revision<1)&&t.push("Target revision must be positive"),q(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 E(t)}function fe(e){let t=[];e?.schemaVersion!==ot&&t.push("Review report schemaVersion is invalid"),C(e?.reportId,"reportId",t),C(e?.runId,"runId",t),Te(e?.startedAt,"startedAt",t),Te(e?.completedAt,"completedAt",t),Date.parse(e?.completedAt)<Date.parse(e?.startedAt)&&t.push("completedAt cannot precede startedAt");try{st(e.pack)}catch(r){t.push(r instanceof Error?r.message:String(r))}try{at(e.target)}catch(r){t.push(r instanceof Error?r.message:String(r))}let n=new Set,i=new Set;for(let r of e?.findings??[])C(r?.findingId,"findingId",t),n.has(r.findingId)&&t.push(`Duplicate findingId ${r.findingId}`),n.add(r.findingId),/^[a-f0-9]{64}$/u.test(r?.fingerprint??"")||t.push(`Finding ${r.findingId} has invalid fingerprint`),i.has(r.fingerprint)&&t.push(`Duplicate finding fingerprint ${r.fingerprint}`),i.add(r.fingerprint),q(r?.title,`finding ${r.findingId} title`,t),q(r?.summary,`finding ${r.findingId} summary`,t),Zt(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=Yt(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 E([...new Set(t)])}function ci(e,t){fe(e);let n=e,i=S(n),o=t.artifactId??`review_${T(`${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:k(n),sizeBytes:Buffer.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i},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:Kt(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 di(e){if(e.kind!=="review-report"||e.mediaType!=="application/vnd.xeno.review-report+json")throw new E([`Artifact ${e.artifactId} is not a XENO review report`]);if(e.content.storage.type!=="inline"||typeof e.content.storage.text!="string")throw new E(["Review report requires inline JSON content"]);let t;try{t=JSON.parse(e.content.storage.text)}catch(n){throw new E([`Review report JSON is invalid: ${n instanceof Error?n.message:String(n)}`])}if(fe(t),!Ai(k(t),e.content.hash))throw new E(["Review report content hash is invalid"]);return structuredClone(t)}function fi(e,t={}){fe(e);let n=[];for(let i of e.findings){if(t.verifiedOnly!==!1&&i.state!=="verified")continue;let o=i.anchors.find(r=>r.kind==="source-line"||r.kind==="file"||r.kind==="diff-hunk");!o||!("path"in o)||n.push({findingId:i.findingId,path:o.path,...o.kind==="source-line"?{line:o.startLine}:{},severity:i.severity,verified:i.state==="verified",body:[`**${i.severity.toUpperCase()} - ${i.title}**`,"",i.summary,"",`Evidence: ${i.evidence.map(r=>r.summary).join("; ")||"none"}`,i.remediation?`Suggested remediation: ${i.remediation}`:"",`XENO finding: ${i.findingId} (${i.state}, confidence ${i.confidence.toFixed(2)})`].filter(Boolean).join(`
9
- `)})}return n}function pi(e,t){let n=new Map;for(let i of e){Wt(i.finding),_e(i.reviewerAgentId,"reviewerAgentId");let o=ui(i.finding),r=n.get(o)??[];r.push(structuredClone(i)),n.set(o,r)}return[...n.entries()].map(([i,o])=>{let r=[...o].sort((c,s)=>K(s.finding.severity)-K(c.finding.severity))[0],a=zt(o.flatMap(c=>c.finding.evidence));return{findingId:_e(t("finding"),"findingId"),fingerprint:i,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)=>K(s.finding.severity)>K(c)?s.finding.severity:c,r.finding.severity),confidence:en(Math.max(...o.map(c=>c.finding.confidence))),state:"unverified",verificationBasis:"none",anchors:Kt(o.flatMap(c=>c.finding.anchors)),evidence:a,verifications:[],...r.finding.remediation?{remediation:r.finding.remediation}:{},duplicateProposalCount:o.length}})}function ui(e){let t=e.anchors.map(Gt).sort();return k({ruleId:e.ruleId??"",title:gi(e.title),anchors:t}).value}function li(e,t,n){let i=[];C(e?.reviewerAgentId,"reviewerAgentId",i),e?.dimension!==t&&i.push(`Reviewer returned dimension ${e?.dimension} for requested ${t}`),Te(e?.completedAt,"reviewer completedAt",i),(!Array.isArray(e?.findings)||e.findings.length>n)&&i.push("Reviewer finding list is invalid or exceeds maxFindings");for(let o of e?.findings??[]){try{Wt(o)}catch(r){i.push(r instanceof Error?r.message:String(r))}o.dimension!==t&&i.push(`Finding dimension ${o.dimension} differs from reviewer dimension ${t}`)}if(i.length>0)throw new E([...new Set(i)])}function Wt(e){let t=[];Qt(e?.dimension)||t.push(`Invalid finding dimension ${e?.dimension}`),q(e?.title,"finding title",t),q(e?.summary,"finding summary",t),Zt(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 n of e?.evidence??[])ct(n,t);if(e?.ruleId!==void 0&&C(e.ruleId,"ruleId",t),t.length>0)throw new E([...new Set(t)])}function mi(e){let t=[];C(e?.verifierAgentId,"verifierAgentId",t),["reproduced","rejected","inconclusive"].includes(e?.outcome)||t.push("Verifier outcome is invalid"),q(e?.rationale,"verifier rationale",t),Te(e?.completedAt,"verifier completedAt",t),Array.isArray(e?.evidence)||t.push("Verifier evidence must be an array");for(let n of e?.evidence??[])ct(n,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 E([...new Set(t)])}function ct(e,t){C(e?.evidenceId,"evidenceId",t),C(e?.producerId,"evidence producerId",t),q(e?.summary,"evidence summary",t),(typeof e?.kind!="string"||!(Ut.includes(e.kind)||F(e.kind)))&&t.push(`Invalid evidence kind ${e?.kind}`)}function zt(e){let t=new Map;for(let n of e){let i=[];if(ct(n,i),i.length>0)throw new E(i);let o=t.get(n.evidenceId);if(o&&S(o)!==S(n))throw new E([`Conflicting evidence ID ${n.evidenceId}`]);t.set(n.evidenceId,structuredClone(n))}return[...t.values()].sort((n,i)=>n.evidenceId.localeCompare(i.evidenceId))}function vi(e){let t=new Map;for(let n of e){if(t.has(n.verifierAgentId))throw new E([`Verifier ${n.verifierAgentId} returned more than one result for a finding`]);t.set(n.verifierAgentId,structuredClone(n))}return[...t.values()].sort((n,i)=>n.verifierAgentId.localeCompare(i.verifierAgentId))}function Kt(e){let t=new Map;for(let n of e)t.set(Gt(n),structuredClone(n));return[...t.entries()].sort(([n],[i])=>n.localeCompare(i)).map(([,n])=>n)}function Gt(e){return S(e)}function Yt(e){let t={info:0,low:0,medium:0,high:0,critical:0};for(let n of e)t[n.severity]+=1;return{total:e.length,verified:e.filter(n=>n.state==="verified").length,unverified:e.filter(n=>n.state==="unverified").length,rejected:e.filter(n=>n.state==="rejected").length,bySeverity:t}}function hi(e,t){return K(t.severity)-K(e.severity)||+(t.state==="verified")-+(e.state==="verified")||e.fingerprint.localeCompare(t.fingerprint)}function K(e){return{info:0,low:1,medium:2,high:3,critical:4}[e]}function Zt(e){return typeof e=="string"&&["info","low","medium","high","critical"].includes(e)}function Qt(e){return typeof e=="string"&&(Bt.includes(e)||F(e))}function gi(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function en(e){return Math.max(0,Math.min(1,Number(e.toFixed(6))))}function C(e,t,n){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u.test(e))&&n.push(`${t} has an invalid identifier`)}function _e(e,t){let n=[];if(C(e,t,n),n.length>0)throw new E(n);return e}function q(e,t,n){(typeof e!="string"||e.trim().length===0||e.length>64*1024)&&n.push(`${t} must be non-empty and no longer than 65536 characters`)}function Te(e,t,n){(typeof e!="string"||!e.includes("T")||!Number.isFinite(Date.parse(e)))&&n.push(`${t} must be an ISO 8601 timestamp`)}function Ai(e,t){return e.algorithm===t.algorithm&&e.value===t.value}var pe=require("node:buffer");function yi(e,t){let n=t.contentEncoding??"utf8",i=n==="base64"?pe.Buffer.from(e.content,"base64"):pe.Buffer.from(e.content,"utf8"),o=[t.identity?.runId,t.identity?.taskId,t.identity?.turnId].filter(Boolean).join(":"),r=T(`${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??Si(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:T(i),sizeBytes:i.byteLength,encoding:n,storage:n==="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:n}}};return I(a),a}function Ii(e){I(e);let t=e.extensions?.["xeno.legacy.agentArtifact"];if(dt(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 wi(e,t){let n=tn(e),i=S(n),o={schemaVersion:1,artifactId:t.artifactId??e.id,revision:t.revision??1,kind:bi(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:k(n),sizeBytes:pe.Buffer.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i}},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":n}};return I(o),o}function Ei(e){I(e);let t=e.extensions?.["xeno.legacy.toolEvidence"];if(_i(t))return structuredClone(t);throw new TypeError("XENO artifact does not contain lossless legacy ToolEvidence data")}function Ri(e,t){let n=tn(e),i=e.files.map(a=>a.patch).filter(a=>!!a);if(e.files.length>0&&i.length===e.files.length&&i.every(a=>a.startsWith("diff --git ")))try{let a=Ge(i.join(`
8
+ `:i==="r"?"\r":i==="\\"?"\\":i==='"'?'"':String.fromCharCode(Number.parseInt(i,8)))}function Vt(e){let t=e.split(" ",1)[0].trim();if(t!=="/dev/null")return j($t(t))}function j(e){let t=e.replace(/\\/g,"/");return t.startsWith("a/")||t.startsWith("b/")?t.slice(2):t}function Yn(e){return!Pt(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=>Pt(t)&&typeof t.displayPath=="string"&&Array.isArray(t.headerLines)&&Array.isArray(t.hunks))}function Pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function we(e,t,n,i,o){if(e===void 0)return t;if(!Number.isInteger(e)||e<n||e>i)throw new TypeError(`${o} must be an integer between ${n} and ${i}`);return e}function Zn(e){return e.split("-").map(t=>t[0].toUpperCase()+t.slice(1)).join(" ")}function Qn(e){return e instanceof Error?e:new Error(String(e))}var Dt=require("node:crypto");var U=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,Dt.randomUUID)()}`)}async addComment(t){let n=Re(t.body,"Review comment body",65536),i=await this.repository.require(t.artifactId,t.revision),o=Ze(i,t),r=Ee(this.idFactory(),"Comment ID"),a=ei(t.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:i.recordVersion,event:{type:"comment-added",artifactId:i.artifact.artifactId,artifactRevision:i.artifact.revision,artifactHash:i.artifact.content.hash,actor:this.actor,commentId:r,body:n,...o?{anchor:o}:{},...a?{parentCommentId:a}:{}}})}async setCommentResolution(t){let n=Ee(t.commentId,"Review comment ID"),i=Ot(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:n,...i?{reason:i}:{}}})}async decide(t){let n=await this.repository.require(t.artifactId,t.revision);if(n.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${n.artifact.state}`);let i=Ze(n,t),o=Ot(t.rationale,"Decision rationale",64*1024),r=await this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:"decision-recorded",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,decision:t.decision,...o?{rationale:o}:{},...i?{scope:i}:{}}});if(i||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 Ze(e,t){if((t.line!==void 0||t.hunkId!==void 0)&&!t.file)throw P("Line and hunk anchors require a file");if(t.line!==void 0&&t.hunkId!==void 0)throw P("Line and hunk anchors cannot be combined");if(!t.file)return;let n=Ft(t.file);if(t.line!==void 0&&(!Number.isInteger(t.line)||t.line<1))throw P("Review line must be a positive integer");if(e.artifact.kind==="diff"||e.artifact.kind==="patch"){let o=Ye(e.artifact).files.find(r=>r.displayPath===n);if(!o)throw P(`File ${n} is not present in this artifact`);if(t.hunkId&&!o.hunks.some(r=>r.hunkId===t.hunkId))throw P(`Hunk ${t.hunkId} is not present in ${n}`)}return t.hunkId?{kind:"diff-hunk",path:n,hunkId:Ee(t.hunkId,"Hunk ID"),artifactId:e.artifact.artifactId,revision:e.artifact.revision}:t.line!==void 0?{kind:"source-line",path:n,startLine:t.line}:{kind:"file",path:n}}function Ft(e){let t=Re(e,"Artifact review file",4096).replace(/\\/g,"/").replace(/^\.\//,"");if(t.startsWith("../")||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").some(n=>n===".."||n.length===0))throw P("Artifact review file anchors must be repository-relative paths");return t}function Re(e,t,n){let i=typeof e=="string"?e.trim():"";if(!i)throw P(`${t} cannot be empty`);if(i.length>n)throw P(`${t} exceeds ${n} characters`);return i}function Ot(e,t,n){if(e!==void 0)return Re(e,t,n)}function Ee(e,t){let n=Re(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(n))throw P(`${t} contains unsupported characters`);return n}function ei(e,t){return e===void 0?void 0:Ee(e,t)}function P(e){return new u("ARTIFACT_REVIEW_INVALID",e)}var Lt=require("node:crypto");var z="xeno.spec.v1",ce="xeno.spec-execution.v1",w=class extends Error{constructor(n){super(`XENO spec is invalid: ${n.join("; ")}`);this.issues=n;this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},Qe=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,Lt.randomUUID)())}async create(t,n){if(t.revision!==1||t.predecessorRevision!==void 0)throw new w(["A new spec must begin at revision 1 without a predecessor"]);let i=et(t,n);return await this.repository.create(i.requirements),await this.repository.create(i.design),await this.repository.create(i.taskGraph),await this.repository.create(i.plan),i}async revise(t,n){let i=W(t.specId),o=await this.repository.require(i.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=et(t,n);return await this.repository.createRevision(r.requirements,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.design,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.taskGraph,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.plan,{actor:n.producer,reason:"spec-revised"}),r}async approve(t,n,i){return new U({repository:this.repository,actor:n}).decide({artifactId:W(t).plan,decision:"approved",...i?{rationale:i}:{}})}async reject(t,n,i){return new U({repository:this.repository,actor:n}).decide({artifactId:W(t).plan,decision:"rejected",rationale:i})}async startExecution(t,n){let i=await this.repository.require(W(t).plan);if(i.artifact.state!=="approved")throw new w([`Spec ${t} must be approved before execution`]);let o=tt(i.artifact),r=this.now(),a={schemaVersion:ce,executionId:`spec_execution_${this.idFactory()}`,specId:o.specId,specRevision:o.revision,planArtifactId:i.artifact.artifactId,planHash:{...i.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(nt(a,{producer:n,identity:i.artifact.identity,sensitivity:i.artifact.sensitivity,accessPolicyId:i.artifact.accessPolicyId}))}async updateExecution(t,n,i){let o=await this.repository.require(t),r=Ht(o.artifact),a=await this.repository.require(r.planArtifactId,r.specRevision);if(a.artifact.state!=="approved"||!de(a.artifact.content.hash,r.planHash))throw new w(["Execution is no longer bound to the approved plan revision"]);let c=n(structuredClone(r));c.schemaVersion=ce,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(),it(c,tt(a.artifact));let s=nt(c,{producer:i,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:i,reason:"spec-execution-updated"})}};function W(e){let t=ii(e,"specId");return{plan:`spec_${t}_plan`,requirements:`spec_${t}_requirements`,design:`spec_${t}_design`,taskGraph:`spec_${t}_task_graph`}}function Mt(e){let t=[];e?.schemaVersion!==z&&t.push(`schemaVersion must be ${z}`),ae(e?.specId,"specId",t),(!Number.isInteger(e?.revision)||e.revision<1)&&t.push("revision must be a positive integer"),C(e?.title,"title",t),C(e?.problem,"problem",t),Se(e?.createdAt,"createdAt",t),Se(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 n=Xe(e?.requirements,"requirement",t),i=Xe(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){ae(s?.id,"acceptance criterion id",t),C(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??[])ae(d,"required evidence kind",t)}for(let s of e?.requirements??[])C(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`);C(e?.design?.summary,"design summary",t);let a=Xe(e?.design?.decisions,"design decision",t),c=Xe(e?.design?.risks,"risk",t);for(let s of e?.design?.decisions??[]){C(s?.decision,`design decision ${s?.id??"?"}`,t),C(s?.rationale,`design rationale ${s?.id??"?"}`,t);for(let d of s?.requirementIds??[])n.has(d)||t.push(`Design decision ${s.id} references unknown requirement ${d}`)}for(let s of e?.design?.risks??[])C(s?.description,`risk ${s?.id??"?"}`,t),C(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??[]){C(s?.title,`task title ${s?.id??"?"}`,t),C(s?.description,`task description ${s?.id??"?"}`,t);for(let d of s?.dependsOn??[])i.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??[])n.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??[])qt(d)||t.push(`Task ${s.id} has unsafe expected path ${d}`)}return ri(e?.tasks??[])&&t.push("Task dependency graph contains a cycle"),[...new Set(t)]}function be(e){let t=Mt(e);if(t.length>0)throw new w(t)}function et(e,t){be(e);let n=W(e.specId),i=e.revision,o={...t,createdAt:e.updatedAt,state:"draft"},r=se({artifactId:n.requirements,revision:i,predecessorRevision:e.predecessorRevision,kind:"requirements",title:`${e.title} - requirements`,value:{schemaVersion:z,specId:e.specId,revision:i,problem:e.problem,requirements:e.requirements,acceptanceCriteria:e.acceptanceCriteria},context:o}),a=se({artifactId:n.design,revision:i,predecessorRevision:e.predecessorRevision,kind:"design",title:`${e.title} - design`,value:{schemaVersion:z,specId:e.specId,revision:i,design:e.design,...e.sourceBaseline?{sourceBaseline:e.sourceBaseline}:{}},context:o}),c=se({artifactId:n.taskGraph,revision:i,predecessorRevision:e.predecessorRevision,kind:"task-graph",title:`${e.title} - task graph`,value:{schemaVersion:z,specId:e.specId,revision:i,tasks:e.tasks},context:o}),s=[r,a,c].map(f=>({relation:"decomposes",target:{type:"artifact",id:f.artifactId,revision:f.revision}})),d=se({artifactId:n.plan,revision:i,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 tt(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=jt(e);if(be(t),t.revision!==e.revision)throw new w(["Spec and artifact revisions differ"]);if(!de(k(t),e.content.hash))throw new w(["Spec artifact content hash is invalid"]);return structuredClone(t)}function nt(e,t,n=1,i){let o=structuredClone(e);return se({artifactId:e.executionId,revision:n,predecessorRevision:i,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 Ht(e){if(e.kind!=="custom:xeno.spec-execution")throw new w([`Artifact ${e.artifactId} is not a spec execution`]);let t=jt(e);if(t.schemaVersion!==ce||t.executionId!==e.artifactId)throw new w(["Spec execution identity or schema is invalid"]);if(!de(k(t),e.content.hash))throw new w(["Spec execution content hash is invalid"]);return structuredClone(t)}function it(e,t){let n=[];e.schemaVersion!==ce&&n.push("Execution schema is invalid"),(e.specId!==t.specId||e.specRevision!==t.revision)&&n.push("Execution is bound to the wrong spec revision");let i=new Map(t.tasks.map(r=>[r.id,r])),o=new Set;for(let r of e.tasks){o.has(r.taskId)&&n.push(`Duplicate execution task ${r.taskId}`),o.add(r.taskId);let a=i.get(r.taskId);if(!a){n.push(`Unknown execution task ${r.taskId}`);continue}for(let c of a.acceptanceCriterionIds)Array.isArray(r.acceptanceEvidence?.[c])||n.push(`Task ${r.taskId} is missing acceptance evidence slot ${c}`)}for(let r of i.keys())o.has(r)||n.push(`Execution is missing task ${r}`);for(let r of e.observedPaths)oi(r)||n.push(`Unsafe observed path ${r}`);if(Se(e.createdAt,"execution createdAt",n),Se(e.updatedAt,"execution updatedAt",n),n.length>0)throw new w([...new Set(n)])}function ti(e,t,n,i,o=new Date().toISOString()){be(e),it(n,e);let r=[];(!de(t,i)||!de(n.planHash,i))&&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(n.tasks.map(d=>[d.taskId,d]));for(let d of n.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 n.observedPaths)s.some(f=>si(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:n.executionId,checkedAt:o,drifted:r.length>0,findings:r}}function se(e){let t=e.value,n=S(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:ni(e.kind),sensitivity:e.context.sensitivity??"internal",...e.context.identity?{identity:structuredClone(e.context.identity)}:{},content:{hash:k(t),sizeBytes:Buffer.byteLength(n,"utf8"),encoding:"utf8",storage:{type:"inline",text:n},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 ni(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 jt(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(n){throw new w([`Spec artifact JSON is invalid: ${n instanceof Error?n.message:String(n)}`])}}function Xe(e,t,n){let i=new Set;(!Array.isArray(e)||e.length===0)&&n.push(`${t} list cannot be empty`);for(let o of e??[])ae(o?.id,`${t} id`,n),i.has(o?.id??"")&&n.push(`Duplicate ${t}: ${o?.id}`),o?.id&&i.add(o.id);return i}function ae(e,t,n){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(e))&&n.push(`${t} must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}`)}function C(e,t,n){(typeof e!="string"||e.trim().length===0||e.length>64*1024)&&n.push(`${t} must be non-empty and no longer than 65536 characters`)}function Se(e,t,n){(typeof e!="string"||!e.includes("T")||!Number.isFinite(Date.parse(e)))&&n.push(`${t} must be an ISO 8601 timestamp`)}function ii(e,t){let n=[];if(ae(e,t,n),n.length>0)throw new w(n);return e}function ri(e){let t=new Map(e.map(r=>[r.id,r])),n=new Set,i=new Set,o=r=>{if(n.has(r))return!0;if(i.has(r))return!1;n.add(r);for(let a of t.get(r)?.dependsOn??[])if(o(a))return!0;return n.delete(r),i.add(r),!1};return e.some(r=>o(r.id))}function qt(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 oi(e){return qt(e)&&!e.includes("*")}function si(e,t){let n=e.replace(/\\/gu,"/"),i=t.replace(/\\/gu,"/");if(i.endsWith("/**")){let o=i.slice(0,-3).replace(/\/$/u,"");return n===o||n.startsWith(`${o}/`)}if(i.endsWith("/*")){let o=i.slice(0,-2).replace(/\/$/u,""),r=n.startsWith(`${o}/`)?n.slice(o.length+1):"";return r.length>0&&!r.includes("/")}return n===i}function de(e,t){return e.algorithm===t.algorithm&&e.value===t.value}var Jt=require("node:crypto");var ot="xeno.review-report.v1",Bt=["correctness","security","performance","api","tests","documentation"],Ut=["source","test","trace","artifact","reproduction","benchmark"],E=class extends Error{constructor(n){super(`XENO review is invalid: ${n.join("; ")}`);this.issues=n;this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},rt=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??(n=>`${n}_${(0,Jt.randomUUID)()}`)}async run(t){st(t.pack),at(t.target),_e(t.runId,"runId");let n=this.now(),i=await Promise.all(t.pack.dimensions.map(async(s,d)=>{let f=await this.reviewer({...t,dimension:s,reviewerSlot:d});return li(f,s,t.pack.maxFindings),structuredClone(f)})),o=i.flatMap(s=>s.findings.map(d=>({finding:d,reviewerAgentId:s.reviewerAgentId})));if(o.length>t.pack.maxFindings)throw new E([`Reviewers returned ${o.length} findings, exceeding maxFindings ${t.pack.maxFindings}`]);let r=pi(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 mi(_),structuredClone(_)})):[];s.verifications=vi(d),s.evidence=zt([...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"),R=new Set(s.evidence.map(v=>v.producerId)).size;f>=t.pack.minimumVerifierReproductions?(s.state="verified",s.verificationBasis="verifier"):t.pack.allowIndependentEvidenceVerification&&R>=t.pack.minimumIndependentEvidenceProducers?(s.state="verified",s.verificationBasis="independent-evidence"):g?(s.state="rejected",s.verificationBasis="verifier"):(s.state="unverified",s.verificationBasis="none");let O=s.verifications.map(v=>v.confidence).filter(v=>v!==void 0);O.length>0&&(s.confidence=en(Math.min(s.confidence,...O)))}r.sort(hi);let a=this.now(),c={schemaVersion:ot,reportId:_e(this.idFactory("report"),"reportId"),runId:t.runId,pack:structuredClone(t.pack),target:structuredClone(t.target),startedAt:n,completedAt:a,reviewers:i.map(s=>({agentId:s.reviewerAgentId,dimension:s.dimension,findingCount:s.findings.length})),findings:r,summary:Yt(r)};return fe(c),c}};function ai(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 st(e){let t=[];e?.schemaVersion!=="xeno.review-pack.v1"&&t.push("Review pack schemaVersion must be xeno.review-pack.v1"),x(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 n of e?.dimensions??[])Qt(n)||t.push(`Invalid review dimension ${n}`);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 E(t)}function at(e){let t=[];if(x(e?.artifactId,"target artifactId",t),(!Number.isInteger(e?.revision)||e.revision<1)&&t.push("Target revision must be positive"),q(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 E(t)}function fe(e){let t=[];e?.schemaVersion!==ot&&t.push("Review report schemaVersion is invalid"),x(e?.reportId,"reportId",t),x(e?.runId,"runId",t),Te(e?.startedAt,"startedAt",t),Te(e?.completedAt,"completedAt",t),Date.parse(e?.completedAt)<Date.parse(e?.startedAt)&&t.push("completedAt cannot precede startedAt");try{st(e.pack)}catch(r){t.push(r instanceof Error?r.message:String(r))}try{at(e.target)}catch(r){t.push(r instanceof Error?r.message:String(r))}let n=new Set,i=new Set;for(let r of e?.findings??[])x(r?.findingId,"findingId",t),n.has(r.findingId)&&t.push(`Duplicate findingId ${r.findingId}`),n.add(r.findingId),/^[a-f0-9]{64}$/u.test(r?.fingerprint??"")||t.push(`Finding ${r.findingId} has invalid fingerprint`),i.has(r.fingerprint)&&t.push(`Duplicate finding fingerprint ${r.fingerprint}`),i.add(r.fingerprint),q(r?.title,`finding ${r.findingId} title`,t),q(r?.summary,`finding ${r.findingId} summary`,t),Zt(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=Yt(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 E([...new Set(t)])}function ci(e,t){fe(e);let n=e,i=S(n),o=t.artifactId??`review_${T(`${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:k(n),sizeBytes:Buffer.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i},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:Kt(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 di(e){if(e.kind!=="review-report"||e.mediaType!=="application/vnd.xeno.review-report+json")throw new E([`Artifact ${e.artifactId} is not a XENO review report`]);if(e.content.storage.type!=="inline"||typeof e.content.storage.text!="string")throw new E(["Review report requires inline JSON content"]);let t;try{t=JSON.parse(e.content.storage.text)}catch(n){throw new E([`Review report JSON is invalid: ${n instanceof Error?n.message:String(n)}`])}if(fe(t),!Ai(k(t),e.content.hash))throw new E(["Review report content hash is invalid"]);return structuredClone(t)}function fi(e,t={}){fe(e);let n=[];for(let i of e.findings){if(t.verifiedOnly!==!1&&i.state!=="verified")continue;let o=i.anchors.find(r=>r.kind==="source-line"||r.kind==="file"||r.kind==="diff-hunk");!o||!("path"in o)||n.push({findingId:i.findingId,path:o.path,...o.kind==="source-line"?{line:o.startLine}:{},severity:i.severity,verified:i.state==="verified",body:[`**${i.severity.toUpperCase()} - ${i.title}**`,"",i.summary,"",`Evidence: ${i.evidence.map(r=>r.summary).join("; ")||"none"}`,i.remediation?`Suggested remediation: ${i.remediation}`:"",`XENO finding: ${i.findingId} (${i.state}, confidence ${i.confidence.toFixed(2)})`].filter(Boolean).join(`
9
+ `)})}return n}function pi(e,t){let n=new Map;for(let i of e){Wt(i.finding),_e(i.reviewerAgentId,"reviewerAgentId");let o=ui(i.finding),r=n.get(o)??[];r.push(structuredClone(i)),n.set(o,r)}return[...n.entries()].map(([i,o])=>{let r=[...o].sort((c,s)=>K(s.finding.severity)-K(c.finding.severity))[0],a=zt(o.flatMap(c=>c.finding.evidence));return{findingId:_e(t("finding"),"findingId"),fingerprint:i,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)=>K(s.finding.severity)>K(c)?s.finding.severity:c,r.finding.severity),confidence:en(Math.max(...o.map(c=>c.finding.confidence))),state:"unverified",verificationBasis:"none",anchors:Kt(o.flatMap(c=>c.finding.anchors)),evidence:a,verifications:[],...r.finding.remediation?{remediation:r.finding.remediation}:{},duplicateProposalCount:o.length}})}function ui(e){let t=e.anchors.map(Gt).sort();return k({ruleId:e.ruleId??"",title:gi(e.title),anchors:t}).value}function li(e,t,n){let i=[];x(e?.reviewerAgentId,"reviewerAgentId",i),e?.dimension!==t&&i.push(`Reviewer returned dimension ${e?.dimension} for requested ${t}`),Te(e?.completedAt,"reviewer completedAt",i),(!Array.isArray(e?.findings)||e.findings.length>n)&&i.push("Reviewer finding list is invalid or exceeds maxFindings");for(let o of e?.findings??[]){try{Wt(o)}catch(r){i.push(r instanceof Error?r.message:String(r))}o.dimension!==t&&i.push(`Finding dimension ${o.dimension} differs from reviewer dimension ${t}`)}if(i.length>0)throw new E([...new Set(i)])}function Wt(e){let t=[];Qt(e?.dimension)||t.push(`Invalid finding dimension ${e?.dimension}`),q(e?.title,"finding title",t),q(e?.summary,"finding summary",t),Zt(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 n of e?.evidence??[])ct(n,t);if(e?.ruleId!==void 0&&x(e.ruleId,"ruleId",t),t.length>0)throw new E([...new Set(t)])}function mi(e){let t=[];x(e?.verifierAgentId,"verifierAgentId",t),["reproduced","rejected","inconclusive"].includes(e?.outcome)||t.push("Verifier outcome is invalid"),q(e?.rationale,"verifier rationale",t),Te(e?.completedAt,"verifier completedAt",t),Array.isArray(e?.evidence)||t.push("Verifier evidence must be an array");for(let n of e?.evidence??[])ct(n,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 E([...new Set(t)])}function ct(e,t){x(e?.evidenceId,"evidenceId",t),x(e?.producerId,"evidence producerId",t),q(e?.summary,"evidence summary",t),(typeof e?.kind!="string"||!(Ut.includes(e.kind)||F(e.kind)))&&t.push(`Invalid evidence kind ${e?.kind}`)}function zt(e){let t=new Map;for(let n of e){let i=[];if(ct(n,i),i.length>0)throw new E(i);let o=t.get(n.evidenceId);if(o&&S(o)!==S(n))throw new E([`Conflicting evidence ID ${n.evidenceId}`]);t.set(n.evidenceId,structuredClone(n))}return[...t.values()].sort((n,i)=>n.evidenceId.localeCompare(i.evidenceId))}function vi(e){let t=new Map;for(let n of e){if(t.has(n.verifierAgentId))throw new E([`Verifier ${n.verifierAgentId} returned more than one result for a finding`]);t.set(n.verifierAgentId,structuredClone(n))}return[...t.values()].sort((n,i)=>n.verifierAgentId.localeCompare(i.verifierAgentId))}function Kt(e){let t=new Map;for(let n of e)t.set(Gt(n),structuredClone(n));return[...t.entries()].sort(([n],[i])=>n.localeCompare(i)).map(([,n])=>n)}function Gt(e){return S(e)}function Yt(e){let t={info:0,low:0,medium:0,high:0,critical:0};for(let n of e)t[n.severity]+=1;return{total:e.length,verified:e.filter(n=>n.state==="verified").length,unverified:e.filter(n=>n.state==="unverified").length,rejected:e.filter(n=>n.state==="rejected").length,bySeverity:t}}function hi(e,t){return K(t.severity)-K(e.severity)||+(t.state==="verified")-+(e.state==="verified")||e.fingerprint.localeCompare(t.fingerprint)}function K(e){return{info:0,low:1,medium:2,high:3,critical:4}[e]}function Zt(e){return typeof e=="string"&&["info","low","medium","high","critical"].includes(e)}function Qt(e){return typeof e=="string"&&(Bt.includes(e)||F(e))}function gi(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function en(e){return Math.max(0,Math.min(1,Number(e.toFixed(6))))}function x(e,t,n){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u.test(e))&&n.push(`${t} has an invalid identifier`)}function _e(e,t){let n=[];if(x(e,t,n),n.length>0)throw new E(n);return e}function q(e,t,n){(typeof e!="string"||e.trim().length===0||e.length>64*1024)&&n.push(`${t} must be non-empty and no longer than 65536 characters`)}function Te(e,t,n){(typeof e!="string"||!e.includes("T")||!Number.isFinite(Date.parse(e)))&&n.push(`${t} must be an ISO 8601 timestamp`)}function Ai(e,t){return e.algorithm===t.algorithm&&e.value===t.value}var pe=require("node:buffer");function yi(e,t){let n=t.contentEncoding??"utf8",i=n==="base64"?pe.Buffer.from(e.content,"base64"):pe.Buffer.from(e.content,"utf8"),o=[t.identity?.runId,t.identity?.taskId,t.identity?.turnId].filter(Boolean).join(":"),r=T(`${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??Si(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:T(i),sizeBytes:i.byteLength,encoding:n,storage:n==="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:n}}};return I(a),a}function Ii(e){I(e);let t=e.extensions?.["xeno.legacy.agentArtifact"];if(dt(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 wi(e,t){let n=tn(e),i=S(n),o={schemaVersion:1,artifactId:t.artifactId??e.id,revision:t.revision??1,kind:bi(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:k(n),sizeBytes:pe.Buffer.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i}},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":n}};return I(o),o}function Ei(e){I(e);let t=e.extensions?.["xeno.legacy.toolEvidence"];if(_i(t))return structuredClone(t);throw new TypeError("XENO artifact does not contain lossless legacy ToolEvidence data")}function Ri(e,t){let n=tn(e),i=e.files.map(a=>a.patch).filter(a=>!!a);if(e.files.length>0&&i.length===e.files.length&&i.every(a=>a.startsWith("diff --git ")))try{let a=Ge(i.join(`
10
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":n}};return I(c),c}catch{}let o=S(n),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:k(n),sizeBytes:pe.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":n}};return I(r),r}function Xi(e){I(e);let t=e.extensions?.["xeno.legacy.turnDiffSummary"];if(Ti(t))return structuredClone(t);throw new TypeError("XENO artifact does not contain lossless TurnDiffSummary data")}function Si(e){let t=e.name.toLowerCase(),n=e.mimeType?.toLowerCase()??"";return t.endsWith(".patch")||n.includes("patch")?"patch":t.endsWith(".diff")||n.includes("diff")?"diff":n.startsWith("image/")?"screenshot":n.startsWith("video/")?"recording":n.includes("json")&&t.includes("report")?"test-report":"file"}function bi(e){return e.kind==="artifact"?e.path?"file":"custom:tool-artifact-evidence":e.kind==="verification"?"test-report":"custom:tool-process-evidence"}function tn(e){return JSON.parse(JSON.stringify(e))}function dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _i(e){return dt(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 Ti(e){return dt(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_ACTOR_KINDS,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION,XENO_ARTIFACT_SCHEMA_VERSION,XENO_ARTIFACT_SENSITIVITIES,XENO_ARTIFACT_STATES,XENO_BUILTIN_ARTIFACT_KINDS,XENO_EVIDENCE_EDGE_TYPES,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION,XENO_EVIDENCE_NODE_TYPES,XENO_REVIEW_DIMENSIONS,XENO_REVIEW_EVIDENCE_KINDS,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});