@xenosystem/agent-sdk 0.10.37 → 0.10.39
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.
- package/dist/artifacts/index.cjs +9 -9
- package/dist/artifacts/index.js +9 -9
- package/dist/artifacts/metafile-cjs.json +1 -1
- package/dist/artifacts/metafile-esm.json +1 -1
- package/dist/automation/index.cjs +8 -8
- package/dist/automation/index.d.cts +10 -0
- package/dist/automation/index.d.ts +10 -0
- package/dist/automation/index.js +9 -9
- package/dist/automation/metafile-cjs.json +1 -1
- package/dist/automation/metafile-esm.json +1 -1
- package/dist/control-plane/index.cjs +1 -1
- package/dist/control-plane/index.js +1 -1
- package/dist/electron/index.cjs +221 -200
- package/dist/electron/index.d.cts +91 -1
- package/dist/electron/index.d.ts +91 -1
- package/dist/electron/index.js +221 -200
- package/dist/electron/metafile-cjs.json +1 -1
- package/dist/electron/metafile-esm.json +1 -1
- package/dist/index.cjs +397 -372
- package/dist/index.d.cts +136 -4
- package/dist/index.d.ts +136 -4
- package/dist/index.js +397 -372
- package/dist/intelligence/index.cjs +9 -9
- package/dist/intelligence/index.js +9 -9
- package/dist/intelligence/metafile-cjs.json +1 -1
- package/dist/intelligence/metafile-esm.json +1 -1
- package/dist/mcp/index.d.cts +10 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/providers/index.cjs +9 -9
- package/dist/providers/index.js +9 -9
- package/dist/providers/metafile-cjs.json +1 -1
- package/dist/providers/metafile-esm.json +1 -1
- package/dist/recipes/index.cjs +2 -2
- package/dist/recipes/index.js +2 -2
- package/dist/recipes/metafile-cjs.json +1 -1
- package/dist/recipes/metafile-esm.json +1 -1
- package/dist/research/index.cjs +3 -3
- package/dist/research/index.js +3 -3
- package/dist/research/metafile-cjs.json +1 -1
- package/dist/research/metafile-esm.json +1 -1
- package/dist/session/index.cjs +25 -25
- package/dist/session/index.js +25 -25
- package/dist/session/metafile-cjs.json +1 -1
- package/dist/session/metafile-esm.json +1 -1
- package/dist/sharing/index.cjs +4 -4
- package/dist/sharing/index.js +4 -4
- package/dist/sharing/metafile-cjs.json +1 -1
- package/dist/sharing/metafile-esm.json +1 -1
- package/dist/utils/index.cjs +23 -23
- package/dist/utils/index.d.cts +15 -1
- package/dist/utils/index.d.ts +15 -1
- package/dist/utils/index.js +23 -23
- package/dist/utils/metafile-cjs.json +1 -1
- package/dist/utils/metafile-esm.json +1 -1
- package/package.json +3 -3
package/dist/artifacts/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
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:()=>We,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 W(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 z(t,e,n,i){typeof t=="string"&&t.startsWith(e)&&(W(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"):z(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"),z(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),z(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"),z(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"),z(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"),z(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),z(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)?W(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 We=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=>Wn(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=zn(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 Wn(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 zn(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"),ze=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,ze.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
|
|
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
|
|
4
|
-
`),await
|
|
1
|
+
"use strict";var Sn=Object.create;var we=Object.defineProperty;var _n=Object.getOwnPropertyDescriptor;var xn=Object.getOwnPropertyNames;var Tn=Object.getPrototypeOf,kn=Object.prototype.hasOwnProperty;var Cn=(t,e)=>{for(var n in e)we(t,n,{get:e[n],enumerable:!0})},Tt=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of xn(e))!kn.call(t,o)&&o!==n&&we(t,o,{get:()=>e[o],enumerable:!(i=_n(e,o))||i.enumerable});return t};var Nn=(t,e,n)=>(n=t!=null?Sn(Tn(t)):{},Tt(e||!t||!t.__esModule?we(n,"default",{value:t,enumerable:!0}):n,t)),Pn=t=>Tt(we({},"__esModule",{value:!0}),t);var tr={};Cn(tr,{FileXenoArtifactRepository:()=>Ze,InMemoryXenoArtifactRepository:()=>ne,XENO_ARTIFACT_ACTOR_KINDS:()=>je,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION:()=>nt,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:()=>V,XENO_PAGE_MAX_BYTES:()=>wn,XENO_PAGE_MAX_FILES:()=>Et,XENO_REVIEW_DIMENSIONS:()=>fn,XENO_REVIEW_EVIDENCE_KINDS:()=>pn,XENO_REVIEW_REPORT_SCHEMA_VERSION:()=>mt,XENO_SPEC_EXECUTION_SCHEMA_VERSION:()=>ge,XENO_SPEC_SCHEMA_VERSION:()=>oe,XenoArtifactRepositoryError:()=>u,XenoArtifactReviewService:()=>ie,XenoArtifactStateTransitionError:()=>Xe,XenoArtifactValidationError:()=>K,XenoDiffParseError:()=>T,XenoEvidenceGraphBuilder:()=>Ue,XenoEvidenceGraphValidationError:()=>_e,XenoMultiAgentReviewCoordinator:()=>lt,XenoPageStore:()=>Rt,XenoReviewValidationError:()=>b,XenoSpecLifecycleService:()=>ct,XenoSpecValidationError:()=>R,assertValidXenoArtifact:()=>X,assertValidXenoEvidenceGraph:()=>te,assertValidXenoReviewPack:()=>ht,assertValidXenoReviewReport:()=>ye,assertValidXenoReviewTarget:()=>gt,assertValidXenoSpecDocument:()=>$e,assertValidXenoSpecExecution:()=>ut,assertXenoArtifactStateTransition:()=>pe,buildXenoArtifactReviewAnchor:()=>at,canTransitionXenoArtifactState:()=>$t,canonicalizeArtifactJson:()=>C,defaultXenoReviewPack:()=>Ci,detectXenoSpecDrift:()=>bi,extractPageTitle:()=>En,legacyAgentArtifactToXenoArtifact:()=>Bi,normalizePagePath:()=>Xt,normalizeRepositoryRelativePath:()=>nn,pageContentType:()=>De,parseUnifiedDiff:()=>rt,sha256ArtifactBytes:()=>k,sha256ArtifactJson:()=>N,summarizeXenoArtifactReview:()=>be,toolEvidenceToXenoArtifact:()=>Ji,turnDiffSummaryToXenoArtifact:()=>Ui,unifiedDiffToXenoArtifact:()=>ot,validateXenoArtifact:()=>Pt,validateXenoArtifactReviewEvent:()=>Re,validateXenoEvidenceGraph:()=>Vt,validateXenoSpecDocument:()=>on,xenoArtifactToDiffDocument:()=>st,xenoArtifactToLegacyAgentArtifact:()=>qi,xenoArtifactToReviewReport:()=>Pi,xenoArtifactToSpecDocument:()=>ft,xenoArtifactToSpecExecution:()=>sn,xenoArtifactToToolEvidence:()=>zi,xenoArtifactToTurnDiffSummary:()=>Wi,xenoReviewReportToArtifact:()=>Ni,xenoReviewReportToGitHubComments:()=>$i,xenoSpecArtifactIds:()=>re,xenoSpecExecutionToArtifact:()=>pt,xenoSpecToArtifactBundle:()=>dt});module.exports=Pn(tr);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 kt=require("node:crypto");function k(t){return{algorithm:"sha256",value:(0,kt.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 $n=/^[a-z0-9][a-z0-9._/-]{0,127}$/,qe="custom:";function U(t,e=qe){return t.startsWith(e)?$n.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}))}},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"},On={draft:["pending_review","superseded","archived"],pending_review:["approved","rejected","superseded","archived"],approved:["superseded","archived"],rejected:["superseded","archived"],superseded:["archived"],archived:[]},Vn="[\\u0000-\\u001f\\u007f]",Dn=new RegExp(Vn),Ct=/^[a-f0-9]{64}$/,Fn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ln=new Set(Me),Mn=new Set(He),Hn=new Set(je),jn=new Set(Le),Bn=new Set(ae),qn=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`),Dn.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)&&(U(t,e)||p(i,n,"invalid_custom_name",`Custom name after ${e} is invalid`))}function Nt(t,e,n){if(!t||typeof t!="object"){p(n,e,"missing_actor","Actor is required");return}l(t.kind,`${e}.kind`,n,64),Hn.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 ze(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 Pt(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"&&!jn.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),Ln.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),Mn.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"&&!Ct.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&&(Fn.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"):(Nt(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"&&!qn.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"&&!Bn.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)=>ze(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=Pt(t);if(e.length>0)throw new K("XENO artifact validation failed",e)}function $t(t,e){return On[t].includes(e)}function pe(t,e){if(!$t(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),Nt(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"&&!Ct.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&&ze(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&&ze(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"]),zn=new Set(ae),Un=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 Ot(t,e){return t.startsWith(qe)?U(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"||!Ot(f.type,zn))&&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"||!Ot(f.type,Un))&&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 Ue=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(Dt(e)),this.touch(n),te(n),this.graph=n,this}addEdge(e){let n=Se(this.graph);return n.edges.push(Ft(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 Dt(t){return{...t,...t.attributes?{attributes:structuredClone(t.attributes)}:{}}}function Ft(t){return{...t,...t.producer?{producer:{...t.producer}}:{},...t.attributes?{attributes:structuredClone(t.attributes)}:{}}}function Se(t){return{...t,nodes:t.nodes.map(Dt),edges:t.edges.map(Ft)}}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(Lt).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),G(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(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"){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),G(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?G(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=>Gn(i.artifact,e)).sort(Lt).map(G)}async listRevisions(e){let n=this.records.get(e);return n?[...n.values()].sort((i,o)=>i.artifact.revision-o.artifact.revision).map(G):[]}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,G(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 K("XENO artifact review event validation failed",r);return i.reviewEvents.push(o),i.recordVersion+=1,G(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=Yn(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=Wn(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 Wn(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 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:le(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 Gn(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 Lt(t,e){return t.artifact.createdAt.localeCompare(e.artifact.createdAt)||t.artifact.artifactId.localeCompare(e.artifact.artifactId)||t.artifact.revision-e.artifact.revision}function Yn(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 G(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 tt=require("node:crypto"),P=require("node:fs/promises"),M=require("node:path");var L=Nn(require("node:fs/promises"),1);var Mt=Symbol.for("@xenosystem/agent-sdk/file-cache"),Ht=globalThis,We=Ht[Mt]??{entries:new Map,counters:{reads:0,hits:0}};Ht[Mt]=We;var vr=We.entries,yr=We.counters;var Zn=new Set(["EACCES","EBUSY","EPERM"]),Qn=[10,20,40,80,160,320,640];async function jt(t,e){for(let n=0;;n+=1)try{await L.rename(t,e);return}catch(i){let o=i.code,r=Qn[n];if(process.platform!=="win32"||!o||!Zn.has(o)||r===void 0)throw i;await new Promise(s=>setTimeout(s,r))}}var H=require("node:fs"),Ke=require("node:os"),qt=require("node:path");function ei(){return new Date().toISOString()}function ti(){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 ni(t){if(!t||t<=0)return!1;try{return process.kill(t,0),!0}catch{return!1}}function ii(t){return t.hostname!==(0,Ke.hostname)()?!0:ni(t.pid)}function Bt(t,e){(0,H.mkdirSync)((0,qt.dirname)(t),{recursive:!0}),(0,H.writeFileSync)(t,JSON.stringify(e,null,2)+`
|
|
2
|
+
`,{encoding:"utf8",flag:"wx"})}function ri(t,e){let n=Jt(t);n?.pid!==e.pid||n.hostname!==e.hostname||(0,H.rmSync)(t,{force:!0})}function zt(t,e,n){let i=ei(),o={schemaVersion:1,name:e,pid:process.pid,hostname:(0,Ke.hostname)(),processStartedAt:ti(),version:n,acquiredAt:i,updatedAt:i};try{Bt(t,o)}catch(r){if(r.code!=="EEXIST")throw r;let d=Jt(t);if(d&&ii(d))throw new Error(`${e} is already locked by PID ${d.pid} on ${d.hostname}.`);(0,H.rmSync)(t,{force:!0}),Bt(t,o)}return{record:o,release:()=>{ri(t,o)}}}var Ut="0.10.39";var nt=1,oi="repository.v1.json",si=5e3,ai=20,ci=64*1024*1024,Ze=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??oi;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,si,100,6e4,"lockTimeoutMs"),this.lockRetryMs=Ge(e.lockRetryMs,ai,1,1e3,"lockRetryMs"),this.maxSnapshotBytes=Ge(e.maxSnapshotBytes,ci,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 zt(this.lockPath,`artifact-repository:${(0,M.basename)(this.snapshotPath)}`,Ut)}catch(i){if(!(i instanceof Error)||!/already locked by PID/.test(i.message))throw i;n=i,await li(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 ui(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,tt.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:nt,generation:e.generation,createdAt:e.createdAt,updatedAt:n,state:e.repository.exportState()},generation:e.generation+1},r=fi(o),s=`${JSON.stringify(r,null,2)}
|
|
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 Wt(this.backupPath,`${JSON.stringify(e.sourceSnapshot,null,2)}
|
|
4
|
+
`),await Wt(this.snapshotPath,s)}async readSnapshot(e,n){let i;try{i=await(0,P.stat)(e)}catch(o){if(!n&&Qe(o,"ENOENT")||n&&Qe(o,"ENOENT"))return;throw et("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 di(JSON.parse(o.toString("utf8")),e)}catch(o){throw o instanceof u?o:et("Unable to parse artifact repository snapshot",e,o,!0)}}};function di(t,e){if(!Ye(t)||t.schemaVersion!==nt||!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))||!Ye(t.state)||t.state.schemaVersion!==1||!Array.isArray(t.state.records)||!Ye(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=pi(n),o=Kt(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 fi(t){return{...structuredClone(t),checksum:{algorithm:"sha256",value:Kt(t)}}}function pi(t){return{schemaVersion:t.schemaVersion,generation:t.generation,createdAt:t.createdAt,updatedAt:t.updatedAt,state:t.state}}function Kt(t){return k(JSON.stringify(t)).value}async function Wt(t,e){await(0,P.mkdir)((0,M.dirname)(t),{recursive:!0,mode:448});let n=`${t}.tmp.${process.pid}.${(0,tt.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 jt(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 Ye(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Qe(t,e){return t instanceof Error&&t.code===e}async function ui(t){try{return(await(0,P.stat)(t)).isFile()}catch(e){if(Qe(e,"ENOENT"))return!1;throw et("Unable to inspect artifact repository backup",t,e)}}function xe(t){return t instanceof Error?t:new Error(String(t))}function et(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 li(t){return new Promise(e=>setTimeout(e,t))}var it=require("node:buffer");var mi=16*1024*1024,hi=5e3,gi=1e5,vi=1e6,yi=/^@@ -(\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 rt(t,e={}){if(typeof t!="string")throw new TypeError("Unified diff must be a string");let n=Te(e.maxBytes,mi,1024,256*1024*1024,"maxBytes"),i=Te(e.maxFiles,hi,1,1e5,"maxFiles"),o=Te(e.maxHunks,gi,1,1e6,"maxHunks"),r=Te(e.maxLines,vi,1,5e6,"maxLines");if(it.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,`
|
|
6
6
|
`),d=s.length===0?[]:s.split(`
|
|
7
|
-
`);if(d.length>r)throw new T(`Unified diff exceeds ${r} lines`);let a=[],c,f=0,g=(m,h)=>{if(c&&
|
|
8
|
-
`:i==="r"?"\r":i==="\\"?"\\":i==='"'?'"':String.fromCharCode(Number.parseInt(i,8)))}function zt(t){let e=t.split(" ",1)[0].trim();if(e!=="/dev/null")return Y(Kt(e))}function Y(t){let e=t.replace(/\\/g,"/");return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function yi(t){return!Gt(t)||t.schemaVersion!==1||!["working-tree","staged","turn","commit","preview"].includes(String(t.mode))||!Array.isArray(t.files)||!Number.isSafeInteger(t.additions)||!Number.isSafeInteger(t.deletions)||typeof t.rawDiff!="string"?!1:t.files.every(e=>Gt(e)&&typeof e.displayPath=="string"&&Array.isArray(e.headerLines)&&Array.isArray(e.hunks))}function Gt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Te(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 Ai(t){return t.split("-").map(e=>e[0].toUpperCase()+e.slice(1)).join(" ")}function Ii(t){return t instanceof Error?t:new Error(String(t))}var Zt=require("node:crypto");var ie=class{repository;actor;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");if(!e.actor?.kind||!e.actor.id?.trim())throw new TypeError("Review actor is required");this.repository=e.repository,this.actor=structuredClone(e.actor),this.idFactory=e.idFactory??(()=>`comment_${(0,Zt.randomUUID)()}`)}async addComment(e){let n=Ce(e.body,"Review comment body",65536),i=await this.repository.require(e.artifactId,e.revision),o=st(i,e),r=ke(this.idFactory(),"Comment ID"),s=wi(e.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:i.recordVersion,event:{type:"comment-added",artifactId:i.artifact.artifactId,artifactRevision:i.artifact.revision,artifactHash:i.artifact.content.hash,actor:this.actor,commentId:r,body:n,...o?{anchor:o}:{},...s?{parentCommentId:s}:{}}})}async setCommentResolution(e){let n=ke(e.commentId,"Review comment ID"),i=Yt(e.reason,"Resolution reason",16*1024),o=await this.repository.require(e.artifactId,e.revision);return this.repository.appendReviewEvent({expectedRecordVersion:o.recordVersion,event:{type:e.resolved?"comment-resolved":"comment-reopened",artifactId:o.artifact.artifactId,artifactRevision:o.artifact.revision,artifactHash:o.artifact.content.hash,actor:this.actor,commentId:n,...i?{reason:i}:{}}})}async decide(e){let n=await this.repository.require(e.artifactId,e.revision);if(n.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${n.artifact.state}`);let i=st(n,e),o=Yt(e.rationale,"Decision rationale",64*1024),r=await this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:"decision-recorded",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,decision:e.decision,...o?{rationale:o}:{},...i?{scope:i}:{}}});if(i||e.decision==="changes_requested")return r;let s=r.reviewEvents.at(-1);if(!s||s.type!=="decision-recorded")throw new u("ARTIFACT_REVIEW_INVALID","Artifact decision event was not recorded");return this.repository.transition({artifactId:r.artifact.artifactId,revision:r.artifact.revision,expectedRecordVersion:r.recordVersion,toState:e.decision,actor:this.actor,reviewEventId:s.eventId,...o?{reason:o}:{}})}};function st(t,e){if((e.line!==void 0||e.hunkId!==void 0)&&!e.file)throw j("Line and hunk anchors require a file");if(e.line!==void 0&&e.hunkId!==void 0)throw j("Line and hunk anchors cannot be combined");if(!e.file)return;let n=Qt(e.file);if(e.line!==void 0&&(!Number.isInteger(e.line)||e.line<1))throw j("Review line must be a positive integer");if(t.artifact.kind==="diff"||t.artifact.kind==="patch"){let o=ot(t.artifact).files.find(r=>r.displayPath===n);if(!o)throw j(`File ${n} is not present in this artifact`);if(e.hunkId&&!o.hunks.some(r=>r.hunkId===e.hunkId))throw j(`Hunk ${e.hunkId} is not present in ${n}`)}return e.hunkId?{kind:"diff-hunk",path:n,hunkId:ke(e.hunkId,"Hunk ID"),artifactId:t.artifact.artifactId,revision:t.artifact.revision}:e.line!==void 0?{kind:"source-line",path:n,startLine:e.line}:{kind:"file",path:n}}function Qt(t){let e=Ce(t,"Artifact review file",4096).replace(/\\/g,"/").replace(/^\.\//,"");if(e.startsWith("../")||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.split("/").some(n=>n===".."||n.length===0))throw j("Artifact review file anchors must be repository-relative paths");return e}function Ce(t,e,n){let i=typeof t=="string"?t.trim():"";if(!i)throw j(`${e} cannot be empty`);if(i.length>n)throw j(`${e} exceeds ${n} characters`);return i}function Yt(t,e,n){if(t!==void 0)return Ce(t,e,n)}function ke(t,e){let n=Ce(t,e,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(n))throw j(`${e} contains unsupported characters`);return n}function wi(t,e){return t===void 0?void 0:ke(t,e)}function j(t){return new u("ARTIFACT_REVIEW_INVALID",t)}var en=require("node:crypto");var oe="xeno.spec.v1",ge="xeno.spec-execution.v1",R=class extends Error{constructor(n){super(`XENO spec is invalid: ${n.join("; ")}`);this.issues=n;this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},at=class{repository;now;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");this.repository=e.repository,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(()=>(0,en.randomUUID)())}async create(e,n){if(e.revision!==1||e.predecessorRevision!==void 0)throw new R(["A new spec must begin at revision 1 without a predecessor"]);let i=ct(e,n);return await this.repository.create(i.requirements),await this.repository.create(i.design),await this.repository.create(i.taskGraph),await this.repository.create(i.plan),i}async revise(e,n){let i=re(e.specId),o=await this.repository.require(i.plan);if(e.revision!==o.artifact.revision+1||e.predecessorRevision!==o.artifact.revision)throw new R([`Revision ${e.revision} must follow approved or reviewed revision ${o.artifact.revision}`]);let r=ct(e,n);return await this.repository.createRevision(r.requirements,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.design,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.taskGraph,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.plan,{actor:n.producer,reason:"spec-revised"}),r}async approve(e,n,i){return new ie({repository:this.repository,actor:n}).decide({artifactId:re(e).plan,decision:"approved",...i?{rationale:i}:{}})}async reject(e,n,i){return new ie({repository:this.repository,actor:n}).decide({artifactId:re(e).plan,decision:"rejected",rationale:i})}async startExecution(e,n){let i=await this.repository.require(re(e).plan);if(i.artifact.state!=="approved")throw new R([`Spec ${e} must be approved before execution`]);let o=dt(i.artifact),r=this.now(),s={schemaVersion:ge,executionId:`spec_execution_${this.idFactory()}`,specId:o.specId,specRevision:o.revision,planArtifactId:i.artifact.artifactId,planHash:{...i.artifact.content.hash},state:"ready",createdAt:r,updatedAt:r,observedPaths:[],tasks:o.tasks.map(d=>({taskId:d.id,status:"pending",evidence:[],acceptanceEvidence:Object.fromEntries(d.acceptanceCriterionIds.map(a=>[a,[]]))}))};return this.repository.create(ft(s,{producer:n,identity:i.artifact.identity,sensitivity:i.artifact.sensitivity,accessPolicyId:i.artifact.accessPolicyId}))}async updateExecution(e,n,i){let o=await this.repository.require(e),r=nn(o.artifact),s=await this.repository.require(r.planArtifactId,r.specRevision);if(s.artifact.state!=="approved"||!ve(s.artifact.content.hash,r.planHash))throw new R(["Execution is no longer bound to the approved plan revision"]);let d=n(structuredClone(r));d.schemaVersion=ge,d.executionId=r.executionId,d.specId=r.specId,d.specRevision=r.specRevision,d.planArtifactId=r.planArtifactId,d.planHash={...r.planHash},d.createdAt=r.createdAt,d.updatedAt=this.now(),pt(d,dt(s.artifact));let a=ft(d,{producer:i,identity:o.artifact.identity,sensitivity:o.artifact.sensitivity,accessPolicyId:o.artifact.accessPolicyId},o.artifact.revision+1,o.artifact.revision);return this.repository.createRevision(a,{actor:i,reason:"spec-execution-updated"})}};function re(t){let e=Ri(t,"specId");return{plan:`spec_${e}_plan`,requirements:`spec_${e}_requirements`,design:`spec_${e}_design`,taskGraph:`spec_${e}_task_graph`}}function tn(t){let e=[];t?.schemaVersion!==oe&&e.push(`schemaVersion must be ${oe}`),he(t?.specId,"specId",e),(!Number.isInteger(t?.revision)||t.revision<1)&&e.push("revision must be a positive integer"),$(t?.title,"title",e),$(t?.problem,"problem",e),Pe(t?.createdAt,"createdAt",e),Pe(t?.updatedAt,"updatedAt",e),t?.predecessorRevision!==void 0&&(!Number.isInteger(t.predecessorRevision)||t.predecessorRevision!==t.revision-1)&&e.push("predecessorRevision must be the immediately preceding revision");let n=Ne(t?.requirements,"requirement",e),i=Ne(t?.tasks,"task",e),o=new Set,r=[...Array.isArray(t?.acceptanceCriteria)?t.acceptanceCriteria:[],...Array.isArray(t?.requirements)?t.requirements.flatMap(a=>Array.isArray(a.acceptanceCriteria)?a.acceptanceCriteria:[]):[]];for(let a of r){he(a?.id,"acceptance criterion id",e),$(a?.text,`acceptance criterion ${a?.id??"?"}`,e),o.has(a?.id)&&e.push(`Duplicate acceptance criterion: ${a?.id}`),o.add(a?.id);for(let c of a?.requiredEvidenceKinds??[])he(c,"required evidence kind",e)}for(let a of t?.requirements??[])$(a?.text,`requirement ${a?.id??"?"}`,e),["must","should","could"].includes(a?.priority)||e.push(`Requirement ${a?.id??"?"} has invalid priority`),(!Array.isArray(a?.acceptanceCriteria)||a.acceptanceCriteria.length===0)&&e.push(`Requirement ${a?.id??"?"} needs at least one acceptance criterion`);$(t?.design?.summary,"design summary",e);let s=Ne(t?.design?.decisions,"design decision",e),d=Ne(t?.design?.risks,"risk",e);for(let a of t?.design?.decisions??[]){$(a?.decision,`design decision ${a?.id??"?"}`,e),$(a?.rationale,`design rationale ${a?.id??"?"}`,e);for(let c of a?.requirementIds??[])n.has(c)||e.push(`Design decision ${a.id} references unknown requirement ${c}`)}for(let a of t?.design?.risks??[])$(a?.description,`risk ${a?.id??"?"}`,e),$(a?.mitigation,`risk mitigation ${a?.id??"?"}`,e),["low","medium","high","critical"].includes(a?.impact)||e.push(`Risk ${a?.id??"?"} has invalid impact`);for(let a of t?.tasks??[]){$(a?.title,`task title ${a?.id??"?"}`,e),$(a?.description,`task description ${a?.id??"?"}`,e);for(let c of a?.dependsOn??[])i.has(c)||e.push(`Task ${a.id} depends on unknown task ${c}`),c===a.id&&e.push(`Task ${a.id} cannot depend on itself`);for(let c of a?.requirementIds??[])n.has(c)||e.push(`Task ${a.id} references unknown requirement ${c}`);for(let c of a?.acceptanceCriterionIds??[])o.has(c)||e.push(`Task ${a.id} references unknown acceptance criterion ${c}`);for(let c of a?.expectedPaths??[])on(c)||e.push(`Task ${a.id} has unsafe expected path ${c}`)}return bi(t?.tasks??[])&&e.push("Task dependency graph contains a cycle"),[...new Set(e)]}function $e(t){let e=tn(t);if(e.length>0)throw new R(e)}function ct(t,e){$e(t);let n=re(t.specId),i=t.revision,o={...e,createdAt:t.updatedAt,state:"draft"},r=me({artifactId:n.requirements,revision:i,predecessorRevision:t.predecessorRevision,kind:"requirements",title:`${t.title} - requirements`,value:{schemaVersion:oe,specId:t.specId,revision:i,problem:t.problem,requirements:t.requirements,acceptanceCriteria:t.acceptanceCriteria},context:o}),s=me({artifactId:n.design,revision:i,predecessorRevision:t.predecessorRevision,kind:"design",title:`${t.title} - design`,value:{schemaVersion:oe,specId:t.specId,revision:i,design:t.design,...t.sourceBaseline?{sourceBaseline:t.sourceBaseline}:{}},context:o}),d=me({artifactId:n.taskGraph,revision:i,predecessorRevision:t.predecessorRevision,kind:"task-graph",title:`${t.title} - task graph`,value:{schemaVersion:oe,specId:t.specId,revision:i,tasks:t.tasks},context:o}),a=[r,s,d].map(f=>({relation:"decomposes",target:{type:"artifact",id:f.artifactId,revision:f.revision}})),c=me({artifactId:n.plan,revision:i,predecessorRevision:t.predecessorRevision,kind:"plan",title:t.title,description:t.problem,value:t,context:{...e,createdAt:t.updatedAt,state:"pending_review"},relationships:a,extensions:{"xeno.spec.id":t.specId,"xeno.spec.revision":t.revision,"xeno.spec.requirements_hash":r.content.hash.value,"xeno.spec.design_hash":s.content.hash.value,"xeno.spec.task_graph_hash":d.content.hash.value}});return{document:structuredClone(t),plan:c,requirements:r,design:s,taskGraph:d}}function dt(t){if(t.kind!=="plan"||t.mediaType!=="application/vnd.xeno.spec+json")throw new R([`Artifact ${t.artifactId} is not a XENO spec plan`]);let e=rn(t);if($e(e),e.revision!==t.revision)throw new R(["Spec and artifact revisions differ"]);if(!ve(N(e),t.content.hash))throw new R(["Spec artifact content hash is invalid"]);return structuredClone(e)}function ft(t,e,n=1,i){let o=structuredClone(t);return me({artifactId:t.executionId,revision:n,predecessorRevision:i,kind:"custom:xeno.spec-execution",title:`Execution of ${t.specId} revision ${t.specRevision}`,description:`Execution state: ${t.state}`,value:o,context:{...e,createdAt:t.updatedAt,state:t.state==="completed"?"pending_review":"draft"},relationships:[{relation:"implements",target:{type:"artifact",id:t.planArtifactId,revision:t.specRevision}}],extensions:{"xeno.spec.execution_state":t.state,"xeno.spec.plan_hash":t.planHash.value}})}function nn(t){if(t.kind!=="custom:xeno.spec-execution")throw new R([`Artifact ${t.artifactId} is not a spec execution`]);let e=rn(t);if(e.schemaVersion!==ge||e.executionId!==t.artifactId)throw new R(["Spec execution identity or schema is invalid"]);if(!ve(N(e),t.content.hash))throw new R(["Spec execution content hash is invalid"]);return structuredClone(e)}function pt(t,e){let n=[];t.schemaVersion!==ge&&n.push("Execution schema is invalid"),(t.specId!==e.specId||t.specRevision!==e.revision)&&n.push("Execution is bound to the wrong spec revision");let i=new Map(e.tasks.map(r=>[r.id,r])),o=new Set;for(let r of t.tasks){o.has(r.taskId)&&n.push(`Duplicate execution task ${r.taskId}`),o.add(r.taskId);let s=i.get(r.taskId);if(!s){n.push(`Unknown execution task ${r.taskId}`);continue}for(let d of s.acceptanceCriterionIds)Array.isArray(r.acceptanceEvidence?.[d])||n.push(`Task ${r.taskId} is missing acceptance evidence slot ${d}`)}for(let r of i.keys())o.has(r)||n.push(`Execution is missing task ${r}`);for(let r of t.observedPaths)Si(r)||n.push(`Unsafe observed path ${r}`);if(Pe(t.createdAt,"execution createdAt",n),Pe(t.updatedAt,"execution updatedAt",n),n.length>0)throw new R([...new Set(n)])}function Ei(t,e,n,i,o=new Date().toISOString()){$e(t),pt(n,t);let r=[];(!ve(e,i)||!ve(n.planHash,i))&&r.push({code:"PLAN_HASH_MISMATCH",severity:"error",message:"Execution is not bound to the approved plan content hash"});let s=new Map(t.tasks.map(c=>[c.id,c])),d=new Map(n.tasks.map(c=>[c.taskId,c]));for(let c of n.tasks){let f=s.get(c.taskId);if(!f){r.push({code:"UNKNOWN_TASK",severity:"error",taskId:c.taskId,message:`Unknown task ${c.taskId}`});continue}if(c.status==="completed"){c.evidence.length===0&&r.push({code:"MISSING_TASK_EVIDENCE",severity:"error",taskId:f.id,message:`Completed task ${f.id} has no evidence`});for(let g of f.dependsOn??[])d.get(g)?.status!=="completed"&&r.push({code:"DEPENDENCY_INCOMPLETE",severity:"error",taskId:f.id,message:`Task ${f.id} completed before dependency ${g}`});for(let g of f.acceptanceCriterionIds)(c.acceptanceEvidence[g]??[]).length===0&&r.push({code:"MISSING_ACCEPTANCE_EVIDENCE",severity:"error",taskId:f.id,criterionId:g,message:`Completed task ${f.id} has no evidence for ${g}`})}}let a=t.tasks.flatMap(c=>c.expectedPaths??[]);for(let c of n.observedPaths)a.some(f=>_i(c,f))||r.push({code:"UNKNOWN_PATH",severity:"warning",path:c,message:`Observed path ${c} is outside the approved task plan`});return{schemaVersion:"xeno.spec-drift.v1",specId:t.specId,specRevision:t.revision,executionId:n.executionId,checkedAt:o,drifted:r.length>0,findings:r}}function me(t){let e=t.value,n=C(e);return{schemaVersion:1,artifactId:t.artifactId,revision:t.revision,kind:t.kind,title:t.title,...t.description?{description:t.description}:{},state:t.context.state,createdAt:t.context.createdAt??new Date().toISOString(),mediaType:Xi(t.kind),sensitivity:t.context.sensitivity??"internal",...t.context.identity?{identity:structuredClone(t.context.identity)}:{},content:{hash:N(e),sizeBytes:Buffer.byteLength(n,"utf8"),encoding:"utf8",storage:{type:"inline",text:n},redactedPreview:t.title},provenance:{producer:structuredClone(t.context.producer)},...t.relationships?.length?{relationships:structuredClone(t.relationships)}:{},...t.predecessorRevision!==void 0?{predecessorRevision:t.predecessorRevision}:{},...t.context.accessPolicyId?{accessPolicyId:t.context.accessPolicyId}:{},...t.extensions?{extensions:structuredClone(t.extensions)}:{}}}function Xi(t){return t==="plan"?"application/vnd.xeno.spec+json":t==="custom:xeno.spec-execution"?"application/vnd.xeno.spec-execution+json":`application/vnd.xeno.spec-${t}+json`}function rn(t){let e=t.content.storage;if(e.type!=="inline"||typeof e.text!="string")throw new R(["Spec artifacts require inline JSON content"]);try{return JSON.parse(e.text)}catch(n){throw new R([`Spec artifact JSON is invalid: ${n instanceof Error?n.message:String(n)}`])}}function Ne(t,e,n){let i=new Set;(!Array.isArray(t)||t.length===0)&&n.push(`${e} list cannot be empty`);for(let o of t??[])he(o?.id,`${e} id`,n),i.has(o?.id??"")&&n.push(`Duplicate ${e}: ${o?.id}`),o?.id&&i.add(o.id);return i}function he(t,e,n){(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(t))&&n.push(`${e} must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}`)}function $(t,e,n){(typeof t!="string"||t.trim().length===0||t.length>64*1024)&&n.push(`${e} must be non-empty and no longer than 65536 characters`)}function Pe(t,e,n){(typeof t!="string"||!t.includes("T")||!Number.isFinite(Date.parse(t)))&&n.push(`${e} must be an ISO 8601 timestamp`)}function Ri(t,e){let n=[];if(he(t,e,n),n.length>0)throw new R(n);return t}function bi(t){let e=new Map(t.map(r=>[r.id,r])),n=new Set,i=new Set,o=r=>{if(n.has(r))return!0;if(i.has(r))return!1;n.add(r);for(let s of e.get(r)?.dependsOn??[])if(o(s))return!0;return n.delete(r),i.add(r),!1};return t.some(r=>o(r.id))}function on(t){let e=t.replace(/\\/gu,"/");return e.length>0&&e.length<=4096&&!e.startsWith("/")&&!/^[A-Za-z]:/u.test(e)&&!e.split("/").includes("..")}function Si(t){return on(t)&&!t.includes("*")}function _i(t,e){let n=t.replace(/\\/gu,"/"),i=e.replace(/\\/gu,"/");if(i.endsWith("/**")){let o=i.slice(0,-3).replace(/\/$/u,"");return n===o||n.startsWith(`${o}/`)}if(i.endsWith("/*")){let o=i.slice(0,-2).replace(/\/$/u,""),r=n.startsWith(`${o}/`)?n.slice(o.length+1):"";return r.length>0&&!r.includes("/")}return n===i}function ve(t,e){return t.algorithm===e.algorithm&&t.value===e.value}var sn=require("node:crypto");var lt="xeno.review-report.v1",an=["correctness","security","performance","api","tests","documentation"],cn=["source","test","trace","artifact","reproduction","benchmark"],b=class extends Error{constructor(n){super(`XENO review is invalid: ${n.join("; ")}`);this.issues=n;this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},ut=class{reviewer;verifier;now;idFactory;constructor(e){if(typeof e?.reviewer!="function")throw new TypeError("Review agent executor is required");this.reviewer=e.reviewer,this.verifier=e.verifier,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(n=>`${n}_${(0,sn.randomUUID)()}`)}async run(e){mt(e.pack),ht(e.target),Ve(e.runId,"runId");let n=this.now(),i=await Promise.all(e.pack.dimensions.map(async(a,c)=>{let f=await this.reviewer({...e,dimension:a,reviewerSlot:c});return $i(f,a,e.pack.maxFindings),structuredClone(f)})),o=i.flatMap(a=>a.findings.map(c=>({finding:c,reviewerAgentId:a.reviewerAgentId})));if(o.length>e.pack.maxFindings)throw new b([`Reviewers returned ${o.length} findings, exceeding maxFindings ${e.pack.maxFindings}`]);let r=Ni(o,this.idFactory);for(let a of r){let c=this.verifier?await Promise.all(Array.from({length:e.pack.verifierCount},async(m,h)=>{let _=await this.verifier({...e,finding:structuredClone(a),verifierSlot:h});return Vi(_),structuredClone(_)})):[];a.verifications=Oi(c),a.evidence=fn([...a.evidence,...a.verifications.flatMap(m=>m.evidence)]);let f=new Set(a.verifications.filter(m=>m.outcome==="reproduced").map(m=>m.verifierAgentId)).size,g=a.verifications.length>0&&a.verifications.every(m=>m.outcome==="rejected"),y=new Set(a.evidence.map(m=>m.producerId)).size;f>=e.pack.minimumVerifierReproductions?(a.state="verified",a.verificationBasis="verifier"):e.pack.allowIndependentEvidenceVerification&&y>=e.pack.minimumIndependentEvidenceProducers?(a.state="verified",a.verificationBasis="independent-evidence"):g?(a.state="rejected",a.verificationBasis="verifier"):(a.state="unverified",a.verificationBasis="none");let D=a.verifications.map(m=>m.confidence).filter(m=>m!==void 0);D.length>0&&(a.confidence=gn(Math.min(a.confidence,...D)))}r.sort(Di);let s=this.now(),d={schemaVersion:lt,reportId:Ve(this.idFactory("report"),"reportId"),runId:e.runId,pack:structuredClone(e.pack),target:structuredClone(e.target),startedAt:n,completedAt:s,reviewers:i.map(a=>({agentId:a.reviewerAgentId,dimension:a.dimension,findingCount:a.findings.length})),findings:r,summary:ln(r)};return ye(d),d}};function xi(t="xeno-production-review"){return{schemaVersion:"xeno.review-pack.v1",packId:t,version:"1.0.0",dimensions:["correctness","security","performance","api","tests","documentation"],verifierCount:1,minimumVerifierReproductions:1,allowIndependentEvidenceVerification:!1,minimumIndependentEvidenceProducers:2,maxFindings:256}}function mt(t){let e=[];t?.schemaVersion!=="xeno.review-pack.v1"&&e.push("Review pack schemaVersion must be xeno.review-pack.v1"),V(t?.packId,"packId",e),(typeof t?.version!="string"||!/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/u.test(t.version))&&e.push("Review pack version must be semantic version text"),(!Array.isArray(t?.dimensions)||t.dimensions.length===0)&&e.push("Review pack needs at least one dimension"),new Set(t?.dimensions??[]).size!==(t?.dimensions??[]).length&&e.push("Review pack dimensions must be unique");for(let n of t?.dimensions??[])hn(n)||e.push(`Invalid review dimension ${n}`);if((!Number.isInteger(t?.verifierCount)||t.verifierCount<0||t.verifierCount>8)&&e.push("verifierCount must be 0 through 8"),(!Number.isInteger(t?.minimumVerifierReproductions)||t.minimumVerifierReproductions<1||t.minimumVerifierReproductions>Math.max(1,t.verifierCount))&&e.push("minimumVerifierReproductions must be positive and no greater than verifierCount"),(!Number.isInteger(t?.minimumIndependentEvidenceProducers)||t.minimumIndependentEvidenceProducers<2)&&e.push("minimumIndependentEvidenceProducers must be at least 2"),(!Number.isInteger(t?.maxFindings)||t.maxFindings<1||t.maxFindings>2048)&&e.push("maxFindings must be 1 through 2048"),e.length>0)throw new b(e)}function ht(t){let e=[];if(V(t?.artifactId,"target artifactId",e),(!Number.isInteger(t?.revision)||t.revision<1)&&e.push("Target revision must be positive"),Z(t?.title,"target title",e),(t?.contentHash?.algorithm!=="sha256"||!/^[a-f0-9]{64}$/u.test(t?.contentHash?.value??""))&&e.push("Target contentHash must be lowercase sha256"),e.length>0)throw new b(e)}function ye(t){let e=[];t?.schemaVersion!==lt&&e.push("Review report schemaVersion is invalid"),V(t?.reportId,"reportId",e),V(t?.runId,"runId",e),Oe(t?.startedAt,"startedAt",e),Oe(t?.completedAt,"completedAt",e),Date.parse(t?.completedAt)<Date.parse(t?.startedAt)&&e.push("completedAt cannot precede startedAt");try{mt(t.pack)}catch(r){e.push(r instanceof Error?r.message:String(r))}try{ht(t.target)}catch(r){e.push(r instanceof Error?r.message:String(r))}let n=new Set,i=new Set;for(let r of t?.findings??[])V(r?.findingId,"findingId",e),n.has(r.findingId)&&e.push(`Duplicate findingId ${r.findingId}`),n.add(r.findingId),/^[a-f0-9]{64}$/u.test(r?.fingerprint??"")||e.push(`Finding ${r.findingId} has invalid fingerprint`),i.has(r.fingerprint)&&e.push(`Duplicate finding fingerprint ${r.fingerprint}`),i.add(r.fingerprint),Z(r?.title,`finding ${r.findingId} title`,e),Z(r?.summary,`finding ${r.findingId} summary`,e),mn(r?.severity)||e.push(`Finding ${r.findingId} has invalid severity`),(!Number.isFinite(r?.confidence)||r.confidence<0||r.confidence>1)&&e.push(`Finding ${r.findingId} has invalid confidence`),r?.state==="verified"&&r.verificationBasis==="none"&&e.push(`Finding ${r.findingId} cannot be verified without a basis`),r?.state!=="verified"&&r.verificationBasis==="independent-evidence"&&e.push(`Finding ${r.findingId} has inconsistent evidence verification`);let o=ln(t?.findings??[]);if((o.total!==t?.summary?.total||o.verified!==t?.summary?.verified||o.unverified!==t?.summary?.unverified||o.rejected!==t?.summary?.rejected||Object.keys(o.bySeverity).some(r=>o.bySeverity[r]!==t?.summary?.bySeverity?.[r]))&&e.push("Review report summary is inconsistent"),e.length>0)throw new b([...new Set(e)])}function Ti(t,e){ye(t);let n=t,i=C(n),o=e.artifactId??`review_${k(`${t.runId}:${t.target.artifactId}:${t.target.contentHash.value}`).value.slice(0,24)}`,r={schemaVersion:1,artifactId:o,revision:1,kind:"review-report",title:`Review of ${t.target.title}`,description:`${t.summary.verified} verified, ${t.summary.unverified} unverified, ${t.summary.rejected} rejected findings`,state:"pending_review",createdAt:e.createdAt??t.completedAt,mediaType:"application/vnd.xeno.review-report+json",sensitivity:e.sensitivity??"internal",...e.identity?{identity:structuredClone(e.identity)}:{},content:{hash:N(n),sizeBytes:Buffer.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i},redactedPreview:`${t.summary.total} findings; ${t.summary.verified} verified`},provenance:{producer:structuredClone(e.producer),sourceArtifactIds:[t.target.artifactId],attributes:{reviewPackId:t.pack.packId,reviewPackVersion:t.pack.version}},relationships:[{relation:"reviews",target:{type:"artifact",id:t.target.artifactId,revision:t.target.revision}}],anchors:pn(t.findings.flatMap(s=>s.anchors)),...e.accessPolicyId?{accessPolicyId:e.accessPolicyId}:{},extensions:{"xeno.review.pack":t.pack.packId,"xeno.review.verified":t.summary.verified,"xeno.review.unverified":t.summary.unverified,"xeno.review.rejected":t.summary.rejected}};return X(r),r}function ki(t){if(t.kind!=="review-report"||t.mediaType!=="application/vnd.xeno.review-report+json")throw new b([`Artifact ${t.artifactId} is not a XENO review report`]);if(t.content.storage.type!=="inline"||typeof t.content.storage.text!="string")throw new b(["Review report requires inline JSON content"]);let e;try{e=JSON.parse(t.content.storage.text)}catch(n){throw new b([`Review report JSON is invalid: ${n instanceof Error?n.message:String(n)}`])}if(ye(e),!Li(N(e),t.content.hash))throw new b(["Review report content hash is invalid"]);return structuredClone(e)}function Ci(t,e={}){ye(t);let n=[];for(let i of t.findings){if(e.verifiedOnly!==!1&&i.state!=="verified")continue;let o=i.anchors.find(r=>r.kind==="source-line"||r.kind==="file"||r.kind==="diff-hunk");!o||!("path"in o)||n.push({findingId:i.findingId,path:o.path,...o.kind==="source-line"?{line:o.startLine}:{},severity:i.severity,verified:i.state==="verified",body:[`**${i.severity.toUpperCase()} - ${i.title}**`,"",i.summary,"",`Evidence: ${i.evidence.map(r=>r.summary).join("; ")||"none"}`,i.remediation?`Suggested remediation: ${i.remediation}`:"",`XENO finding: ${i.findingId} (${i.state}, confidence ${i.confidence.toFixed(2)})`].filter(Boolean).join(`
|
|
9
|
-
`)})}return n}function
|
|
10
|
-
`),{artifactId:e.artifactId??`turn_diff_${t.turnId}`,revision:e.revision??1,createdAt:e.createdAt??t.completedAt,title:`Turn ${t.turnId} changes`,producer:e.producer,identity:{...e.identity?structuredClone(e.identity):{},turnId:e.identity?.turnId??t.turnId},sensitivity:e.sensitivity??"internal",...e.accessPolicyId?{accessPolicyId:e.accessPolicyId}:{},mode:"turn"}),d={...s,state:e.state??s.state,extensions:{...s.extensions??{},"xeno.legacy.turnDiffSummary":n}};return X(d),d}catch{}let o=C(n),r={schemaVersion:1,artifactId:e.artifactId??`turn_diff_${t.turnId}`,revision:e.revision??1,kind:"diff",title:`Turn ${t.turnId} changes`,state:e.state??"pending_review",createdAt:e.createdAt??t.completedAt,mediaType:"application/vnd.xeno.turn-diff+json",sensitivity:e.sensitivity??"internal",identity:{...e.identity?structuredClone(e.identity):{},turnId:e.identity?.turnId??t.turnId},content:{hash:N(n),sizeBytes:Ae.Buffer.byteLength(o,"utf8"),encoding:"utf8",storage:{type:"inline",text:o}},provenance:{producer:{...e.producer}},anchors:t.files.map(s=>({kind:"custom:source-file",data:{path:s.path}})),...e.accessPolicyId?{accessPolicyId:e.accessPolicyId}:{},extensions:{"xeno.legacy.turnDiffSummary":n}};return X(r),r}function
|
|
11
|
-
`))}readSidecar(e){try{let n=JSON.parse((0,I.readFileSync)(this.sidecarPath(e),"utf8"));return Array.isArray(n.publications)?n.publications:[]}catch{return[]}}async get(e,n){let i=await this.repository.get(e,n);if(!(!i||i.artifact.kind!=="page"))return this.toPublished(i)}async list(){let e=await this.repository.list({kinds:["page"]});return(await Promise.all(e.map(i=>this.toPublished(i)))).sort((i,o)=>(o.updatedAt??o.createdAt).localeCompare(i.updatedAt??i.createdAt))}resolveFile(e,n,i){let o=i===
|
|
7
|
+
`);if(d.length>r)throw new T(`Unified diff exceeds ${r} lines`);let a=[],c,f=0,g=(m,h)=>{if(c&&Gt(c,a),a.length>=i)throw new T(`Unified diff exceeds ${i} files`);return c={oldPath:m,newPath:h,status:"modified",binary:!1,headerLines:[],hunks:[]},c};for(let m=0;m<d.length;m+=1){let h=d[m];if(h.startsWith("diff --git ")){let[_,B]=Ai(h.slice(11),m+1);g(_,B).headerLines.push(h);continue}if(h.startsWith("--- ")){(!c||c.hunks.length>0)&&(c=g()),c.oldPath=Yt(h.slice(4)),c.headerLines.push(h);continue}if(h.startsWith("+++ ")){c||(c=g()),c.newPath=Yt(h.slice(4)),c.headerLines.push(h);continue}if(h.startsWith("@@ ")){if(!c)throw new T("Hunk appears before a file header",m+1);if(f>=o)throw new T(`Unified diff exceeds ${o} hunks`,m+1);let _=yi.exec(h);if(!_)throw new T("Malformed unified diff hunk header",m+1);let B=Number(_[1]),Q=_[2]===void 0?1:Number(_[2]),ee=Number(_[3]),q=_[4]===void 0?1:Number(_[4]),F=[],x=B,w=ee,J=0,Ie=0,z=m+1;for(;z<d.length;z+=1){let E=d[z],Rn=x-B===Q,bn=w-ee===q;if(Rn&&bn&&E.length===0||E.startsWith("diff --git ")||E.startsWith("@@ ")||E.startsWith("--- ")&&d[z+1]?.startsWith("+++ "))break;if(E.startsWith("+"))F.push({kind:"addition",text:E.slice(1),newLine:w}),w+=1,J+=1;else if(E.startsWith("-"))F.push({kind:"deletion",text:E.slice(1),oldLine:x}),x+=1,Ie+=1;else if(E.startsWith(" "))F.push({kind:"context",text:E.slice(1),oldLine:x,newLine:w}),x+=1,w+=1;else if(E==="\")F.push({kind:"no-newline",text:E});else{if(E.length===0&&z===d.length-1)break;throw new T("Unexpected line inside unified diff hunk",z+1)}}let St=F.filter(E=>E.kind==="context"||E.kind==="deletion").length,_t=F.filter(E=>E.kind==="context"||E.kind==="addition").length;if(St!==Q||_t!==q)throw new T(`Hunk line counts do not match header (expected -${Q}/+${q}, observed -${St}/+${_t})`,m+1);let xt=h,Xn=k(JSON.stringify({oldPath:c.oldPath??null,newPath:c.newPath??null,header:xt,lines:F})).value.slice(0,32);c.hunks.push({hunkId:Xn,header:xt,..._[5]?{section:_[5]}:{},oldStart:B,oldLines:Q,newStart:ee,newLines:q,additions:J,deletions:Ie,lines:F}),f+=1,m=z-1;continue}if(!c){if(h.trim().length===0)continue;throw new T("Content appears before the first diff file header",m+1)}c.headerLines.push(h),h.startsWith("new file mode ")?c.status="added":h.startsWith("deleted file mode ")?c.status="deleted":h.startsWith("rename from ")?(c.status="renamed",c.oldPath=Y(h.slice(12))):h.startsWith("rename to ")?(c.status="renamed",c.newPath=Y(h.slice(10))):h.startsWith("copy from ")?(c.status="copied",c.oldPath=Y(h.slice(10))):h.startsWith("copy to ")?(c.status="copied",c.newPath=Y(h.slice(8))):(h.startsWith("Binary files ")||h==="GIT binary patch")&&(c.binary=!0,c.status="binary")}c&&Gt(c,a);let y=a.reduce((m,h)=>m+h.additions,0),D=a.reduce((m,h)=>m+h.deletions,0);return{schemaVersion:1,mode:e.mode??"working-tree",...e.repositoryId?{repositoryId:e.repositoryId}:{},...e.baseRef?{baseRef:e.baseRef}:{},...e.headRef?{headRef:e.headRef}:{},files:a,additions:y,deletions:D,rawDiff:s}}function ot(t,e){let n=rt(t,{mode:e.mode,repositoryId:e.repositoryId,baseRef:e.baseRef,headRef:e.headRef}),i=n,o=C(i),r=[e.identity?.runId,e.identity?.turnId,e.identity?.taskId,e.repositoryId,e.mode].filter(Boolean).join(":"),s=e.kind??"diff",d=e.artifactId??`${s}_${k(`${r}:${n.rawDiff}`).value.slice(0,24)}`,a=e.revision??1,c={schemaVersion:1,artifactId:d,revision:a,kind:s,title:e.title??`${Ei(n.mode)} diff (${n.files.length} files)`,...e.description?{description:e.description}:{},state:"pending_review",createdAt:e.createdAt??new Date().toISOString(),mediaType:`application/vnd.xeno.${s}+json`,sensitivity:e.sensitivity??"internal",...e.identity?{identity:structuredClone(e.identity)}:{},content:{hash:N(i),sizeBytes:it.Buffer.byteLength(o,"utf8"),encoding:"utf8",storage:{type:"inline",text:o},redactedPreview:`${n.files.length} files, +${n.additions}/-${n.deletions}`},provenance:{producer:{...e.producer}},anchors:n.files.flatMap(f=>[{kind:"file",path:f.displayPath,...e.repositoryId?{repositoryId:e.repositoryId}:{}},...f.hunks.map(g=>({kind:"diff-hunk",path:f.displayPath,hunkId:g.hunkId,artifactId:d,revision:a}))]),...a>1?{predecessorRevision:e.predecessorRevision??a-1}:{},...e.accessPolicyId?{accessPolicyId:e.accessPolicyId}:{},extensions:{"xeno.diff.mode":n.mode,"xeno.diff.files":n.files.length,"xeno.diff.additions":n.additions,"xeno.diff.deletions":n.deletions}};return X(c),c}function st(t){if(X(t),t.kind!=="diff"&&t.kind!=="patch")throw new TypeError("Artifact is not a diff or patch");if(t.content.storage.type!=="inline"||typeof t.content.storage.text!="string")throw new TypeError("Diff artifact content is not available inline");let e;try{e=JSON.parse(t.content.storage.text)}catch(i){throw new T(`Diff artifact JSON is malformed: ${Xi(i).message}`)}if(!wi(e))throw new T("Diff artifact document is invalid");let n=rt(e.rawDiff,{mode:e.mode,repositoryId:e.repositoryId,baseRef:e.baseRef,headRef:e.headRef});if(C(n)!==C(e))throw new T("Diff artifact document does not match its raw diff");return n}function Gt(t,e){if(!t.oldPath&&!t.newPath)throw new T("Diff file has no path");t.oldPath||(t.status="added"),t.newPath||(t.status="deleted"),t.binary&&(t.status="binary");let n=t.hunks.reduce((o,r)=>o+r.additions,0),i=t.hunks.reduce((o,r)=>o+r.deletions,0);e.push({...t.oldPath?{oldPath:t.oldPath}:{},...t.newPath?{newPath:t.newPath}:{},displayPath:t.newPath??t.oldPath,status:t.status,additions:n,deletions:i,binary:t.binary,headerLines:[...t.headerLines],hunks:structuredClone(t.hunks)})}function Ai(t,e){let n=Ii(t);if(n.length!==2)throw new T("Malformed diff --git path pair",e);return[Y(n[0]),Y(n[1])]}function Ii(t){let e=[],n=0;for(;n<t.length;){for(;t[n]===" ";)n+=1;if(n>=t.length)break;if(t[n]==='"'){let i='"';n+=1;let o=!1;for(;n<t.length;){let r=t[n];if(i+=r,n+=1,!o&&r==='"')break;o=!o&&r==="\\",r!=="\\"&&(o=!1)}e.push(Qt(i))}else{let i=t.indexOf(" ",n);if(i===-1){e.push(t.slice(n));break}e.push(t.slice(n,i)),n=i+1}}return e}function Qt(t){return!t.startsWith('"')||!t.endsWith('"')?t:t.slice(1,-1).replace(/\\([\\"tnr]|[0-7]{1,3})/g,(n,i)=>i==="t"?" ":i==="n"?`
|
|
8
|
+
`:i==="r"?"\r":i==="\\"?"\\":i==='"'?'"':String.fromCharCode(Number.parseInt(i,8)))}function Yt(t){let e=t.split(" ",1)[0].trim();if(e!=="/dev/null")return Y(Qt(e))}function Y(t){let e=t.replace(/\\/g,"/");return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function wi(t){return!Zt(t)||t.schemaVersion!==1||!["working-tree","staged","turn","commit","preview"].includes(String(t.mode))||!Array.isArray(t.files)||!Number.isSafeInteger(t.additions)||!Number.isSafeInteger(t.deletions)||typeof t.rawDiff!="string"?!1:t.files.every(e=>Zt(e)&&typeof e.displayPath=="string"&&Array.isArray(e.headerLines)&&Array.isArray(e.hunks))}function Zt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Te(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 Ei(t){return t.split("-").map(e=>e[0].toUpperCase()+e.slice(1)).join(" ")}function Xi(t){return t instanceof Error?t:new Error(String(t))}var tn=require("node:crypto");var ie=class{repository;actor;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");if(!e.actor?.kind||!e.actor.id?.trim())throw new TypeError("Review actor is required");this.repository=e.repository,this.actor=structuredClone(e.actor),this.idFactory=e.idFactory??(()=>`comment_${(0,tn.randomUUID)()}`)}async addComment(e){let n=Ce(e.body,"Review comment body",65536),i=await this.repository.require(e.artifactId,e.revision),o=at(i,e),r=ke(this.idFactory(),"Comment ID"),s=Ri(e.parentCommentId,"Parent comment ID");return this.repository.appendReviewEvent({expectedRecordVersion:i.recordVersion,event:{type:"comment-added",artifactId:i.artifact.artifactId,artifactRevision:i.artifact.revision,artifactHash:i.artifact.content.hash,actor:this.actor,commentId:r,body:n,...o?{anchor:o}:{},...s?{parentCommentId:s}:{}}})}async setCommentResolution(e){let n=ke(e.commentId,"Review comment ID"),i=en(e.reason,"Resolution reason",16*1024),o=await this.repository.require(e.artifactId,e.revision);return this.repository.appendReviewEvent({expectedRecordVersion:o.recordVersion,event:{type:e.resolved?"comment-resolved":"comment-reopened",artifactId:o.artifact.artifactId,artifactRevision:o.artifact.revision,artifactHash:o.artifact.content.hash,actor:this.actor,commentId:n,...i?{reason:i}:{}}})}async decide(e){let n=await this.repository.require(e.artifactId,e.revision);if(n.artifact.state!=="pending_review")throw new u("ARTIFACT_REVIEW_INVALID",`Artifact must be pending_review, found ${n.artifact.state}`);let i=at(n,e),o=en(e.rationale,"Decision rationale",64*1024),r=await this.repository.appendReviewEvent({expectedRecordVersion:n.recordVersion,event:{type:"decision-recorded",artifactId:n.artifact.artifactId,artifactRevision:n.artifact.revision,artifactHash:n.artifact.content.hash,actor:this.actor,decision:e.decision,...o?{rationale:o}:{},...i?{scope:i}:{}}});if(i||e.decision==="changes_requested")return r;let s=r.reviewEvents.at(-1);if(!s||s.type!=="decision-recorded")throw new u("ARTIFACT_REVIEW_INVALID","Artifact decision event was not recorded");return this.repository.transition({artifactId:r.artifact.artifactId,revision:r.artifact.revision,expectedRecordVersion:r.recordVersion,toState:e.decision,actor:this.actor,reviewEventId:s.eventId,...o?{reason:o}:{}})}};function at(t,e){if((e.line!==void 0||e.hunkId!==void 0)&&!e.file)throw j("Line and hunk anchors require a file");if(e.line!==void 0&&e.hunkId!==void 0)throw j("Line and hunk anchors cannot be combined");if(!e.file)return;let n=nn(e.file);if(e.line!==void 0&&(!Number.isInteger(e.line)||e.line<1))throw j("Review line must be a positive integer");if(t.artifact.kind==="diff"||t.artifact.kind==="patch"){let o=st(t.artifact).files.find(r=>r.displayPath===n);if(!o)throw j(`File ${n} is not present in this artifact`);if(e.hunkId&&!o.hunks.some(r=>r.hunkId===e.hunkId))throw j(`Hunk ${e.hunkId} is not present in ${n}`)}return e.hunkId?{kind:"diff-hunk",path:n,hunkId:ke(e.hunkId,"Hunk ID"),artifactId:t.artifact.artifactId,revision:t.artifact.revision}:e.line!==void 0?{kind:"source-line",path:n,startLine:e.line}:{kind:"file",path:n}}function nn(t){let e=Ce(t,"Artifact review file",4096).replace(/\\/g,"/").replace(/^\.\//,"");if(e.startsWith("../")||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.split("/").some(n=>n===".."||n.length===0))throw j("Artifact review file anchors must be repository-relative paths");return e}function Ce(t,e,n){let i=typeof t=="string"?t.trim():"";if(!i)throw j(`${e} cannot be empty`);if(i.length>n)throw j(`${e} exceeds ${n} characters`);return i}function en(t,e,n){if(t!==void 0)return Ce(t,e,n)}function ke(t,e){let n=Ce(t,e,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(n))throw j(`${e} contains unsupported characters`);return n}function Ri(t,e){return t===void 0?void 0:ke(t,e)}function j(t){return new u("ARTIFACT_REVIEW_INVALID",t)}var rn=require("node:crypto");var oe="xeno.spec.v1",ge="xeno.spec-execution.v1",R=class extends Error{constructor(n){super(`XENO spec is invalid: ${n.join("; ")}`);this.issues=n;this.name="XenoSpecValidationError"}issues;code="XENO_SPEC_INVALID"},ct=class{repository;now;idFactory;constructor(e){if(!e?.repository)throw new TypeError("Artifact repository is required");this.repository=e.repository,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(()=>(0,rn.randomUUID)())}async create(e,n){if(e.revision!==1||e.predecessorRevision!==void 0)throw new R(["A new spec must begin at revision 1 without a predecessor"]);let i=dt(e,n);return await this.repository.create(i.requirements),await this.repository.create(i.design),await this.repository.create(i.taskGraph),await this.repository.create(i.plan),i}async revise(e,n){let i=re(e.specId),o=await this.repository.require(i.plan);if(e.revision!==o.artifact.revision+1||e.predecessorRevision!==o.artifact.revision)throw new R([`Revision ${e.revision} must follow approved or reviewed revision ${o.artifact.revision}`]);let r=dt(e,n);return await this.repository.createRevision(r.requirements,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.design,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.taskGraph,{actor:n.producer,reason:"spec-revised"}),await this.repository.createRevision(r.plan,{actor:n.producer,reason:"spec-revised"}),r}async approve(e,n,i){return new ie({repository:this.repository,actor:n}).decide({artifactId:re(e).plan,decision:"approved",...i?{rationale:i}:{}})}async reject(e,n,i){return new ie({repository:this.repository,actor:n}).decide({artifactId:re(e).plan,decision:"rejected",rationale:i})}async startExecution(e,n){let i=await this.repository.require(re(e).plan);if(i.artifact.state!=="approved")throw new R([`Spec ${e} must be approved before execution`]);let o=ft(i.artifact),r=this.now(),s={schemaVersion:ge,executionId:`spec_execution_${this.idFactory()}`,specId:o.specId,specRevision:o.revision,planArtifactId:i.artifact.artifactId,planHash:{...i.artifact.content.hash},state:"ready",createdAt:r,updatedAt:r,observedPaths:[],tasks:o.tasks.map(d=>({taskId:d.id,status:"pending",evidence:[],acceptanceEvidence:Object.fromEntries(d.acceptanceCriterionIds.map(a=>[a,[]]))}))};return this.repository.create(pt(s,{producer:n,identity:i.artifact.identity,sensitivity:i.artifact.sensitivity,accessPolicyId:i.artifact.accessPolicyId}))}async updateExecution(e,n,i){let o=await this.repository.require(e),r=sn(o.artifact),s=await this.repository.require(r.planArtifactId,r.specRevision);if(s.artifact.state!=="approved"||!ve(s.artifact.content.hash,r.planHash))throw new R(["Execution is no longer bound to the approved plan revision"]);let d=n(structuredClone(r));d.schemaVersion=ge,d.executionId=r.executionId,d.specId=r.specId,d.specRevision=r.specRevision,d.planArtifactId=r.planArtifactId,d.planHash={...r.planHash},d.createdAt=r.createdAt,d.updatedAt=this.now(),ut(d,ft(s.artifact));let a=pt(d,{producer:i,identity:o.artifact.identity,sensitivity:o.artifact.sensitivity,accessPolicyId:o.artifact.accessPolicyId},o.artifact.revision+1,o.artifact.revision);return this.repository.createRevision(a,{actor:i,reason:"spec-execution-updated"})}};function re(t){let e=_i(t,"specId");return{plan:`spec_${e}_plan`,requirements:`spec_${e}_requirements`,design:`spec_${e}_design`,taskGraph:`spec_${e}_task_graph`}}function on(t){let e=[];t?.schemaVersion!==oe&&e.push(`schemaVersion must be ${oe}`),he(t?.specId,"specId",e),(!Number.isInteger(t?.revision)||t.revision<1)&&e.push("revision must be a positive integer"),$(t?.title,"title",e),$(t?.problem,"problem",e),Pe(t?.createdAt,"createdAt",e),Pe(t?.updatedAt,"updatedAt",e),t?.predecessorRevision!==void 0&&(!Number.isInteger(t.predecessorRevision)||t.predecessorRevision!==t.revision-1)&&e.push("predecessorRevision must be the immediately preceding revision");let n=Ne(t?.requirements,"requirement",e),i=Ne(t?.tasks,"task",e),o=new Set,r=[...Array.isArray(t?.acceptanceCriteria)?t.acceptanceCriteria:[],...Array.isArray(t?.requirements)?t.requirements.flatMap(a=>Array.isArray(a.acceptanceCriteria)?a.acceptanceCriteria:[]):[]];for(let a of r){he(a?.id,"acceptance criterion id",e),$(a?.text,`acceptance criterion ${a?.id??"?"}`,e),o.has(a?.id)&&e.push(`Duplicate acceptance criterion: ${a?.id}`),o.add(a?.id);for(let c of a?.requiredEvidenceKinds??[])he(c,"required evidence kind",e)}for(let a of t?.requirements??[])$(a?.text,`requirement ${a?.id??"?"}`,e),["must","should","could"].includes(a?.priority)||e.push(`Requirement ${a?.id??"?"} has invalid priority`),(!Array.isArray(a?.acceptanceCriteria)||a.acceptanceCriteria.length===0)&&e.push(`Requirement ${a?.id??"?"} needs at least one acceptance criterion`);$(t?.design?.summary,"design summary",e);let s=Ne(t?.design?.decisions,"design decision",e),d=Ne(t?.design?.risks,"risk",e);for(let a of t?.design?.decisions??[]){$(a?.decision,`design decision ${a?.id??"?"}`,e),$(a?.rationale,`design rationale ${a?.id??"?"}`,e);for(let c of a?.requirementIds??[])n.has(c)||e.push(`Design decision ${a.id} references unknown requirement ${c}`)}for(let a of t?.design?.risks??[])$(a?.description,`risk ${a?.id??"?"}`,e),$(a?.mitigation,`risk mitigation ${a?.id??"?"}`,e),["low","medium","high","critical"].includes(a?.impact)||e.push(`Risk ${a?.id??"?"} has invalid impact`);for(let a of t?.tasks??[]){$(a?.title,`task title ${a?.id??"?"}`,e),$(a?.description,`task description ${a?.id??"?"}`,e);for(let c of a?.dependsOn??[])i.has(c)||e.push(`Task ${a.id} depends on unknown task ${c}`),c===a.id&&e.push(`Task ${a.id} cannot depend on itself`);for(let c of a?.requirementIds??[])n.has(c)||e.push(`Task ${a.id} references unknown requirement ${c}`);for(let c of a?.acceptanceCriterionIds??[])o.has(c)||e.push(`Task ${a.id} references unknown acceptance criterion ${c}`);for(let c of a?.expectedPaths??[])cn(c)||e.push(`Task ${a.id} has unsafe expected path ${c}`)}return xi(t?.tasks??[])&&e.push("Task dependency graph contains a cycle"),[...new Set(e)]}function $e(t){let e=on(t);if(e.length>0)throw new R(e)}function dt(t,e){$e(t);let n=re(t.specId),i=t.revision,o={...e,createdAt:t.updatedAt,state:"draft"},r=me({artifactId:n.requirements,revision:i,predecessorRevision:t.predecessorRevision,kind:"requirements",title:`${t.title} - requirements`,value:{schemaVersion:oe,specId:t.specId,revision:i,problem:t.problem,requirements:t.requirements,acceptanceCriteria:t.acceptanceCriteria},context:o}),s=me({artifactId:n.design,revision:i,predecessorRevision:t.predecessorRevision,kind:"design",title:`${t.title} - design`,value:{schemaVersion:oe,specId:t.specId,revision:i,design:t.design,...t.sourceBaseline?{sourceBaseline:t.sourceBaseline}:{}},context:o}),d=me({artifactId:n.taskGraph,revision:i,predecessorRevision:t.predecessorRevision,kind:"task-graph",title:`${t.title} - task graph`,value:{schemaVersion:oe,specId:t.specId,revision:i,tasks:t.tasks},context:o}),a=[r,s,d].map(f=>({relation:"decomposes",target:{type:"artifact",id:f.artifactId,revision:f.revision}})),c=me({artifactId:n.plan,revision:i,predecessorRevision:t.predecessorRevision,kind:"plan",title:t.title,description:t.problem,value:t,context:{...e,createdAt:t.updatedAt,state:"pending_review"},relationships:a,extensions:{"xeno.spec.id":t.specId,"xeno.spec.revision":t.revision,"xeno.spec.requirements_hash":r.content.hash.value,"xeno.spec.design_hash":s.content.hash.value,"xeno.spec.task_graph_hash":d.content.hash.value}});return{document:structuredClone(t),plan:c,requirements:r,design:s,taskGraph:d}}function ft(t){if(t.kind!=="plan"||t.mediaType!=="application/vnd.xeno.spec+json")throw new R([`Artifact ${t.artifactId} is not a XENO spec plan`]);let e=an(t);if($e(e),e.revision!==t.revision)throw new R(["Spec and artifact revisions differ"]);if(!ve(N(e),t.content.hash))throw new R(["Spec artifact content hash is invalid"]);return structuredClone(e)}function pt(t,e,n=1,i){let o=structuredClone(t);return me({artifactId:t.executionId,revision:n,predecessorRevision:i,kind:"custom:xeno.spec-execution",title:`Execution of ${t.specId} revision ${t.specRevision}`,description:`Execution state: ${t.state}`,value:o,context:{...e,createdAt:t.updatedAt,state:t.state==="completed"?"pending_review":"draft"},relationships:[{relation:"implements",target:{type:"artifact",id:t.planArtifactId,revision:t.specRevision}}],extensions:{"xeno.spec.execution_state":t.state,"xeno.spec.plan_hash":t.planHash.value}})}function sn(t){if(t.kind!=="custom:xeno.spec-execution")throw new R([`Artifact ${t.artifactId} is not a spec execution`]);let e=an(t);if(e.schemaVersion!==ge||e.executionId!==t.artifactId)throw new R(["Spec execution identity or schema is invalid"]);if(!ve(N(e),t.content.hash))throw new R(["Spec execution content hash is invalid"]);return structuredClone(e)}function ut(t,e){let n=[];t.schemaVersion!==ge&&n.push("Execution schema is invalid"),(t.specId!==e.specId||t.specRevision!==e.revision)&&n.push("Execution is bound to the wrong spec revision");let i=new Map(e.tasks.map(r=>[r.id,r])),o=new Set;for(let r of t.tasks){o.has(r.taskId)&&n.push(`Duplicate execution task ${r.taskId}`),o.add(r.taskId);let s=i.get(r.taskId);if(!s){n.push(`Unknown execution task ${r.taskId}`);continue}for(let d of s.acceptanceCriterionIds)Array.isArray(r.acceptanceEvidence?.[d])||n.push(`Task ${r.taskId} is missing acceptance evidence slot ${d}`)}for(let r of i.keys())o.has(r)||n.push(`Execution is missing task ${r}`);for(let r of t.observedPaths)Ti(r)||n.push(`Unsafe observed path ${r}`);if(Pe(t.createdAt,"execution createdAt",n),Pe(t.updatedAt,"execution updatedAt",n),n.length>0)throw new R([...new Set(n)])}function bi(t,e,n,i,o=new Date().toISOString()){$e(t),ut(n,t);let r=[];(!ve(e,i)||!ve(n.planHash,i))&&r.push({code:"PLAN_HASH_MISMATCH",severity:"error",message:"Execution is not bound to the approved plan content hash"});let s=new Map(t.tasks.map(c=>[c.id,c])),d=new Map(n.tasks.map(c=>[c.taskId,c]));for(let c of n.tasks){let f=s.get(c.taskId);if(!f){r.push({code:"UNKNOWN_TASK",severity:"error",taskId:c.taskId,message:`Unknown task ${c.taskId}`});continue}if(c.status==="completed"){c.evidence.length===0&&r.push({code:"MISSING_TASK_EVIDENCE",severity:"error",taskId:f.id,message:`Completed task ${f.id} has no evidence`});for(let g of f.dependsOn??[])d.get(g)?.status!=="completed"&&r.push({code:"DEPENDENCY_INCOMPLETE",severity:"error",taskId:f.id,message:`Task ${f.id} completed before dependency ${g}`});for(let g of f.acceptanceCriterionIds)(c.acceptanceEvidence[g]??[]).length===0&&r.push({code:"MISSING_ACCEPTANCE_EVIDENCE",severity:"error",taskId:f.id,criterionId:g,message:`Completed task ${f.id} has no evidence for ${g}`})}}let a=t.tasks.flatMap(c=>c.expectedPaths??[]);for(let c of n.observedPaths)a.some(f=>ki(c,f))||r.push({code:"UNKNOWN_PATH",severity:"warning",path:c,message:`Observed path ${c} is outside the approved task plan`});return{schemaVersion:"xeno.spec-drift.v1",specId:t.specId,specRevision:t.revision,executionId:n.executionId,checkedAt:o,drifted:r.length>0,findings:r}}function me(t){let e=t.value,n=C(e);return{schemaVersion:1,artifactId:t.artifactId,revision:t.revision,kind:t.kind,title:t.title,...t.description?{description:t.description}:{},state:t.context.state,createdAt:t.context.createdAt??new Date().toISOString(),mediaType:Si(t.kind),sensitivity:t.context.sensitivity??"internal",...t.context.identity?{identity:structuredClone(t.context.identity)}:{},content:{hash:N(e),sizeBytes:Buffer.byteLength(n,"utf8"),encoding:"utf8",storage:{type:"inline",text:n},redactedPreview:t.title},provenance:{producer:structuredClone(t.context.producer)},...t.relationships?.length?{relationships:structuredClone(t.relationships)}:{},...t.predecessorRevision!==void 0?{predecessorRevision:t.predecessorRevision}:{},...t.context.accessPolicyId?{accessPolicyId:t.context.accessPolicyId}:{},...t.extensions?{extensions:structuredClone(t.extensions)}:{}}}function Si(t){return t==="plan"?"application/vnd.xeno.spec+json":t==="custom:xeno.spec-execution"?"application/vnd.xeno.spec-execution+json":`application/vnd.xeno.spec-${t}+json`}function an(t){let e=t.content.storage;if(e.type!=="inline"||typeof e.text!="string")throw new R(["Spec artifacts require inline JSON content"]);try{return JSON.parse(e.text)}catch(n){throw new R([`Spec artifact JSON is invalid: ${n instanceof Error?n.message:String(n)}`])}}function Ne(t,e,n){let i=new Set;(!Array.isArray(t)||t.length===0)&&n.push(`${e} list cannot be empty`);for(let o of t??[])he(o?.id,`${e} id`,n),i.has(o?.id??"")&&n.push(`Duplicate ${e}: ${o?.id}`),o?.id&&i.add(o.id);return i}function he(t,e,n){(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(t))&&n.push(`${e} must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}`)}function $(t,e,n){(typeof t!="string"||t.trim().length===0||t.length>64*1024)&&n.push(`${e} must be non-empty and no longer than 65536 characters`)}function Pe(t,e,n){(typeof t!="string"||!t.includes("T")||!Number.isFinite(Date.parse(t)))&&n.push(`${e} must be an ISO 8601 timestamp`)}function _i(t,e){let n=[];if(he(t,e,n),n.length>0)throw new R(n);return t}function xi(t){let e=new Map(t.map(r=>[r.id,r])),n=new Set,i=new Set,o=r=>{if(n.has(r))return!0;if(i.has(r))return!1;n.add(r);for(let s of e.get(r)?.dependsOn??[])if(o(s))return!0;return n.delete(r),i.add(r),!1};return t.some(r=>o(r.id))}function cn(t){let e=t.replace(/\\/gu,"/");return e.length>0&&e.length<=4096&&!e.startsWith("/")&&!/^[A-Za-z]:/u.test(e)&&!e.split("/").includes("..")}function Ti(t){return cn(t)&&!t.includes("*")}function ki(t,e){let n=t.replace(/\\/gu,"/"),i=e.replace(/\\/gu,"/");if(i.endsWith("/**")){let o=i.slice(0,-3).replace(/\/$/u,"");return n===o||n.startsWith(`${o}/`)}if(i.endsWith("/*")){let o=i.slice(0,-2).replace(/\/$/u,""),r=n.startsWith(`${o}/`)?n.slice(o.length+1):"";return r.length>0&&!r.includes("/")}return n===i}function ve(t,e){return t.algorithm===e.algorithm&&t.value===e.value}var dn=require("node:crypto");var mt="xeno.review-report.v1",fn=["correctness","security","performance","api","tests","documentation"],pn=["source","test","trace","artifact","reproduction","benchmark"],b=class extends Error{constructor(n){super(`XENO review is invalid: ${n.join("; ")}`);this.issues=n;this.name="XenoReviewValidationError"}issues;code="XENO_REVIEW_INVALID"},lt=class{reviewer;verifier;now;idFactory;constructor(e){if(typeof e?.reviewer!="function")throw new TypeError("Review agent executor is required");this.reviewer=e.reviewer,this.verifier=e.verifier,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(n=>`${n}_${(0,dn.randomUUID)()}`)}async run(e){ht(e.pack),gt(e.target),Oe(e.runId,"runId");let n=this.now(),i=await Promise.all(e.pack.dimensions.map(async(a,c)=>{let f=await this.reviewer({...e,dimension:a,reviewerSlot:c});return Di(f,a,e.pack.maxFindings),structuredClone(f)})),o=i.flatMap(a=>a.findings.map(c=>({finding:c,reviewerAgentId:a.reviewerAgentId})));if(o.length>e.pack.maxFindings)throw new b([`Reviewers returned ${o.length} findings, exceeding maxFindings ${e.pack.maxFindings}`]);let r=Oi(o,this.idFactory);for(let a of r){let c=this.verifier?await Promise.all(Array.from({length:e.pack.verifierCount},async(m,h)=>{let _=await this.verifier({...e,finding:structuredClone(a),verifierSlot:h});return Fi(_),structuredClone(_)})):[];a.verifications=Li(c),a.evidence=ln([...a.evidence,...a.verifications.flatMap(m=>m.evidence)]);let f=new Set(a.verifications.filter(m=>m.outcome==="reproduced").map(m=>m.verifierAgentId)).size,g=a.verifications.length>0&&a.verifications.every(m=>m.outcome==="rejected"),y=new Set(a.evidence.map(m=>m.producerId)).size;f>=e.pack.minimumVerifierReproductions?(a.state="verified",a.verificationBasis="verifier"):e.pack.allowIndependentEvidenceVerification&&y>=e.pack.minimumIndependentEvidenceProducers?(a.state="verified",a.verificationBasis="independent-evidence"):g?(a.state="rejected",a.verificationBasis="verifier"):(a.state="unverified",a.verificationBasis="none");let D=a.verifications.map(m=>m.confidence).filter(m=>m!==void 0);D.length>0&&(a.confidence=An(Math.min(a.confidence,...D)))}r.sort(Mi);let s=this.now(),d={schemaVersion:mt,reportId:Oe(this.idFactory("report"),"reportId"),runId:e.runId,pack:structuredClone(e.pack),target:structuredClone(e.target),startedAt:n,completedAt:s,reviewers:i.map(a=>({agentId:a.reviewerAgentId,dimension:a.dimension,findingCount:a.findings.length})),findings:r,summary:gn(r)};return ye(d),d}};function Ci(t="xeno-production-review"){return{schemaVersion:"xeno.review-pack.v1",packId:t,version:"1.0.0",dimensions:["correctness","security","performance","api","tests","documentation"],verifierCount:1,minimumVerifierReproductions:1,allowIndependentEvidenceVerification:!1,minimumIndependentEvidenceProducers:2,maxFindings:256}}function ht(t){let e=[];t?.schemaVersion!=="xeno.review-pack.v1"&&e.push("Review pack schemaVersion must be xeno.review-pack.v1"),O(t?.packId,"packId",e),(typeof t?.version!="string"||!/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/u.test(t.version))&&e.push("Review pack version must be semantic version text"),(!Array.isArray(t?.dimensions)||t.dimensions.length===0)&&e.push("Review pack needs at least one dimension"),new Set(t?.dimensions??[]).size!==(t?.dimensions??[]).length&&e.push("Review pack dimensions must be unique");for(let n of t?.dimensions??[])yn(n)||e.push(`Invalid review dimension ${n}`);if((!Number.isInteger(t?.verifierCount)||t.verifierCount<0||t.verifierCount>8)&&e.push("verifierCount must be 0 through 8"),(!Number.isInteger(t?.minimumVerifierReproductions)||t.minimumVerifierReproductions<1||t.minimumVerifierReproductions>Math.max(1,t.verifierCount))&&e.push("minimumVerifierReproductions must be positive and no greater than verifierCount"),(!Number.isInteger(t?.minimumIndependentEvidenceProducers)||t.minimumIndependentEvidenceProducers<2)&&e.push("minimumIndependentEvidenceProducers must be at least 2"),(!Number.isInteger(t?.maxFindings)||t.maxFindings<1||t.maxFindings>2048)&&e.push("maxFindings must be 1 through 2048"),e.length>0)throw new b(e)}function gt(t){let e=[];if(O(t?.artifactId,"target artifactId",e),(!Number.isInteger(t?.revision)||t.revision<1)&&e.push("Target revision must be positive"),Z(t?.title,"target title",e),(t?.contentHash?.algorithm!=="sha256"||!/^[a-f0-9]{64}$/u.test(t?.contentHash?.value??""))&&e.push("Target contentHash must be lowercase sha256"),e.length>0)throw new b(e)}function ye(t){let e=[];t?.schemaVersion!==mt&&e.push("Review report schemaVersion is invalid"),O(t?.reportId,"reportId",e),O(t?.runId,"runId",e),Ve(t?.startedAt,"startedAt",e),Ve(t?.completedAt,"completedAt",e),Date.parse(t?.completedAt)<Date.parse(t?.startedAt)&&e.push("completedAt cannot precede startedAt");try{ht(t.pack)}catch(r){e.push(r instanceof Error?r.message:String(r))}try{gt(t.target)}catch(r){e.push(r instanceof Error?r.message:String(r))}let n=new Set,i=new Set;for(let r of t?.findings??[])O(r?.findingId,"findingId",e),n.has(r.findingId)&&e.push(`Duplicate findingId ${r.findingId}`),n.add(r.findingId),/^[a-f0-9]{64}$/u.test(r?.fingerprint??"")||e.push(`Finding ${r.findingId} has invalid fingerprint`),i.has(r.fingerprint)&&e.push(`Duplicate finding fingerprint ${r.fingerprint}`),i.add(r.fingerprint),Z(r?.title,`finding ${r.findingId} title`,e),Z(r?.summary,`finding ${r.findingId} summary`,e),vn(r?.severity)||e.push(`Finding ${r.findingId} has invalid severity`),(!Number.isFinite(r?.confidence)||r.confidence<0||r.confidence>1)&&e.push(`Finding ${r.findingId} has invalid confidence`),r?.state==="verified"&&r.verificationBasis==="none"&&e.push(`Finding ${r.findingId} cannot be verified without a basis`),r?.state!=="verified"&&r.verificationBasis==="independent-evidence"&&e.push(`Finding ${r.findingId} has inconsistent evidence verification`);let o=gn(t?.findings??[]);if((o.total!==t?.summary?.total||o.verified!==t?.summary?.verified||o.unverified!==t?.summary?.unverified||o.rejected!==t?.summary?.rejected||Object.keys(o.bySeverity).some(r=>o.bySeverity[r]!==t?.summary?.bySeverity?.[r]))&&e.push("Review report summary is inconsistent"),e.length>0)throw new b([...new Set(e)])}function Ni(t,e){ye(t);let n=t,i=C(n),o=e.artifactId??`review_${k(`${t.runId}:${t.target.artifactId}:${t.target.contentHash.value}`).value.slice(0,24)}`,r={schemaVersion:1,artifactId:o,revision:1,kind:"review-report",title:`Review of ${t.target.title}`,description:`${t.summary.verified} verified, ${t.summary.unverified} unverified, ${t.summary.rejected} rejected findings`,state:"pending_review",createdAt:e.createdAt??t.completedAt,mediaType:"application/vnd.xeno.review-report+json",sensitivity:e.sensitivity??"internal",...e.identity?{identity:structuredClone(e.identity)}:{},content:{hash:N(n),sizeBytes:Buffer.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i},redactedPreview:`${t.summary.total} findings; ${t.summary.verified} verified`},provenance:{producer:structuredClone(e.producer),sourceArtifactIds:[t.target.artifactId],attributes:{reviewPackId:t.pack.packId,reviewPackVersion:t.pack.version}},relationships:[{relation:"reviews",target:{type:"artifact",id:t.target.artifactId,revision:t.target.revision}}],anchors:mn(t.findings.flatMap(s=>s.anchors)),...e.accessPolicyId?{accessPolicyId:e.accessPolicyId}:{},extensions:{"xeno.review.pack":t.pack.packId,"xeno.review.verified":t.summary.verified,"xeno.review.unverified":t.summary.unverified,"xeno.review.rejected":t.summary.rejected}};return X(r),r}function Pi(t){if(t.kind!=="review-report"||t.mediaType!=="application/vnd.xeno.review-report+json")throw new b([`Artifact ${t.artifactId} is not a XENO review report`]);if(t.content.storage.type!=="inline"||typeof t.content.storage.text!="string")throw new b(["Review report requires inline JSON content"]);let e;try{e=JSON.parse(t.content.storage.text)}catch(n){throw new b([`Review report JSON is invalid: ${n instanceof Error?n.message:String(n)}`])}if(ye(e),!ji(N(e),t.content.hash))throw new b(["Review report content hash is invalid"]);return structuredClone(e)}function $i(t,e={}){ye(t);let n=[];for(let i of t.findings){if(e.verifiedOnly!==!1&&i.state!=="verified")continue;let o=i.anchors.find(r=>r.kind==="source-line"||r.kind==="file"||r.kind==="diff-hunk");!o||!("path"in o)||n.push({findingId:i.findingId,path:o.path,...o.kind==="source-line"?{line:o.startLine}:{},severity:i.severity,verified:i.state==="verified",body:[`**${i.severity.toUpperCase()} - ${i.title}**`,"",i.summary,"",`Evidence: ${i.evidence.map(r=>r.summary).join("; ")||"none"}`,i.remediation?`Suggested remediation: ${i.remediation}`:"",`XENO finding: ${i.findingId} (${i.state}, confidence ${i.confidence.toFixed(2)})`].filter(Boolean).join(`
|
|
9
|
+
`)})}return n}function Oi(t,e){let n=new Map;for(let i of t){un(i.finding),Oe(i.reviewerAgentId,"reviewerAgentId");let o=Vi(i.finding),r=n.get(o)??[];r.push(structuredClone(i)),n.set(o,r)}return[...n.entries()].map(([i,o])=>{let r=[...o].sort((d,a)=>se(a.finding.severity)-se(d.finding.severity))[0],s=ln(o.flatMap(d=>d.finding.evidence));return{findingId:Oe(e("finding"),"findingId"),fingerprint:i,ruleIds:[...new Set(o.flatMap(d=>d.finding.ruleId?[d.finding.ruleId]:[]))].sort(),dimensions:[...new Set(o.map(d=>d.finding.dimension))].sort(),reviewerAgentIds:[...new Set(o.map(d=>d.reviewerAgentId))].sort(),title:r.finding.title,summary:r.finding.summary,severity:o.reduce((d,a)=>se(a.finding.severity)>se(d)?a.finding.severity:d,r.finding.severity),confidence:An(Math.max(...o.map(d=>d.finding.confidence))),state:"unverified",verificationBasis:"none",anchors:mn(o.flatMap(d=>d.finding.anchors)),evidence:s,verifications:[],...r.finding.remediation?{remediation:r.finding.remediation}:{},duplicateProposalCount:o.length}})}function Vi(t){let e=t.anchors.map(hn).sort();return N({ruleId:t.ruleId??"",title:Hi(t.title),anchors:e}).value}function Di(t,e,n){let i=[];O(t?.reviewerAgentId,"reviewerAgentId",i),t?.dimension!==e&&i.push(`Reviewer returned dimension ${t?.dimension} for requested ${e}`),Ve(t?.completedAt,"reviewer completedAt",i),(!Array.isArray(t?.findings)||t.findings.length>n)&&i.push("Reviewer finding list is invalid or exceeds maxFindings");for(let o of t?.findings??[]){try{un(o)}catch(r){i.push(r instanceof Error?r.message:String(r))}o.dimension!==e&&i.push(`Finding dimension ${o.dimension} differs from reviewer dimension ${e}`)}if(i.length>0)throw new b([...new Set(i)])}function un(t){let e=[];yn(t?.dimension)||e.push(`Invalid finding dimension ${t?.dimension}`),Z(t?.title,"finding title",e),Z(t?.summary,"finding summary",e),vn(t?.severity)||e.push(`Invalid finding severity ${t?.severity}`),(!Number.isFinite(t?.confidence)||t.confidence<0||t.confidence>1)&&e.push("Finding confidence must be 0 through 1"),(!Array.isArray(t?.anchors)||t.anchors.length===0)&&e.push("Finding needs at least one source or artifact anchor"),Array.isArray(t?.evidence)||e.push("Finding evidence must be an array");for(let n of t?.evidence??[])vt(n,e);if(t?.ruleId!==void 0&&O(t.ruleId,"ruleId",e),e.length>0)throw new b([...new Set(e)])}function Fi(t){let e=[];O(t?.verifierAgentId,"verifierAgentId",e),["reproduced","rejected","inconclusive"].includes(t?.outcome)||e.push("Verifier outcome is invalid"),Z(t?.rationale,"verifier rationale",e),Ve(t?.completedAt,"verifier completedAt",e),Array.isArray(t?.evidence)||e.push("Verifier evidence must be an array");for(let n of t?.evidence??[])vt(n,e);if(t?.outcome==="reproduced"&&(t?.evidence?.length??0)===0&&e.push("A reproduced finding requires verifier evidence"),t?.confidence!==void 0&&(!Number.isFinite(t.confidence)||t.confidence<0||t.confidence>1)&&e.push("Verifier confidence must be 0 through 1"),e.length>0)throw new b([...new Set(e)])}function vt(t,e){O(t?.evidenceId,"evidenceId",e),O(t?.producerId,"evidence producerId",e),Z(t?.summary,"evidence summary",e),(typeof t?.kind!="string"||!(pn.includes(t.kind)||U(t.kind)))&&e.push(`Invalid evidence kind ${t?.kind}`)}function ln(t){let e=new Map;for(let n of t){let i=[];if(vt(n,i),i.length>0)throw new b(i);let o=e.get(n.evidenceId);if(o&&C(o)!==C(n))throw new b([`Conflicting evidence ID ${n.evidenceId}`]);e.set(n.evidenceId,structuredClone(n))}return[...e.values()].sort((n,i)=>n.evidenceId.localeCompare(i.evidenceId))}function Li(t){let e=new Map;for(let n of t){if(e.has(n.verifierAgentId))throw new b([`Verifier ${n.verifierAgentId} returned more than one result for a finding`]);e.set(n.verifierAgentId,structuredClone(n))}return[...e.values()].sort((n,i)=>n.verifierAgentId.localeCompare(i.verifierAgentId))}function mn(t){let e=new Map;for(let n of t)e.set(hn(n),structuredClone(n));return[...e.entries()].sort(([n],[i])=>n.localeCompare(i)).map(([,n])=>n)}function hn(t){return C(t)}function gn(t){let e={info:0,low:0,medium:0,high:0,critical:0};for(let n of t)e[n.severity]+=1;return{total:t.length,verified:t.filter(n=>n.state==="verified").length,unverified:t.filter(n=>n.state==="unverified").length,rejected:t.filter(n=>n.state==="rejected").length,bySeverity:e}}function Mi(t,e){return se(e.severity)-se(t.severity)||+(e.state==="verified")-+(t.state==="verified")||t.fingerprint.localeCompare(e.fingerprint)}function se(t){return{info:0,low:1,medium:2,high:3,critical:4}[t]}function vn(t){return typeof t=="string"&&["info","low","medium","high","critical"].includes(t)}function yn(t){return typeof t=="string"&&(fn.includes(t)||U(t))}function Hi(t){return t.trim().toLowerCase().replace(/\s+/gu," ")}function An(t){return Math.max(0,Math.min(1,Number(t.toFixed(6))))}function O(t,e,n){(typeof t!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u.test(t))&&n.push(`${e} has an invalid identifier`)}function Oe(t,e){let n=[];if(O(t,e,n),n.length>0)throw new b(n);return t}function Z(t,e,n){(typeof t!="string"||t.trim().length===0||t.length>64*1024)&&n.push(`${e} must be non-empty and no longer than 65536 characters`)}function Ve(t,e,n){(typeof t!="string"||!t.includes("T")||!Number.isFinite(Date.parse(t)))&&n.push(`${e} must be an ISO 8601 timestamp`)}function ji(t,e){return t.algorithm===e.algorithm&&t.value===e.value}var Ae=require("node:buffer");function Bi(t,e){let n=e.contentEncoding??"utf8",i=n==="base64"?Ae.Buffer.from(t.content,"base64"):Ae.Buffer.from(t.content,"utf8"),o=[e.identity?.runId,e.identity?.taskId,e.identity?.turnId].filter(Boolean).join(":"),r=k(`${o}:${t.name}:${t.mimeType??""}:${t.content}`).value.slice(0,24),s={schemaVersion:1,artifactId:e.artifactId??`legacy_agent_artifact_${r}`,revision:e.revision??1,kind:e.kind??Ki(t),title:t.name,state:e.state??"draft",createdAt:e.createdAt??new Date().toISOString(),mediaType:t.mimeType??"text/plain",sensitivity:e.sensitivity??"internal",...e.identity?{identity:structuredClone(e.identity)}:{},content:{hash:k(i),sizeBytes:i.byteLength,encoding:n,storage:n==="base64"?{type:"inline",base64:t.content}:{type:"inline",text:t.content}},provenance:{producer:{...e.producer}},...e.accessPolicyId?{accessPolicyId:e.accessPolicyId}:{},extensions:{"xeno.legacy.agentArtifact":{name:t.name,...t.mimeType?{mimeType:t.mimeType}:{},content:t.content,encoding:n}}};return X(s),s}function qi(t){X(t);let e=t.extensions?.["xeno.legacy.agentArtifact"];if(yt(e)&&typeof e.name=="string"&&typeof e.content=="string")return{name:e.name,...typeof e.mimeType=="string"?{mimeType:e.mimeType}:{},content:e.content};if(t.content.storage.type!=="inline")throw new TypeError("Only inline XENO artifacts can be converted to legacy AgentArtifact values");return{name:t.title,mimeType:t.mediaType,content:t.content.storage.text??t.content.storage.base64??""}}function Ji(t,e){let n=In(t),i=C(n),o={schemaVersion:1,artifactId:e.artifactId??t.id,revision:e.revision??1,kind:Gi(t),title:t.path?`Evidence for ${t.path}`:`Tool evidence ${t.id}`,state:e.state??"draft",createdAt:e.createdAt??t.observedAt,mediaType:"application/vnd.xeno.tool-evidence+json",sensitivity:e.sensitivity??"internal",...e.identity?{identity:structuredClone(e.identity)}:{},content:{hash:N(n),sizeBytes:Ae.Buffer.byteLength(i,"utf8"),encoding:"utf8",storage:{type:"inline",text:i}},provenance:{producer:{...e.producer},operationId:t.operationId,attributes:{legacyEvidenceId:t.id,legacyEvidenceKind:t.kind,legacyEvidenceStatus:t.status}},...e.accessPolicyId?{accessPolicyId:e.accessPolicyId}:{},extensions:{"xeno.legacy.toolEvidence":n}};return X(o),o}function zi(t){X(t);let e=t.extensions?.["xeno.legacy.toolEvidence"];if(Yi(e))return structuredClone(e);throw new TypeError("XENO artifact does not contain lossless legacy ToolEvidence data")}function Ui(t,e){let n=In(t),i=t.files.map(s=>s.patch).filter(s=>!!s);if(t.files.length>0&&i.length===t.files.length&&i.every(s=>s.startsWith("diff --git ")))try{let s=ot(i.join(`
|
|
10
|
+
`),{artifactId:e.artifactId??`turn_diff_${t.turnId}`,revision:e.revision??1,createdAt:e.createdAt??t.completedAt,title:`Turn ${t.turnId} changes`,producer:e.producer,identity:{...e.identity?structuredClone(e.identity):{},turnId:e.identity?.turnId??t.turnId},sensitivity:e.sensitivity??"internal",...e.accessPolicyId?{accessPolicyId:e.accessPolicyId}:{},mode:"turn"}),d={...s,state:e.state??s.state,extensions:{...s.extensions??{},"xeno.legacy.turnDiffSummary":n}};return X(d),d}catch{}let o=C(n),r={schemaVersion:1,artifactId:e.artifactId??`turn_diff_${t.turnId}`,revision:e.revision??1,kind:"diff",title:`Turn ${t.turnId} changes`,state:e.state??"pending_review",createdAt:e.createdAt??t.completedAt,mediaType:"application/vnd.xeno.turn-diff+json",sensitivity:e.sensitivity??"internal",identity:{...e.identity?structuredClone(e.identity):{},turnId:e.identity?.turnId??t.turnId},content:{hash:N(n),sizeBytes:Ae.Buffer.byteLength(o,"utf8"),encoding:"utf8",storage:{type:"inline",text:o}},provenance:{producer:{...e.producer}},anchors:t.files.map(s=>({kind:"custom:source-file",data:{path:s.path}})),...e.accessPolicyId?{accessPolicyId:e.accessPolicyId}:{},extensions:{"xeno.legacy.turnDiffSummary":n}};return X(r),r}function Wi(t){X(t);let e=t.extensions?.["xeno.legacy.turnDiffSummary"];if(Zi(e))return structuredClone(e);throw new TypeError("XENO artifact does not contain lossless TurnDiffSummary data")}function Ki(t){let e=t.name.toLowerCase(),n=t.mimeType?.toLowerCase()??"";return e.endsWith(".patch")||n.includes("patch")?"patch":e.endsWith(".diff")||n.includes("diff")?"diff":n.startsWith("image/")?"screenshot":n.startsWith("video/")?"recording":n.includes("json")&&e.includes("report")?"test-report":"file"}function Gi(t){return t.kind==="artifact"?t.path?"file":"custom:tool-artifact-evidence":t.kind==="verification"?"test-report":"custom:tool-process-evidence"}function In(t){return JSON.parse(JSON.stringify(t))}function yt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Yi(t){return yt(t)?typeof t.id=="string"&&(t.kind==="artifact"||t.kind==="process"||t.kind==="verification")&&(t.status==="pending"||t.status==="verified"||t.status==="failed")&&typeof t.observedAt=="string"&&typeof t.operationId=="string":!1}function Zi(t){return yt(t)?typeof t.turnId=="string"&&typeof t.startedAt=="string"&&typeof t.completedAt=="string"&&Array.isArray(t.files):!1}var bt=require("node:crypto"),I=require("node:fs"),S=require("node:path"),Fe=require("node:crypto");var V="index.html",wn=16*1024*1024,Et=255,Qi={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".md":"text/markdown; charset=utf-8",".txt":"text/plain; charset=utf-8",".csv":"text/csv; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".pdf":"application/pdf",".wasm":"application/wasm"};function De(t){return Qi[(0,S.extname)(t).toLowerCase()]??"application/octet-stream"}function En(t){let e=t.slice(0,8192),i=/<title[^>]*>([\s\S]*?)<\/title>/iu.exec(e)?.[1]?.replace(/\s+/gu," ").trim();return i?i.slice(0,200):void 0}function Xt(t){let e=t.trim().replace(/\\/gu,"/");if(!e)return{error:"A file path is required."};if(e.startsWith("/")||/^[a-zA-Z]:/u.test(e))return{error:`File path must be relative: ${t}`};let n=e.split("/");return n.some(i=>i===""||i==="."||i==="..")?{error:`File path must not contain empty, "." or ".." segments: ${t}`}:n.some(i=>/[<>:"|?*\u0000-\u001f]/u.test(i))?{error:`File path contains characters a filesystem refuses: ${t}`}:n.join("/")===V?{error:`${V} is the page itself; supporting files need another path.`}:{path:n.join("/")}}function er(t){return(0,bt.createHash)("sha256").update(t).digest("hex")}function At(t){return typeof t=="string"?new TextEncoder().encode(t):t}function It(t,e){let n=`${t}.${process.pid}.${(0,Fe.randomUUID)().slice(0,8)}.tmp`;(0,I.writeFileSync)(n,e);try{(0,I.renameSync)(n,t)}catch(i){throw(0,I.rmSync)(n,{force:!0}),i}}function wt(t){let e=t.artifact.extensions?.page;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}var Rt=class{repository;directory;now;maxBytes;constructor(e){if(!e?.repository)throw new TypeError("XenoPageStore requires an artifact repository");if(typeof e.directory!="string"||!e.directory.trim())throw new TypeError("XenoPageStore requires a directory");this.repository=e.repository,this.directory=(0,S.resolve)(e.directory),this.now=e.now??(()=>new Date().toISOString()),this.maxBytes=e.maxBytes??wn}revisionDirectory(e,n){if(!/^[A-Za-z0-9_-]+$/u.test(e))throw new TypeError(`Unsafe artifact id: ${e}`);return(0,S.join)(this.directory,e,`r${n}`)}async publish(e){let n=typeof e.html=="string"?e.html:"";if(!n.trim())throw new TypeError("A page needs HTML content.");let i=new Map;for(let x of e.files??[]){let w=Xt(x.path);if("error"in w)throw new TypeError(w.error);if(i.has(w.path))throw new TypeError(`Duplicate file path: ${w.path}`);i.set(w.path,{bytes:At(x.bytes),contentType:x.contentType??De(w.path)})}if(i.size>Et)throw new TypeError(`A page may carry at most ${Et} files.`);let o=At(n),r=o.byteLength+[...i.values()].reduce((x,w)=>x+w.bytes.byteLength,0);if(r>this.maxBytes)throw new TypeError(`Page revision is ${r} bytes; the limit is ${this.maxBytes}.`);let s=(0,bt.createHash)("sha256").update(o),d={};for(let[x,w]of[...i.entries()].sort(([J],[Ie])=>J.localeCompare(Ie)))d[x]={sha256:er(w.bytes),sizeBytes:w.bytes.byteLength,contentType:w.contentType},s.update(`\0${x}\0${d[x].sha256}`);let a=s.digest("hex"),c=e.artifactId?await this.repository.get(e.artifactId):void 0;if(e.artifactId&&!c)throw new TypeError(`Unknown page artifact ${e.artifactId}.`);if(c&&c.artifact.kind!=="page")throw new TypeError(`Artifact ${e.artifactId} is a ${c.artifact.kind}, not a page.`);if(c&&c.artifact.content.hash.value===a)return{...await this.toPublished(c),unchanged:!0};let f=c?.artifact.artifactId??`page_${(0,Fe.randomUUID)().replaceAll("-","").slice(0,20)}`,g=c?c.artifact.revision+1:1,y=this.revisionDirectory(f,g);(0,I.mkdirSync)(y,{recursive:!0});let D=(0,S.join)(y,V);It(D,o);for(let[x,w]of i){let J=(0,S.join)(y,...x.split("/"));(0,I.mkdirSync)((0,S.join)(J,".."),{recursive:!0}),It(J,w.bytes)}let m=c?wt(c):{},h=e.title?.trim()||En(n)||(typeof m.title=="string"?m.title:void 0)||"Untitled page",_=e.icon?.trim()||(typeof m.icon=="string"?m.icon:void 0),B=e.description?.trim()||c?.artifact.description,Q=Array.isArray(m.publications)?m.publications:[],ee=this.now(),q={schemaVersion:1,artifactId:f,revision:g,kind:"page",title:h,...B?{description:B}:{},state:"draft",createdAt:c?.artifact.createdAt??ee,updatedAt:ee,mediaType:"text/html",sensitivity:c?.artifact.sensitivity??"internal",...e.identity??c?.artifact.identity?{identity:e.identity??c.artifact.identity}:{},content:{hash:{algorithm:"sha256",value:a},sizeBytes:r,storage:{type:"file",path:D},encoding:"utf8",redactedPreview:n.slice(0,200)},provenance:{producer:e.producer},...c?{predecessorRevision:c.artifact.revision}:{},extensions:{page:{entry:V,htmlSha256:k(o).value,files:d,..._?{icon:_}:{},title:h,publications:Q,...e.home?{requestedHome:e.home}:{}}}},F=c?await this.repository.createRevision(q,{actor:e.producer,reason:"page republished"}):await this.repository.create(q);return this.toPublished(F)}async recordPublication(e,n){let i=await this.repository.require(e),o=wt(i),s=(await this.toPublished(i)).publications.filter(a=>a.home!==n.home);s.push(n);let d={...i.artifact,revision:i.artifact.revision,extensions:{...i.artifact.extensions,page:{...o,publications:s}}};return this.writeSidecar(e,{publications:s}),this.toPublished({...i,artifact:d})}sidecarPath(e){return(0,S.join)(this.directory,e,"publications.json")}writeSidecar(e,n){(0,I.mkdirSync)((0,S.join)(this.directory,e),{recursive:!0}),It(this.sidecarPath(e),At(`${JSON.stringify(n,null,2)}
|
|
11
|
+
`))}readSidecar(e){try{let n=JSON.parse((0,I.readFileSync)(this.sidecarPath(e),"utf8"));return Array.isArray(n.publications)?n.publications:[]}catch{return[]}}async get(e,n){let i=await this.repository.get(e,n);if(!(!i||i.artifact.kind!=="page"))return this.toPublished(i)}async list(){let e=await this.repository.list({kinds:["page"]});return(await Promise.all(e.map(i=>this.toPublished(i)))).sort((i,o)=>(o.updatedAt??o.createdAt).localeCompare(i.updatedAt??i.createdAt))}resolveFile(e,n,i){let o=i===V||i===""?{path:V}:Xt(i);if("error"in o)return;let r=this.revisionDirectory(e,n),s=(0,S.resolve)(r,...o.path.split("/"));if(!(s!==r&&!s.startsWith(r+S.sep))&&!(!(0,I.existsSync)(s)||!(0,I.statSync)(s).isFile()))return{path:s,contentType:De(s)}}readEntry(e,n){let i=this.resolveFile(e,n,V);return i?(0,I.readFileSync)(i.path,"utf8"):void 0}readRevision(e,n){let i=this.revisionDirectory(e,n),o=(0,I.readFileSync)((0,S.join)(i,V),"utf8"),r=[],s=(d,a)=>{for(let c of(0,I.readdirSync)(d,{withFileTypes:!0})){let f=a?`${a}/${c.name}`:c.name;c.isDirectory()?s((0,S.join)(d,c.name),f):f!==V&&r.push({path:f,bytes:(0,I.readFileSync)((0,S.join)(d,c.name)),contentType:De(f)})}};return s(i,""),{html:o,files:r}}async addComment(e,n,i,o){let r=await this.repository.require(e);if(r.artifact.kind!=="page")throw new TypeError(`Artifact ${e} is a ${r.artifact.kind}, not a page.`);let s=n.trim();if(!s)throw new TypeError("A comment needs text.");let a=(await this.repository.appendReviewEvent({event:{type:"comment-added",artifactId:e,artifactRevision:r.artifact.revision,artifactHash:r.artifact.content.hash,actor:i,commentId:`cmt_${(0,Fe.randomUUID)().replaceAll("-","").slice(0,16)}`,body:s.slice(0,2e4),...o?{anchor:o}:{}}})).reviewEvents.at(-1);if(!a||a.type!=="comment-added")throw new Error("Comment was not recorded.");return a}async listComments(e){await this.repository.require(e);let n=await this.repository.listRevisions(e),i=new Set,o=[];for(let r of n)for(let s of r.reviewEvents)s.type!=="comment-added"||i.has(s.commentId)||(i.add(s.commentId),o.push(s));return o.sort((r,s)=>r.recordedAt.localeCompare(s.recordedAt)||r.sequence-s.sequence)}async toPublished(e){let n=wt(e),i=n.files&&typeof n.files=="object"&&!Array.isArray(n.files)?n.files:{},o=this.readSidecar(e.artifact.artifactId),s=[...(Array.isArray(n.publications)?n.publications:[]).filter(d=>!o.some(a=>a.home===d.home)),...o];return{artifactId:e.artifact.artifactId,revision:e.artifact.revision,title:e.artifact.title,...e.artifact.description?{description:e.artifact.description}:{},...typeof n.icon=="string"?{icon:n.icon}:{},hash:e.artifact.content.hash.value,sizeBytes:e.artifact.content.sizeBytes,files:i,directory:this.revisionDirectory(e.artifact.artifactId,e.artifact.revision),entryPath:(0,S.join)(this.revisionDirectory(e.artifact.artifactId,e.artifact.revision),V),publications:s,createdAt:e.artifact.createdAt,...e.artifact.updatedAt?{updatedAt:e.artifact.updatedAt}:{}}}};0&&(module.exports={FileXenoArtifactRepository,InMemoryXenoArtifactRepository,XENO_ARTIFACT_ACTOR_KINDS,XENO_ARTIFACT_FILE_REPOSITORY_SCHEMA_VERSION,XENO_ARTIFACT_SCHEMA_VERSION,XENO_ARTIFACT_SENSITIVITIES,XENO_ARTIFACT_STATES,XENO_BUILTIN_ARTIFACT_KINDS,XENO_EVIDENCE_EDGE_TYPES,XENO_EVIDENCE_GRAPH_SCHEMA_VERSION,XENO_EVIDENCE_NODE_TYPES,XENO_PAGE_ENTRY,XENO_PAGE_MAX_BYTES,XENO_PAGE_MAX_FILES,XENO_REVIEW_DIMENSIONS,XENO_REVIEW_EVIDENCE_KINDS,XENO_REVIEW_REPORT_SCHEMA_VERSION,XENO_SPEC_EXECUTION_SCHEMA_VERSION,XENO_SPEC_SCHEMA_VERSION,XenoArtifactRepositoryError,XenoArtifactReviewService,XenoArtifactStateTransitionError,XenoArtifactValidationError,XenoDiffParseError,XenoEvidenceGraphBuilder,XenoEvidenceGraphValidationError,XenoMultiAgentReviewCoordinator,XenoPageStore,XenoReviewValidationError,XenoSpecLifecycleService,XenoSpecValidationError,assertValidXenoArtifact,assertValidXenoEvidenceGraph,assertValidXenoReviewPack,assertValidXenoReviewReport,assertValidXenoReviewTarget,assertValidXenoSpecDocument,assertValidXenoSpecExecution,assertXenoArtifactStateTransition,buildXenoArtifactReviewAnchor,canTransitionXenoArtifactState,canonicalizeArtifactJson,defaultXenoReviewPack,detectXenoSpecDrift,extractPageTitle,legacyAgentArtifactToXenoArtifact,normalizePagePath,normalizeRepositoryRelativePath,pageContentType,parseUnifiedDiff,sha256ArtifactBytes,sha256ArtifactJson,summarizeXenoArtifactReview,toolEvidenceToXenoArtifact,turnDiffSummaryToXenoArtifact,unifiedDiffToXenoArtifact,validateXenoArtifact,validateXenoArtifactReviewEvent,validateXenoEvidenceGraph,validateXenoSpecDocument,xenoArtifactToDiffDocument,xenoArtifactToLegacyAgentArtifact,xenoArtifactToReviewReport,xenoArtifactToSpecDocument,xenoArtifactToSpecExecution,xenoArtifactToToolEvidence,xenoArtifactToTurnDiffSummary,xenoReviewReportToArtifact,xenoReviewReportToGitHubComments,xenoSpecArtifactIds,xenoSpecExecutionToArtifact,xenoSpecToArtifactBundle});
|