@xenosystem/agent-sdk 0.10.26 → 0.10.29

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.
@@ -1,5 +1,5 @@
1
1
  "use strict";var Xn=Object.create;var we=Object.defineProperty;var Rn=Object.getOwnPropertyDescriptor;var bn=Object.getOwnPropertyNames;var Sn=Object.getPrototypeOf,_n=Object.prototype.hasOwnProperty;var xn=(t,e)=>{for(var n in e)we(t,n,{get:e[n],enumerable:!0})},xt=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of bn(e))!_n.call(t,o)&&o!==n&&we(t,o,{get:()=>e[o],enumerable:!(i=Rn(e,o))||i.enumerable});return t};var Tn=(t,e,n)=>(n=t!=null?Xn(Sn(t)):{},xt(e||!t||!t.__esModule?we(n,"default",{value:t,enumerable:!0}):n,t)),kn=t=>xt(we({},"__esModule",{value:!0}),t);var Zi={};xn(Zi,{FileXenoArtifactRepository:()=>Ye,InMemoryXenoArtifactRepository:()=>ne,XENO_ARTIFACT_ACTOR_KINDS:()=>je,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION:()=>tt,XENO_ARTIFACT_SCHEMA_VERSION:()=>v,XENO_ARTIFACT_SENSITIVITIES:()=>He,XENO_ARTIFACT_STATES:()=>Me,XENO_BUILTIN_ARTIFACT_KINDS:()=>Le,XENO_EVIDENCE_EDGE_TYPES:()=>ce,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION:()=>Ee,XENO_EVIDENCE_NODE_TYPES:()=>ae,XENO_PAGE_ENTRY:()=>O,XENO_PAGE_MAX_BYTES:()=>yn,XENO_PAGE_MAX_FILES:()=>wt,XENO_REVIEW_DIMENSIONS:()=>an,XENO_REVIEW_EVIDENCE_KINDS:()=>cn,XENO_REVIEW_REPORT_SCHEMA_VERSION:()=>lt,XENO_SPEC_EXECUTION_SCHEMA_VERSION:()=>ge,XENO_SPEC_SCHEMA_VERSION:()=>oe,XenoArtifactRepositoryError:()=>u,XenoArtifactReviewService:()=>ie,XenoArtifactStateTransitionError:()=>Xe,XenoArtifactValidationError:()=>G,XenoDiffParseError:()=>T,XenoEvidenceGraphBuilder:()=>ze,XenoEvidenceGraphValidationError:()=>_e,XenoMultiAgentReviewCoordinator:()=>ut,XenoPageStore:()=>Xt,XenoReviewValidationError:()=>b,XenoSpecLifecycleService:()=>at,XenoSpecValidationError:()=>R,assertValidXenoArtifact:()=>X,assertValidXenoEvidenceGraph:()=>te,assertValidXenoReviewPack:()=>mt,assertValidXenoReviewReport:()=>ye,assertValidXenoReviewTarget:()=>ht,assertValidXenoSpecDocument:()=>$e,assertValidXenoSpecExecution:()=>pt,assertXenoArtifactStateTransition:()=>pe,buildXenoArtifactReviewAnchor:()=>st,canTransitionXenoArtifactState:()=>Pt,canonicalizeArtifactJson:()=>C,defaultXenoReviewPack:()=>xi,detectXenoSpecDrift:()=>Ei,extractPageTitle:()=>An,legacyAgentArtifactToXenoArtifact:()=>Mi,normalizePagePath:()=>Et,normalizeRepositoryRelativePath:()=>Qt,pageContentType:()=>De,parseUnifiedDiff:()=>it,sha256ArtifactBytes:()=>k,sha256ArtifactJson:()=>N,summarizeXenoArtifactReview:()=>be,toolEvidenceToXenoArtifact:()=>ji,turnDiffSummaryToXenoArtifact:()=>qi,unifiedDiffToXenoArtifact:()=>rt,validateXenoArtifact:()=>Nt,validateXenoArtifactReviewEvent:()=>Re,validateXenoEvidenceGraph:()=>Vt,validateXenoSpecDocument:()=>tn,xenoArtifactToDiffDocument:()=>ot,xenoArtifactToLegacyAgentArtifact:()=>Hi,xenoArtifactToReviewReport:()=>ki,xenoArtifactToSpecDocument:()=>dt,xenoArtifactToSpecExecution:()=>nn,xenoArtifactToToolEvidence:()=>Bi,xenoArtifactToTurnDiffSummary:()=>Ji,xenoReviewReportToArtifact:()=>Ti,xenoReviewReportToGitHubComments:()=>Ci,xenoSpecArtifactIds:()=>re,xenoSpecExecutionToArtifact:()=>ft,xenoSpecToArtifactBundle:()=>ct});module.exports=kn(Zi);var v=1,Ee=1,Le=["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","page"],Me=["draft","pending_review","approved","rejected","superseded","archived"],He=["public","internal","confidential","restricted"],je=["agent","tool","user","system","integration"],ae=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],ce=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];var Je=require("node:buffer");var Tt=require("node:crypto");function k(t){return{algorithm:"sha256",value:(0,Tt.createHash)("sha256").update(t).digest("hex")}}function C(t){return JSON.stringify(Be(t,new Set))}function N(t){return k(C(t))}function Be(t,e){if(t===null||typeof t!="object"){if(typeof t=="number"&&!Number.isFinite(t))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return t}if(e.has(t))throw new TypeError("Artifact JSON cannot contain cycles");if(e.add(t),Array.isArray(t)){let i=t.map(o=>Be(o,e));return e.delete(t),i}let n={};for(let i of Object.keys(t).sort((o,r)=>o.localeCompare(r))){let o=t[i];if(o===void 0)throw new TypeError(`Artifact JSON property ${i} is undefined`);n[i]=Be(o,e)}return e.delete(t),n}var Cn=/^[a-z0-9][a-z0-9._/-]{0,127}$/,qe="custom:";function z(t,e=qe){return t.startsWith(e)?Cn.test(t.slice(e.length)):!1}var G=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,n){super(e),this.name="XenoArtifactValidationError",this.issues=n.map(i=>({...i}))}},Xe=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"},Nn={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},Pn="[\\u0000-\\u001f\\u007f]",$n=new RegExp(Pn),kt=/^[a-f0-9]{64}$/,Vn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,On=new Set(Me),Dn=new Set(He),Fn=new Set(je),Ln=new Set(Le),Mn=new Set(ae),Hn=new Set(ce);function p(t,e,n,i){t.push({path:e,code:n,message:i})}function l(t,e,n,i=1024){return typeof t!="string"||t.trim().length===0?(p(n,e,"required_string","Value must be a non-empty string"),!1):(t.length>i&&p(n,e,"string_too_long",`Value must not exceed ${i} characters`),$n.test(t)&&p(n,e,"control_character","Value must not contain control characters"),!0)}function de(t,e,n){t!==void 0&&(!Number.isFinite(Date.parse(t))||!t.includes("T"))&&p(n,e,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function W(t,e,n,i){typeof t=="string"&&t.startsWith(e)&&(z(t,e)||p(i,n,"invalid_custom_name",`Custom name after ${e} is invalid`))}function Ct(t,e,n){if(!t||typeof t!="object"){p(n,e,"missing_actor","Actor is required");return}l(t.kind,`${e}.kind`,n,64),Fn.has(t.kind)||p(n,`${e}.kind`,"unknown_actor_kind","Actor kind is not supported"),l(t.id,`${e}.id`,n,512),t?.displayName!==void 0&&l(t.displayName,`${e}.displayName`,n,512),t?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(t.profileFingerprint)&&p(n,`${e}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function Ue(t,e,n){if(!t||typeof t!="object"){p(n,e,"invalid_anchor","Anchor must be an object");return}switch(t.kind){case"file":l(t.path,`${e}.path`,n,4096);break;case"source-line":l(t.path,`${e}.path`,n,4096),(!Number.isInteger(t.startLine)||t.startLine<1)&&p(n,`${e}.startLine`,"invalid_line","startLine must be a positive integer"),t.endLine!==void 0&&(!Number.isInteger(t.endLine)||t.endLine<t.startLine)&&p(n,`${e}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":l(t.path,`${e}.path`,n,4096),l(t.hunkId,`${e}.hunkId`,n,512);break;case"symbol":l(t.path,`${e}.path`,n,4096),l(t.symbol,`${e}.symbol`,n,1024);break;case"dom-node":l(t.pageId,`${e}.pageId`,n,512),!t.selector&&!t.accessibilityId&&!t.snapshotArtifactId&&p(n,e,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":l(t.recordingArtifactId,`${e}.recordingArtifactId`,n,512),(!Number.isFinite(t.startMs)||t.startMs<0)&&p(n,`${e}.startMs`,"invalid_time","startMs must be a non-negative finite number"),t.endMs!==void 0&&(!Number.isFinite(t.endMs)||t.endMs<t.startMs)&&p(n,`${e}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":l(t.mediaArtifactId,`${e}.mediaArtifactId`,n,512),[t.x,t.y,t.width,t.height].every(Number.isFinite)?(t.width<=0||t.height<=0)&&p(n,e,"invalid_region_size","Region width and height must be positive"):p(n,e,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":l(t.artifactId,`${e}.artifactId`,n,512);break;default:typeof t.kind!="string"||!t.kind.startsWith("custom:")?p(n,`${e}.kind`,"unknown_anchor","Anchor kind is not supported"):W(t.kind,"custom:",`${e}.kind`,n)}}function fe(t,e,n,i){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){Number.isFinite(t)||p(n,e,"non_finite_number","JSON numbers must be finite");return}if(typeof t!="object"){p(n,e,"non_json_value","Value must be JSON-serializable");return}if(i.has(t)){p(n,e,"cyclic_value","Value must not contain cycles");return}if(i.add(t),Array.isArray(t))t.forEach((o,r)=>fe(o,`${e}[${r}]`,n,i));else for(let[o,r]of Object.entries(t))r===void 0?p(n,`${e}.${o}`,"undefined_value","Undefined is not valid JSON"):fe(r,`${e}.${o}`,n,i);i.delete(t)}}function Nt(t){let e=[];if(!t||typeof t!="object")return[{path:"$",code:"invalid_artifact",message:"Artifact must be an object"}];if(t.schemaVersion!==1&&p(e,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(t.artifactId,"artifactId",e,512),(!Number.isInteger(t.revision)||t.revision<1)&&p(e,"revision","invalid_revision","revision must be a positive integer"),l(t.kind,"kind",e,160),typeof t.kind=="string"&&!Ln.has(t.kind)&&!t.kind.startsWith("custom:")&&p(e,"kind","unknown_artifact_kind","Artifact kind is not supported"),W(t.kind,"custom:","kind",e),l(t.title,"title",e,1024),t.description!==void 0&&l(t.description,"description",e,32768),l(t.state,"state",e,64),On.has(t.state)||p(e,"state","unknown_state","Artifact state is not supported"),l(t.createdAt,"createdAt",e,128),de(t.createdAt,"createdAt",e),de(t.updatedAt,"updatedAt",e),t.updatedAt&&Number.isFinite(Date.parse(t.createdAt))&&Date.parse(t.updatedAt)<Date.parse(t.createdAt)&&p(e,"updatedAt","timestamp_order","updatedAt must not precede createdAt"),l(t.mediaType,"mediaType",e,255),l(t.sensitivity,"sensitivity",e,64),Dn.has(t.sensitivity)||p(e,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),t.identity)for(let[i,o]of Object.entries(t.identity))o!==void 0&&l(o,`identity.${i}`,e,512);if(!t.content||typeof t.content!="object")p(e,"content","missing_content","content descriptor is required");else{!t.content.hash||typeof t.content.hash!="object"?p(e,"content.hash","missing_hash","content hash is required"):(l(t.content.hash.algorithm,"content.hash.algorithm",e,128),W(t.content.hash.algorithm,"custom:","content.hash.algorithm",e),typeof t.content.hash.algorithm=="string"&&t.content.hash.algorithm!=="sha256"&&!t.content.hash.algorithm.startsWith("custom:")&&p(e,"content.hash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported"),l(t.content.hash.value,"content.hash.value",e,512),t.content.hash.algorithm==="sha256"&&!kt.test(t.content.hash.value)&&p(e,"content.hash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters")),(!Number.isSafeInteger(t.content.sizeBytes)||t.content.sizeBytes<0)&&p(e,"content.sizeBytes","invalid_size","sizeBytes must be a non-negative safe integer");let i=t.content.storage;if(!i||typeof i!="object")p(e,"content.storage","missing_storage","storage reference is required");else if(i.type==="inline")if(i.text===void 0==(i.base64===void 0))p(e,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;i.text!==void 0?o=Je.Buffer.from(i.text,"utf8"):i.base64!==void 0&&(Vn.test(i.base64)?o=Je.Buffer.from(i.base64,"base64"):p(e,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),o&&t.content.sizeBytes!==o.byteLength&&p(e,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),o&&t.content.hash.algorithm==="sha256"&&k(o).value!==t.content.hash.value&&p(e,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else i.type==="file"?l(i.path,"content.storage.path",e,4096):i.type==="blob"?l(i.uri,"content.storage.uri",e,8192):i.type==="git"?(l(i.commit,"content.storage.commit",e,512),l(i.path,"content.storage.path",e,4096)):i.type==="url"?(l(i.url,"content.storage.url",e,8192),de(i.expiresAt,"content.storage.expiresAt",e)):i.type==="external"?(l(i.provider,"content.storage.provider",e,255),l(i.locator,"content.storage.locator",e,8192)):p(e,"content.storage.type","unknown_storage","Storage type is not supported");t.content.encoding!==void 0&&(typeof t.content.encoding!="string"||t.content.encoding!=="utf8"&&t.content.encoding!=="base64"&&t.content.encoding!=="binary"&&!t.content.encoding.startsWith("custom:"))&&p(e,"content.encoding","unknown_encoding","Content encoding is not supported"),W(t.content.encoding,"custom:","content.encoding",e)}!t.provenance||typeof t.provenance!="object"?p(e,"provenance","missing_provenance","provenance is required"):(Ct(t.provenance.producer,"provenance.producer",e),t.provenance.capabilityLeaseIds?.forEach((i,o)=>l(i,`provenance.capabilityLeaseIds[${o}]`,e,512)),t.provenance.sourceArtifactIds?.forEach((i,o)=>l(i,`provenance.sourceArtifactIds[${o}]`,e,512)),t.provenance.attributes&&fe(t.provenance.attributes,"provenance.attributes",e,new Set));let n=new Set;return t.relationships?.forEach((i,o)=>{let r=`relationships[${o}]`;l(i.relation,`${r}.relation`,e,160),typeof i.relation=="string"&&!Hn.has(i.relation)&&!i.relation.startsWith("custom:")&&p(e,`${r}.relation`,"unknown_relationship","Relationship type is not supported"),W(i.relation,"custom:",`${r}.relation`,e),l(i.target?.type,`${r}.target.type`,e,160),typeof i.target?.type=="string"&&!Mn.has(i.target.type)&&!i.target.type.startsWith("custom:")&&p(e,`${r}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),W(i.target?.type,"custom:",`${r}.target.type`,e),l(i.target?.id,`${r}.target.id`,e,512);let s=`${i.relation}:${i.target?.type}:${i.target?.id}:${i.target?.revision??""}`;n.has(s)&&p(e,r,"duplicate_relationship","Duplicate relationship"),n.add(s),i.attributes&&fe(i.attributes,`${r}.attributes`,e,new Set)}),t.anchors?.forEach((i,o)=>Ue(i,`anchors[${o}]`,e)),t.revision===1&&t.predecessorRevision!==void 0&&p(e,"predecessorRevision","unexpected_predecessor","First revision cannot have a predecessor"),t.revision>1&&(!Number.isInteger(t.predecessorRevision)||(t.predecessorRevision??0)>=t.revision)&&p(e,"predecessorRevision","invalid_predecessor","Later revisions require an earlier predecessor revision"),de(t.retention?.retainUntil,"retention.retainUntil",e),t.retention?.legalHold!==void 0&&typeof t.retention.legalHold!="boolean"&&p(e,"retention.legalHold","invalid_boolean","legalHold must be a boolean"),t.extensions&&fe(t.extensions,"extensions",e,new Set),e}function X(t){let e=Nt(t);if(e.length>0)throw new G("XENO artifact validation failed",e)}function Pt(t,e){return Nn[t].includes(e)}function pe(t,e){if(!Pt(t,e))throw new Xe(t,e)}function Re(t,e){let n=[];return t.schemaVersion!==1&&p(n,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(t.eventId,"eventId",n,512),l(t.artifactId,"artifactId",n,512),(!Number.isInteger(t.artifactRevision)||t.artifactRevision<1)&&p(n,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(t.sequence)||t.sequence<1)&&p(n,"sequence","invalid_sequence","sequence must be a positive integer"),l(t.recordedAt,"recordedAt",n,128),de(t.recordedAt,"recordedAt",n),Ct(t.actor,"actor",n),!t.artifactHash||typeof t.artifactHash!="object"?p(n,"artifactHash","missing_hash","Artifact hash is required"):(l(t.artifactHash.algorithm,"artifactHash.algorithm",n,128),W(t.artifactHash.algorithm,"custom:","artifactHash.algorithm",n),l(t.artifactHash.value,"artifactHash.value",n,512),t.artifactHash.algorithm==="sha256"&&!kt.test(t.artifactHash.value)&&p(n,"artifactHash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters"),typeof t.artifactHash.algorithm=="string"&&t.artifactHash.algorithm!=="sha256"&&!t.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(t.type)||p(n,"type","unknown_review_event","Review event type is not supported"),t.type==="comment-added"?(l(t.commentId,"commentId",n,512),l(t.body,"body",n,65536),t.anchor&&Ue(t.anchor,"anchor",n)):t.type==="comment-resolved"||t.type==="comment-reopened"?l(t.commentId,"commentId",n,512):t.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(t.decision)||p(n,"decision","unknown_review_decision","Review decision is not supported"),t.scope&&Ue(t.scope,"scope",n)),e&&(t.artifactId!==e.artifactId&&p(n,"artifactId","artifact_mismatch","Review event targets a different artifact"),t.artifactRevision!==e.revision&&p(n,"artifactRevision","revision_mismatch","Review event targets a different revision"),t.artifactHash&&(t.artifactHash.algorithm!==e.content.hash.algorithm||t.artifactHash.value!==e.content.hash.value)&&p(n,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),n}function be(t){let e="not_requested",n,i,o,r=0,s=new Set,d=new Set;for(let a of[...t].sort((c,f)=>c.sequence-f.sequence))o=a.recordedAt,a.type==="review-requested"?e="pending":a.type==="review-withdrawn"?e="withdrawn":a.type==="comment-added"?(s.add(a.commentId),d.delete(a.commentId),e==="not_requested"&&(e="pending")):a.type==="comment-resolved"?d.add(a.commentId):a.type==="comment-reopened"?d.delete(a.commentId):a.type==="decision-recorded"&&(a.scope?r+=1:(n=a.decision,i=a.eventId,e=a.decision));return{status:e,totalComments:s.size,unresolvedComments:[...s].filter(a=>!d.has(a)).length,...n?{latestDecision:n}:{},...i?{latestDecisionEventId:i}:{},...r>0?{scopedDecisionCount:r}:{},...o?{lastReviewedAt:o}:{}}}var _e=class extends Error{code="EVIDENCE_GRAPH_INVALID";issues;constructor(e){super("XENO evidence graph validation failed"),this.name="XenoEvidenceGraphValidationError",this.issues=e.map(n=>({...n}))}},jn=new Set(["depends_on","decomposes","supersedes"]),Bn=new Set(ae),qn=new Set(ce);function A(t,e,n,i){t.push({path:e,code:n,message:i})}function ue(t){return t.includes("T")&&Number.isFinite(Date.parse(t))}function $t(t,e){return t.startsWith(qe)?z(t):e.has(t)}function Vt(t){let e=[];if(!t||typeof t!="object")return[{path:"$",code:"invalid_graph",message:"Evidence graph must be an object"}];t.schemaVersion!==1&&A(e,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),(typeof t.graphId!="string"||t.graphId.trim().length===0)&&A(e,"graphId","required_string","graphId must be a non-empty string"),(!Number.isInteger(t.version)||t.version<1)&&A(e,"version","invalid_version","version must be a positive integer"),ue(t.createdAt)||A(e,"createdAt","invalid_timestamp","createdAt must be an ISO 8601 timestamp"),ue(t.updatedAt)||A(e,"updatedAt","invalid_timestamp","updatedAt must be an ISO 8601 timestamp"),ue(t.createdAt)&&ue(t.updatedAt)&&Date.parse(t.updatedAt)<Date.parse(t.createdAt)&&A(e,"updatedAt","timestamp_order","updatedAt must not precede createdAt");let n=new Map;Array.isArray(t.nodes)||A(e,"nodes","invalid_nodes","nodes must be an array"),(Array.isArray(t.nodes)?t.nodes:[]).forEach((f,g)=>{let y=`nodes[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(e,`${y}.id`,"required_string","Node ID must be a non-empty string"):n.has(f.id)?A(e,`${y}.id`,"duplicate_node",`Node ID ${f.id} is duplicated`):n.set(f.id,f),(typeof f.type!="string"||!$t(f.type,Bn))&&A(e,`${y}.type`,"invalid_node_type","Node type is invalid"),f.artifactRevision!==void 0&&(!Number.isInteger(f.artifactRevision)||f.artifactRevision<1)&&A(e,`${y}.artifactRevision`,"invalid_revision","artifactRevision must be a positive integer")});let i=new Set,o=new Set;Array.isArray(t.edges)||A(e,"edges","invalid_edges","edges must be an array"),(Array.isArray(t.edges)?t.edges:[]).forEach((f,g)=>{let y=`edges[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(e,`${y}.id`,"required_string","Edge ID must be a non-empty string"):i.has(f.id)&&A(e,`${y}.id`,"duplicate_edge",`Edge ID ${f.id} is duplicated`),i.add(f.id),(typeof f.type!="string"||!$t(f.type,qn))&&A(e,`${y}.type`,"invalid_edge_type","Edge type is invalid");let D=`${f.type}:${f.from}:${f.to}`;o.has(D)&&A(e,y,"duplicate_edge_identity","Equivalent evidence edge is duplicated"),o.add(D),n.has(f.from)||A(e,`${y}.from`,"dangling_reference",`Source node ${f.from} does not exist`),n.has(f.to)||A(e,`${y}.to`,"dangling_reference",`Target node ${f.to} does not exist`),f.from===f.to&&A(e,y,"self_edge","Evidence edges cannot point to the same node"),ue(f.createdAt)||A(e,`${y}.createdAt`,"invalid_timestamp","createdAt must be an ISO 8601 timestamp")});let r=(Array.isArray(t.edges)?t.edges:[]).filter(f=>jn.has(f.type)),s=new Map;for(let f of r){let g=s.get(f.from)??[];g.push(f.to),s.set(f.from,g)}let d=new Set,a=new Set,c=f=>{if(d.has(f))return!0;if(a.has(f))return!1;d.add(f);for(let g of s.get(f)??[])if(c(g))return!0;return d.delete(f),a.add(f),!1};for(let f of n.keys())if(c(f)){A(e,"edges","cyclic_graph","Dependency, decomposition, and supersession edges must be acyclic");break}return e}function te(t){let e=Vt(t);if(e.length>0)throw new _e(e)}var ze=class{now;graph;constructor(e){if("schemaVersion"in e)te(e),this.now=()=>new Date().toISOString(),this.graph=Se(e);else{this.now=e.now??(()=>new Date().toISOString());let n=this.now();this.graph={schemaVersion:1,graphId:e.graphId,version:1,createdAt:n,updatedAt:n,nodes:[],edges:[]},te(this.graph)}}addNode(e){let n=Se(this.graph);return n.nodes.push(Ot(e)),this.touch(n),te(n),this.graph=n,this}addEdge(e){let n=Se(this.graph);return n.edges.push(Dt(e)),this.touch(n),te(n),this.graph=n,this}build(){return te(this.graph),Se(this.graph)}touch(e){e.version+=1,e.updatedAt=this.now()}};function Ot(t){return{...t,...t.attributes?{attributes:structuredClone(t.attributes)}:{}}}function Dt(t){return{...t,...t.producer?{producer:{...t.producer}}:{},...t.attributes?{attributes:structuredClone(t.attributes)}:{}}}function Se(t){return{...t,nodes:t.nodes.map(Ot),edges:t.edges.map(Dt)}}var u=class extends Error{constructor(n,i,o,r){super(i,r);this.code=n;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},ne=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(e={}){this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(n=>(this.idCounter+=1,`${n}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),e.initialState&&this.hydrate(e.initialState)}exportState(){let e=[...this.records.values()].flatMap(n=>[...n.values()]).sort(Ft).map(n=>({artifact:le(n.artifact),recordVersion:n.recordVersion,lifecycleEvents:structuredClone(n.lifecycleEvents),reviewEvents:structuredClone(n.reviewEvents)}));return{schemaVersion:1,records:e}}async create(e){if(X(e),this.assertInitialState(e),e.revision!==1)throw new u("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:e.artifactId,revision:e.revision});if(this.records.has(e.artifactId))throw new u("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let n=le(e),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),K(o)}async createRevision(e,n={}){X(e),this.assertInitialState(e);let i=this.getMutable(e.artifactId);this.assertVersion(i,n.expectedRecordVersion);let o=i.artifact.revision+1;if(e.revision!==o||e.predecessorRevision!==i.artifact.revision)throw new u("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${i.artifact.revision}`,{artifactId:e.artifactId,currentRevision:i.artifact.revision,requestedRevision:e.revision});if(Un(e,i.artifact))throw new u("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(i.artifact.state==="archived")throw new u("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:i.artifact.revision});if(i.artifact.state!=="superseded"){pe(i.artifact.state,"superseded");let a=this.now(),c=this.createLifecycleEvent({artifact:i.artifact,sequence:i.lifecycleEvents.length+1,actor:n.actor??e.provenance.producer,fromState:i.artifact.state,toState:"superseded",reason:n.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});i.artifact.state="superseded",i.artifact.updatedAt=a,i.lifecycleEvents.push(c),i.recordVersion+=1}let r=le(e),s=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}`}),d={artifact:r,recordVersion:1,lifecycleEvents:[s],reviewEvents:[]};return this.records.get(r.artifactId)?.set(r.revision,d),this.currentRevisions.set(r.artifactId,r.revision),K(d)}async get(e,n){let i=this.records.get(e);if(!i)return;let o=n??this.currentRevisions.get(e);if(o===void 0)return;let r=i.get(o);return r?K(r):void 0}async require(e,n){let i=await this.get(e,n);if(!i)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${e}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:e,...n===void 0?{}:{revision:n}});return i}async list(e={}){let n=[];for(let[i,o]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(i)))if(e.includeSuperseded)n.push(...o.values());else{let r=this.currentRevisions.get(i);if(r!==void 0){let s=o.get(r);s&&n.push(s)}}return n.filter(i=>zn(i.artifact,e)).sort(Ft).map(K)}async listRevisions(e){let n=this.records.get(e);return n?[...n.values()].sort((i,o)=>i.artifact.revision-o.artifact.revision).map(K):[]}async transition(e){let n=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(n,e.expectedRecordVersion),pe(n.artifact.state,e.toState),e.toState==="approved"||e.toState==="rejected"){let s=e.reviewEventId?n.reviewEvents.find(a=>a.eventId===e.reviewEventId&&a.type==="decision-recorded"):void 0,d=be(n.reviewEvents);if(!s||s.decision!==e.toState||d.latestDecisionEventId!==s.eventId)throw new u("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${e.toState} requires a matching decision event`,{artifactId:e.artifactId,revision:n.artifact.revision});if(e.toState==="approved"&&d.unresolvedComments>0)throw new u("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${d.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:n.artifact.revision,unresolvedComments:d.unresolvedComments})}let i=this.now(),o=n.artifact.state,r=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:e.actor,fromState:o,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:i});return n.artifact.state=e.toState,n.artifact.updatedAt=i,n.lifecycleEvents.push(r),n.recordVersion+=1,K(n)}async appendReviewEvent(e){let n=e.event,i=this.getMutable(n.artifactId,n.artifactRevision);if(this.assertVersion(i,e.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=Re(o,i.artifact);if(r.length>0)throw new G("XENO artifact review event validation failed",r);return i.reviewEvents.push(o),i.recordVersion+=1,K(i)}getMutable(e,n){let i=this.records.get(e),o=n??this.currentRevisions.get(e),r=o===void 0?void 0:i?.get(o);if(!r)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${e}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:e,...n===void 0?{}:{revision:n}});return r}assertVersion(e,n){if(n!==void 0&&n!==e.recordVersion)throw new u("ARTIFACT_CONFLICT",`Expected record version ${n}, found ${e.recordVersion}`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision,expectedRecordVersion:n,actualRecordVersion:e.recordVersion})}assertInitialState(e){if(e.state!=="draft"&&e.state!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:e.artifactId,revision:e.revision})}assertReviewCommentState(e,n){if(n.type==="comment-added"){if(e.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&&!e.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(!e.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=Wn(e.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(e){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:e.artifact.artifactId,revision:e.artifact.revision,sequence:e.sequence,recordedAt:e.recordedAt??this.now(),actor:{...e.actor},fromState:e.fromState,toState:e.toState,...e.reason?{reason:e.reason}:{},...e.reviewEventId?{reviewEventId:e.reviewEventId}:{}}}nextEventId(e){let n=this.idFactory(e);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 ${e} ID`);return this.eventIds.add(n),n}hydrate(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new u("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let n=[...e.records].sort((i,o)=>i.artifact.artifactId.localeCompare(o.artifact.artifactId)||i.artifact.revision-o.artifact.revision);for(let i of n){let o=Jn(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((s,d)=>s.artifact.revision-d.artifact.revision);for(let s=0;s<r.length;s+=1){let d=r[s],a=s+1;if(d.artifact.revision!==a)throw new u("ARTIFACT_REVISION_INVALID",`Persisted artifact ${i} is missing revision ${a}`);if(s===0&&d.artifact.predecessorRevision!==void 0)throw new u("ARTIFACT_REVISION_INVALID",`Initial revision for ${i} cannot declare a predecessor`);if(s>0&&d.artifact.predecessorRevision!==a-1)throw new u("ARTIFACT_REVISION_INVALID",`Persisted revision ${i}:${a} has an invalid predecessor`);if(s<r.length-1&&d.artifact.state!=="superseded")throw new u("ARTIFACT_REVISION_INVALID",`Non-current revision ${i}:${a} must be superseded`)}}}};function Jn(t,e){if(X(t.artifact),!Number.isInteger(t.recordVersion)||t.recordVersion<1)throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact recordVersion must be a positive integer",{artifactId:t.artifact.artifactId,revision:t.artifact.revision});if(!Array.isArray(t.lifecycleEvents)||t.lifecycleEvents.length===0||!Array.isArray(t.reviewEvents))throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact records require lifecycle and review event arrays",{artifactId:t.artifact.artifactId,revision:t.artifact.revision});let n=t.lifecycleEvents.length+t.reviewEvents.length;if(t.recordVersion!==n)throw new u("ARTIFACT_REVISION_INVALID",`Persisted record version ${t.recordVersion} does not match ${n} mutations`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision});let i=null;for(let r=0;r<t.lifecycleEvents.length;r+=1){let s=t.lifecycleEvents[r];if(s.schemaVersion!==1||s.artifactId!==t.artifact.artifactId||s.revision!==t.artifact.revision||s.sequence!==r+1||s.fromState!==i||typeof s.eventId!="string"||s.eventId.length===0||e.has(s.eventId)||!Number.isFinite(Date.parse(s.recordedAt)))throw new u("ARTIFACT_REVISION_INVALID",`Persisted lifecycle event ${r+1} is invalid`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision});if(i===null){if(s.toState!=="draft"&&s.toState!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:t.artifact.artifactId,revision:t.artifact.revision})}else pe(i,s.toState);e.add(s.eventId),i=s.toState}if(i!==t.artifact.state)throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact state does not match its lifecycle tail",{artifactId:t.artifact.artifactId,revision:t.artifact.revision});let o=new Map;for(let r=0;r<t.reviewEvents.length;r+=1){let s=t.reviewEvents[r];if(s.sequence!==r+1||e.has(s.eventId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted review event ${r+1} has an invalid sequence or duplicate ID`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision});let d=Re(s,t.artifact);if(d.length>0)throw new G("Persisted XENO artifact review event validation failed",d);if(s.type==="comment-added"){if(o.has(s.commentId)||s.parentCommentId!==void 0&&!o.has(s.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted comment ${s.commentId} has an invalid identity or parent`);o.set(s.commentId,!1)}else if(s.type==="comment-resolved"||s.type==="comment-reopened"){let a=o.get(s.commentId);if(a===void 0||s.type==="comment-resolved"&&a||s.type==="comment-reopened"&&!a)throw new u("ARTIFACT_REVIEW_INVALID",`Persisted comment transition for ${s.commentId} is invalid`);o.set(s.commentId,s.type==="comment-resolved")}e.add(s.eventId)}return{artifact:le(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}}function Un(t,e){return t.content.hash.algorithm===e.content.hash.algorithm&&t.content.hash.value===e.content.hash.value}function zn(t,e){return!(e.kinds&&!e.kinds.includes(t.kind)||e.states&&!e.states.includes(t.state)||e.runId&&t.identity?.runId!==e.runId||e.sessionId&&t.identity?.sessionId!==e.sessionId||e.turnId&&t.identity?.turnId!==e.turnId||e.taskId&&t.identity?.taskId!==e.taskId||e.workspaceId&&t.identity?.workspaceId!==e.workspaceId||e.repositoryId&&t.identity?.repositoryId!==e.repositoryId||e.producerId&&t.provenance.producer.id!==e.producerId||e.sensitivity&&!e.sensitivity.includes(t.sensitivity))}function Ft(t,e){return t.artifact.createdAt.localeCompare(e.artifact.createdAt)||t.artifact.artifactId.localeCompare(e.artifact.artifactId)||t.artifact.revision-e.artifact.revision}function Wn(t,e){let n=!1;for(let i of t)(i.type==="comment-resolved"||i.type==="comment-reopened")&&i.commentId===e&&(n=i.type==="comment-resolved");return{resolved:n}}function le(t){return structuredClone(t)}function K(t){return{artifact:le(t.artifact),recordVersion:t.recordVersion,etag:`${t.artifact.artifactId}:${t.artifact.revision}:${t.recordVersion}`,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents),reviewSummary:be(t.reviewEvents)}}var et=require("node:crypto"),P=require("node:fs/promises"),M=require("node:path");var L=Tn(require("node:fs/promises"),1);var Gn=new Set(["EACCES","EBUSY","EPERM"]),Kn=[10,20,40,80,160,320,640];async function Lt(t,e){for(let n=0;;n+=1)try{await L.rename(t,e);return}catch(i){let o=i.code,r=Kn[n];if(process.platform!=="win32"||!o||!Gn.has(o)||r===void 0)throw i;await new Promise(s=>setTimeout(s,r))}}var H=require("node:fs"),We=require("node:os"),Ht=require("node:path");function Yn(){return new Date().toISOString()}function Zn(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function jt(t){try{return JSON.parse((0,H.readFileSync)(t,"utf8"))}catch{return null}}function Qn(t){if(!t||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function ei(t){return t.hostname!==(0,We.hostname)()?!0:Qn(t.pid)}function Mt(t,e){(0,H.mkdirSync)((0,Ht.dirname)(t),{recursive:!0}),(0,H.writeFileSync)(t,JSON.stringify(e,null,2)+`
2
- `,{encoding:"utf8",flag:"wx"})}function ti(t,e){let n=jt(t);n?.pid!==e.pid||n.hostname!==e.hostname||(0,H.rmSync)(t,{force:!0})}function Bt(t,e,n){let i=Yn(),o={schemaVersion:1,name:e,pid:process.pid,hostname:(0,We.hostname)(),processStartedAt:Zn(),version:n,acquiredAt:i,updatedAt:i};try{Mt(t,o)}catch(r){if(r.code!=="EEXIST")throw r;let d=jt(t);if(d&&ei(d))throw new Error(`${e} is already locked by PID ${d.pid} on ${d.hostname}.`);(0,H.rmSync)(t,{force:!0}),Mt(t,o)}return{record:o,release:()=>{ti(t,o)}}}var qt="0.10.26";var tt=1,ni="repository.v1.json",ii=5e3,ri=20,oi=64*1024*1024,Ye=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let n=e.snapshotFileName??ni;if((0,M.basename)(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,M.resolve)(e.directory),this.snapshotPath=(0,M.join)(this.directory,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Ge(e.lockTimeoutMs,ii,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Ge(e.lockRetryMs,ri,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Ge(e.maxSnapshotBytes,oi,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(n=>n.create(e))}async createRevision(e,n){return this.mutate(i=>i.createRevision(e,n))}async get(e,n){return(await this.load()).repository.get(e,n)}async require(e,n){return(await this.load()).repository.require(e,n)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(n=>n.transition(e))}async appendReviewEvent(e){return this.mutate(n=>n.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await e(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(e){let n=this.mutationTail.then(e,e);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let e=Date.now(),n;for(;Date.now()-e<=this.lockTimeoutMs;)try{return Bt(this.lockPath,`artifact-repository:${(0,M.basename)(this.snapshotPath)}`,qt)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await fi(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let e,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){e=xe(r)}if(!n&&(e||await di(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),n=r,i=!0)}catch(r){throw e?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,xe(r)])}):r}if(!n&&e)throw e;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new ne({now:this.now,idFactory:r=>`${r}_${(0,et.randomUUID)()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(e){let n=this.now(),o={...{schemaVersion:tt,generation:e.generation,createdAt:e.createdAt,updatedAt:n,state:e.repository.exportState()},generation:e.generation+1},r=ai(o),s=`${JSON.stringify(r,null,2)}
2
+ `,{encoding:"utf8",flag:"wx"})}function ti(t,e){let n=jt(t);n?.pid!==e.pid||n.hostname!==e.hostname||(0,H.rmSync)(t,{force:!0})}function Bt(t,e,n){let i=Yn(),o={schemaVersion:1,name:e,pid:process.pid,hostname:(0,We.hostname)(),processStartedAt:Zn(),version:n,acquiredAt:i,updatedAt:i};try{Mt(t,o)}catch(r){if(r.code!=="EEXIST")throw r;let d=jt(t);if(d&&ei(d))throw new Error(`${e} is already locked by PID ${d.pid} on ${d.hostname}.`);(0,H.rmSync)(t,{force:!0}),Mt(t,o)}return{record:o,release:()=>{ti(t,o)}}}var qt="0.10.29";var tt=1,ni="repository.v1.json",ii=5e3,ri=20,oi=64*1024*1024,Ye=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let n=e.snapshotFileName??ni;if((0,M.basename)(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=(0,M.resolve)(e.directory),this.snapshotPath=(0,M.join)(this.directory,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Ge(e.lockTimeoutMs,ii,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Ge(e.lockRetryMs,ri,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Ge(e.maxSnapshotBytes,oi,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(n=>n.create(e))}async createRevision(e,n){return this.mutate(i=>i.createRevision(e,n))}async get(e,n){return(await this.load()).repository.get(e,n)}async require(e,n){return(await this.load()).repository.require(e,n)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(n=>n.transition(e))}async appendReviewEvent(e){return this.mutate(n=>n.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await e(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(e){let n=this.mutationTail.then(e,e);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let e=Date.now(),n;for(;Date.now()-e<=this.lockTimeoutMs;)try{return Bt(this.lockPath,`artifact-repository:${(0,M.basename)(this.snapshotPath)}`,qt)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await fi(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let e,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){e=xe(r)}if(!n&&(e||await di(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),n=r,i=!0)}catch(r){throw e?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,xe(r)])}):r}if(!n&&e)throw e;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new ne({now:this.now,idFactory:r=>`${r}_${(0,et.randomUUID)()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(e){let n=this.now(),o={...{schemaVersion:tt,generation:e.generation,createdAt:e.createdAt,updatedAt:n,state:e.repository.exportState()},generation:e.generation+1},r=ai(o),s=`${JSON.stringify(r,null,2)}
3
3
  `;if(Buffer.byteLength(s,"utf8")>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await(0,P.mkdir)(this.directory,{recursive:!0,mode:448}),e.hasSnapshot&&!e.recoveredFromBackup&&e.sourceSnapshot&&await Jt(this.backupPath,`${JSON.stringify(e.sourceSnapshot,null,2)}
4
4
  `),await Jt(this.snapshotPath,s)}async readSnapshot(e,n){let i;try{i=await(0,P.stat)(e)}catch(o){if(!n&&Ze(o,"ENOENT")||n&&Ze(o,"ENOENT"))return;throw Qe("Unable to inspect artifact repository snapshot",e,o)}if(!i.isFile()||i.size>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:e,sizeBytes:i.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await(0,P.readFile)(e);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return si(JSON.parse(o.toString("utf8")),e)}catch(o){throw o instanceof u?o:Qe("Unable to parse artifact repository snapshot",e,o,!0)}}};function si(t,e){if(!Ke(t)||t.schemaVersion!==tt||!Number.isInteger(t.generation)||t.generation<0||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt))||!Ke(t.state)||t.state.schemaVersion!==1||!Array.isArray(t.state.records)||!Ke(t.checksum)||t.checksum.algorithm!=="sha256"||typeof t.checksum.value!="string")throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:e});let n=t,i=ci(n),o=Ut(i);if(n.checksum.value!==o)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:e});return new ne({initialState:n.state}),structuredClone(n)}function ai(t){return{...structuredClone(t),checksum:{algorithm:"sha256",value:Ut(t)}}}function ci(t){return{schemaVersion:t.schemaVersion,generation:t.generation,createdAt:t.createdAt,updatedAt:t.updatedAt,state:t.state}}function Ut(t){return k(JSON.stringify(t)).value}async function Jt(t,e){await(0,P.mkdir)((0,M.dirname)(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${(0,et.randomUUID)()}`,i;try{i=await(0,P.open)(n,"wx",384),await i.writeFile(e,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,await Lt(n,t);try{let o=await(0,P.open)((0,M.dirname)(t),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{i&&await i.close().catch(()=>{}),await(0,P.unlink)(n).catch(()=>{})}}function Ge(t,e,n,i,o){if(t===void 0)return e;if(!Number.isInteger(t)||t<n||t>i)throw new TypeError(`${o} must be an integer between ${n} and ${i}`);return t}function Ke(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ze(t,e){return t instanceof Error&&t.code===e}async function di(t){try{return(await(0,P.stat)(t)).isFile()}catch(e){if(Ze(e,"ENOENT"))return!1;throw Qe("Unable to inspect artifact repository backup",t,e)}}function xe(t){return t instanceof Error?t:new Error(String(t))}function Qe(t,e,n,i=!1){return new u(i?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${t}: ${xe(n).message}`,{snapshotPath:e},{cause:xe(n)})}function fi(t){return new Promise(e=>setTimeout(e,t))}var nt=require("node:buffer");var pi=16*1024*1024,ui=5e3,li=1e5,mi=1e6,hi=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,T=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 it(t,e={}){if(typeof t!="string")throw new TypeError("Unified diff must be a string");let n=Te(e.maxBytes,pi,1024,256*1024*1024,"maxBytes"),i=Te(e.maxFiles,ui,1,1e5,"maxFiles"),o=Te(e.maxHunks,li,1,1e6,"maxHunks"),r=Te(e.maxLines,mi,1,5e6,"maxLines");if(nt.Buffer.byteLength(t,"utf8")>n)throw new T(`Unified diff exceeds ${n} bytes`);let s=t.replace(/\r\n/g,`
5
5
  `).replace(/\r/g,`
@@ -1,5 +1,5 @@
1
1
  var v=1,pe=1,Ye=["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","page"],Ze=["draft","pending_review","approved","rejected","superseded","archived"],Qe=["public","internal","confidential","restricted"],et=["agent","tool","user","system","integration"],ue=["requirement","design-decision","risk","task","agent","run","tool-call","edit","commit","test-case","test-run","finding","approval","artifact","release","claim"],le=["decomposes","depends_on","implements","changes","tests","verifies","finds","fixes","reviews","approves","rejects","supersedes","derived_from","produced_by","supports_claim","contradicts_claim","released_as"];import{Buffer as tt}from"node:buffer";import{createHash as pn}from"node:crypto";function x(t){return{algorithm:"sha256",value:pn("sha256").update(t).digest("hex")}}function T(t){return JSON.stringify(xe(t,new Set))}function k(t){return x(T(t))}function xe(t,e){if(t===null||typeof t!="object"){if(typeof t=="number"&&!Number.isFinite(t))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return t}if(e.has(t))throw new TypeError("Artifact JSON cannot contain cycles");if(e.add(t),Array.isArray(t)){let i=t.map(o=>xe(o,e));return e.delete(t),i}let n={};for(let i of Object.keys(t).sort((o,r)=>o.localeCompare(r))){let o=t[i];if(o===void 0)throw new TypeError(`Artifact JSON property ${i} is undefined`);n[i]=xe(o,e)}return e.delete(t),n}var un=/^[a-z0-9][a-z0-9._/-]{0,127}$/,Te="custom:";function B(t,e=Te){return t.startsWith(e)?un.test(t.slice(e.length)):!1}var K=class extends Error{code="ARTIFACT_INVALID";issues;constructor(e,n){super(e),this.name="XenoArtifactValidationError",this.issues=n.map(i=>({...i}))}},ke=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]",hn=new RegExp(mn),nt=/^[a-f0-9]{64}$/,gn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,vn=new Set(Ze),yn=new Set(Qe),An=new Set(et),In=new Set(Ye),wn=new Set(ue),En=new Set(le);function p(t,e,n,i){t.push({path:e,code:n,message:i})}function l(t,e,n,i=1024){return typeof t!="string"||t.trim().length===0?(p(n,e,"required_string","Value must be a non-empty string"),!1):(t.length>i&&p(n,e,"string_too_long",`Value must not exceed ${i} characters`),hn.test(t)&&p(n,e,"control_character","Value must not contain control characters"),!0)}function Z(t,e,n){t!==void 0&&(!Number.isFinite(Date.parse(t))||!t.includes("T"))&&p(n,e,"invalid_timestamp","Value must be an ISO 8601 timestamp")}function q(t,e,n,i){typeof t=="string"&&t.startsWith(e)&&(B(t,e)||p(i,n,"invalid_custom_name",`Custom name after ${e} is invalid`))}function it(t,e,n){if(!t||typeof t!="object"){p(n,e,"missing_actor","Actor is required");return}l(t.kind,`${e}.kind`,n,64),An.has(t.kind)||p(n,`${e}.kind`,"unknown_actor_kind","Actor kind is not supported"),l(t.id,`${e}.id`,n,512),t?.displayName!==void 0&&l(t.displayName,`${e}.displayName`,n,512),t?.profileFingerprint!==void 0&&!/^[a-f0-9]{64}$/.test(t.profileFingerprint)&&p(n,`${e}.profileFingerprint`,"invalid_fingerprint","Profile fingerprint must be 64 lowercase hexadecimal characters")}function Ce(t,e,n){if(!t||typeof t!="object"){p(n,e,"invalid_anchor","Anchor must be an object");return}switch(t.kind){case"file":l(t.path,`${e}.path`,n,4096);break;case"source-line":l(t.path,`${e}.path`,n,4096),(!Number.isInteger(t.startLine)||t.startLine<1)&&p(n,`${e}.startLine`,"invalid_line","startLine must be a positive integer"),t.endLine!==void 0&&(!Number.isInteger(t.endLine)||t.endLine<t.startLine)&&p(n,`${e}.endLine`,"invalid_line_range","endLine must be greater than or equal to startLine");break;case"diff-hunk":l(t.path,`${e}.path`,n,4096),l(t.hunkId,`${e}.hunkId`,n,512);break;case"symbol":l(t.path,`${e}.path`,n,4096),l(t.symbol,`${e}.symbol`,n,1024);break;case"dom-node":l(t.pageId,`${e}.pageId`,n,512),!t.selector&&!t.accessibilityId&&!t.snapshotArtifactId&&p(n,e,"missing_dom_locator","DOM anchors require a selector, accessibility ID, or snapshot artifact ID");break;case"timeline":l(t.recordingArtifactId,`${e}.recordingArtifactId`,n,512),(!Number.isFinite(t.startMs)||t.startMs<0)&&p(n,`${e}.startMs`,"invalid_time","startMs must be a non-negative finite number"),t.endMs!==void 0&&(!Number.isFinite(t.endMs)||t.endMs<t.startMs)&&p(n,`${e}.endMs`,"invalid_time_range","endMs must be greater than or equal to startMs");break;case"region":l(t.mediaArtifactId,`${e}.mediaArtifactId`,n,512),[t.x,t.y,t.width,t.height].every(Number.isFinite)?(t.width<=0||t.height<=0)&&p(n,e,"invalid_region_size","Region width and height must be positive"):p(n,e,"invalid_region","Region coordinates must be finite numbers");break;case"artifact":l(t.artifactId,`${e}.artifactId`,n,512);break;default:typeof t.kind!="string"||!t.kind.startsWith("custom:")?p(n,`${e}.kind`,"unknown_anchor","Anchor kind is not supported"):q(t.kind,"custom:",`${e}.kind`,n)}}function Q(t,e,n,i){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){Number.isFinite(t)||p(n,e,"non_finite_number","JSON numbers must be finite");return}if(typeof t!="object"){p(n,e,"non_json_value","Value must be JSON-serializable");return}if(i.has(t)){p(n,e,"cyclic_value","Value must not contain cycles");return}if(i.add(t),Array.isArray(t))t.forEach((o,r)=>Q(o,`${e}[${r}]`,n,i));else for(let[o,r]of Object.entries(t))r===void 0?p(n,`${e}.${o}`,"undefined_value","Undefined is not valid JSON"):Q(r,`${e}.${o}`,n,i);i.delete(t)}}function Xn(t){let e=[];if(!t||typeof t!="object")return[{path:"$",code:"invalid_artifact",message:"Artifact must be an object"}];if(t.schemaVersion!==1&&p(e,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(t.artifactId,"artifactId",e,512),(!Number.isInteger(t.revision)||t.revision<1)&&p(e,"revision","invalid_revision","revision must be a positive integer"),l(t.kind,"kind",e,160),typeof t.kind=="string"&&!In.has(t.kind)&&!t.kind.startsWith("custom:")&&p(e,"kind","unknown_artifact_kind","Artifact kind is not supported"),q(t.kind,"custom:","kind",e),l(t.title,"title",e,1024),t.description!==void 0&&l(t.description,"description",e,32768),l(t.state,"state",e,64),vn.has(t.state)||p(e,"state","unknown_state","Artifact state is not supported"),l(t.createdAt,"createdAt",e,128),Z(t.createdAt,"createdAt",e),Z(t.updatedAt,"updatedAt",e),t.updatedAt&&Number.isFinite(Date.parse(t.createdAt))&&Date.parse(t.updatedAt)<Date.parse(t.createdAt)&&p(e,"updatedAt","timestamp_order","updatedAt must not precede createdAt"),l(t.mediaType,"mediaType",e,255),l(t.sensitivity,"sensitivity",e,64),yn.has(t.sensitivity)||p(e,"sensitivity","unknown_sensitivity","Sensitivity is not supported"),t.identity)for(let[i,o]of Object.entries(t.identity))o!==void 0&&l(o,`identity.${i}`,e,512);if(!t.content||typeof t.content!="object")p(e,"content","missing_content","content descriptor is required");else{!t.content.hash||typeof t.content.hash!="object"?p(e,"content.hash","missing_hash","content hash is required"):(l(t.content.hash.algorithm,"content.hash.algorithm",e,128),q(t.content.hash.algorithm,"custom:","content.hash.algorithm",e),typeof t.content.hash.algorithm=="string"&&t.content.hash.algorithm!=="sha256"&&!t.content.hash.algorithm.startsWith("custom:")&&p(e,"content.hash.algorithm","unknown_hash_algorithm","Hash algorithm is not supported"),l(t.content.hash.value,"content.hash.value",e,512),t.content.hash.algorithm==="sha256"&&!nt.test(t.content.hash.value)&&p(e,"content.hash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters")),(!Number.isSafeInteger(t.content.sizeBytes)||t.content.sizeBytes<0)&&p(e,"content.sizeBytes","invalid_size","sizeBytes must be a non-negative safe integer");let i=t.content.storage;if(!i||typeof i!="object")p(e,"content.storage","missing_storage","storage reference is required");else if(i.type==="inline")if(i.text===void 0==(i.base64===void 0))p(e,"content.storage","invalid_inline_storage","Inline storage requires exactly one of text or base64");else{let o;i.text!==void 0?o=tt.from(i.text,"utf8"):i.base64!==void 0&&(gn.test(i.base64)?o=tt.from(i.base64,"base64"):p(e,"content.storage.base64","invalid_base64","Inline base64 content is malformed")),o&&t.content.sizeBytes!==o.byteLength&&p(e,"content.sizeBytes","content_size_mismatch","sizeBytes does not match inline content"),o&&t.content.hash.algorithm==="sha256"&&x(o).value!==t.content.hash.value&&p(e,"content.hash.value","content_hash_mismatch","Hash does not match inline content")}else i.type==="file"?l(i.path,"content.storage.path",e,4096):i.type==="blob"?l(i.uri,"content.storage.uri",e,8192):i.type==="git"?(l(i.commit,"content.storage.commit",e,512),l(i.path,"content.storage.path",e,4096)):i.type==="url"?(l(i.url,"content.storage.url",e,8192),Z(i.expiresAt,"content.storage.expiresAt",e)):i.type==="external"?(l(i.provider,"content.storage.provider",e,255),l(i.locator,"content.storage.locator",e,8192)):p(e,"content.storage.type","unknown_storage","Storage type is not supported");t.content.encoding!==void 0&&(typeof t.content.encoding!="string"||t.content.encoding!=="utf8"&&t.content.encoding!=="base64"&&t.content.encoding!=="binary"&&!t.content.encoding.startsWith("custom:"))&&p(e,"content.encoding","unknown_encoding","Content encoding is not supported"),q(t.content.encoding,"custom:","content.encoding",e)}!t.provenance||typeof t.provenance!="object"?p(e,"provenance","missing_provenance","provenance is required"):(it(t.provenance.producer,"provenance.producer",e),t.provenance.capabilityLeaseIds?.forEach((i,o)=>l(i,`provenance.capabilityLeaseIds[${o}]`,e,512)),t.provenance.sourceArtifactIds?.forEach((i,o)=>l(i,`provenance.sourceArtifactIds[${o}]`,e,512)),t.provenance.attributes&&Q(t.provenance.attributes,"provenance.attributes",e,new Set));let n=new Set;return t.relationships?.forEach((i,o)=>{let r=`relationships[${o}]`;l(i.relation,`${r}.relation`,e,160),typeof i.relation=="string"&&!En.has(i.relation)&&!i.relation.startsWith("custom:")&&p(e,`${r}.relation`,"unknown_relationship","Relationship type is not supported"),q(i.relation,"custom:",`${r}.relation`,e),l(i.target?.type,`${r}.target.type`,e,160),typeof i.target?.type=="string"&&!wn.has(i.target.type)&&!i.target.type.startsWith("custom:")&&p(e,`${r}.target.type`,"unknown_reference_type","Evidence reference type is not supported"),q(i.target?.type,"custom:",`${r}.target.type`,e),l(i.target?.id,`${r}.target.id`,e,512);let s=`${i.relation}:${i.target?.type}:${i.target?.id}:${i.target?.revision??""}`;n.has(s)&&p(e,r,"duplicate_relationship","Duplicate relationship"),n.add(s),i.attributes&&Q(i.attributes,`${r}.attributes`,e,new Set)}),t.anchors?.forEach((i,o)=>Ce(i,`anchors[${o}]`,e)),t.revision===1&&t.predecessorRevision!==void 0&&p(e,"predecessorRevision","unexpected_predecessor","First revision cannot have a predecessor"),t.revision>1&&(!Number.isInteger(t.predecessorRevision)||(t.predecessorRevision??0)>=t.revision)&&p(e,"predecessorRevision","invalid_predecessor","Later revisions require an earlier predecessor revision"),Z(t.retention?.retainUntil,"retention.retainUntil",e),t.retention?.legalHold!==void 0&&typeof t.retention.legalHold!="boolean"&&p(e,"retention.legalHold","invalid_boolean","legalHold must be a boolean"),t.extensions&&Q(t.extensions,"extensions",e,new Set),e}function R(t){let e=Xn(t);if(e.length>0)throw new K("XENO artifact validation failed",e)}function Rn(t,e){return ln[t].includes(e)}function me(t,e){if(!Rn(t,e))throw new ke(t,e)}function Ne(t,e){let n=[];return t.schemaVersion!==1&&p(n,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),l(t.eventId,"eventId",n,512),l(t.artifactId,"artifactId",n,512),(!Number.isInteger(t.artifactRevision)||t.artifactRevision<1)&&p(n,"artifactRevision","invalid_revision","artifactRevision must be a positive integer"),(!Number.isInteger(t.sequence)||t.sequence<1)&&p(n,"sequence","invalid_sequence","sequence must be a positive integer"),l(t.recordedAt,"recordedAt",n,128),Z(t.recordedAt,"recordedAt",n),it(t.actor,"actor",n),!t.artifactHash||typeof t.artifactHash!="object"?p(n,"artifactHash","missing_hash","Artifact hash is required"):(l(t.artifactHash.algorithm,"artifactHash.algorithm",n,128),q(t.artifactHash.algorithm,"custom:","artifactHash.algorithm",n),l(t.artifactHash.value,"artifactHash.value",n,512),t.artifactHash.algorithm==="sha256"&&!nt.test(t.artifactHash.value)&&p(n,"artifactHash.value","invalid_sha256","SHA-256 hash must be 64 lowercase hexadecimal characters"),typeof t.artifactHash.algorithm=="string"&&t.artifactHash.algorithm!=="sha256"&&!t.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(t.type)||p(n,"type","unknown_review_event","Review event type is not supported"),t.type==="comment-added"?(l(t.commentId,"commentId",n,512),l(t.body,"body",n,65536),t.anchor&&Ce(t.anchor,"anchor",n)):t.type==="comment-resolved"||t.type==="comment-reopened"?l(t.commentId,"commentId",n,512):t.type==="decision-recorded"&&(["approved","rejected","changes_requested"].includes(t.decision)||p(n,"decision","unknown_review_decision","Review decision is not supported"),t.scope&&Ce(t.scope,"scope",n)),e&&(t.artifactId!==e.artifactId&&p(n,"artifactId","artifact_mismatch","Review event targets a different artifact"),t.artifactRevision!==e.revision&&p(n,"artifactRevision","revision_mismatch","Review event targets a different revision"),t.artifactHash&&(t.artifactHash.algorithm!==e.content.hash.algorithm||t.artifactHash.value!==e.content.hash.value)&&p(n,"artifactHash","hash_mismatch","Review event hash does not match the artifact revision")),n}function Pe(t){let e="not_requested",n,i,o,r=0,s=new Set,d=new Set;for(let a of[...t].sort((c,f)=>c.sequence-f.sequence))o=a.recordedAt,a.type==="review-requested"?e="pending":a.type==="review-withdrawn"?e="withdrawn":a.type==="comment-added"?(s.add(a.commentId),d.delete(a.commentId),e==="not_requested"&&(e="pending")):a.type==="comment-resolved"?d.add(a.commentId):a.type==="comment-reopened"?d.delete(a.commentId):a.type==="decision-recorded"&&(a.scope?r+=1:(n=a.decision,i=a.eventId,e=a.decision));return{status:e,totalComments:s.size,unresolvedComments:[...s].filter(a=>!d.has(a)).length,...n?{latestDecision:n}:{},...i?{latestDecisionEventId:i}:{},...r>0?{scopedDecisionCount:r}:{},...o?{lastReviewedAt:o}:{}}}var $e=class extends Error{code="EVIDENCE_GRAPH_INVALID";issues;constructor(e){super("XENO evidence graph validation failed"),this.name="XenoEvidenceGraphValidationError",this.issues=e.map(n=>({...n}))}},bn=new Set(["depends_on","decomposes","supersedes"]),Sn=new Set(ue),_n=new Set(le);function A(t,e,n,i){t.push({path:e,code:n,message:i})}function ee(t){return t.includes("T")&&Number.isFinite(Date.parse(t))}function rt(t,e){return t.startsWith(Te)?B(t):e.has(t)}function xn(t){let e=[];if(!t||typeof t!="object")return[{path:"$",code:"invalid_graph",message:"Evidence graph must be an object"}];t.schemaVersion!==1&&A(e,"schemaVersion","unsupported_schema",`schemaVersion must be ${1}`),(typeof t.graphId!="string"||t.graphId.trim().length===0)&&A(e,"graphId","required_string","graphId must be a non-empty string"),(!Number.isInteger(t.version)||t.version<1)&&A(e,"version","invalid_version","version must be a positive integer"),ee(t.createdAt)||A(e,"createdAt","invalid_timestamp","createdAt must be an ISO 8601 timestamp"),ee(t.updatedAt)||A(e,"updatedAt","invalid_timestamp","updatedAt must be an ISO 8601 timestamp"),ee(t.createdAt)&&ee(t.updatedAt)&&Date.parse(t.updatedAt)<Date.parse(t.createdAt)&&A(e,"updatedAt","timestamp_order","updatedAt must not precede createdAt");let n=new Map;Array.isArray(t.nodes)||A(e,"nodes","invalid_nodes","nodes must be an array"),(Array.isArray(t.nodes)?t.nodes:[]).forEach((f,g)=>{let y=`nodes[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(e,`${y}.id`,"required_string","Node ID must be a non-empty string"):n.has(f.id)?A(e,`${y}.id`,"duplicate_node",`Node ID ${f.id} is duplicated`):n.set(f.id,f),(typeof f.type!="string"||!rt(f.type,Sn))&&A(e,`${y}.type`,"invalid_node_type","Node type is invalid"),f.artifactRevision!==void 0&&(!Number.isInteger(f.artifactRevision)||f.artifactRevision<1)&&A(e,`${y}.artifactRevision`,"invalid_revision","artifactRevision must be a positive integer")});let i=new Set,o=new Set;Array.isArray(t.edges)||A(e,"edges","invalid_edges","edges must be an array"),(Array.isArray(t.edges)?t.edges:[]).forEach((f,g)=>{let y=`edges[${g}]`;typeof f.id!="string"||f.id.trim().length===0?A(e,`${y}.id`,"required_string","Edge ID must be a non-empty string"):i.has(f.id)&&A(e,`${y}.id`,"duplicate_edge",`Edge ID ${f.id} is duplicated`),i.add(f.id),(typeof f.type!="string"||!rt(f.type,_n))&&A(e,`${y}.type`,"invalid_edge_type","Edge type is invalid");let P=`${f.type}:${f.from}:${f.to}`;o.has(P)&&A(e,y,"duplicate_edge_identity","Equivalent evidence edge is duplicated"),o.add(P),n.has(f.from)||A(e,`${y}.from`,"dangling_reference",`Source node ${f.from} does not exist`),n.has(f.to)||A(e,`${y}.to`,"dangling_reference",`Target node ${f.to} does not exist`),f.from===f.to&&A(e,y,"self_edge","Evidence edges cannot point to the same node"),ee(f.createdAt)||A(e,`${y}.createdAt`,"invalid_timestamp","createdAt must be an ISO 8601 timestamp")});let r=(Array.isArray(t.edges)?t.edges:[]).filter(f=>bn.has(f.type)),s=new Map;for(let f of r){let g=s.get(f.from)??[];g.push(f.to),s.set(f.from,g)}let d=new Set,a=new Set,c=f=>{if(d.has(f))return!0;if(a.has(f))return!1;d.add(f);for(let g of s.get(f)??[])if(c(g))return!0;return d.delete(f),a.add(f),!1};for(let f of n.keys())if(c(f)){A(e,"edges","cyclic_graph","Dependency, decomposition, and supersession edges must be acyclic");break}return e}function te(t){let e=xn(t);if(e.length>0)throw new $e(e)}var ot=class{now;graph;constructor(e){if("schemaVersion"in e)te(e),this.now=()=>new Date().toISOString(),this.graph=he(e);else{this.now=e.now??(()=>new Date().toISOString());let n=this.now();this.graph={schemaVersion:1,graphId:e.graphId,version:1,createdAt:n,updatedAt:n,nodes:[],edges:[]},te(this.graph)}}addNode(e){let n=he(this.graph);return n.nodes.push(st(e)),this.touch(n),te(n),this.graph=n,this}addEdge(e){let n=he(this.graph);return n.edges.push(at(e)),this.touch(n),te(n),this.graph=n,this}build(){return te(this.graph),he(this.graph)}touch(e){e.version+=1,e.updatedAt=this.now()}};function st(t){return{...t,...t.attributes?{attributes:structuredClone(t.attributes)}:{}}}function at(t){return{...t,...t.producer?{producer:{...t.producer}}:{},...t.attributes?{attributes:structuredClone(t.attributes)}:{}}}function he(t){return{...t,nodes:t.nodes.map(st),edges:t.edges.map(at)}}var u=class extends Error{constructor(n,i,o,r){super(i,r);this.code=n;this.detail=o;this.name="XenoArtifactRepositoryError"}code;detail},ie=class{records=new Map;currentRevisions=new Map;now;idFactory;eventIds=new Set;idCounter=0;constructor(e={}){this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(n=>(this.idCounter+=1,`${n}_${Date.now().toString(36)}_${this.idCounter.toString(36)}`)),e.initialState&&this.hydrate(e.initialState)}exportState(){let e=[...this.records.values()].flatMap(n=>[...n.values()]).sort(ct).map(n=>({artifact:ne(n.artifact),recordVersion:n.recordVersion,lifecycleEvents:structuredClone(n.lifecycleEvents),reviewEvents:structuredClone(n.reviewEvents)}));return{schemaVersion:1,records:e}}async create(e){if(R(e),this.assertInitialState(e),e.revision!==1)throw new u("ARTIFACT_REVISION_INVALID","A new artifact must begin at revision 1",{artifactId:e.artifactId,revision:e.revision});if(this.records.has(e.artifactId))throw new u("ARTIFACT_ALREADY_EXISTS",`Artifact ${e.artifactId} already exists`,{artifactId:e.artifactId});let n=ne(e),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),J(o)}async createRevision(e,n={}){R(e),this.assertInitialState(e);let i=this.getMutable(e.artifactId);this.assertVersion(i,n.expectedRecordVersion);let o=i.artifact.revision+1;if(e.revision!==o||e.predecessorRevision!==i.artifact.revision)throw new u("ARTIFACT_REVISION_INVALID",`Revision ${e.revision} does not follow current revision ${i.artifact.revision}`,{artifactId:e.artifactId,currentRevision:i.artifact.revision,requestedRevision:e.revision});if(kn(e,i.artifact))throw new u("ARTIFACT_CONTENT_UNCHANGED","A new artifact revision must have a different content hash",{artifactId:e.artifactId,revision:e.revision});if(i.artifact.state==="archived")throw new u("ARTIFACT_REVISION_INVALID","Archived artifacts cannot receive new revisions",{artifactId:e.artifactId,revision:i.artifact.revision});if(i.artifact.state!=="superseded"){me(i.artifact.state,"superseded");let a=this.now(),c=this.createLifecycleEvent({artifact:i.artifact,sequence:i.lifecycleEvents.length+1,actor:n.actor??e.provenance.producer,fromState:i.artifact.state,toState:"superseded",reason:n.reason??`superseded-by-revision-${e.revision}`,recordedAt:a});i.artifact.state="superseded",i.artifact.updatedAt=a,i.lifecycleEvents.push(c),i.recordVersion+=1}let r=ne(e),s=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}`}),d={artifact:r,recordVersion:1,lifecycleEvents:[s],reviewEvents:[]};return this.records.get(r.artifactId)?.set(r.revision,d),this.currentRevisions.set(r.artifactId,r.revision),J(d)}async get(e,n){let i=this.records.get(e);if(!i)return;let o=n??this.currentRevisions.get(e);if(o===void 0)return;let r=i.get(o);return r?J(r):void 0}async require(e,n){let i=await this.get(e,n);if(!i)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${e}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:e,...n===void 0?{}:{revision:n}});return i}async list(e={}){let n=[];for(let[i,o]of this.records)if(!(e.artifactIds&&!e.artifactIds.includes(i)))if(e.includeSuperseded)n.push(...o.values());else{let r=this.currentRevisions.get(i);if(r!==void 0){let s=o.get(r);s&&n.push(s)}}return n.filter(i=>Cn(i.artifact,e)).sort(ct).map(J)}async listRevisions(e){let n=this.records.get(e);return n?[...n.values()].sort((i,o)=>i.artifact.revision-o.artifact.revision).map(J):[]}async transition(e){let n=this.getMutable(e.artifactId,e.revision);if(this.assertVersion(n,e.expectedRecordVersion),me(n.artifact.state,e.toState),e.toState==="approved"||e.toState==="rejected"){let s=e.reviewEventId?n.reviewEvents.find(a=>a.eventId===e.reviewEventId&&a.type==="decision-recorded"):void 0,d=Pe(n.reviewEvents);if(!s||s.decision!==e.toState||d.latestDecisionEventId!==s.eventId)throw new u("ARTIFACT_REVIEW_DECISION_REQUIRED",`Transition to ${e.toState} requires a matching decision event`,{artifactId:e.artifactId,revision:n.artifact.revision});if(e.toState==="approved"&&d.unresolvedComments>0)throw new u("ARTIFACT_UNRESOLVED_COMMENTS",`Artifact has ${d.unresolvedComments} unresolved review comment(s)`,{artifactId:e.artifactId,revision:n.artifact.revision,unresolvedComments:d.unresolvedComments})}let i=this.now(),o=n.artifact.state,r=this.createLifecycleEvent({artifact:n.artifact,sequence:n.lifecycleEvents.length+1,actor:e.actor,fromState:o,toState:e.toState,reason:e.reason,reviewEventId:e.reviewEventId,recordedAt:i});return n.artifact.state=e.toState,n.artifact.updatedAt=i,n.lifecycleEvents.push(r),n.recordVersion+=1,J(n)}async appendReviewEvent(e){let n=e.event,i=this.getMutable(n.artifactId,n.artifactRevision);if(this.assertVersion(i,e.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=Ne(o,i.artifact);if(r.length>0)throw new K("XENO artifact review event validation failed",r);return i.reviewEvents.push(o),i.recordVersion+=1,J(i)}getMutable(e,n){let i=this.records.get(e),o=n??this.currentRevisions.get(e),r=o===void 0?void 0:i?.get(o);if(!r)throw new u("ARTIFACT_NOT_FOUND",`Artifact ${e}${n===void 0?"":` revision ${n}`} was not found`,{artifactId:e,...n===void 0?{}:{revision:n}});return r}assertVersion(e,n){if(n!==void 0&&n!==e.recordVersion)throw new u("ARTIFACT_CONFLICT",`Expected record version ${n}, found ${e.recordVersion}`,{artifactId:e.artifact.artifactId,revision:e.artifact.revision,expectedRecordVersion:n,actualRecordVersion:e.recordVersion})}assertInitialState(e){if(e.state!=="draft"&&e.state!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","New artifact revisions must begin in draft or pending_review state",{artifactId:e.artifactId,revision:e.revision})}assertReviewCommentState(e,n){if(n.type==="comment-added"){if(e.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&&!e.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(!e.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=Nn(e.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(e){return{schemaVersion:1,eventId:this.nextEventId("artifact_event"),artifactId:e.artifact.artifactId,revision:e.artifact.revision,sequence:e.sequence,recordedAt:e.recordedAt??this.now(),actor:{...e.actor},fromState:e.fromState,toState:e.toState,...e.reason?{reason:e.reason}:{},...e.reviewEventId?{reviewEventId:e.reviewEventId}:{}}}nextEventId(e){let n=this.idFactory(e);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 ${e} ID`);return this.eventIds.add(n),n}hydrate(e){if(e.schemaVersion!==1||!Array.isArray(e.records))throw new u("ARTIFACT_REVISION_INVALID","Artifact repository state has an unsupported schema or record collection");let n=[...e.records].sort((i,o)=>i.artifact.artifactId.localeCompare(o.artifact.artifactId)||i.artifact.revision-o.artifact.revision);for(let i of n){let o=Tn(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((s,d)=>s.artifact.revision-d.artifact.revision);for(let s=0;s<r.length;s+=1){let d=r[s],a=s+1;if(d.artifact.revision!==a)throw new u("ARTIFACT_REVISION_INVALID",`Persisted artifact ${i} is missing revision ${a}`);if(s===0&&d.artifact.predecessorRevision!==void 0)throw new u("ARTIFACT_REVISION_INVALID",`Initial revision for ${i} cannot declare a predecessor`);if(s>0&&d.artifact.predecessorRevision!==a-1)throw new u("ARTIFACT_REVISION_INVALID",`Persisted revision ${i}:${a} has an invalid predecessor`);if(s<r.length-1&&d.artifact.state!=="superseded")throw new u("ARTIFACT_REVISION_INVALID",`Non-current revision ${i}:${a} must be superseded`)}}}};function Tn(t,e){if(R(t.artifact),!Number.isInteger(t.recordVersion)||t.recordVersion<1)throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact recordVersion must be a positive integer",{artifactId:t.artifact.artifactId,revision:t.artifact.revision});if(!Array.isArray(t.lifecycleEvents)||t.lifecycleEvents.length===0||!Array.isArray(t.reviewEvents))throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact records require lifecycle and review event arrays",{artifactId:t.artifact.artifactId,revision:t.artifact.revision});let n=t.lifecycleEvents.length+t.reviewEvents.length;if(t.recordVersion!==n)throw new u("ARTIFACT_REVISION_INVALID",`Persisted record version ${t.recordVersion} does not match ${n} mutations`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision});let i=null;for(let r=0;r<t.lifecycleEvents.length;r+=1){let s=t.lifecycleEvents[r];if(s.schemaVersion!==1||s.artifactId!==t.artifact.artifactId||s.revision!==t.artifact.revision||s.sequence!==r+1||s.fromState!==i||typeof s.eventId!="string"||s.eventId.length===0||e.has(s.eventId)||!Number.isFinite(Date.parse(s.recordedAt)))throw new u("ARTIFACT_REVISION_INVALID",`Persisted lifecycle event ${r+1} is invalid`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision});if(i===null){if(s.toState!=="draft"&&s.toState!=="pending_review")throw new u("ARTIFACT_REVISION_INVALID","A persisted artifact must begin in draft or pending_review state",{artifactId:t.artifact.artifactId,revision:t.artifact.revision})}else me(i,s.toState);e.add(s.eventId),i=s.toState}if(i!==t.artifact.state)throw new u("ARTIFACT_REVISION_INVALID","Persisted artifact state does not match its lifecycle tail",{artifactId:t.artifact.artifactId,revision:t.artifact.revision});let o=new Map;for(let r=0;r<t.reviewEvents.length;r+=1){let s=t.reviewEvents[r];if(s.sequence!==r+1||e.has(s.eventId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted review event ${r+1} has an invalid sequence or duplicate ID`,{artifactId:t.artifact.artifactId,revision:t.artifact.revision});let d=Ne(s,t.artifact);if(d.length>0)throw new K("Persisted XENO artifact review event validation failed",d);if(s.type==="comment-added"){if(o.has(s.commentId)||s.parentCommentId!==void 0&&!o.has(s.parentCommentId))throw new u("ARTIFACT_REVIEW_INVALID",`Persisted comment ${s.commentId} has an invalid identity or parent`);o.set(s.commentId,!1)}else if(s.type==="comment-resolved"||s.type==="comment-reopened"){let a=o.get(s.commentId);if(a===void 0||s.type==="comment-resolved"&&a||s.type==="comment-reopened"&&!a)throw new u("ARTIFACT_REVIEW_INVALID",`Persisted comment transition for ${s.commentId} is invalid`);o.set(s.commentId,s.type==="comment-resolved")}e.add(s.eventId)}return{artifact:ne(t.artifact),recordVersion:t.recordVersion,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents)}}function kn(t,e){return t.content.hash.algorithm===e.content.hash.algorithm&&t.content.hash.value===e.content.hash.value}function Cn(t,e){return!(e.kinds&&!e.kinds.includes(t.kind)||e.states&&!e.states.includes(t.state)||e.runId&&t.identity?.runId!==e.runId||e.sessionId&&t.identity?.sessionId!==e.sessionId||e.turnId&&t.identity?.turnId!==e.turnId||e.taskId&&t.identity?.taskId!==e.taskId||e.workspaceId&&t.identity?.workspaceId!==e.workspaceId||e.repositoryId&&t.identity?.repositoryId!==e.repositoryId||e.producerId&&t.provenance.producer.id!==e.producerId||e.sensitivity&&!e.sensitivity.includes(t.sensitivity))}function ct(t,e){return t.artifact.createdAt.localeCompare(e.artifact.createdAt)||t.artifact.artifactId.localeCompare(e.artifact.artifactId)||t.artifact.revision-e.artifact.revision}function Nn(t,e){let n=!1;for(let i of t)(i.type==="comment-resolved"||i.type==="comment-reopened")&&i.commentId===e&&(n=i.type==="comment-resolved");return{resolved:n}}function ne(t){return structuredClone(t)}function J(t){return{artifact:ne(t.artifact),recordVersion:t.recordVersion,etag:`${t.artifact.artifactId}:${t.artifact.revision}:${t.recordVersion}`,lifecycleEvents:structuredClone(t.lifecycleEvents),reviewEvents:structuredClone(t.reviewEvents),reviewSummary:Pe(t.reviewEvents)}}import{randomUUID as wt}from"node:crypto";import{mkdir as Et,open as gt,readFile as qn,stat as Xt,unlink as Jn}from"node:fs/promises";import{basename as vt,dirname as yt,join as Un,resolve as zn}from"node:path";import*as V from"node:fs/promises";var Pn=new Set(["EACCES","EBUSY","EPERM"]),$n=[10,20,40,80,160,320,640];async function dt(t,e){for(let n=0;;n+=1)try{await V.rename(t,e);return}catch(i){let o=i.code,r=$n[n];if(process.platform!=="win32"||!o||!Pn.has(o)||r===void 0)throw i;await new Promise(s=>setTimeout(s,r))}}import{mkdirSync as Vn,readFileSync as On,rmSync as pt,writeFileSync as Dn}from"node:fs";import{hostname as ut}from"node:os";import{dirname as Fn}from"node:path";function Ln(){return new Date().toISOString()}function Mn(){return new Date(Date.now()-Math.floor(process.uptime()*1e3)).toISOString()}function lt(t){try{return JSON.parse(On(t,"utf8"))}catch{return null}}function Hn(t){if(!t||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function jn(t){return t.hostname!==ut()?!0:Hn(t.pid)}function ft(t,e){Vn(Fn(t),{recursive:!0}),Dn(t,JSON.stringify(e,null,2)+`
2
- `,{encoding:"utf8",flag:"wx"})}function Bn(t,e){let n=lt(t);n?.pid!==e.pid||n.hostname!==e.hostname||pt(t,{force:!0})}function mt(t,e,n){let i=Ln(),o={schemaVersion:1,name:e,pid:process.pid,hostname:ut(),processStartedAt:Mn(),version:n,acquiredAt:i,updatedAt:i};try{ft(t,o)}catch(r){if(r.code!=="EEXIST")throw r;let d=lt(t);if(d&&jn(d))throw new Error(`${e} is already locked by PID ${d.pid} on ${d.hostname}.`);pt(t,{force:!0}),ft(t,o)}return{record:o,release:()=>{Bn(t,o)}}}var ht="0.10.26";var Rt=1,Wn="repository.v1.json",Gn=5e3,Kn=20,Yn=64*1024*1024,At=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let n=e.snapshotFileName??Wn;if(vt(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=zn(e.directory),this.snapshotPath=Un(this.directory,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Ve(e.lockTimeoutMs,Gn,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Ve(e.lockRetryMs,Kn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Ve(e.maxSnapshotBytes,Yn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(n=>n.create(e))}async createRevision(e,n){return this.mutate(i=>i.createRevision(e,n))}async get(e,n){return(await this.load()).repository.get(e,n)}async require(e,n){return(await this.load()).repository.require(e,n)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(n=>n.transition(e))}async appendReviewEvent(e){return this.mutate(n=>n.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await e(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(e){let n=this.mutationTail.then(e,e);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let e=Date.now(),n;for(;Date.now()-e<=this.lockTimeoutMs;)try{return mt(this.lockPath,`artifact-repository:${vt(this.snapshotPath)}`,ht)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await ni(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let e,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){e=ge(r)}if(!n&&(e||await ti(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),n=r,i=!0)}catch(r){throw e?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,ge(r)])}):r}if(!n&&e)throw e;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new ie({now:this.now,idFactory:r=>`${r}_${wt()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(e){let n=this.now(),o={...{schemaVersion:Rt,generation:e.generation,createdAt:e.createdAt,updatedAt:n,state:e.repository.exportState()},generation:e.generation+1},r=Qn(o),s=`${JSON.stringify(r,null,2)}
2
+ `,{encoding:"utf8",flag:"wx"})}function Bn(t,e){let n=lt(t);n?.pid!==e.pid||n.hostname!==e.hostname||pt(t,{force:!0})}function mt(t,e,n){let i=Ln(),o={schemaVersion:1,name:e,pid:process.pid,hostname:ut(),processStartedAt:Mn(),version:n,acquiredAt:i,updatedAt:i};try{ft(t,o)}catch(r){if(r.code!=="EEXIST")throw r;let d=lt(t);if(d&&jn(d))throw new Error(`${e} is already locked by PID ${d.pid} on ${d.hostname}.`);pt(t,{force:!0}),ft(t,o)}return{record:o,release:()=>{Bn(t,o)}}}var ht="0.10.29";var Rt=1,Wn="repository.v1.json",Gn=5e3,Kn=20,Yn=64*1024*1024,At=class{directory;snapshotPath;backupPath;lockPath;now;lockTimeoutMs;lockRetryMs;maxSnapshotBytes;onRecovery;mutationTail=Promise.resolve();constructor(e){if(!e||typeof e.directory!="string"||e.directory.trim().length===0)throw new TypeError("Artifact repository directory is required");let n=e.snapshotFileName??Wn;if(vt(n)!==n||!/^[A-Za-z0-9_.-]+$/.test(n))throw new TypeError("Artifact snapshot filename must be a safe basename");this.directory=zn(e.directory),this.snapshotPath=Un(this.directory,n),this.backupPath=`${this.snapshotPath}.bak`,this.lockPath=`${this.snapshotPath}.lock`,this.now=e.now??(()=>new Date().toISOString()),this.lockTimeoutMs=Ve(e.lockTimeoutMs,Gn,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Ve(e.lockRetryMs,Kn,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Ve(e.maxSnapshotBytes,Yn,1024,1024*1024*1024,"maxSnapshotBytes"),this.onRecovery=e.onRecovery}async create(e){return this.mutate(n=>n.create(e))}async createRevision(e,n){return this.mutate(i=>i.createRevision(e,n))}async get(e,n){return(await this.load()).repository.get(e,n)}async require(e,n){return(await this.load()).repository.require(e,n)}async list(e){return(await this.load()).repository.list(e)}async listRevisions(e){return(await this.load()).repository.listRevisions(e)}async transition(e){return this.mutate(n=>n.transition(e))}async appendReviewEvent(e){return this.mutate(n=>n.appendReviewEvent(e))}async inspectSnapshot(){return this.readSnapshot(this.snapshotPath,!0)}async mutate(e){return this.enqueueMutation(async()=>{let n=await this.acquireLock();try{let i=await this.load(),o=await e(i.repository);return await this.persist(i),o}finally{n.release()}})}async enqueueMutation(e){let n=this.mutationTail.then(e,e);return this.mutationTail=n.then(()=>{},()=>{}),n}async acquireLock(){let e=Date.now(),n;for(;Date.now()-e<=this.lockTimeoutMs;)try{return mt(this.lockPath,`artifact-repository:${vt(this.snapshotPath)}`,ht)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await ni(this.lockRetryMs)}throw new u("ARTIFACT_PERSISTENCE_LOCKED",`Artifact repository remained locked for ${this.lockTimeoutMs}ms`,{snapshotPath:this.snapshotPath},{cause:n})}async load(){let e,n,i=!1;try{n=await this.readSnapshot(this.snapshotPath,!1)}catch(r){e=ge(r)}if(!n&&(e||await ti(this.backupPath)))try{let r=await this.readSnapshot(this.backupPath,!0);r&&(this.onRecovery?.({snapshotPath:this.snapshotPath,backupPath:this.backupPath,reason:e?.message??"primary snapshot missing"}),n=r,i=!0)}catch(r){throw e?new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository primary and backup snapshots are unreadable",{snapshotPath:this.snapshotPath,backupPath:this.backupPath},{cause:new AggregateError([e,ge(r)])}):r}if(!n&&e)throw e;let o=n?.state??{schemaVersion:1,records:[]};return{repository:new ie({now:this.now,idFactory:r=>`${r}_${wt()}`,initialState:o}),generation:n?.generation??0,createdAt:n?.createdAt??this.now(),hasSnapshot:n!==void 0,recoveredFromBackup:i,...n?{sourceSnapshot:n}:{}}}async persist(e){let n=this.now(),o={...{schemaVersion:Rt,generation:e.generation,createdAt:e.createdAt,updatedAt:n,state:e.repository.exportState()},generation:e.generation+1},r=Qn(o),s=`${JSON.stringify(r,null,2)}
3
3
  `;if(Buffer.byteLength(s,"utf8")>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_IO",`Artifact repository snapshot exceeds ${this.maxSnapshotBytes} bytes`,{snapshotPath:this.snapshotPath,maxSnapshotBytes:this.maxSnapshotBytes});await Et(this.directory,{recursive:!0,mode:448}),e.hasSnapshot&&!e.recoveredFromBackup&&e.sourceSnapshot&&await It(this.backupPath,`${JSON.stringify(e.sourceSnapshot,null,2)}
4
4
  `),await It(this.snapshotPath,s)}async readSnapshot(e,n){let i;try{i=await Xt(e)}catch(o){if(!n&&De(o,"ENOENT")||n&&De(o,"ENOENT"))return;throw Fe("Unable to inspect artifact repository snapshot",e,o)}if(!i.isFile()||i.size>this.maxSnapshotBytes)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot is not a bounded regular file",{snapshotPath:e,sizeBytes:i.size,maxSnapshotBytes:this.maxSnapshotBytes});try{let o=await qn(e);if(o.byteLength>this.maxSnapshotBytes)throw new Error("snapshot grew beyond the configured size limit while reading");return Zn(JSON.parse(o.toString("utf8")),e)}catch(o){throw o instanceof u?o:Fe("Unable to parse artifact repository snapshot",e,o,!0)}}};function Zn(t,e){if(!Oe(t)||t.schemaVersion!==Rt||!Number.isInteger(t.generation)||t.generation<0||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt))||!Oe(t.state)||t.state.schemaVersion!==1||!Array.isArray(t.state.records)||!Oe(t.checksum)||t.checksum.algorithm!=="sha256"||typeof t.checksum.value!="string")throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot envelope is invalid",{snapshotPath:e});let n=t,i=ei(n),o=bt(i);if(n.checksum.value!==o)throw new u("ARTIFACT_PERSISTENCE_CORRUPT","Artifact repository snapshot checksum does not match its payload",{snapshotPath:e});return new ie({initialState:n.state}),structuredClone(n)}function Qn(t){return{...structuredClone(t),checksum:{algorithm:"sha256",value:bt(t)}}}function ei(t){return{schemaVersion:t.schemaVersion,generation:t.generation,createdAt:t.createdAt,updatedAt:t.updatedAt,state:t.state}}function bt(t){return x(JSON.stringify(t)).value}async function It(t,e){await Et(yt(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${wt()}`,i;try{i=await gt(n,"wx",384),await i.writeFile(e,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,await dt(n,t);try{let o=await gt(yt(t),"r");try{await o.sync()}finally{await o.close()}}catch{}}finally{i&&await i.close().catch(()=>{}),await Jn(n).catch(()=>{})}}function Ve(t,e,n,i,o){if(t===void 0)return e;if(!Number.isInteger(t)||t<n||t>i)throw new TypeError(`${o} must be an integer between ${n} and ${i}`);return t}function Oe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function De(t,e){return t instanceof Error&&t.code===e}async function ti(t){try{return(await Xt(t)).isFile()}catch(e){if(De(e,"ENOENT"))return!1;throw Fe("Unable to inspect artifact repository backup",t,e)}}function ge(t){return t instanceof Error?t:new Error(String(t))}function Fe(t,e,n,i=!1){return new u(i?"ARTIFACT_PERSISTENCE_CORRUPT":"ARTIFACT_PERSISTENCE_IO",`${t}: ${ge(n).message}`,{snapshotPath:e},{cause:ge(n)})}function ni(t){return new Promise(e=>setTimeout(e,t))}import{Buffer as Tt}from"node:buffer";var ii=16*1024*1024,ri=5e3,oi=1e5,si=1e6,ai=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s?(.*))?$/,_=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 kt(t,e={}){if(typeof t!="string")throw new TypeError("Unified diff must be a string");let n=ve(e.maxBytes,ii,1024,256*1024*1024,"maxBytes"),i=ve(e.maxFiles,ri,1,1e5,"maxFiles"),o=ve(e.maxHunks,oi,1,1e6,"maxHunks"),r=ve(e.maxLines,si,1,5e6,"maxLines");if(Tt.byteLength(t,"utf8")>n)throw new _(`Unified diff exceeds ${n} bytes`);let s=t.replace(/\r\n/g,`
5
5
  `).replace(/\r/g,`