dic-workflow-kit 1.1.3 → 1.1.4
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/.codex-plugin/plugin.json +14 -10
- package/CHANGELOG.md +56 -1
- package/INSTRUCTION.md +108 -29
- package/README.md +234 -134
- package/README.zh-CN.md +280 -194
- package/adapters/bitfun/README.md +2 -2
- package/agents/adversarial-challenger.md +23 -0
- package/agents/code-repairer.md +1 -1
- package/agents/contract-oracle.md +1 -1
- package/agents/evidence-auditor.md +23 -0
- package/agents/final-reviewer.md +13 -2
- package/agents/flow-auditor.md +1 -1
- package/agents/impact-analyst.md +21 -0
- package/agents/impl-inspector.md +1 -1
- package/agents/profile-builder.md +7 -3
- package/agents/repair-planner.md +1 -1
- package/agents/semantic-conflict-auditor.md +21 -0
- package/agents/spec-reader.md +1 -1
- package/agents/validation-runner.md +1 -1
- package/dist/dic-workflow-kit.mjs +17 -13
- package/package.json +5 -2
- package/schemas/final-result.schema.json +16 -1
- package/schemas/harness-plan.schema.json +143 -0
- package/schemas/harness-run.schema.json +75 -0
- package/schemas/ontology-action.schema.json +9 -1
- package/schemas/ontology-snapshot.schema.json +75 -1
- package/schemas/project-profile.schema.json +42 -0
- package/skills/knowledge-bdd/SKILL.md +1 -1
- package/skills/knowledge-change-impact/SKILL.md +43 -0
- package/skills/knowledge-change-impact/agents/openai.yaml +4 -0
- package/skills/knowledge-openspec/SKILL.md +1 -1
- package/skills/knowledge-repair-distill/SKILL.md +1 -1
- package/skills/quality-adversarial-challenge/SKILL.md +42 -0
- package/skills/quality-adversarial-challenge/agents/openai.yaml +4 -0
- package/skills/quality-ci-gate/SKILL.md +45 -0
- package/skills/quality-ci-gate/agents/openai.yaml +4 -0
- package/skills/quality-ci-gate/references/ci-gate.md +22 -0
- package/skills/quality-code-review/SKILL.md +32 -0
- package/skills/quality-code-review/agents/openai.yaml +4 -0
- package/skills/quality-code-review/references/code-review.md +13 -0
- package/skills/quality-cross-spec-consistency/SKILL.md +45 -0
- package/skills/quality-cross-spec-consistency/agents/openai.yaml +4 -0
- package/skills/quality-dt-review/SKILL.md +32 -0
- package/skills/quality-dt-review/agents/openai.yaml +4 -0
- package/skills/quality-dt-review/references/dt-review.md +14 -0
- package/skills/quality-evidence-audit/SKILL.md +41 -0
- package/skills/quality-evidence-audit/agents/openai.yaml +4 -0
- package/skills/quality-repository-gate/SKILL.md +38 -0
- package/skills/quality-repository-gate/agents/openai.yaml +4 -0
- package/skills/quality-repository-gate/references/repository-gate.md +13 -0
- package/skills/quality-review-orchestrator/SKILL.md +100 -0
- package/skills/quality-review-orchestrator/agents/openai.yaml +4 -0
- package/skills/quality-review-orchestrator/references/quality-model.md +73 -0
- package/skills/quality-spec-review/SKILL.md +40 -0
- package/skills/quality-spec-review/agents/openai.yaml +4 -0
- package/skills/quality-spec-review/references/spec-review.md +14 -0
- package/skills/quality-sr-ar-review/SKILL.md +32 -0
- package/skills/quality-sr-ar-review/agents/openai.yaml +4 -0
- package/skills/quality-sr-ar-review/references/sr-ar-review.md +14 -0
- package/skills/workflow-core/SKILL.md +49 -2
- package/skills/workflow-harness/SKILL.md +73 -0
- package/skills/workflow-harness/agents/openai.yaml +4 -0
- package/skills/workflow-intake/SKILL.md +8 -2
- package/skills/workflow-profile/SKILL.md +16 -1
- package/skills/workflow-repair/SKILL.md +7 -4
|
@@ -1,18 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createHash as Be}from"node:crypto";import{mkdir as ce,lstat as ye,readFile as q,readdir as Ge,rename as me,rm as B,rmdir as St,stat as Je,writeFile as le}from"node:fs/promises";import{homedir as V}from"node:os";import{dirname as M,isAbsolute as Ye,join as w,relative as ze,resolve as E,sep as vt}from"node:path";import{fileURLToPath as At}from"node:url";import{createHash as Ne}from"node:crypto";import{appendFile as lt,readFile as ne,realpath as Pe,stat as dt}from"node:fs/promises";import{isAbsolute as pt,relative as ut,resolve as Y}from"node:path";var ft=new Map([["workflow-intake",new Set(["IntakeDesignSource"])],["spec-reader",new Set(["IntakeDesignSource"])],["contract-oracle",new Set(["ConfirmObligation"])],["impl-inspector",new Set(["ObserveImplementation","OpenGap"])],["repair-planner",new Set(["ProposeRepair"])],["final-reviewer",new Set(["ApproveRepair","CloseGap","MarkBlocked","SupersedeSource"])],["code-repairer",new Set(["ApplyRepair"])],["validation-runner",new Set(["RunValidation","AttachEvidence"])]]),$e=new Map([["IntakeDesignSource",new Set(["Project","DesignSource","Change"])],["ConfirmObligation",new Set(["Requirement","Scenario"])],["ObserveImplementation",new Set(["Requirement","Scenario"])],["OpenGap",new Set(["Requirement","Scenario"])],["ProposeRepair",new Set(["Gap"])],["ApproveRepair",new Set(["RepairAction"])],["ApplyRepair",new Set(["RepairAction"])],["RunValidation",new Set(["Requirement","Scenario","RepairAction"])],["AttachEvidence",new Set(["Validation"])],["CloseGap",new Set(["Gap"])],["MarkBlocked",new Set(["Gap","RepairAction","Validation"])],["SupersedeSource",new Set(["DesignSource","Change","Requirement","Scenario"])]]),ht=new Set(["ApplyRepair","RunValidation","AttachEvidence","ObserveImplementation","CloseGap","MarkBlocked","SupersedeSource"]),yt=new Map([["IntakeDesignSource",{objectTypes:new Set(["DesignSource","Change"]),linkTypes:new Set(["CONTAINS"]),lifecycle:new Set(["draft","active"])}],["ConfirmObligation",{objectTypes:new Set,linkTypes:new Set,lifecycle:new Set(["confirmed"])}],["OpenGap",{objectTypes:new Set(["Gap"]),linkTypes:new Set(["VIOLATES"]),lifecycle:new Set}],["ObserveImplementation",{objectTypes:new Set(["ImplementationUnit"]),linkTypes:new Set(["IMPLEMENTED_BY"]),lifecycle:new Set}],["ProposeRepair",{objectTypes:new Set(["RepairAction"]),linkTypes:new Set(["RESOLVES"]),lifecycle:new Set}],["ApproveRepair",{objectTypes:new Set,linkTypes:new Set,lifecycle:new Set(["approved"])}],["ApplyRepair",{objectTypes:new Set(["ImplementationUnit"]),linkTypes:new Set(["IMPLEMENTED_BY"]),lifecycle:new Set(["in_progress","resolved"])}],["RunValidation",{objectTypes:new Set(["Validation"]),linkTypes:new Set(["VERIFIED_BY"]),lifecycle:new Set}],["AttachEvidence",{objectTypes:new Set(["Evidence"]),linkTypes:new Set(["PRODUCES"]),lifecycle:new Set}],["CloseGap",{objectTypes:new Set,linkTypes:new Set,lifecycle:new Set(["resolved"])}],["MarkBlocked",{objectTypes:new Set,linkTypes:new Set,lifecycle:new Set(["blocked"])}],["SupersedeSource",{objectTypes:new Set(["DesignSource","Change","Requirement","Scenario"]),linkTypes:new Set(["SUPERSEDES"]),lifecycle:new Set(["superseded"])}]]);function N(e,t,n,i,o=[]){return{id:e,status:t===null?"NOT_APPLICABLE":t?"PASS":"FAIL",severity:n,message:i,objectIds:[...new Set(o)].sort()}}function C(e){return Array.isArray(e)?e.map(C):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,C(e[t])])):e}function ue(e){let t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!["snapshotRevision","invariantResults"].includes(n)));return Ne("sha256").update(JSON.stringify(C(t))).digest("hex")}function mt(e,t){let n=Array.isArray(e?.objects)?e.objects:[],i=Array.isArray(e?.links)?e.links:[],o=new Map(n.map(l=>[l.id,l])),a=new Set,c=[...t];for(;c.length>0;){let l=c.pop(),p=o.get(l);if(p){if(["Requirement","Scenario"].includes(p.type)){if(a.has(l))continue;if(a.add(l),p.type==="Scenario")for(let s of i)s.type==="REFINES"&&s.from===l&&c.push(s.to)}else if(p.type==="RepairAction"){let s=new Set(i.filter(r=>r.type==="RESOLVES"&&r.from===l).map(r=>r.to));for(let r of i)r.type==="VIOLATES"&&s.has(r.from)&&c.push(r.to)}}}return a}function Ce(e,t){let n=Array.isArray(e?.objects)?e.objects:[],i=Array.isArray(e?.links)?e.links:[],o=new Map(n.map(l=>[l.id,l])),a=mt(e,t),c=new Set;for(let l of i)if(a.has(l.from)&&["DERIVED_FROM","IMPLEMENTED_BY"].includes(l.type)){let p=o.get(l.to);["DesignSource","ImplementationUnit"].includes(p?.type)&&c.add(l.to)}return[...c].sort().map(l=>({objectId:l,contentHash:o.get(l)?.provenance?.contentHash??""}))}function z(e){let t=Array.isArray(e?.objects)?e.objects:[],n=Array.isArray(e?.links)?e.links:[];return t.filter(o=>o.type==="Validation").map(o=>{let a=n.filter(I=>I.type==="VERIFIED_BY"&&I.to===o.id).map(I=>I.from),c=a.length>0,l=Ce(e,a),p=Array.isArray(o.properties?.inputs)?o.properties.inputs:[],s=new Map,r=[];for(let I of p)s.has(I?.objectId)?r.push(I?.objectId):s.set(I?.objectId,I?.contentHash);let d=l.filter(I=>!s.has(I.objectId)).map(I=>I.objectId),m=l.filter(I=>s.has(I.objectId)&&s.get(I.objectId)!==I.contentHash).map(I=>I.objectId),h=typeof o.properties?.executedAt!="string"||Number.isNaN(Date.parse(o.properties.executedAt)),S="CURRENT";return r.length>0||h?S="INVALID":m.length>0?S="STALE":d.length>0&&(S="INCOMPLETE"),{id:o.id,required:c,status:S,targetIds:[...new Set(a)].sort(),requiredInputIds:l.map(I=>I.objectId),missingInputIds:d,staleInputIds:m,duplicateInputIds:r}})}function oe(e,t=""){let n=Array.isArray(e?.objects)?e.objects:[],i=Array.isArray(e?.links)?e.links:[],o=n.map(u=>u.id),a=new Map(n.map(u=>[u.id,u])),c=new Set(o),l=[...new Set(o.filter((u,L)=>o.indexOf(u)!==L))],p=[N("ontology.snapshot.schema",e?.schema==="dic.ontology-snapshot.v1","blocking","Ontology snapshot must declare dic.ontology-snapshot.v1."),N("ontology.snapshot.revision",e?.snapshotRevision?e.snapshotRevision===ue(e):null,"blocking","Snapshot revision must match its canonical semantic content."),N("ontology.object-ids.unique",l.length===0,"blocking","Every ontology object must have a unique stable ID.",l)],s=i.filter(u=>!c.has(u.from)||!c.has(u.to)).map(u=>u.id);p.push(N("ontology.links.resolve",s.length===0,"blocking","Every link endpoint must resolve to an object in the snapshot.",s));let r=new Map([["CONTAINS",[new Set(["Project"]),null]],["PROPOSES",[new Set(["Change"]),new Set(["Requirement","Scenario"])]],["DERIVED_FROM",[new Set(["Requirement","Scenario"]),new Set(["DesignSource"])]],["REFINES",[new Set(["Scenario"]),new Set(["Requirement"])]],["IMPLEMENTED_BY",[new Set(["Requirement","Scenario"]),new Set(["ImplementationUnit"])]],["VERIFIED_BY",[new Set(["Requirement","Scenario","RepairAction"]),new Set(["Validation"])]],["VIOLATES",[new Set(["Gap"]),new Set(["Requirement","Scenario"])]],["RESOLVES",[new Set(["RepairAction"]),new Set(["Gap"])]],["PRODUCES",[new Set(["Validation","AgentRun"]),new Set(["Evidence"])]],["SUPPORTS",[new Set(["Evidence"]),new Set(["Decision"])]],["CONTRADICTS",[new Set(["Evidence"]),new Set(["Decision"])]],["REMAINS_AFTER",[new Set(["Risk"]),new Set(["RepairAction"])]]]),d=[];for(let u of i){let L=a.get(u.from),de=a.get(u.to);if(!L||!de)continue;let pe=!1;if(u.type==="SUPERSEDES")pe=L.type===de.type;else{let ee=r.get(u.type);pe=!!(ee&&ee[0].has(L.type)&&(ee[1]===null||ee[1].has(de.type)))}pe||d.push(u.id)}p.push(N("ontology.links.type-compatible",d.length===0,"blocking","Every link must satisfy its object-type domain and range contract.",d));let m=n.filter(u=>["Requirement","Scenario"].includes(u.type)&&["confirmed","active"].includes(u.lifecycle)),h=new Set(i.filter(u=>u.type==="DERIVED_FROM").map(u=>u.from)),S=m.filter(u=>!h.has(u.id)).map(u=>u.id);p.push(N("obligation.active.has-source",S.length===0,"blocking","Every active obligation must link to a source-backed design object.",S));let I=new Set(i.filter(u=>u.type==="REFINES").map(u=>u.from)),v=m.filter(u=>u.type==="Scenario"&&!I.has(u.id)).map(u=>u.id);p.push(N("scenario.active.refines-requirement",v.length===0,"blocking","Every active scenario must refine a requirement.",v));let y=n.filter(u=>u.type==="Gap"&&u.lifecycle==="resolved"),f=new Map(i.filter(u=>u.type==="RESOLVES").map(u=>[u.to,u.from])),k=new Set(n.filter(u=>u.type==="Validation"&&["active","confirmed","resolved"].includes(u.lifecycle)&&u.properties?.status==="PASS").map(u=>u.id)),P=i.filter(u=>u.type==="VERIFIED_BY"),A=new Set(P.filter(u=>k.has(u.to)).map(u=>u.from)),g=y.filter(u=>{let L=f.get(u.id);return!L||!A.has(L)}).map(u=>u.id);p.push(N("gap.resolved.has-verified-repair",g.length===0,"blocking","Every resolved gap must have a resolving repair action with validation.",g));let b=t.toUpperCase()==="PASS";p.push(N("pass.obligations.nonempty",b?m.length>0:null,"blocking","PASS requires at least one active, source-backed obligation."));let D=new Set(n.filter(u=>u.type==="ImplementationUnit"&&["active","confirmed","resolved"].includes(u.lifecycle)).map(u=>u.id)),Ae=i.filter(u=>u.type==="IMPLEMENTED_BY"),at=new Set(Ae.filter(u=>D.has(u.to)).map(u=>u.from)),Ie=Ae.filter(u=>!D.has(u.to)).map(u=>u.to);p.push(N("pass.implementations.current",b?Ie.length===0:null,"blocking","PASS requires every referenced ImplementationUnit to have a current lifecycle.",b?Ie:[]));let ke=m.filter(u=>u.type==="Requirement"&&!at.has(u.id)).map(u=>u.id);p.push(N("pass.requirements.implemented",b?ke.length===0:null,"blocking","PASS requires every active requirement to have an implementation disposition.",b?ke:[]));let Ee=m.filter(u=>!A.has(u.id)).map(u=>u.id);p.push(N("pass.obligations.verified",b?Ee.length===0:null,"blocking","PASS requires every active obligation to link to validation evidence.",b?Ee:[]));let be=P.filter(u=>!k.has(u.to)).map(u=>u.to);p.push(N("pass.validations.successful",b?be.length===0:null,"blocking","PASS requires every referenced Validation to be active and successful.",b?be:[]));let Re=z(e).filter(u=>u.required&&u.status!=="CURRENT").map(u=>u.id);p.push(N("pass.validations.inputs-current",b?Re.length===0:null,"blocking","PASS requires every referenced Validation to bind the current design and implementation content hashes.",b?Re:[]));let rt=new Set(P.filter(u=>k.has(u.to)).map(u=>u.to)),ct=new Set(i.filter(u=>u.type==="PRODUCES").map(u=>u.from)),je=[...rt].filter(u=>!ct.has(u));p.push(N("pass.validations.have-evidence",b?je.length===0:null,"blocking","PASS requires every referenced validation to produce durable evidence.",b?je:[]));let Oe=n.filter(u=>u.type==="Gap"&&!["resolved","rejected","superseded"].includes(u.lifecycle)&&u.properties?.severity==="blocking").map(u=>u.id);return p.push(N("pass.gaps.no-open-blocking",b?Oe.length===0:null,"blocking","PASS is forbidden while a blocking gap remains open.",b?Oe:[])),p}function G(e){return String(e??"").trim().toLowerCase()}function J(e,t){let n=ut(Y(t),Y(e));return n===""||!n.startsWith("..")&&!pt(n)}async function ie(e,t,n){let i=Y(e,t);if(!J(i,e))return{status:"OUTSIDE_PROJECT",actual:""};try{let[o,a]=await Promise.all([Pe(e),Pe(i)]);if(!J(a,o))return{status:"OUTSIDE_PROJECT",actual:""};if(!(await dt(a)).isFile())return{status:"INVALID",actual:""};let c=H(await ne(a));return{status:c===n?"UNCHANGED":"CHANGED",actual:c}}catch(o){if(o?.code==="ENOENT")return{status:"MISSING",actual:""};throw o}}function gt(e,t){let n=[],i=e?.parameters?.ontologyPatch;if(e?.status!=="completed")return i&&n.push("ontologyPatch is materialized only by a completed action"),n;if(!i||typeof i!="object"||Array.isArray(i))return["completed action requires parameters.ontologyPatch"];let o=Array.isArray(i.addObjects)?i.addObjects:[],a=Array.isArray(i.addLinks)?i.addLinks:[],c=Array.isArray(i.lifecycleTransitions)?i.lifecycleTransitions:[];o.length+a.length+c.length===0&&n.push("completed action ontologyPatch must contain at least one effect");let l=yt.get(e.type);if(!l)return[...n,`no ontology patch rule for ${e.type}`];let p=new Map((Array.isArray(t?.objects)?t.objects:[]).map(f=>[f.id,f])),s=new Map;for(let f of o){if(!f?.id||!f?.type){n.push("added ontology object requires id and type");continue}if(l.objectTypes.has(f.type)||n.push(`${e.type} cannot add object type ${f.type}`),(p.has(f.id)||s.has(f.id))&&n.push(`added ontology object ID already exists: ${f.id}`),G(f?.provenance?.createdBy)!==G(e.actor)&&n.push(`added object provenance actor mismatch: ${f.id}`),["AttachEvidence","ApplyRepair","ObserveImplementation"].includes(e.type)&&["Evidence","ImplementationUnit"].includes(f.type)){let k=f.type;(typeof f?.properties?.path!="string"||!f.properties.path)&&n.push(`${k} requires a project-relative artifact path: ${f.id}`),/^[a-f0-9]{64}$/u.test(f?.provenance?.contentHash??"")||n.push(`${k} requires a SHA-256 provenance contentHash: ${f.id}`),f?.interfaces?.includes("ContentAddressed")||n.push(`${k} requires the ContentAddressed interface: ${f.id}`)}s.set(f.id,f)}if(e.type==="RunValidation"){let f=Ce(t,e.targets);for(let k of s.values()){if(k.type!=="Validation")continue;["PASS","FAIL","BLOCKED"].includes(k.properties?.status)||n.push(`Validation requires status PASS, FAIL, or BLOCKED: ${k.id}`),(typeof k.properties?.executedAt!="string"||Number.isNaN(Date.parse(k.properties.executedAt)))&&n.push(`Validation requires a valid executedAt timestamp: ${k.id}`);let P=k.properties?.inputs;if(!Array.isArray(P)){n.push(`Validation requires an inputs array: ${k.id}`);continue}let A=P.map(g=>g?.objectId);new Set(A).size!==A.length&&n.push(`Validation inputs must use unique objectId values: ${k.id}`);for(let g of P)(typeof g?.objectId!="string"||!/^[a-f0-9]{64}$/u.test(g?.contentHash??""))&&n.push(`Validation input requires objectId and SHA-256 contentHash: ${k.id}`);if(k.properties?.status==="PASS"){let g=new Map(P.map(D=>[D?.objectId,D?.contentHash])),b=f.filter(D=>g.get(D.objectId)!==D.contentHash);b.length>0&&n.push(`PASS Validation must bind current design and implementation inputs: ${k.id} (${b.map(D=>D.objectId).join(", ")})`)}}}let r=new Set((Array.isArray(t?.links)?t.links:[]).map(f=>f.id)),d=new Set,m=new Set([...p.keys(),...s.keys()]),h=Array.isArray(t?.links)?t.links:[],S=new Set(e.targets),I=new Set(h.filter(f=>f.type==="RESOLVES"&&S.has(f.from)).map(f=>f.to)),v=new Set(h.filter(f=>f.type==="VIOLATES"&&I.has(f.from)).map(f=>f.to));for(let f of a){if(!f?.id||!f?.type){n.push("added ontology link requires id and type");continue}l.linkTypes.has(f.type)||n.push(`${e.type} cannot add link type ${f.type}`),(r.has(f.id)||d.has(f.id))&&n.push(`added ontology link ID already exists: ${f.id}`),(!m.has(f.from)||!m.has(f.to))&&n.push(`added ontology link endpoint does not resolve: ${f.id}`),G(f?.provenance?.createdBy)!==G(e.actor)&&n.push(`added link provenance actor mismatch: ${f.id}`);let k=s.get(f.from)?.type,P=s.get(f.to)?.type;e.type==="OpenGap"&&(k!=="Gap"||!S.has(f.to))?n.push(`OpenGap VIOLATES must connect a new Gap to an action target: ${f.id}`):e.type==="ObserveImplementation"&&(!S.has(f.from)||P!=="ImplementationUnit")?n.push(`ObserveImplementation IMPLEMENTED_BY must connect a target obligation to a new ImplementationUnit: ${f.id}`):e.type==="ProposeRepair"&&(k!=="RepairAction"||!S.has(f.to))?n.push(`ProposeRepair RESOLVES must connect a new RepairAction to a target Gap: ${f.id}`):e.type==="ApplyRepair"&&(!v.has(f.from)||P!=="ImplementationUnit")?n.push(`ApplyRepair IMPLEMENTED_BY is outside the targeted repair obligation: ${f.id}`):e.type==="RunValidation"&&(!S.has(f.from)||P!=="Validation")?n.push(`RunValidation VERIFIED_BY must connect a target to a new Validation: ${f.id}`):e.type==="AttachEvidence"&&(!S.has(f.from)||P!=="Evidence")?n.push(`AttachEvidence PRODUCES must connect a target Validation to new Evidence: ${f.id}`):e.type==="SupersedeSource"&&!S.has(f.to)&&n.push(`SupersedeSource SUPERSEDES must point to an action target: ${f.id}`),d.add(f.id)}for(let f of c)e.targets.includes(f?.objectId)||n.push(`lifecycle transition is outside action targets: ${f?.objectId}`),p.has(f?.objectId)?p.get(f.objectId)?.lifecycle===f?.to&&n.push(`lifecycle transition is a no-op: ${f.objectId}`):n.push(`lifecycle transition target does not resolve: ${f?.objectId}`),l.lifecycle.has(f?.to)||n.push(`${e.type} cannot transition lifecycle to ${f?.to}`);let y={IntakeDesignSource:[1,0,0],ConfirmObligation:[0,0,1],ObserveImplementation:[1,1,0],OpenGap:[1,1,0],ProposeRepair:[1,1,0],ApproveRepair:[0,0,1],ApplyRepair:[1,1,0],RunValidation:[1,1,0],AttachEvidence:[1,1,0],CloseGap:[0,0,1],MarkBlocked:[0,0,1],SupersedeSource:[0,0,1]}[e.type];return(o.length<y[0]||a.length<y[1]||c.length<y[2])&&n.push(`${e.type} ontologyPatch is missing its required semantic effects`),n}function fe(e,t,n,i){let o=[];e?.schema!=="dic.ontology-action.v1"&&o.push("action schema must be dic.ontology-action.v1"),/^act-[a-zA-Z0-9._:-]+$/u.test(e?.id??"")||o.push("action ID must use the act- stable-ID format"),e?.expectedSnapshotRevision!==void 0&&e.expectedSnapshotRevision!==t?.snapshotRevision&&o.push("action expectedSnapshotRevision does not match the current snapshot"),$e.has(e?.type)||o.push(`unsupported action type: ${e?.type??"<missing>"}`),["proposed","approved","in_progress","completed","rejected","blocked","rolled_back"].includes(e?.status)||o.push(`unsupported action status: ${e?.status??"<missing>"}`);let a=G(e?.actor);ft.get(a)?.has(e?.type)||o.push(`actor ${e?.actor??"<missing>"} cannot perform ${e?.type??"<missing>"}`);let l=new Map((Array.isArray(t?.objects)?t.objects:[]).map(s=>[s.id,s]));if(!Array.isArray(e?.targets)||e.targets.length===0)o.push("action must target at least one ontology object");else{new Set(e.targets).size!==e.targets.length&&o.push("action targets must be unique");let s=$e.get(e.type);for(let r of e.targets){let d=l.get(r);d?s?.has(d.type)||o.push(`${e.type} cannot target ${d.type}: ${r}`):o.push(`target does not resolve: ${r}`)}}let p=["completed","blocked","rolled_back"].includes(e?.status);if(e?.status==="completed")for(let[s,r]of[["preconditions","precondition"],["postconditions","postcondition"]])(!Array.isArray(e?.[s])||e[s].length===0||e[s].some(d=>d.status!=="PASS"))&&o.push(`terminal action requires every ${r} to PASS`);else e?.status==="rolled_back"?(!Array.isArray(e?.postconditions)||e.postconditions.length===0||e.postconditions.some(s=>s.status!=="PASS"))&&o.push("rolled_back action requires verified rollback postconditions"):e?.status==="blocked"&&([...Array.isArray(e?.preconditions)?e.preconditions:[],...Array.isArray(e?.postconditions)?e.postconditions:[]].some(r=>r.status!=="PASS")||o.push("blocked action must identify a failed or pending condition"));if(p&&ht.has(e.type)&&(!Array.isArray(e.evidence)||e.evidence.length===0)&&o.push(`${e.type} requires durable evidence before terminal status`),e?.type==="ApplyRepair")if(!Array.isArray(e.allowedPaths)||e.allowedPaths.length===0)o.push("ApplyRepair requires a non-empty allowedPaths scope");else{let s=Array.isArray(n?.protectedPaths)?n.protectedPaths:[];for(let r of e.allowedPaths){let d=Y(i,r);if(!J(d,i)){o.push(`allowed path escapes project root: ${r}`);continue}for(let m of s){let h=Y(i,m);(J(d,h)||J(h,d))&&o.push(`allowed path overlaps protected design source: ${r}`)}}}return o.push(...gt(e,t)),o}async function Te(e,t){if(!["AttachEvidence","ApplyRepair","ObserveImplementation"].includes(e?.type)||e?.status!=="completed")return[];let n=(e?.parameters?.ontologyPatch?.addObjects??[]).filter(o=>["Evidence","ImplementationUnit"].includes(o?.type)),i=[];for(let o of n){let a=o?.properties?.path,c=o?.provenance?.contentHash;if(!a||!c)continue;let l=await ie(t,a,c);l.status==="OUTSIDE_PROJECT"?i.push(`${o.type} artifact escapes project root: ${o.id}`):l.status==="MISSING"?i.push(`${o.type} artifact is missing: ${o.id}`):l.status==="INVALID"?i.push(`${o.type} artifact is not a regular file: ${o.id}`):l.status==="CHANGED"&&i.push(`${o.type} artifact hash mismatch: ${o.id}`)}return i}async function j(e){return JSON.parse(await ne(e,"utf8"))}function te(e){let t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>n!=="recordHash"));return H(JSON.stringify(C(t)))}function _(e){let t=[],n="0".repeat(64),i=!1,o=new Map;for(let[a,c]of e.entries()){let l=a+1,p=JSON.stringify(c?.action),s=H(p);if(c?.schema==="dic.ontology-action-record.v1")i&&t.push(`legacy ledger record follows v2 record at line ${l}`),c.sha256!==s&&t.push(`action ledger hash mismatch at line ${l}`),n=te(c);else if(c?.schema==="dic.ontology-action-record.v2"){i=!0,c.sequence!==l&&t.push(`action ledger sequence mismatch at line ${l}`),c.previousHash!==n&&t.push(`action ledger chain mismatch at line ${l}`),c.actionHash!==s&&t.push(`action ledger action hash mismatch at line ${l}`);let d=te(c);c.recordHash!==d&&t.push(`action ledger record hash mismatch at line ${l}`),n=d}else{t.push(`unsupported action ledger schema at line ${l}`);continue}let r=o.get(c.action?.id);r&&r!==s&&t.push(`action ledger ID collision: ${c.action.id}`),o.set(c.action?.id,s)}return{valid:t.length===0,errors:t,headHash:n,recordCount:e.length}}async function xe(e,t,{dryRun:n=!1,baseSnapshotRevision:i="",appliedActionIds:o=[]}={}){let a=[];try{a=(await ne(e,"utf8")).split(/\r?\n/u).filter(Boolean).map(h=>JSON.parse(h))}catch(h){if(h?.code!=="ENOENT")throw h}let c=_(a);if(!c.valid)throw new Error(c.errors.join("; "));let l=JSON.stringify(t),p=H(l),s=a.find(h=>h.action?.id===t.id);if(s){if((s.actionHash??s.sha256)!==p)throw new Error(`action ID collision with different payload: ${t.id}`);return{recorded:!1,duplicate:!0,sha256:p,actionHash:p,recordHash:s.recordHash??te(s),ledgerHeadHash:c.headHash}}let r=new Set(o),d=a.map(h=>h.action?.id).filter(h=>h&&!r.has(h));if(d.length>0)throw new Error(`ledger has unapplied action(s): ${d.join(", ")}; run ontology-reconcile before recording another action`);if(!/^[a-f0-9]{64}$/u.test(i))throw new Error("recording an action requires a canonical base snapshot revision");let m={schema:"dic.ontology-action-record.v2",sequence:a.length+1,recordedAt:new Date().toISOString(),previousHash:c.headHash,baseSnapshotRevision:i,actionHash:p,action:t};return m.recordHash=te(m),n||await lt(e,`${JSON.stringify(m)}
|
|
3
|
-
`,"utf8"),{recorded:!n,duplicate:!1,dryRun:n,sha256:p,actionHash:p,recordHash:m.recordHash,ledgerHeadHash:m.recordHash,sequence:m.sequence,baseSnapshotRevision:i}}function he(e){return e.split(/\r?\n/u).filter(Boolean).map((t,n)=>{try{return JSON.parse(t)}catch{throw new Error(`invalid action ledger JSON at line ${n+1}`)}})}async function se(e){try{let t=he(await ne(e,"utf8")),n=_(t);if(!n.valid)throw new Error(n.errors.join("; "));return t}catch(t){if(t?.code==="ENOENT")return[];throw t}}function ae(e,t,n,i){let o=_(t);if(!o.valid)throw new Error(o.errors.join("; "));let a=structuredClone(e);a.appliedActionIds=Array.isArray(a.appliedActionIds)?[...a.appliedActionIds]:[];let c=new Set(a.appliedActionIds),l=new Map,p=0,s=0;for(let d of t){let m=JSON.stringify(d.action),h=H(m),S=l.get(d.action?.id);if(S&&S!==h)throw new Error(`action ledger ID collision: ${d.action.id}`);if(l.set(d.action?.id,h),c.has(d.action.id)){s+=1;continue}if(d.schema==="dic.ontology-action-record.v2"&&d.baseSnapshotRevision!==a.snapshotRevision)throw new Error(`action ${d.action.id} was recorded against snapshot ${d.baseSnapshotRevision}, current revision is ${a.snapshotRevision}`);let I=fe(d.action,a,n,i);if(I.length>0)throw new Error(`action ${d.action.id} cannot be materialized: ${I.join("; ")}`);let v=d.action.parameters.ontologyPatch;a.objects.push(...structuredClone(v.addObjects??[])),a.links.push(...structuredClone(v.addLinks??[]));let y=new Map(a.objects.map(f=>[f.id,f]));for(let f of v.lifecycleTransitions??[])y.get(f.objectId).lifecycle=f.to;a.appliedActionIds.push(d.action.id),c.add(d.action.id),a.snapshotRevision=ue(a),p+=1}a.snapshotRevision=ue(a),a.invariantResults=oe(a);let r=a.invariantResults.filter(d=>d.status==="FAIL"&&d.severity==="blocking");if(r.length>0)throw new Error(`reconciled ontology violates structural invariants: ${r.map(d=>d.id).join(", ")}`);return{snapshot:a,applied:p,skipped:s,total:t.length}}function U(e,t,n=""){let i=Array.isArray(e?.objects)?e.objects:[],o=Array.isArray(e?.links)?e.links:[],a=new Map(i.map(c=>[c.id,c]));if(t==="uncovered"){let c=new Set(i.filter(r=>r.type==="ImplementationUnit"&&["active","confirmed","resolved"].includes(r.lifecycle)).map(r=>r.id)),l=new Set(o.filter(r=>r.type==="IMPLEMENTED_BY"&&c.has(r.to)).map(r=>r.from)),p=new Set(i.filter(r=>r.type==="Validation"&&["active","confirmed","resolved"].includes(r.lifecycle)&&r.properties?.status==="PASS").map(r=>r.id)),s=new Set(o.filter(r=>r.type==="VERIFIED_BY"&&p.has(r.to)).map(r=>r.from));return i.filter(r=>["Requirement","Scenario"].includes(r.type)&&["active","confirmed"].includes(r.lifecycle)&&(!l.has(r.id)||!s.has(r.id))).map(r=>({id:r.id,type:r.type,lifecycle:r.lifecycle,missingImplementation:r.type==="Requirement"&&!l.has(r.id),missingValidation:!s.has(r.id)}))}if(t==="gaps")return i.filter(c=>c.type==="Gap"&&!["resolved","rejected","superseded"].includes(c.lifecycle));if(t==="unevidenced"){let c=new Set(o.filter(l=>l.type==="PRODUCES").map(l=>l.from));return i.filter(l=>l.type==="Validation"&&!c.has(l.id))}if(t==="impact"){if(!n||!a.has(n))throw new Error("impact query requires --id resolving to an ontology object");let c=new Set(["PROPOSES","DERIVED_FROM","REFINES","IMPLEMENTED_BY","VERIFIED_BY","VIOLATES","RESOLVES","PRODUCES","SUPERSEDES"]),l=new Map;for(let r of o.filter(d=>c.has(d.type)))l.has(r.from)||l.set(r.from,[]),l.has(r.to)||l.set(r.to,[]),l.get(r.from).push({id:r.to,link:r}),l.get(r.to).push({id:r.from,link:r});let p=[{id:n,depth:0}],s=new Map([[n,{depth:0,via:null}]]);for(;p.length>0;){let r=p.shift();if(!(r.depth>=4))for(let d of l.get(r.id)??[])s.has(d.id)||(s.set(d.id,{depth:r.depth+1,via:d.link.type}),p.push({id:d.id,depth:r.depth+1}))}return[...s.entries()].map(([r,d])=>({id:r,type:a.get(r)?.type,lifecycle:a.get(r)?.lifecycle,...d}))}throw new Error(`unsupported ontology query: ${t}`)}async function K(e,t){let n=(Array.isArray(e?.objects)?e.objects:[]).filter(o=>o.type==="DesignSource"),i=[];for(let o of n){let a=o?.provenance?.contentHash??"",c=o?.properties?.path??o?.provenance?.source;if(!c||!a){i.push({id:o.id,path:c??"",status:"UNTRACKED",expected:a,actual:""});continue}let l=await ie(t,c,a);i.push({id:o.id,path:c,status:l.status,expected:a,actual:l.actual})}return i}async function W(e,t){let n=Array.isArray(e?.objects)?e.objects:[],i=Array.isArray(e?.links)?e.links:[],o=new Map(n.map(s=>[s.id,s])),a=new Set(n.filter(s=>s.type==="Validation"&&["active","confirmed","resolved"].includes(s.lifecycle)).map(s=>s.id)),c=new Set(i.filter(s=>s.type==="PRODUCES"&&a.has(s.from)&&o.get(s.to)?.type==="Evidence").map(s=>s.to)),l=n.filter(s=>s.type==="Evidence"),p=[];for(let s of l){let r=s?.provenance?.contentHash??"",d=s?.properties?.path??"",m=c.has(s.id);if(!d||!r){p.push({id:s.id,path:d,required:m,status:"UNTRACKED",expected:r,actual:""});continue}if(m&&!["active","confirmed","resolved"].includes(s.lifecycle)){p.push({id:s.id,path:d,required:m,status:"INACTIVE",expected:r,actual:""});continue}let h=await ie(t,d,r);p.push({id:s.id,path:d,required:m,status:h.status,expected:r,actual:h.actual})}return p}async function X(e,t){let n=Array.isArray(e?.objects)?e.objects:[],i=Array.isArray(e?.links)?e.links:[],o=new Map(n.map(s=>[s.id,s])),a=new Set(n.filter(s=>["Requirement","Scenario"].includes(s.type)&&["active","confirmed"].includes(s.lifecycle)).map(s=>s.id)),c=new Set(i.filter(s=>s.type==="IMPLEMENTED_BY"&&a.has(s.from)&&o.get(s.to)?.type==="ImplementationUnit").map(s=>s.to)),l=n.filter(s=>s.type==="ImplementationUnit"),p=[];for(let s of l){let r=s?.provenance?.contentHash??"",d=s?.properties?.path??"",m=c.has(s.id);if(!d||!r){p.push({id:s.id,path:d,required:m,status:"UNTRACKED",expected:r,actual:""});continue}if(m&&!["active","confirmed","resolved"].includes(s.lifecycle)){p.push({id:s.id,path:d,required:m,status:"INACTIVE",expected:r,actual:""});continue}let h=await ie(t,d,r);p.push({id:s.id,path:d,required:m,status:h.status,expected:r,actual:h.actual})}return p}function wt(e,t){let n=t.filter(p=>p.status!=="UNCHANGED"),i=new Map;for(let p of n)for(let s of U(e,"impact",p.id)){let r=i.get(s.id);(!r||s.depth<r.depth)&&i.set(s.id,{...s,changedSourceIds:r?.changedSourceIds??[]}),i.get(s.id).changedSourceIds.push(p.id)}let o=[...i.values()].map(p=>({...p,changedSourceIds:[...new Set(p.changedSourceIds)].sort()})).sort((p,s)=>p.depth-s.depth||p.id.localeCompare(s.id)),a=new Set(o.map(p=>p.type)),c=[],l=(p,s)=>{c.some(r=>r.stage===p)||c.push({stage:p,reason:s})};return n.length>0&&(l("workflow-intake","Refresh changed or missing design-source revisions."),l("spec-reader","Re-read the changed authoritative source neighborhood."),l("contract-oracle","Reconfirm affected obligations and lifecycle.")),["Requirement","Scenario"].some(p=>a.has(p))&&(l("flow-auditor","Re-evaluate affected behavioral and lifecycle flows."),l("impl-inspector","Recheck implementation mappings for affected obligations.")),["ImplementationUnit","Gap","RepairAction"].some(p=>a.has(p))&&(l("repair-planner","Replan only impacted gaps and repair actions."),l("code-repairer","Execute approved impacted repair slices only.")),["Validation","Evidence"].some(p=>a.has(p))&&l("validation-runner","Refresh invalidated validation and evidence."),n.length>0&&l("final-reviewer","Recompute invariants after incremental reconciliation."),{clean:n.length===0,changedSources:n,impactedObjects:o,recommendedStages:c}}function qe(e,t,n,i){let o=wt(e,t),a=n.filter(r=>r.required&&r.status!=="UNCHANGED"),c=i.filter(r=>r.required&&r.status!=="UNCHANGED"),l=new Map(o.impactedObjects.map(r=>[r.id,{...r,integrityIssueIds:[]}]));for(let r of[...a,...c])for(let d of U(e,"impact",r.id)){let m=l.get(d.id);(!m||d.depth<m.depth)&&l.set(d.id,{...d,changedSourceIds:m?.changedSourceIds??[],integrityIssueIds:m?.integrityIssueIds??[]}),l.get(d.id).integrityIssueIds.push(r.id)}let p=o.recommendedStages.map(r=>({...r})),s=(r,d)=>{p.some(m=>m.stage===r)||p.push({stage:r,reason:d})};return a.length>0&&(s("impl-inspector","Reinspect drifted implementation files and refresh or challenge their mappings."),s("validation-runner","Rerun validations affected by implementation drift.")),c.length>0&&s("validation-runner","Regenerate missing or drifted content-addressed Evidence artifacts."),(a.length>0||c.length>0)&&s("final-reviewer","Recompute gates and Attestation after integrity recovery."),{...o,clean:o.clean&&a.length===0&&c.length===0,implementationIssues:a,evidenceIssues:c,impactedObjects:[...l.values()].map(r=>({...r,changedSourceIds:[...new Set(r.changedSourceIds??[])].sort(),integrityIssueIds:[...new Set(r.integrityIssueIds??[])].sort()})).sort((r,d)=>r.depth-d.depth||r.id.localeCompare(d.id)),recommendedStages:p}}function De(e,t){let n=Array.isArray(e?.objects)?e.objects:[],i=Array.isArray(e?.links)?e.links:[],o=new Map(n.map(h=>[h.id,h])),a=o.get(t);if(!a)throw new Error(`ontology object does not resolve: ${t}`);let c=h=>({id:h.id,type:h.type,lifecycle:h.lifecycle,title:h.properties?.title??"",path:h.properties?.path??"",status:h.properties?.status??"",sourceLocator:h.provenance?.sourceLocator??"",sourceRevision:h.provenance?.sourceRevision??"",createdBy:h.provenance?.createdBy??""}),l=[];for(let h of i)h.from===t&&o.has(h.to)?l.push({direction:"outgoing",type:h.type,object:c(o.get(h.to)),linkId:h.id}):h.to===t&&o.has(h.from)&&l.push({direction:"incoming",type:h.type,object:c(o.get(h.from)),linkId:h.id});l.sort((h,S)=>h.type.localeCompare(S.type)||h.object.id.localeCompare(S.object.id));let p=new Set(["DesignSource","ImplementationUnit","Gap","RepairAction","Validation","Evidence","Decision","Risk"]),s=new Map;for(let h of i)s.has(h.from)||s.set(h.from,[]),s.has(h.to)||s.set(h.to,[]),s.get(h.from).push({id:h.to,type:h.type,direction:"outgoing"}),s.get(h.to).push({id:h.from,type:h.type,direction:"incoming"});let r=[{id:t,objects:[t],links:[]}],d=new Map([[t,0]]),m=[];for(;r.length>0;){let h=r.shift();if(!(h.links.length>=4))for(let S of s.get(h.id)??[]){if(h.objects.includes(S.id))continue;let I=[...h.objects,S.id],v=[...h.links,{type:S.type,direction:S.direction}],y=o.get(S.id);if(!y)continue;p.has(y.type)&&m.push({target:c(y),objectIds:I,links:v});let f=v.length;(d.get(S.id)??Number.POSITIVE_INFINITY)>f&&(d.set(S.id,f),r.push({id:S.id,objects:I,links:v}))}}return m.sort((h,S)=>h.links.length-S.links.length||h.target.type.localeCompare(S.target.type)||h.target.id.localeCompare(S.target.id)),{object:c(a),properties:a.properties??{},provenance:a.provenance??{},interfaces:a.interfaces??[],relations:l,evidenceChains:m}}function H(e){return Ne("sha256").update(e).digest("hex")}function Le(e){let t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!["attestationId","contentHash"].includes(n)));return H(JSON.stringify(C(t)))}function He(e){return z(e).filter(t=>t.required).map(t=>({id:t.id,status:t.status,targetIds:t.targetIds,requiredInputIds:t.requiredInputIds,missingInputIds:t.missingInputIds,staleInputIds:t.staleInputIds}))}function Ve({snapshot:e,ledgerText:t,ledgerHeadHash:n,status:i,summary:o,sourceDrift:a,evidenceIntegrity:c,implementationIntegrity:l,invariants:p,createdAt:s=new Date().toISOString()}){let r={schema:"dic.ontology-attestation.v1",attestationId:"",contentHash:"",version:e.version,status:i,final:!0,summary:o,createdAt:s,snapshot:{snapshotId:e.snapshotId,snapshotRevision:e.snapshotRevision},ledger:{sha256:H(t),actionCount:t.split(/\r?\n/u).filter(Boolean).length,headHash:n},sources:a.map(d=>({id:d.id,path:d.path,status:d.status,contentHash:d.actual||d.expected||""})),evidence:c.filter(d=>d.required).map(d=>({id:d.id,path:d.path,status:d.status,contentHash:d.actual||d.expected||""})),implementations:l.filter(d=>d.required).map(d=>({id:d.id,path:d.path,status:d.status,contentHash:d.actual||d.expected||""})),validationCausality:He(e),invariants:p};return r.contentHash=Le(r),r.attestationId=`att-${r.contentHash.slice(0,16)}`,r}function Me({attestation:e,snapshot:t,ledgerText:n,ledgerHeadHash:i,sourceDrift:o,evidenceIntegrity:a,implementationIntegrity:c,invariants:l,expectedContentHash:p=""}){let s=[],r=Le(e);e?.schema!=="dic.ontology-attestation.v1"&&s.push("unsupported ontology attestation schema"),["PASS","PARTIAL","BLOCKED","FAIL"].includes(e?.status)||s.push("unsupported ontology attestation status"),e?.final!==!0&&s.push("ontology attestation is not final"),(typeof e?.summary!="string"||!e.summary.trim())&&s.push("ontology attestation summary is empty"),(typeof e?.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))&&s.push("ontology attestation timestamp is invalid"),e?.contentHash!==r&&s.push("attestation content hash mismatch"),p&&e?.contentHash!==p&&s.push("attestation content hash does not match the external anchor"),e?.attestationId!==`att-${r.slice(0,16)}`&&s.push("attestation ID does not match its content hash"),(e?.snapshot?.snapshotId!==t?.snapshotId||e?.snapshot?.snapshotRevision!==t?.snapshotRevision)&&s.push("attestation snapshot identity or revision is stale"),e?.version!==t?.version&&s.push("attestation version does not match the snapshot"),e?.ledger?.sha256!==H(n)&&s.push("attestation action ledger hash is stale"),e?.ledger?.headHash!==i&&s.push("attestation action ledger head is stale");let d=n.split(/\r?\n/u).filter(Boolean).length;e?.ledger?.actionCount!==d&&s.push("attestation action count is stale");let m=o.map(v=>({id:v.id,path:v.path,status:v.status,contentHash:v.actual||v.expected||""}));JSON.stringify(C(e?.sources??[]))!==JSON.stringify(C(m))&&s.push("attested source inventory is stale");let h=a.filter(v=>v.required).map(v=>({id:v.id,path:v.path,status:v.status,contentHash:v.actual||v.expected||""}));JSON.stringify(C(e?.evidence??[]))!==JSON.stringify(C(h))&&s.push("attested Evidence artifact inventory is stale");let S=c.filter(v=>v.required).map(v=>({id:v.id,path:v.path,status:v.status,contentHash:v.actual||v.expected||""}));JSON.stringify(C(e?.implementations??[]))!==JSON.stringify(C(S))&&s.push("attested ImplementationUnit artifact inventory is stale"),JSON.stringify(C(e?.validationCausality??[]))!==JSON.stringify(C(He(t)))&&s.push("attested Validation input causality is stale"),JSON.stringify(C(e?.invariants??[]))!==JSON.stringify(C(l))&&s.push("attested invariant results are stale");let I=l.filter(v=>v.status==="FAIL"&&v.severity==="blocking");return I.length>0&&s.push(`current ontology gate fails: ${I.map(v=>v.id).join(", ")}`),{valid:s.length===0,errors:s,attestationId:e?.attestationId??"",status:e?.status??""}}function R(e){return String(e??"").replace(/\|/gu,"\\|").replace(/\r?\n/gu," ")}function Ue(e,t,n,i,o=""){let a=Array.isArray(e?.objects)?e.objects:[],c=Array.isArray(e?.links)?e.links:[],l=new Map;for(let y of a)l.set(y.type,(l.get(y.type)??0)+1);let p=U(e,"uncovered"),s=U(e,"gaps"),r=U(e,"unevidenced"),d=z(e),m=oe(e,o),h=t.filter(y=>y.status!=="UNCHANGED");m.push({id:"pass.sources.no-drift",status:o==="PASS"?h.length===0?"PASS":"FAIL":"NOT_APPLICABLE",severity:"blocking",message:"PASS requires every tracked design source to match its recorded revision.",objectIds:o==="PASS"?h.map(y=>y.id):[]});let S=i.filter(y=>y.required&&y.status!=="UNCHANGED");m.push({id:"pass.implementation.artifacts-current",status:o==="PASS"?S.length===0?"PASS":"FAIL":"NOT_APPLICABLE",severity:"blocking",message:"PASS requires every required ImplementationUnit artifact to exist and match its recorded SHA-256 hash.",objectIds:o==="PASS"?S.map(y=>y.id):[]});let I=n.filter(y=>y.required&&y.status!=="UNCHANGED");return m.push({id:"pass.evidence.artifacts-current",status:o==="PASS"?I.length===0?"PASS":"FAIL":"NOT_APPLICABLE",severity:"blocking",message:"PASS requires every required Evidence artifact to exist and match its recorded SHA-256 hash.",objectIds:o==="PASS"?I.map(y=>y.id):[]}),["# DIC Ontology Report","",`- Snapshot: \`${e.snapshotId}\``,`- Revision: \`${e.snapshotRevision||"unversioned"}\``,`- Requested gate: ${o||"STRUCTURAL"}`,`- Objects / links: ${a.length} / ${c.length}`,`- Uncovered obligations: ${p.length}`,`- Open gaps: ${s.length}`,`- Unevidenced validations: ${r.length}`,"","## Object Inventory","","| Type | Count |","| --- | ---: |",...[...l.entries()].sort(([y],[f])=>y.localeCompare(f)).map(([y,f])=>`| ${R(y)} | ${f} |`),"","## Gate Invariants","","| Status | Severity | Invariant | Affected |","| --- | --- | --- | ---: |",...m.map(y=>`| ${y.status} | ${y.severity} | ${R(y.id)} | ${y.objectIds.length} |`),"","## Design Sources","","| Status | Object | Path |","| --- | --- | --- |",...t.map(y=>`| ${y.status} | \`${R(y.id)}\` | \`${R(y.path)}\` |`),"","## Uncovered Obligations","","| Object | Type | Missing implementation | Missing validation |","| --- | --- | --- | --- |",...p.map(y=>`| \`${R(y.id)}\` | ${y.type} | ${y.missingImplementation} | ${y.missingValidation} |`),"","## Evidence Artifacts","","| Status | Required | Object | Path |","| --- | --- | --- | --- |",...n.map(y=>`| ${y.status} | ${y.required} | \`${R(y.id)}\` | \`${R(y.path)}\` |`),"","## Validation Causality","","| Status | Required | Validation | Targets | Required inputs | Missing | Stale |","| --- | --- | --- | --- | --- | --- | --- |",...d.map(y=>`| ${y.status} | ${y.required} | \`${R(y.id)}\` | ${R(y.targetIds.join(", "))} | ${R(y.requiredInputIds.join(", "))} | ${R(y.missingInputIds.join(", "))} | ${R(y.staleInputIds.join(", "))} |`),"","## Implementation Artifacts","","| Status | Required | Object | Path |","| --- | --- | --- | --- |",...i.map(y=>`| ${y.status} | ${y.required} | \`${R(y.id)}\` | \`${R(y.path)}\` |`),"","## Open Gaps","","| Object | Lifecycle | Severity | Title |","| --- | --- | --- | --- |",...s.map(y=>`| \`${R(y.id)}\` | ${y.lifecycle} | ${R(y.properties?.severity)} | ${R(y.properties?.title)} |`),"","## Unevidenced Validations","","| Object | Lifecycle | Status |","| --- | --- | --- |",...r.map(y=>`| \`${R(y.id)}\` | ${y.lifecycle} | ${R(y.properties?.status)} |`),"","_Generated from ontology state; edit the ontology through authorized actions, then regenerate this view._",""].join(`
|
|
4
|
-
`)}var F="dic-workflow-kit",_e=".dic-workflow-kit-install.json",Z=E(M(At(import.meta.url)),".."),It=new Map([["codex","codex"],["claude","claude-code"],["claude-code","claude-code"],["opencode","opencode"],["mimo","mimo-code"],["mimocode","mimo-code"],["mimo-code","mimo-code"],["bitfun","bitfun"]]),kt=[".codex-plugin","adapters","agents","schemas","skills","INSTRUCTION.md"];function $(e,t,n){let i=e[t+1];if(!i)throw new Error(`${n} requires a value`);return i}function Et(e){let t=e[0]??"help",n="codex",i="user",o,a,c=process.cwd(),l=!1,p=!1,s=!1,r,d,m,h,S="",I="",v="",y="",f,k,P="";for(let A=1;A<e.length;A+=1){let g=e[A];if(g==="--host"){let b=$(e,A,g).toLowerCase();if(n=It.get(b),!n)throw new Error(`unsupported host: ${b}; expected codex, claude-code, opencode, mimo-code, or bitfun`);A+=1}else if(g==="--scope"){if(i=$(e,A,g).toLowerCase(),!["user","project"].includes(i))throw new Error("--scope must be user or project");A+=1}else if(g==="--install-root")o=E($(e,A,g)),A+=1;else if(g==="--project-root")c=E($(e,A,g)),A+=1;else if(g==="--root")c=E($(e,A,g)),A+=1;else if(g==="--snapshot")r=E($(e,A,g)),A+=1;else if(g==="--action")d=E($(e,A,g)),A+=1;else if(g==="--profile")m=E($(e,A,g)),A+=1;else if(g==="--ledger")h=E($(e,A,g)),A+=1;else if(g==="--status"){if(S=$(e,A,g).toUpperCase(),!["PASS","PARTIAL","BLOCKED","FAIL"].includes(S))throw new Error("--status must be PASS, PARTIAL, BLOCKED, or FAIL");A+=1}else if(g==="--query"){if(I=$(e,A,g).toLowerCase(),!["uncovered","gaps","unevidenced","impact"].includes(I))throw new Error("--query must be uncovered, gaps, unevidenced, or impact");A+=1}else if(g==="--id")v=$(e,A,g),A+=1;else if(g==="--summary")y=$(e,A,g),A+=1;else if(g==="--output")f=E($(e,A,g)),A+=1;else if(g==="--attestation")k=E($(e,A,g)),A+=1;else if(g==="--expected-hash"){if(P=$(e,A,g).toLowerCase(),!/^[a-f0-9]{64}$/u.test(P))throw new Error("--expected-hash must be a 64-character SHA-256 digest");A+=1}else if(g==="--marketplace-root")a=E($(e,A,g)),A+=1;else if(g==="--dry-run")l=!0;else if(g==="--force")p=!0;else if(g==="--json")s=!0;else throw new Error(`unknown argument: ${g}`)}if(n!=="codex"&&a)throw new Error("--marketplace-root is only valid for --host codex");if(n==="codex"&&i==="project")throw new Error("Codex plugin installation supports user scope only");return{command:t,host:n,scope:i,installRoot:o,marketplaceRoot:a,projectRoot:c,dryRun:l,force:p,json:s,snapshot:r,action:d,profile:m,ledger:h,status:S,query:I,id:v,summary:y,output:f,attestation:k,expectedHash:P}}function Ke({host:e,scope:t,projectRoot:n}){if(t==="project"){let i={"claude-code":".claude",opencode:".opencode","mimo-code":".mimocode",bitfun:".bitfun"}[e];return w(n,i)}if(e==="claude-code")return w(V(),".claude");if(e==="opencode")return w(process.env.XDG_CONFIG_HOME||w(V(),".config"),"opencode");if(e==="mimo-code")return process.env.MIMOCODE_HOME?E(process.env.MIMOCODE_HOME):process.platform==="win32"&&process.env.LOCALAPPDATA?w(process.env.LOCALAPPDATA,"mimocode"):w(process.env.XDG_CONFIG_HOME||w(V(),".config"),"mimocode");if(e==="bitfun")throw new Error("BitFun user scope uses separate platform-native Skills and agents roots");return w(V(),".agents","plugins")}function bt(){let e,t;if(process.platform==="win32"){let n=process.env.APPDATA||w(V(),"AppData","Roaming");e=w(n,"BitFun","skills"),t=w(process.env.BITFUN_USER_ROOT?E(process.env.BITFUN_USER_ROOT):w(n,"bitfun"),"agents")}else if(process.platform==="darwin"){let n=w(V(),"Library","Application Support");e=w(n,"BitFun","skills"),t=w(process.env.BITFUN_USER_ROOT?E(process.env.BITFUN_USER_ROOT):w(n,"bitfun"),"agents")}else e=w(process.env.XDG_DATA_HOME||w(V(),".local","share"),"BitFun","skills"),t=w(process.env.BITFUN_USER_ROOT?E(process.env.BITFUN_USER_ROOT):w(process.env.XDG_CONFIG_HOME||w(V(),".config"),"bitfun"),"agents");return{skillsRoot:e,agentsRoot:t}}function Rt(e){if(e.installRoot)return{root:e.installRoot,skillsRoot:w(e.installRoot,"skills"),agentsRoot:w(e.installRoot,"agents")};if(e.host==="bitfun"&&e.scope==="user"){let n=bt();return{root:M(n.skillsRoot),...n}}let t=Ke(e);return{root:t,skillsRoot:w(t,"skills"),agentsRoot:w(t,"agents")}}function We(e){if(e.host==="codex"){let n=e.marketplaceRoot||e.installRoot||Ke(e),i=w(n,"plugins",F);return{root:i,skillsRoot:w(i,"skills"),agentsRoot:w(i,"agents"),manifestPath:w(i,_e),marketplaceRoot:n,marketplacePath:w(n,"marketplace.json")}}let t=Rt(e);return{...t,manifestPath:w(t.root,_e)}}async function Q(e){try{return await Je(e),!0}catch(t){if(t?.code==="ENOENT")return!1;throw t}}function re(e){return Be("sha256").update(e).digest("hex")}async function Xe(e){return re(await q(e))}async function jt(){return JSON.parse(await q(w(Z,"package.json"),"utf8"))}async function ge(e,t){let n=`${e}.${process.pid}.tmp`;await ce(M(e),{recursive:!0}),await le(n,`${JSON.stringify(t,null,2)}
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import{createHash as bt}from"node:crypto";import{mkdir as Ae,lstat as $e,readFile as H,readdir as kt,rename as Le,rm as Z,rmdir as un,stat as Pt,writeFile as ve}from"node:fs/promises";import{homedir as F}from"node:os";import{dirname as B,isAbsolute as Nt,join as A,relative as Ot,resolve as b,sep as fn}from"node:path";import{fileURLToPath as hn}from"node:url";import{createHash as tt}from"node:crypto";import{appendFile as Wt,readFile as he,realpath as Ze,stat as Jt}from"node:fs/promises";import{isAbsolute as Yt,relative as Kt,resolve as oe}from"node:path";var be=new Map([["workflow-intake",new Set(["IntakeDesignSource"])],["spec-reader",new Set(["IntakeDesignSource"])],["contract-oracle",new Set(["ConfirmObligation"])],["impl-inspector",new Set(["ObserveImplementation","OpenGap"])],["repair-planner",new Set(["ProposeRepair"])],["final-reviewer",new Set(["ApproveRepair","CloseGap","MarkBlocked","SupersedeSource","RecordDecision","RecordWaiver"])],["code-repairer",new Set(["ApplyRepair"])],["validation-runner",new Set(["RunValidation","AttachEvidence","RecordGateRun"])],["evidence-auditor",new Set(["RecordGateRun","AssertClaim"])],["adversarial-challenger",new Set(["ChallengeClaim","RecordCounterexample"])]]);be.get("workflow-intake").add("RegisterCandidate");be.get("workflow-intake").add("RegisterPolicy");var et=new Map([["IntakeDesignSource",new Set(["Project","DesignSource","Change"])],["ConfirmObligation",new Set(["Requirement","Scenario"])],["ObserveImplementation",new Set(["Requirement","Scenario"])],["OpenGap",new Set(["Requirement","Scenario"])],["ProposeRepair",new Set(["Gap"])],["ApproveRepair",new Set(["RepairAction"])],["ApplyRepair",new Set(["RepairAction"])],["RunValidation",new Set(["Requirement","Scenario","RepairAction"])],["AttachEvidence",new Set(["Validation"])],["CloseGap",new Set(["Gap"])],["MarkBlocked",new Set(["Gap","RepairAction","Validation"])],["SupersedeSource",new Set(["DesignSource","Change","Requirement","Scenario"])],["RegisterCandidate",new Set(["Project"])],["RecordGateRun",new Set(["Candidate"])],["AssertClaim",new Set(["GateRun"])],["ChallengeClaim",new Set(["Claim"])],["RecordCounterexample",new Set(["Claim"])],["RecordDecision",new Set(["GateRun"])],["RecordWaiver",new Set(["Risk"])],["RegisterPolicy",new Set(["Project"])]]),zt=new Set(["ApplyRepair","RunValidation","AttachEvidence","ObserveImplementation","CloseGap","MarkBlocked","SupersedeSource","RecordGateRun","AssertClaim","ChallengeClaim","RecordCounterexample","RecordDecision","RecordWaiver"]),Qt=new Map([["IntakeDesignSource",{objectTypes:new Set(["DesignSource","Change"]),linkTypes:new Set(["CONTAINS"]),lifecycle:new Set(["draft","active"])}],["ConfirmObligation",{objectTypes:new Set,linkTypes:new Set,lifecycle:new Set(["confirmed"])}],["OpenGap",{objectTypes:new Set(["Gap"]),linkTypes:new Set(["VIOLATES"]),lifecycle:new Set}],["ObserveImplementation",{objectTypes:new Set(["ImplementationUnit"]),linkTypes:new Set(["IMPLEMENTED_BY"]),lifecycle:new Set}],["ProposeRepair",{objectTypes:new Set(["RepairAction"]),linkTypes:new Set(["RESOLVES"]),lifecycle:new Set}],["ApproveRepair",{objectTypes:new Set,linkTypes:new Set,lifecycle:new Set(["approved"])}],["ApplyRepair",{objectTypes:new Set(["ImplementationUnit"]),linkTypes:new Set(["IMPLEMENTED_BY"]),lifecycle:new Set(["in_progress","resolved"])}],["RunValidation",{objectTypes:new Set(["Validation"]),linkTypes:new Set(["VERIFIED_BY"]),lifecycle:new Set}],["AttachEvidence",{objectTypes:new Set(["Evidence"]),linkTypes:new Set(["PRODUCES"]),lifecycle:new Set}],["CloseGap",{objectTypes:new Set,linkTypes:new Set,lifecycle:new Set(["resolved"])}],["MarkBlocked",{objectTypes:new Set,linkTypes:new Set,lifecycle:new Set(["blocked"])}],["SupersedeSource",{objectTypes:new Set(["DesignSource","Change","Requirement","Scenario"]),linkTypes:new Set(["SUPERSEDES"]),lifecycle:new Set(["superseded"])}],["RegisterCandidate",{objectTypes:new Set(["Candidate"]),linkTypes:new Set(["CONTAINS"]),lifecycle:new Set}],["RecordGateRun",{objectTypes:new Set(["GateRun"]),linkTypes:new Set(["EVALUATES","GOVERNS"]),lifecycle:new Set}],["AssertClaim",{objectTypes:new Set(["Claim"]),linkTypes:new Set(["ASSERTS","SUPPORTED_BY"]),lifecycle:new Set}],["ChallengeClaim",{objectTypes:new Set(["Challenge"]),linkTypes:new Set(["CHALLENGES"]),lifecycle:new Set}],["RecordCounterexample",{objectTypes:new Set(["Counterexample"]),linkTypes:new Set(["REFUTES"]),lifecycle:new Set}],["RecordDecision",{objectTypes:new Set(["Decision"]),linkTypes:new Set(["DECIDES"]),lifecycle:new Set}],["RecordWaiver",{objectTypes:new Set(["Waiver"]),linkTypes:new Set(["WAIVES"]),lifecycle:new Set}],["RegisterPolicy",{objectTypes:new Set(["Policy"]),linkTypes:new Set(["CONTAINS"]),lifecycle:new Set}]]);function P(e,t,n,s,i=[]){return{id:e,status:t===null?"NOT_APPLICABLE":t?"PASS":"FAIL",severity:n,message:s,objectIds:[...new Set(i)].sort()}}function j(e){return Array.isArray(e)?e.map(j):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,j(e[t])])):e}function Ce(e){let t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!["snapshotRevision","invariantResults"].includes(n)));return tt("sha256").update(JSON.stringify(j(t))).digest("hex")}function Xt(e,t){let n=Array.isArray(e?.objects)?e.objects:[],s=Array.isArray(e?.links)?e.links:[],i=new Map(n.map(l=>[l.id,l])),a=new Set,r=[...t];for(;r.length>0;){let l=r.pop(),d=i.get(l);if(d){if(["Requirement","Scenario"].includes(d.type)){if(a.has(l))continue;if(a.add(l),d.type==="Scenario")for(let o of s)o.type==="REFINES"&&o.from===l&&r.push(o.to)}else if(d.type==="RepairAction"){let o=new Set(s.filter(c=>c.type==="RESOLVES"&&c.from===l).map(c=>c.to));for(let c of s)c.type==="VIOLATES"&&o.has(c.from)&&r.push(c.to)}}}return a}function nt(e,t){let n=Array.isArray(e?.objects)?e.objects:[],s=Array.isArray(e?.links)?e.links:[],i=new Map(n.map(l=>[l.id,l])),a=Xt(e,t),r=new Set;for(let l of s)if(a.has(l.from)&&["DERIVED_FROM","IMPLEMENTED_BY"].includes(l.type)){let d=i.get(l.to);["DesignSource","ImplementationUnit"].includes(d?.type)&&r.add(l.to)}return[...r].sort().map(l=>({objectId:l,contentHash:i.get(l)?.provenance?.contentHash??""}))}function ae(e){let t=Array.isArray(e?.objects)?e.objects:[],n=Array.isArray(e?.links)?e.links:[];return t.filter(i=>i.type==="Validation").map(i=>{let a=n.filter(y=>y.type==="VERIFIED_BY"&&y.to===i.id).map(y=>y.from),r=a.length>0,l=nt(e,a),d=Array.isArray(i.properties?.inputs)?i.properties.inputs:[],o=new Map,c=[];for(let y of d)o.has(y?.objectId)?c.push(y?.objectId):o.set(y?.objectId,y?.contentHash);let p=l.filter(y=>!o.has(y.objectId)).map(y=>y.objectId),I=l.filter(y=>o.has(y.objectId)&&o.get(y.objectId)!==y.contentHash).map(y=>y.objectId),h=typeof i.properties?.executedAt!="string"||Number.isNaN(Date.parse(i.properties.executedAt)),S="CURRENT";return c.length>0||h?S="INVALID":I.length>0?S="STALE":p.length>0&&(S="INCOMPLETE"),{id:i.id,required:r,status:S,targetIds:[...new Set(a)].sort(),requiredInputIds:l.map(y=>y.objectId),missingInputIds:p,staleInputIds:I,duplicateInputIds:c}})}function ge(e,t=""){let n=Array.isArray(e?.objects)?e.objects:[],s=Array.isArray(e?.links)?e.links:[],i=n.map(u=>u.id),a=new Map(n.map(u=>[u.id,u])),r=new Set(i),l=[...new Set(i.filter((u,x)=>i.indexOf(u)!==x))],d=[P("ontology.snapshot.schema",e?.schema==="dic.ontology-snapshot.v1","blocking","Ontology snapshot must declare dic.ontology-snapshot.v1."),P("ontology.snapshot.revision",e?.snapshotRevision?e.snapshotRevision===Ce(e):null,"blocking","Snapshot revision must match its canonical semantic content."),P("ontology.object-ids.unique",l.length===0,"blocking","Every ontology object must have a unique stable ID.",l)],o=s.filter(u=>!r.has(u.from)||!r.has(u.to)).map(u=>u.id);d.push(P("ontology.links.resolve",o.length===0,"blocking","Every link endpoint must resolve to an object in the snapshot.",o));let c=new Map([["CONTAINS",[new Set(["Project"]),null]],["PROPOSES",[new Set(["Change"]),new Set(["Requirement","Scenario"])]],["DERIVED_FROM",[new Set(["Requirement","Scenario"]),new Set(["DesignSource"])]],["REFINES",[new Set(["Scenario"]),new Set(["Requirement"])]],["IMPLEMENTED_BY",[new Set(["Requirement","Scenario"]),new Set(["ImplementationUnit"])]],["VERIFIED_BY",[new Set(["Requirement","Scenario","RepairAction"]),new Set(["Validation"])]],["VIOLATES",[new Set(["Gap"]),new Set(["Requirement","Scenario"])]],["RESOLVES",[new Set(["RepairAction"]),new Set(["Gap"])]],["PRODUCES",[new Set(["Validation","AgentRun"]),new Set(["Evidence"])]],["SUPPORTS",[new Set(["Evidence"]),new Set(["Decision"])]],["CONTRADICTS",[new Set(["Evidence"]),new Set(["Decision"])]],["REMAINS_AFTER",[new Set(["Risk"]),new Set(["RepairAction"])]],["EVALUATES",[new Set(["GateRun"]),new Set(["Candidate"])]],["DECIDES",[new Set(["Decision"]),new Set(["GateRun"])]],["ASSERTS",[new Set(["AgentRun","GateRun"]),new Set(["Claim"])]],["CHALLENGES",[new Set(["Challenge"]),new Set(["Claim"])]],["REFUTES",[new Set(["Counterexample"]),new Set(["Claim"])]],["SUPPORTED_BY",[new Set(["Claim"]),new Set(["Evidence"])]],["WAIVES",[new Set(["Waiver"]),new Set(["Risk"])]],["GOVERNS",[new Set(["Policy"]),new Set(["GateRun"])]]]),p=[];for(let u of s){let x=a.get(u.from),te=a.get(u.to);if(!x||!te)continue;let ne=!1;if(u.type==="SUPERSEDES")ne=x.type===te.type;else{let z=c.get(u.type);ne=!!(z&&z[0].has(x.type)&&(z[1]===null||z[1].has(te.type)))}ne||p.push(u.id)}d.push(P("ontology.links.type-compatible",p.length===0,"blocking","Every link must satisfy its object-type domain and range contract.",p));let I=[["GateRun","EVALUATES","from","gate-run.has-candidate"],["Decision","DECIDES","from","decision.has-gate-run"],["Challenge","CHALLENGES","from","challenge.has-claim"],["Counterexample","REFUTES","from","counterexample.has-claim"],["Waiver","WAIVES","from","waiver.has-risk"]];for(let[u,x,te,ne]of I){let z=new Set(s.filter(M=>M.type===x).map(M=>M[te])),Xe=n.filter(M=>M.type===u&&!z.has(M.id)&&!(u==="Decision"&&!n.some(Bt=>Bt.type==="GateRun"))).map(M=>M.id);d.push(P(ne,Xe.length===0,"blocking",`Every ${u} must participate in its required ${x} relation.`,Xe))}let h=n.filter(u=>["Requirement","Scenario"].includes(u.type)&&["confirmed","active"].includes(u.lifecycle)),S=new Set(s.filter(u=>u.type==="DERIVED_FROM").map(u=>u.from)),y=h.filter(u=>!S.has(u.id)).map(u=>u.id);d.push(P("obligation.active.has-source",y.length===0,"blocking","Every active obligation must link to a source-backed design object.",y));let m=new Set(s.filter(u=>u.type==="REFINES").map(u=>u.from)),g=h.filter(u=>u.type==="Scenario"&&!m.has(u.id)).map(u=>u.id);d.push(P("scenario.active.refines-requirement",g.length===0,"blocking","Every active scenario must refine a requirement.",g));let R=n.filter(u=>u.type==="Gap"&&u.lifecycle==="resolved"),f=new Map(s.filter(u=>u.type==="RESOLVES").map(u=>[u.to,u.from])),v=new Set(n.filter(u=>u.type==="Validation"&&["active","confirmed","resolved"].includes(u.lifecycle)&&u.properties?.status==="PASS").map(u=>u.id)),N=s.filter(u=>u.type==="VERIFIED_BY"),G=new Set(N.filter(u=>v.has(u.to)).map(u=>u.from)),E=R.filter(u=>{let x=f.get(u.id);return!x||!G.has(x)}).map(u=>u.id);d.push(P("gap.resolved.has-verified-repair",E.length===0,"blocking","Every resolved gap must have a resolving repair action with validation.",E));let w=t.toUpperCase()==="PASS",D=new Set(s.filter(u=>u.type==="DECIDES").map(u=>u.to)),Ge=n.filter(u=>u.type==="GateRun"&&u.properties?.status!=="SKIPPED"&&!D.has(u.id)).map(u=>u.id);d.push(P("pass.gate-runs.decided",w?Ge.length===0:null,"blocking","PASS requires every executed GateRun to have an explicit Decision.",w?Ge:[]));let Mt=new Set(s.filter(u=>u.type==="SUPPORTED_BY").map(u=>u.from)),Me=n.filter(u=>u.type==="Claim"&&["confirmed","active","resolved"].includes(u.lifecycle)&&!Mt.has(u.id)).map(u=>u.id);d.push(P("pass.claims.evidenced",w?Me.length===0:null,"blocking","PASS requires every active Claim to be linked to durable Evidence.",w?Me:[]));let _e=n.filter(u=>u.type==="Challenge"&&!["resolved","rejected","superseded"].includes(u.lifecycle)).map(u=>u.id);d.push(P("pass.challenges.resolved",w?_e.length===0:null,"blocking","PASS is forbidden while an adversarial Challenge remains unresolved.",w?_e:[])),d.push(P("pass.obligations.nonempty",w?h.length>0:null,"blocking","PASS requires at least one active, source-backed obligation."));let Ve=new Set(n.filter(u=>u.type==="ImplementationUnit"&&["active","confirmed","resolved"].includes(u.lifecycle)).map(u=>u.id)),Fe=s.filter(u=>u.type==="IMPLEMENTED_BY"),_t=new Set(Fe.filter(u=>Ve.has(u.to)).map(u=>u.from)),Be=Fe.filter(u=>!Ve.has(u.to)).map(u=>u.to);d.push(P("pass.implementations.current",w?Be.length===0:null,"blocking","PASS requires every referenced ImplementationUnit to have a current lifecycle.",w?Be:[]));let We=h.filter(u=>u.type==="Requirement"&&!_t.has(u.id)).map(u=>u.id);d.push(P("pass.requirements.implemented",w?We.length===0:null,"blocking","PASS requires every active requirement to have an implementation disposition.",w?We:[]));let Je=h.filter(u=>!G.has(u.id)).map(u=>u.id);d.push(P("pass.obligations.verified",w?Je.length===0:null,"blocking","PASS requires every active obligation to link to validation evidence.",w?Je:[]));let Ye=N.filter(u=>!v.has(u.to)).map(u=>u.to);d.push(P("pass.validations.successful",w?Ye.length===0:null,"blocking","PASS requires every referenced Validation to be active and successful.",w?Ye:[]));let Ke=ae(e).filter(u=>u.required&&u.status!=="CURRENT").map(u=>u.id);d.push(P("pass.validations.inputs-current",w?Ke.length===0:null,"blocking","PASS requires every referenced Validation to bind the current design and implementation content hashes.",w?Ke:[]));let Vt=new Set(N.filter(u=>v.has(u.to)).map(u=>u.to)),Ft=new Set(s.filter(u=>u.type==="PRODUCES").map(u=>u.from)),ze=[...Vt].filter(u=>!Ft.has(u));d.push(P("pass.validations.have-evidence",w?ze.length===0:null,"blocking","PASS requires every referenced validation to produce durable evidence.",w?ze:[]));let Qe=n.filter(u=>u.type==="Gap"&&!["resolved","rejected","superseded"].includes(u.lifecycle)&&u.properties?.severity==="blocking").map(u=>u.id);return d.push(P("pass.gaps.no-open-blocking",w?Qe.length===0:null,"blocking","PASS is forbidden while a blocking gap remains open.",w?Qe:[])),d}function ie(e){return String(e??"").trim().toLowerCase()}function se(e,t){let n=Kt(oe(t),oe(e));return n===""||!n.startsWith("..")&&!Yt(n)}async function ye(e,t,n){let s=oe(e,t);if(!se(s,e))return{status:"OUTSIDE_PROJECT",actual:""};try{let[i,a]=await Promise.all([Ze(e),Ze(s)]);if(!se(a,i))return{status:"OUTSIDE_PROJECT",actual:""};if(!(await Jt(a)).isFile())return{status:"INVALID",actual:""};let r=_(await he(a));return{status:r===n?"UNCHANGED":"CHANGED",actual:r}}catch(i){if(i?.code==="ENOENT")return{status:"MISSING",actual:""};throw i}}function Zt(e,t){let n=[],s=e?.parameters?.ontologyPatch;if(e?.status!=="completed")return s&&n.push("ontologyPatch is materialized only by a completed action"),n;if(!s||typeof s!="object"||Array.isArray(s))return["completed action requires parameters.ontologyPatch"];let i=Array.isArray(s.addObjects)?s.addObjects:[],a=Array.isArray(s.addLinks)?s.addLinks:[],r=Array.isArray(s.lifecycleTransitions)?s.lifecycleTransitions:[];i.length+a.length+r.length===0&&n.push("completed action ontologyPatch must contain at least one effect");let l=Qt.get(e.type);if(!l)return[...n,`no ontology patch rule for ${e.type}`];let d=new Map((Array.isArray(t?.objects)?t.objects:[]).map(f=>[f.id,f])),o=new Map;for(let f of i){if(!f?.id||!f?.type){n.push("added ontology object requires id and type");continue}if(l.objectTypes.has(f.type)||n.push(`${e.type} cannot add object type ${f.type}`),(d.has(f.id)||o.has(f.id))&&n.push(`added ontology object ID already exists: ${f.id}`),ie(f?.provenance?.createdBy)!==ie(e.actor)&&n.push(`added object provenance actor mismatch: ${f.id}`),["AttachEvidence","ApplyRepair","ObserveImplementation"].includes(e.type)&&["Evidence","ImplementationUnit"].includes(f.type)){let v=f.type;(typeof f?.properties?.path!="string"||!f.properties.path)&&n.push(`${v} requires a project-relative artifact path: ${f.id}`),/^[a-f0-9]{64}$/u.test(f?.provenance?.contentHash??"")||n.push(`${v} requires a SHA-256 provenance contentHash: ${f.id}`),f?.interfaces?.includes("ContentAddressed")||n.push(`${v} requires the ContentAddressed interface: ${f.id}`)}e.type==="RegisterCandidate"&&f.type==="Candidate"&&((typeof f?.properties?.ref!="string"||!f.properties.ref)&&n.push(`Candidate requires a non-empty ref: ${f.id}`),/^[a-f0-9]{64}$/u.test(f?.provenance?.contentHash??"")||n.push(`Candidate requires a SHA-256 provenance contentHash: ${f.id}`),f?.interfaces?.includes("ContentAddressed")||n.push(`Candidate requires the ContentAddressed interface: ${f.id}`)),e.type==="RecordGateRun"&&f.type==="GateRun"&&(["PASS","FAIL","BLOCKED","SKIPPED"].includes(f?.properties?.status)||n.push(`GateRun requires status PASS, FAIL, BLOCKED, or SKIPPED: ${f.id}`),(typeof f?.properties?.executedAt!="string"||Number.isNaN(Date.parse(f.properties.executedAt)))&&n.push(`GateRun requires a valid executedAt timestamp: ${f.id}`)),["AssertClaim","ChallengeClaim","RecordCounterexample","RecordWaiver","RegisterPolicy"].includes(e.type)&&typeof f?.properties?.statement!="string"&&n.push(`${f.type} requires a statement: ${f.id}`),o.set(f.id,f)}if(e.type==="RunValidation"){let f=nt(t,e.targets);for(let v of o.values()){if(v.type!=="Validation")continue;["PASS","FAIL","BLOCKED"].includes(v.properties?.status)||n.push(`Validation requires status PASS, FAIL, or BLOCKED: ${v.id}`),(typeof v.properties?.executedAt!="string"||Number.isNaN(Date.parse(v.properties.executedAt)))&&n.push(`Validation requires a valid executedAt timestamp: ${v.id}`);let N=v.properties?.inputs;if(!Array.isArray(N)){n.push(`Validation requires an inputs array: ${v.id}`);continue}let G=N.map(E=>E?.objectId);new Set(G).size!==G.length&&n.push(`Validation inputs must use unique objectId values: ${v.id}`);for(let E of N)(typeof E?.objectId!="string"||!/^[a-f0-9]{64}$/u.test(E?.contentHash??""))&&n.push(`Validation input requires objectId and SHA-256 contentHash: ${v.id}`);if(v.properties?.status==="PASS"){let E=new Map(N.map(D=>[D?.objectId,D?.contentHash])),w=f.filter(D=>E.get(D.objectId)!==D.contentHash);w.length>0&&n.push(`PASS Validation must bind current design and implementation inputs: ${v.id} (${w.map(D=>D.objectId).join(", ")})`)}}}let c=new Set((Array.isArray(t?.links)?t.links:[]).map(f=>f.id)),p=new Set,I=new Set([...d.keys(),...o.keys()]),h=Array.isArray(t?.links)?t.links:[],S=new Set(e.targets),y=new Set(h.filter(f=>f.type==="RESOLVES"&&S.has(f.from)).map(f=>f.to)),m=new Set(h.filter(f=>f.type==="VIOLATES"&&y.has(f.from)).map(f=>f.to));for(let f of a){if(!f?.id||!f?.type){n.push("added ontology link requires id and type");continue}l.linkTypes.has(f.type)||n.push(`${e.type} cannot add link type ${f.type}`),(c.has(f.id)||p.has(f.id))&&n.push(`added ontology link ID already exists: ${f.id}`),(!I.has(f.from)||!I.has(f.to))&&n.push(`added ontology link endpoint does not resolve: ${f.id}`),ie(f?.provenance?.createdBy)!==ie(e.actor)&&n.push(`added link provenance actor mismatch: ${f.id}`);let v=o.get(f.from)?.type,N=o.get(f.to)?.type;e.type==="OpenGap"&&(v!=="Gap"||!S.has(f.to))?n.push(`OpenGap VIOLATES must connect a new Gap to an action target: ${f.id}`):e.type==="ObserveImplementation"&&(!S.has(f.from)||N!=="ImplementationUnit")?n.push(`ObserveImplementation IMPLEMENTED_BY must connect a target obligation to a new ImplementationUnit: ${f.id}`):e.type==="ProposeRepair"&&(v!=="RepairAction"||!S.has(f.to))?n.push(`ProposeRepair RESOLVES must connect a new RepairAction to a target Gap: ${f.id}`):e.type==="ApplyRepair"&&(!m.has(f.from)||N!=="ImplementationUnit")?n.push(`ApplyRepair IMPLEMENTED_BY is outside the targeted repair obligation: ${f.id}`):e.type==="RunValidation"&&(!S.has(f.from)||N!=="Validation")?n.push(`RunValidation VERIFIED_BY must connect a target to a new Validation: ${f.id}`):e.type==="AttachEvidence"&&(!S.has(f.from)||N!=="Evidence")?n.push(`AttachEvidence PRODUCES must connect a target Validation to new Evidence: ${f.id}`):e.type==="SupersedeSource"&&!S.has(f.to)?n.push(`SupersedeSource SUPERSEDES must point to an action target: ${f.id}`):e.type==="RegisterCandidate"&&(f.type!=="CONTAINS"||!S.has(f.from)||N!=="Candidate")?n.push(`RegisterCandidate CONTAINS must connect the target Project to a new Candidate: ${f.id}`):e.type==="RecordGateRun"&&f.type==="EVALUATES"&&(v!=="GateRun"||!S.has(f.to))?n.push(`RecordGateRun EVALUATES must connect a new GateRun to the target Candidate: ${f.id}`):e.type==="AssertClaim"&&f.type==="ASSERTS"&&(!S.has(f.from)||N!=="Claim")?n.push(`AssertClaim ASSERTS must connect the target GateRun to a new Claim: ${f.id}`):e.type==="ChallengeClaim"&&(v!=="Challenge"||!S.has(f.to))?n.push(`ChallengeClaim CHALLENGES must connect a new Challenge to the target Claim: ${f.id}`):e.type==="RecordCounterexample"&&(v!=="Counterexample"||!S.has(f.to))?n.push(`RecordCounterexample REFUTES must connect a new Counterexample to the target Claim: ${f.id}`):e.type==="RecordDecision"&&(v!=="Decision"||!S.has(f.to))?n.push(`RecordDecision DECIDES must connect a new Decision to the target GateRun: ${f.id}`):e.type==="RecordWaiver"&&(v!=="Waiver"||!S.has(f.to))?n.push(`RecordWaiver WAIVES must connect a new Waiver to the target Risk: ${f.id}`):e.type==="RegisterPolicy"&&(f.type!=="CONTAINS"||!S.has(f.from)||N!=="Policy")&&n.push(`RegisterPolicy CONTAINS must connect the target Project to a new Policy: ${f.id}`),p.add(f.id)}for(let f of r)e.targets.includes(f?.objectId)||n.push(`lifecycle transition is outside action targets: ${f?.objectId}`),d.has(f?.objectId)?d.get(f.objectId)?.lifecycle===f?.to&&n.push(`lifecycle transition is a no-op: ${f.objectId}`):n.push(`lifecycle transition target does not resolve: ${f?.objectId}`),l.lifecycle.has(f?.to)||n.push(`${e.type} cannot transition lifecycle to ${f?.to}`);let g={IntakeDesignSource:[1,0,0],ConfirmObligation:[0,0,1],ObserveImplementation:[1,1,0],OpenGap:[1,1,0],ProposeRepair:[1,1,0],ApproveRepair:[0,0,1],ApplyRepair:[1,1,0],RunValidation:[1,1,0],AttachEvidence:[1,1,0],CloseGap:[0,0,1],MarkBlocked:[0,0,1],SupersedeSource:[0,0,1],RegisterCandidate:[1,1,0],RecordGateRun:[1,1,0],AssertClaim:[1,1,0],ChallengeClaim:[1,1,0],RecordCounterexample:[1,1,0],RecordDecision:[1,1,0],RecordWaiver:[1,1,0],RegisterPolicy:[1,1,0]}[e.type],R={RegisterCandidate:"CONTAINS",RecordGateRun:"EVALUATES",AssertClaim:"ASSERTS",ChallengeClaim:"CHALLENGES",RecordCounterexample:"REFUTES",RecordDecision:"DECIDES",RecordWaiver:"WAIVES",RegisterPolicy:"CONTAINS"}[e.type];return R&&!a.some(f=>f?.type===R)&&n.push(`${e.type} ontologyPatch requires a ${R} relation`),(i.length<g[0]||a.length<g[1]||r.length<g[2])&&n.push(`${e.type} ontologyPatch is missing its required semantic effects`),n}function ke(e,t,n,s){let i=[];e?.schema!=="dic.ontology-action.v1"&&i.push("action schema must be dic.ontology-action.v1"),/^act-[a-zA-Z0-9._:-]+$/u.test(e?.id??"")||i.push("action ID must use the act- stable-ID format"),e?.expectedSnapshotRevision!==void 0&&e.expectedSnapshotRevision!==t?.snapshotRevision&&i.push("action expectedSnapshotRevision does not match the current snapshot"),et.has(e?.type)||i.push(`unsupported action type: ${e?.type??"<missing>"}`),["proposed","approved","in_progress","completed","rejected","blocked","rolled_back"].includes(e?.status)||i.push(`unsupported action status: ${e?.status??"<missing>"}`);let a=ie(e?.actor);be.get(a)?.has(e?.type)||i.push(`actor ${e?.actor??"<missing>"} cannot perform ${e?.type??"<missing>"}`);let l=new Map((Array.isArray(t?.objects)?t.objects:[]).map(o=>[o.id,o]));if(!Array.isArray(e?.targets)||e.targets.length===0)i.push("action must target at least one ontology object");else{new Set(e.targets).size!==e.targets.length&&i.push("action targets must be unique");let o=et.get(e.type);for(let c of e.targets){let p=l.get(c);p?o?.has(p.type)||i.push(`${e.type} cannot target ${p.type}: ${c}`):i.push(`target does not resolve: ${c}`)}}let d=["completed","blocked","rolled_back"].includes(e?.status);if(e?.status==="completed")for(let[o,c]of[["preconditions","precondition"],["postconditions","postcondition"]])(!Array.isArray(e?.[o])||e[o].length===0||e[o].some(p=>p.status!=="PASS"))&&i.push(`terminal action requires every ${c} to PASS`);else e?.status==="rolled_back"?(!Array.isArray(e?.postconditions)||e.postconditions.length===0||e.postconditions.some(o=>o.status!=="PASS"))&&i.push("rolled_back action requires verified rollback postconditions"):e?.status==="blocked"&&([...Array.isArray(e?.preconditions)?e.preconditions:[],...Array.isArray(e?.postconditions)?e.postconditions:[]].some(c=>c.status!=="PASS")||i.push("blocked action must identify a failed or pending condition"));if(d&&zt.has(e.type)&&(!Array.isArray(e.evidence)||e.evidence.length===0)&&i.push(`${e.type} requires durable evidence before terminal status`),e?.type==="ApplyRepair")if(!Array.isArray(e.allowedPaths)||e.allowedPaths.length===0)i.push("ApplyRepair requires a non-empty allowedPaths scope");else{let o=Array.isArray(n?.protectedPaths)?n.protectedPaths:[];for(let c of e.allowedPaths){let p=oe(s,c);if(!se(p,s)){i.push(`allowed path escapes project root: ${c}`);continue}for(let I of o){let h=oe(s,I);(se(p,h)||se(h,p))&&i.push(`allowed path overlaps protected design source: ${c}`)}}}return i.push(...Zt(e,t)),i}async function it(e,t){if(!["AttachEvidence","ApplyRepair","ObserveImplementation"].includes(e?.type)||e?.status!=="completed")return[];let n=(e?.parameters?.ontologyPatch?.addObjects??[]).filter(i=>["Evidence","ImplementationUnit"].includes(i?.type)),s=[];for(let i of n){let a=i?.properties?.path,r=i?.provenance?.contentHash;if(!a||!r)continue;let l=await ye(t,a,r);l.status==="OUTSIDE_PROJECT"?s.push(`${i.type} artifact escapes project root: ${i.id}`):l.status==="MISSING"?s.push(`${i.type} artifact is missing: ${i.id}`):l.status==="INVALID"?s.push(`${i.type} artifact is not a regular file: ${i.id}`):l.status==="CHANGED"&&s.push(`${i.type} artifact hash mismatch: ${i.id}`)}return s}async function C(e){return JSON.parse(await he(e,"utf8"))}function fe(e){let t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>n!=="recordHash"));return _(JSON.stringify(j(t)))}function J(e){let t=[],n="0".repeat(64),s=!1,i=new Map;for(let[a,r]of e.entries()){let l=a+1,d=JSON.stringify(r?.action),o=_(d);if(r?.schema==="dic.ontology-action-record.v1")s&&t.push(`legacy ledger record follows v2 record at line ${l}`),r.sha256!==o&&t.push(`action ledger hash mismatch at line ${l}`),n=fe(r);else if(r?.schema==="dic.ontology-action-record.v2"){s=!0,r.sequence!==l&&t.push(`action ledger sequence mismatch at line ${l}`),r.previousHash!==n&&t.push(`action ledger chain mismatch at line ${l}`),r.actionHash!==o&&t.push(`action ledger action hash mismatch at line ${l}`);let p=fe(r);r.recordHash!==p&&t.push(`action ledger record hash mismatch at line ${l}`),n=p}else{t.push(`unsupported action ledger schema at line ${l}`);continue}let c=i.get(r.action?.id);c&&c!==o&&t.push(`action ledger ID collision: ${r.action.id}`),i.set(r.action?.id,o)}return{valid:t.length===0,errors:t,headHash:n,recordCount:e.length}}async function st(e,t,{dryRun:n=!1,baseSnapshotRevision:s="",appliedActionIds:i=[]}={}){let a=[];try{a=(await he(e,"utf8")).split(/\r?\n/u).filter(Boolean).map(h=>JSON.parse(h))}catch(h){if(h?.code!=="ENOENT")throw h}let r=J(a);if(!r.valid)throw new Error(r.errors.join("; "));let l=JSON.stringify(t),d=_(l),o=a.find(h=>h.action?.id===t.id);if(o){if((o.actionHash??o.sha256)!==d)throw new Error(`action ID collision with different payload: ${t.id}`);return{recorded:!1,duplicate:!0,sha256:d,actionHash:d,recordHash:o.recordHash??fe(o),ledgerHeadHash:r.headHash}}let c=new Set(i),p=a.map(h=>h.action?.id).filter(h=>h&&!c.has(h));if(p.length>0)throw new Error(`ledger has unapplied action(s): ${p.join(", ")}; run ontology-reconcile before recording another action`);if(!/^[a-f0-9]{64}$/u.test(s))throw new Error("recording an action requires a canonical base snapshot revision");let I={schema:"dic.ontology-action-record.v2",sequence:a.length+1,recordedAt:new Date().toISOString(),previousHash:r.headHash,baseSnapshotRevision:s,actionHash:d,action:t};return I.recordHash=fe(I),n||await Wt(e,`${JSON.stringify(I)}
|
|
3
|
+
`,"utf8"),{recorded:!n,duplicate:!1,dryRun:n,sha256:d,actionHash:d,recordHash:I.recordHash,ledgerHeadHash:I.recordHash,sequence:I.sequence,baseSnapshotRevision:s}}function Pe(e){return e.split(/\r?\n/u).filter(Boolean).map((t,n)=>{try{return JSON.parse(t)}catch{throw new Error(`invalid action ledger JSON at line ${n+1}`)}})}async function me(e){try{let t=Pe(await he(e,"utf8")),n=J(t);if(!n.valid)throw new Error(n.errors.join("; "));return t}catch(t){if(t?.code==="ENOENT")return[];throw t}}function Se(e,t,n,s){let i=J(t);if(!i.valid)throw new Error(i.errors.join("; "));let a=structuredClone(e);a.appliedActionIds=Array.isArray(a.appliedActionIds)?[...a.appliedActionIds]:[];let r=new Set(a.appliedActionIds),l=new Map,d=0,o=0;for(let p of t){let I=JSON.stringify(p.action),h=_(I),S=l.get(p.action?.id);if(S&&S!==h)throw new Error(`action ledger ID collision: ${p.action.id}`);if(l.set(p.action?.id,h),r.has(p.action.id)){o+=1;continue}if(p.schema==="dic.ontology-action-record.v2"&&p.baseSnapshotRevision!==a.snapshotRevision)throw new Error(`action ${p.action.id} was recorded against snapshot ${p.baseSnapshotRevision}, current revision is ${a.snapshotRevision}`);let y=ke(p.action,a,n,s);if(y.length>0)throw new Error(`action ${p.action.id} cannot be materialized: ${y.join("; ")}`);let m=p.action.parameters.ontologyPatch;a.objects.push(...structuredClone(m.addObjects??[])),a.links.push(...structuredClone(m.addLinks??[]));let g=new Map(a.objects.map(R=>[R.id,R]));for(let R of m.lifecycleTransitions??[])g.get(R.objectId).lifecycle=R.to;a.appliedActionIds.push(p.action.id),r.add(p.action.id),a.snapshotRevision=Ce(a),d+=1}a.snapshotRevision=Ce(a),a.invariantResults=ge(a);let c=a.invariantResults.filter(p=>p.status==="FAIL"&&p.severity==="blocking");if(c.length>0)throw new Error(`reconciled ontology violates structural invariants: ${c.map(p=>p.id).join(", ")}`);return{snapshot:a,applied:d,skipped:o,total:t.length}}function W(e,t,n=""){let s=Array.isArray(e?.objects)?e.objects:[],i=Array.isArray(e?.links)?e.links:[],a=new Map(s.map(r=>[r.id,r]));if(t==="uncovered"){let r=new Set(s.filter(c=>c.type==="ImplementationUnit"&&["active","confirmed","resolved"].includes(c.lifecycle)).map(c=>c.id)),l=new Set(i.filter(c=>c.type==="IMPLEMENTED_BY"&&r.has(c.to)).map(c=>c.from)),d=new Set(s.filter(c=>c.type==="Validation"&&["active","confirmed","resolved"].includes(c.lifecycle)&&c.properties?.status==="PASS").map(c=>c.id)),o=new Set(i.filter(c=>c.type==="VERIFIED_BY"&&d.has(c.to)).map(c=>c.from));return s.filter(c=>["Requirement","Scenario"].includes(c.type)&&["active","confirmed"].includes(c.lifecycle)&&(!l.has(c.id)||!o.has(c.id))).map(c=>({id:c.id,type:c.type,lifecycle:c.lifecycle,missingImplementation:c.type==="Requirement"&&!l.has(c.id),missingValidation:!o.has(c.id)}))}if(t==="gaps")return s.filter(r=>r.type==="Gap"&&!["resolved","rejected","superseded"].includes(r.lifecycle));if(t==="unevidenced"){let r=new Set(i.filter(l=>l.type==="PRODUCES").map(l=>l.from));return s.filter(l=>l.type==="Validation"&&!r.has(l.id))}if(t==="impact"){if(!n||!a.has(n))throw new Error("impact query requires --id resolving to an ontology object");let r=new Set(["PROPOSES","DERIVED_FROM","REFINES","IMPLEMENTED_BY","VERIFIED_BY","VIOLATES","RESOLVES","PRODUCES","SUPERSEDES"]),l=new Map;for(let c of i.filter(p=>r.has(p.type)))l.has(c.from)||l.set(c.from,[]),l.has(c.to)||l.set(c.to,[]),l.get(c.from).push({id:c.to,link:c}),l.get(c.to).push({id:c.from,link:c});let d=[{id:n,depth:0}],o=new Map([[n,{depth:0,via:null}]]);for(;d.length>0;){let c=d.shift();if(!(c.depth>=4))for(let p of l.get(c.id)??[])o.has(p.id)||(o.set(p.id,{depth:c.depth+1,via:p.link.type}),d.push({id:p.id,depth:c.depth+1}))}return[...o.entries()].map(([c,p])=>({id:c,type:a.get(c)?.type,lifecycle:a.get(c)?.lifecycle,...p}))}throw new Error(`unsupported ontology query: ${t}`)}async function re(e,t){let n=(Array.isArray(e?.objects)?e.objects:[]).filter(i=>i.type==="DesignSource"),s=[];for(let i of n){let a=i?.provenance?.contentHash??"",r=i?.properties?.path??i?.provenance?.source;if(!r||!a){s.push({id:i.id,path:r??"",status:"UNTRACKED",expected:a,actual:""});continue}let l=await ye(t,r,a);s.push({id:i.id,path:r,status:l.status,expected:a,actual:l.actual})}return s}async function ce(e,t){let n=Array.isArray(e?.objects)?e.objects:[],s=Array.isArray(e?.links)?e.links:[],i=new Map(n.map(o=>[o.id,o])),a=new Set(n.filter(o=>o.type==="Validation"&&["active","confirmed","resolved"].includes(o.lifecycle)).map(o=>o.id)),r=new Set(s.filter(o=>o.type==="PRODUCES"&&a.has(o.from)&&i.get(o.to)?.type==="Evidence").map(o=>o.to)),l=n.filter(o=>o.type==="Evidence"),d=[];for(let o of l){let c=o?.provenance?.contentHash??"",p=o?.properties?.path??"",I=r.has(o.id);if(!p||!c){d.push({id:o.id,path:p,required:I,status:"UNTRACKED",expected:c,actual:""});continue}if(I&&!["active","confirmed","resolved"].includes(o.lifecycle)){d.push({id:o.id,path:p,required:I,status:"INACTIVE",expected:c,actual:""});continue}let h=await ye(t,p,c);d.push({id:o.id,path:p,required:I,status:h.status,expected:c,actual:h.actual})}return d}async function le(e,t){let n=Array.isArray(e?.objects)?e.objects:[],s=Array.isArray(e?.links)?e.links:[],i=new Map(n.map(o=>[o.id,o])),a=new Set(n.filter(o=>["Requirement","Scenario"].includes(o.type)&&["active","confirmed"].includes(o.lifecycle)).map(o=>o.id)),r=new Set(s.filter(o=>o.type==="IMPLEMENTED_BY"&&a.has(o.from)&&i.get(o.to)?.type==="ImplementationUnit").map(o=>o.to)),l=n.filter(o=>o.type==="ImplementationUnit"),d=[];for(let o of l){let c=o?.provenance?.contentHash??"",p=o?.properties?.path??"",I=r.has(o.id);if(!p||!c){d.push({id:o.id,path:p,required:I,status:"UNTRACKED",expected:c,actual:""});continue}if(I&&!["active","confirmed","resolved"].includes(o.lifecycle)){d.push({id:o.id,path:p,required:I,status:"INACTIVE",expected:c,actual:""});continue}let h=await ye(t,p,c);d.push({id:o.id,path:p,required:I,status:h.status,expected:c,actual:h.actual})}return d}function en(e,t){let n=t.filter(d=>d.status!=="UNCHANGED"),s=new Map;for(let d of n)for(let o of W(e,"impact",d.id)){let c=s.get(o.id);(!c||o.depth<c.depth)&&s.set(o.id,{...o,changedSourceIds:c?.changedSourceIds??[]}),s.get(o.id).changedSourceIds.push(d.id)}let i=[...s.values()].map(d=>({...d,changedSourceIds:[...new Set(d.changedSourceIds)].sort()})).sort((d,o)=>d.depth-o.depth||d.id.localeCompare(o.id)),a=new Set(i.map(d=>d.type)),r=[],l=(d,o)=>{r.some(c=>c.stage===d)||r.push({stage:d,reason:o})};return n.length>0&&(l("workflow-intake","Refresh changed or missing design-source revisions."),l("spec-reader","Re-read the changed authoritative source neighborhood."),l("contract-oracle","Reconfirm affected obligations and lifecycle.")),["Requirement","Scenario"].some(d=>a.has(d))&&(l("flow-auditor","Re-evaluate affected behavioral and lifecycle flows."),l("impl-inspector","Recheck implementation mappings for affected obligations.")),["ImplementationUnit","Gap","RepairAction"].some(d=>a.has(d))&&(l("repair-planner","Replan only impacted gaps and repair actions."),l("code-repairer","Execute approved impacted repair slices only.")),["Validation","Evidence"].some(d=>a.has(d))&&l("validation-runner","Refresh invalidated validation and evidence."),["Candidate","GateRun","Claim","Policy"].some(d=>a.has(d))&&l("evidence-auditor","Re-audit candidate-bound claims and gate evidence after semantic impact."),["Challenge","Counterexample","Risk","Waiver"].some(d=>a.has(d))&&l("adversarial-challenger","Re-evaluate affected challenge hypotheses and counterexamples."),n.length>0&&l("final-reviewer","Recompute invariants after incremental reconciliation."),{clean:n.length===0,changedSources:n,impactedObjects:i,recommendedStages:r}}function ot(e,t,n,s){let i=en(e,t),a=n.filter(c=>c.required&&c.status!=="UNCHANGED"),r=s.filter(c=>c.required&&c.status!=="UNCHANGED"),l=new Map(i.impactedObjects.map(c=>[c.id,{...c,integrityIssueIds:[]}]));for(let c of[...a,...r])for(let p of W(e,"impact",c.id)){let I=l.get(p.id);(!I||p.depth<I.depth)&&l.set(p.id,{...p,changedSourceIds:I?.changedSourceIds??[],integrityIssueIds:I?.integrityIssueIds??[]}),l.get(p.id).integrityIssueIds.push(c.id)}let d=i.recommendedStages.map(c=>({...c})),o=(c,p)=>{d.some(I=>I.stage===c)||d.push({stage:c,reason:p})};return a.length>0&&(o("impl-inspector","Reinspect drifted implementation files and refresh or challenge their mappings."),o("validation-runner","Rerun validations affected by implementation drift.")),r.length>0&&(o("validation-runner","Regenerate missing or drifted content-addressed Evidence artifacts."),o("evidence-auditor","Re-audit claims that depended on missing or drifted Evidence.")),(a.length>0||r.length>0)&&o("final-reviewer","Recompute gates and Attestation after integrity recovery."),{...i,clean:i.clean&&a.length===0&&r.length===0,implementationIssues:a,evidenceIssues:r,impactedObjects:[...l.values()].map(c=>({...c,changedSourceIds:[...new Set(c.changedSourceIds??[])].sort(),integrityIssueIds:[...new Set(c.integrityIssueIds??[])].sort()})).sort((c,p)=>c.depth-p.depth||c.id.localeCompare(p.id)),recommendedStages:d}}function at(e,t){let n=Array.isArray(e?.objects)?e.objects:[],s=Array.isArray(e?.links)?e.links:[],i=new Map(n.map(h=>[h.id,h])),a=i.get(t);if(!a)throw new Error(`ontology object does not resolve: ${t}`);let r=h=>({id:h.id,type:h.type,lifecycle:h.lifecycle,title:h.properties?.title??"",path:h.properties?.path??"",status:h.properties?.status??"",sourceLocator:h.provenance?.sourceLocator??"",sourceRevision:h.provenance?.sourceRevision??"",createdBy:h.provenance?.createdBy??""}),l=[];for(let h of s)h.from===t&&i.has(h.to)?l.push({direction:"outgoing",type:h.type,object:r(i.get(h.to)),linkId:h.id}):h.to===t&&i.has(h.from)&&l.push({direction:"incoming",type:h.type,object:r(i.get(h.from)),linkId:h.id});l.sort((h,S)=>h.type.localeCompare(S.type)||h.object.id.localeCompare(S.object.id));let d=new Set(["DesignSource","ImplementationUnit","Gap","RepairAction","Validation","Evidence","Decision","Risk","Candidate","GateRun","Claim","Challenge","Counterexample","Waiver","Policy"]),o=new Map;for(let h of s)o.has(h.from)||o.set(h.from,[]),o.has(h.to)||o.set(h.to,[]),o.get(h.from).push({id:h.to,type:h.type,direction:"outgoing"}),o.get(h.to).push({id:h.from,type:h.type,direction:"incoming"});let c=[{id:t,objects:[t],links:[]}],p=new Map([[t,0]]),I=[];for(;c.length>0;){let h=c.shift();if(!(h.links.length>=4))for(let S of o.get(h.id)??[]){if(h.objects.includes(S.id))continue;let y=[...h.objects,S.id],m=[...h.links,{type:S.type,direction:S.direction}],g=i.get(S.id);if(!g)continue;d.has(g.type)&&I.push({target:r(g),objectIds:y,links:m});let R=m.length;(p.get(S.id)??Number.POSITIVE_INFINITY)>R&&(p.set(S.id,R),c.push({id:S.id,objects:y,links:m}))}}return I.sort((h,S)=>h.links.length-S.links.length||h.target.type.localeCompare(S.target.type)||h.target.id.localeCompare(S.target.id)),{object:r(a),properties:a.properties??{},provenance:a.provenance??{},interfaces:a.interfaces??[],relations:l,evidenceChains:I}}function _(e){return tt("sha256").update(e).digest("hex")}function rt(e){let t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!["attestationId","contentHash"].includes(n)));return _(JSON.stringify(j(t)))}function ct(e){return ae(e).filter(t=>t.required).map(t=>({id:t.id,status:t.status,targetIds:t.targetIds,requiredInputIds:t.requiredInputIds,missingInputIds:t.missingInputIds,staleInputIds:t.staleInputIds}))}function lt({snapshot:e,ledgerText:t,ledgerHeadHash:n,status:s,summary:i,sourceDrift:a,evidenceIntegrity:r,implementationIntegrity:l,invariants:d,createdAt:o=new Date().toISOString()}){let c={schema:"dic.ontology-attestation.v1",attestationId:"",contentHash:"",version:e.version,status:s,final:!0,summary:i,createdAt:o,snapshot:{snapshotId:e.snapshotId,snapshotRevision:e.snapshotRevision},ledger:{sha256:_(t),actionCount:t.split(/\r?\n/u).filter(Boolean).length,headHash:n},sources:a.map(p=>({id:p.id,path:p.path,status:p.status,contentHash:p.actual||p.expected||""})),evidence:r.filter(p=>p.required).map(p=>({id:p.id,path:p.path,status:p.status,contentHash:p.actual||p.expected||""})),implementations:l.filter(p=>p.required).map(p=>({id:p.id,path:p.path,status:p.status,contentHash:p.actual||p.expected||""})),validationCausality:ct(e),invariants:d};return c.contentHash=rt(c),c.attestationId=`att-${c.contentHash.slice(0,16)}`,c}function dt({attestation:e,snapshot:t,ledgerText:n,ledgerHeadHash:s,sourceDrift:i,evidenceIntegrity:a,implementationIntegrity:r,invariants:l,expectedContentHash:d=""}){let o=[],c=rt(e);e?.schema!=="dic.ontology-attestation.v1"&&o.push("unsupported ontology attestation schema"),["PASS","PARTIAL","BLOCKED","FAIL"].includes(e?.status)||o.push("unsupported ontology attestation status"),e?.final!==!0&&o.push("ontology attestation is not final"),(typeof e?.summary!="string"||!e.summary.trim())&&o.push("ontology attestation summary is empty"),(typeof e?.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))&&o.push("ontology attestation timestamp is invalid"),e?.contentHash!==c&&o.push("attestation content hash mismatch"),d&&e?.contentHash!==d&&o.push("attestation content hash does not match the external anchor"),e?.attestationId!==`att-${c.slice(0,16)}`&&o.push("attestation ID does not match its content hash"),(e?.snapshot?.snapshotId!==t?.snapshotId||e?.snapshot?.snapshotRevision!==t?.snapshotRevision)&&o.push("attestation snapshot identity or revision is stale"),e?.version!==t?.version&&o.push("attestation version does not match the snapshot"),e?.ledger?.sha256!==_(n)&&o.push("attestation action ledger hash is stale"),e?.ledger?.headHash!==s&&o.push("attestation action ledger head is stale");let p=n.split(/\r?\n/u).filter(Boolean).length;e?.ledger?.actionCount!==p&&o.push("attestation action count is stale");let I=i.map(m=>({id:m.id,path:m.path,status:m.status,contentHash:m.actual||m.expected||""}));JSON.stringify(j(e?.sources??[]))!==JSON.stringify(j(I))&&o.push("attested source inventory is stale");let h=a.filter(m=>m.required).map(m=>({id:m.id,path:m.path,status:m.status,contentHash:m.actual||m.expected||""}));JSON.stringify(j(e?.evidence??[]))!==JSON.stringify(j(h))&&o.push("attested Evidence artifact inventory is stale");let S=r.filter(m=>m.required).map(m=>({id:m.id,path:m.path,status:m.status,contentHash:m.actual||m.expected||""}));JSON.stringify(j(e?.implementations??[]))!==JSON.stringify(j(S))&&o.push("attested ImplementationUnit artifact inventory is stale"),JSON.stringify(j(e?.validationCausality??[]))!==JSON.stringify(j(ct(t)))&&o.push("attested Validation input causality is stale"),JSON.stringify(j(e?.invariants??[]))!==JSON.stringify(j(l))&&o.push("attested invariant results are stale");let y=l.filter(m=>m.status==="FAIL"&&m.severity==="blocking");return y.length>0&&o.push(`current ontology gate fails: ${y.map(m=>m.id).join(", ")}`),{valid:o.length===0,errors:o,attestationId:e?.attestationId??"",status:e?.status??""}}function O(e){return String(e??"").replace(/\|/gu,"\\|").replace(/\r?\n/gu," ")}function pt(e,t,n,s,i=""){let a=Array.isArray(e?.objects)?e.objects:[],r=Array.isArray(e?.links)?e.links:[],l=new Map;for(let g of a)l.set(g.type,(l.get(g.type)??0)+1);let d=W(e,"uncovered"),o=W(e,"gaps"),c=W(e,"unevidenced"),p=ae(e),I=ge(e,i),h=t.filter(g=>g.status!=="UNCHANGED");I.push({id:"pass.sources.no-drift",status:i==="PASS"?h.length===0?"PASS":"FAIL":"NOT_APPLICABLE",severity:"blocking",message:"PASS requires every tracked design source to match its recorded revision.",objectIds:i==="PASS"?h.map(g=>g.id):[]});let S=s.filter(g=>g.required&&g.status!=="UNCHANGED");I.push({id:"pass.implementation.artifacts-current",status:i==="PASS"?S.length===0?"PASS":"FAIL":"NOT_APPLICABLE",severity:"blocking",message:"PASS requires every required ImplementationUnit artifact to exist and match its recorded SHA-256 hash.",objectIds:i==="PASS"?S.map(g=>g.id):[]});let y=n.filter(g=>g.required&&g.status!=="UNCHANGED");return I.push({id:"pass.evidence.artifacts-current",status:i==="PASS"?y.length===0?"PASS":"FAIL":"NOT_APPLICABLE",severity:"blocking",message:"PASS requires every required Evidence artifact to exist and match its recorded SHA-256 hash.",objectIds:i==="PASS"?y.map(g=>g.id):[]}),["# DIC Ontology Report","",`- Snapshot: \`${e.snapshotId}\``,`- Revision: \`${e.snapshotRevision||"unversioned"}\``,`- Requested gate: ${i||"STRUCTURAL"}`,`- Objects / links: ${a.length} / ${r.length}`,`- Uncovered obligations: ${d.length}`,`- Open gaps: ${o.length}`,`- Unevidenced validations: ${c.length}`,"","## Object Inventory","","| Type | Count |","| --- | ---: |",...[...l.entries()].sort(([g],[R])=>g.localeCompare(R)).map(([g,R])=>`| ${O(g)} | ${R} |`),"","## Gate Invariants","","| Status | Severity | Invariant | Affected |","| --- | --- | --- | ---: |",...I.map(g=>`| ${g.status} | ${g.severity} | ${O(g.id)} | ${g.objectIds.length} |`),"","## Design Sources","","| Status | Object | Path |","| --- | --- | --- |",...t.map(g=>`| ${g.status} | \`${O(g.id)}\` | \`${O(g.path)}\` |`),"","## Uncovered Obligations","","| Object | Type | Missing implementation | Missing validation |","| --- | --- | --- | --- |",...d.map(g=>`| \`${O(g.id)}\` | ${g.type} | ${g.missingImplementation} | ${g.missingValidation} |`),"","## Evidence Artifacts","","| Status | Required | Object | Path |","| --- | --- | --- | --- |",...n.map(g=>`| ${g.status} | ${g.required} | \`${O(g.id)}\` | \`${O(g.path)}\` |`),"","## Validation Causality","","| Status | Required | Validation | Targets | Required inputs | Missing | Stale |","| --- | --- | --- | --- | --- | --- | --- |",...p.map(g=>`| ${g.status} | ${g.required} | \`${O(g.id)}\` | ${O(g.targetIds.join(", "))} | ${O(g.requiredInputIds.join(", "))} | ${O(g.missingInputIds.join(", "))} | ${O(g.staleInputIds.join(", "))} |`),"","## Implementation Artifacts","","| Status | Required | Object | Path |","| --- | --- | --- | --- |",...s.map(g=>`| ${g.status} | ${g.required} | \`${O(g.id)}\` | \`${O(g.path)}\` |`),"","## Open Gaps","","| Object | Lifecycle | Severity | Title |","| --- | --- | --- | --- |",...o.map(g=>`| \`${O(g.id)}\` | ${g.lifecycle} | ${O(g.properties?.severity)} | ${O(g.properties?.title)} |`),"","## Unevidenced Validations","","| Object | Lifecycle | Status |","| --- | --- | --- |",...c.map(g=>`| \`${O(g.id)}\` | ${g.lifecycle} | ${O(g.properties?.status)} |`),"","_Generated from ontology state; edit the ontology through authorized actions, then regenerate this view._",""].join(`
|
|
4
|
+
`)}import{execFile as tn}from"node:child_process";import{createHash as nn}from"node:crypto";import{promisify as sn}from"node:util";import{readFile as yt,realpath as ut,stat as mt}from"node:fs/promises";import{isAbsolute as on,relative as St,resolve as Q}from"node:path";var an=sn(tn),de=new Set(["PASS","PASS_WITH_FOLLOW_UP","SKIPPED"]),rn=["reports/","logs/"];function Oe(e){return Array.isArray(e)?e.map(Oe):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Oe(e[t])])):e}function Ie(e){return nn("sha256").update(e).digest("hex")}function X(e){return Ie(JSON.stringify(Oe(e)))}function Te(e){return X(e)}function De(e){return String(e).replaceAll("\\","/").replace(/^\.\//u,"")}function cn(e){let t=De(e);return rn.some(n=>t.startsWith(n))}async function we(e,t,n="utf8"){try{return await an("git",t,{cwd:e,encoding:n,maxBuffer:64*1024*1024,windowsHide:!0})}catch(s){let i=String(s?.stderr??s?.message??"").trim();throw new Error(`\u8BA1\u7B97\u5019\u9009\u7248\u672C\u8EAB\u4EFD\u9700\u8981 Git \u5DE5\u4F5C\u533A\uFF1A${i}`)}}async function pe(e){let t=Q(e),[{stdout:n},{stdout:s},{stdout:i}]=await Promise.all([we(t,["rev-parse","--show-toplevel"]),we(t,["rev-parse","HEAD"]),we(t,["diff","--binary","--no-ext-diff","HEAD","--",".",":(exclude)reports/**",":(exclude)logs/**"])]),a=Q(n.trim()),r=s.trim(),{stdout:l}=await we(t,["ls-files","--others","--exclude-standard","-z","--","."],null),d=l.toString("utf8").split("\0").filter(Boolean).map(De).filter(h=>!cn(h)).sort(),o=[];for(let h of d){let S=Q(a,h);(await mt(S)).isFile()&&o.push({path:h,contentHash:Ie(await yt(S))})}let c=Ie(i),I=X({head:r,trackedDiffHash:c,untracked:o});return{id:`candidate-${I.slice(0,16)}`,ref:i.length>0||o.length>0?`${r}+worktree`:r,contentHash:I,head:r,clean:i.length===0&&o.length===0,trackedDiffHash:c,untracked:o}}function U(e){return Array.isArray(e)&&e.length>0}function L(e,t,n,s,i,a,r,l,d,o){return{id:e,domain:t,skill:n,agent:s,applicability:i,defaultDisposition:a,reason:r,dependsOn:l,invalidatedBy:d,requiredEvidence:o}}function wt(e,t,n=new Date().toISOString()){let s=!!(e?.consistencyScope?.semanticCrossSpecSearchRequired||U(e?.relatedBaselineSpecs)||U(e?.semanticConsistencyCandidates)),i=!!(U(e?.designEntry?.designMap?.architectureDesigns)||U(e?.designEntry?.designMap?.moduleDesigns)||U(e?.designEntry?.designMap?.adrs)||(e?.riskFamilies??[]).includes("architecture")),a=U(e?.implementationRoots),r=U(e?.testRoots)||U(e?.validationCommands),l=new Set(["security","reliability","concurrency","performance","data-integrity","migration","compatibility"]),d=(e?.riskFamilies??[]).some(S=>l.has(String(S).toLowerCase()))||U(e?.semanticConsistencyCandidates),o={security:{domain:"ASSURANCE",skill:"quality-code-review",reason:"\u5B58\u5728\u5B89\u5168\u8FB9\u754C\u6216\u5A01\u80C1\u66B4\u9732\uFF0C\u5FC5\u987B\u6267\u884C\u4E13\u9879\u4FDD\u969C\u3002",evidence:["\u5A01\u80C1\u4E13\u9879\u8BC4\u5BA1","\u5B89\u5168\u6D4B\u8BD5\u6216\u626B\u63CF\u8BC1\u636E"]},performance:{domain:"TEST",skill:"quality-dt-review",reason:"\u5B58\u5728\u6027\u80FD\u98CE\u9669\uFF0C\u5FC5\u987B\u6267\u884C\u6709\u9884\u7B97\u7EA6\u675F\u4E14\u53EF\u590D\u73B0\u7684\u6D4B\u91CF\u3002",evidence:["\u6027\u80FD\u57FA\u51C6\u6216\u5256\u6790\u7ED3\u679C","\u6027\u80FD\u9884\u7B97\u51B3\u5B9A"]},reliability:{domain:"TEST",skill:"quality-dt-review",reason:"\u5B58\u5728\u53EF\u9760\u6027\u98CE\u9669\uFF0C\u5FC5\u987B\u9A8C\u8BC1\u6545\u969C\u8DEF\u5F84\u548C\u6062\u590D\u80FD\u529B\u3002",evidence:["\u6545\u969C\u8DEF\u5F84\u9A8C\u8BC1","\u6062\u590D\u80FD\u529B\u4E0E\u6B8B\u4F59\u98CE\u9669\u51B3\u5B9A"]},concurrency:{domain:"TEST",skill:"quality-dt-review",reason:"\u5B58\u5728\u5E76\u53D1\u98CE\u9669\uFF0C\u5FC5\u987B\u9A8C\u8BC1\u7ADE\u4E89\u3001\u65F6\u5E8F\u548C\u4EA4\u9519\u6267\u884C\u3002",evidence:["\u5E76\u53D1\u538B\u529B\u9A8C\u8BC1","\u65F6\u5E8F\u4E0D\u53D8\u91CF\u51B3\u5B9A"]},"data-integrity":{domain:"ASSURANCE",skill:"quality-code-review",reason:"\u5B58\u5728\u6570\u636E\u5B8C\u6574\u6027\u98CE\u9669\uFF0C\u5FC5\u987B\u5206\u6790\u4E0D\u53D8\u91CF\u3001\u635F\u574F\u8DEF\u5F84\u548C\u6062\u590D\u8DEF\u5F84\u3002",evidence:["\u6570\u636E\u4E0D\u53D8\u91CF\u8BC4\u5BA1","\u6570\u636E\u635F\u574F\u4E0E\u6062\u590D\u9A8C\u8BC1"]},migration:{domain:"DESIGN",skill:"quality-sr-ar-review",reason:"\u5B58\u5728\u8FC1\u79FB\u98CE\u9669\uFF0C\u5FC5\u987B\u9A8C\u8BC1\u6B63\u5411\u3001\u53CD\u5411\u548C\u56DE\u6EDA\u8DEF\u5F84\u3002",evidence:["\u8FC1\u79FB\u517C\u5BB9\u77E9\u9635","\u56DE\u6EDA\u9A8C\u8BC1"]},compatibility:{domain:"DESIGN",skill:"quality-spec-review",reason:"\u5B58\u5728\u517C\u5BB9\u6027\u98CE\u9669\uFF0C\u5FC5\u987B\u660E\u786E\u8986\u76D6\u6D88\u8D39\u8005\u548C\u7248\u672C\u8303\u56F4\u3002",evidence:["\u517C\u5BB9\u6027\u77E9\u9635","\u7248\u672C\u5316\u5951\u7EA6\u9A8C\u8BC1"]}},c=[...new Set((e?.riskFamilies??[]).map(S=>String(S).toLowerCase()))].filter(S=>o[S]).sort().map(S=>{let y=o[S];return L(`specialist.${S}`,y.domain,y.skill,"","REQUIRED","RUN",y.reason,["development.code-review","test.developer-test"],["DESIGN","POLICY","IMPLEMENTATION","TEST","FIXTURE","PIPELINE","CANDIDATE"],y.evidence)}),p=[L("design.authority","DESIGN","workflow-profile","profile-builder","REQUIRED","RUN","\u786E\u8BA4\u4ED3\u5E93\u7279\u5B9A\u7684\u6743\u5A01\u6E90\u3001\u8303\u56F4\u3001\u547D\u4EE4\u548C\u4FDD\u62A4\u8DEF\u5F84\u3002",[],["DESIGN","POLICY","CANDIDATE"],["\u9879\u76EE\u753B\u50CF","\u6743\u5A01\u6E90\u6E05\u5355"]),L("design.cross-spec","DESIGN","quality-cross-spec-consistency","semantic-conflict-auditor","CONDITIONAL",s?"RUN":"ASSESS",s?"\u9879\u76EE\u753B\u50CF\u53D1\u73B0\u5173\u8054\u57FA\u7EBF\u6216\u8BED\u4E49\u4E00\u81F4\u6027\u5019\u9009\uFF0C\u5FC5\u987B\u6267\u884C\u8DE8\u89C4\u683C\u5206\u6790\u3002":"\u5FC5\u987B\u8BB0\u5F55\u4ED3\u5E93\u7EA7\u8BED\u4E49\u51B2\u7A81\u5206\u6790\u4E0D\u9002\u7528\u7684\u539F\u56E0\u3002",["design.authority"],["DESIGN","POLICY","CANDIDATE"],["\u6210\u5BF9\u5F15\u7528\u6743\u5A01\u6E90\u7684\u8BED\u4E49\u51B2\u7A81\u62A5\u544A"]),L("design.spec","DESIGN","quality-spec-review","contract-oracle","REQUIRED","RUN","\u53EA\u6709\u786E\u8BA4\u4E14\u53EF\u6D4B\u8BD5\u7684\u5B9E\u73B0\u4E49\u52A1\u624D\u80FD\u8FDB\u5165\u5F00\u53D1\u9636\u6BB5\u3002",["design.cross-spec"],["DESIGN","POLICY","CANDIDATE"],["\u89C4\u683C\u8BC4\u5BA1","\u5DF2\u786E\u8BA4\u5B9E\u73B0\u4E49\u52A1\u6E05\u5355"]),L("design.architecture","DESIGN","quality-sr-ar-review","","CONDITIONAL",i?"RUN":"ASSESS",i?"\u5B58\u5728\u67B6\u6784\u8BBE\u8BA1\u3001\u6A21\u5757\u8BBE\u8BA1\u3001\u67B6\u6784\u51B3\u7B56\u8BB0\u5F55\u6216\u67B6\u6784\u98CE\u9669\u3002":"\u5FC5\u987B\u8BB0\u5F55\u67B6\u6784\u4E0E\u5B9E\u73B0\u8BC4\u5BA1\u4E0D\u9002\u7528\u7684\u539F\u56E0\u3002",["design.spec"],["DESIGN","POLICY","IMPLEMENTATION","CANDIDATE"],["\u67B6\u6784\u5B9E\u73B0\u51B3\u5B9A"]),L("delivery.plan","DELIVERY","quality-ci-gate","","REQUIRED","RUN","\u5F00\u53D1\u524D\u58F0\u660E\u68C0\u67E5\u9879\u3001\u8D44\u6E90\u9884\u7B97\u3001\u8BC1\u636E\u8981\u6C42\u548C\u5931\u8D25\u7B56\u7565\u3002",["design.architecture"],["DESIGN","POLICY","PIPELINE","CANDIDATE"],["\u7ED1\u5B9A\u5019\u9009\u7248\u672C\u7684\u6301\u7EED\u96C6\u6210\u8BA1\u5212\u51B3\u5B9A"]),L("development.consistency","DEVELOPMENT","workflow-repair","impl-inspector","REQUIRED","RUN","\u5F00\u53D1\u5B8C\u6210\u540E\u68C0\u67E5\u5E76\u6536\u655B\u8BBE\u8BA1\u4E0E\u5B9E\u73B0\u4E00\u81F4\u6027\u3002",["delivery.plan"],["DESIGN","IMPLEMENTATION","TEST","FIXTURE","CANDIDATE"],["\u4E00\u81F4\u6027\u7F3A\u53E3\u62A5\u544A","\u4FEE\u590D\u4E0E\u9A8C\u8BC1\u8BC1\u636E","\u672C\u4F53\u5FEB\u7167"]),L("development.code-review","DEVELOPMENT","quality-code-review","","CONDITIONAL",a?"RUN":"ASSESS",a?"\u9879\u76EE\u753B\u50CF\u4E2D\u5B58\u5728\u5B9E\u73B0\u76EE\u5F55\uFF0C\u5FC5\u987B\u8BC4\u5BA1\u5B9E\u73B0\u53D8\u66F4\u3002":"\u5FC5\u987B\u8BB0\u5F55\u5B9E\u73B0\u53D8\u66F4\u8BC4\u5BA1\u4E0D\u9002\u7528\u7684\u539F\u56E0\u3002",["development.consistency"],["DESIGN","IMPLEMENTATION","POLICY","CANDIDATE"],["\u5E26\u6743\u5A01\u6E90\u951A\u70B9\u7684\u4EE3\u7801\u8BC4\u5BA1"]),L("test.developer-test","TEST","quality-dt-review","validation-runner","CONDITIONAL",r?"RUN":"ASSESS",r?"\u9879\u76EE\u753B\u50CF\u4E2D\u5B58\u5728\u6D4B\u8BD5\u76EE\u5F55\u6216\u53EF\u6267\u884C\u9A8C\u8BC1\u547D\u4EE4\u3002":"\u5FC5\u987B\u8BB0\u5F55\u5F00\u53D1\u8005\u6D4B\u8BD5\u8BC4\u5BA1\u4E0D\u9002\u7528\u7684\u539F\u56E0\u3002",["development.consistency"],["DESIGN","IMPLEMENTATION","TEST","FIXTURE","CANDIDATE"],["\u6D4B\u8BD5\u8D28\u91CF\u8BC4\u5BA1","\u5185\u5BB9\u5BFB\u5740\u9A8C\u8BC1\u65E5\u5FD7"]),...c,L("assurance.adversarial","ASSURANCE","quality-adversarial-challenge","adversarial-challenger","CONDITIONAL",d?"RUN":"ASSESS",d?"\u98CE\u9669\u7C7B\u578B\u6216\u8BED\u4E49\u6B67\u4E49\u8981\u6C42\u6267\u884C\u72EC\u7ACB\u8D28\u8BE2\u3002":"\u5FC5\u987B\u8BB0\u5F55\u4E0D\u5B58\u5728\u5B9E\u8D28\u6027\u72EC\u7ACB\u5931\u8D25\u5047\u8BBE\u7684\u539F\u56E0\u3002",["development.code-review","test.developer-test",...c.map(S=>S.id)],["DESIGN","POLICY","IMPLEMENTATION","TEST","FIXTURE","CANDIDATE"],["\u8D28\u8BE2\u8BB0\u5F55","\u53EF\u590D\u73B0\u53CD\u4F8B\u6216\u5173\u95ED\u8BC1\u636E"]),L("assurance.evidence","ASSURANCE","quality-evidence-audit","evidence-auditor","REQUIRED","RUN","\u7EC8\u6001\u4E3B\u5F20\u5FC5\u987B\u6709\u6548\u3001\u53EF\u590D\u73B0\u5E76\u7ED1\u5B9A\u5F53\u524D\u5019\u9009\u7248\u672C\u3002",["assurance.adversarial"],["DESIGN","POLICY","IMPLEMENTATION","TEST","FIXTURE","PIPELINE","CANDIDATE"],["\u4E3B\u5F20\u4E0E\u8BC1\u636E\u77E9\u9635","\u5B8C\u6574\u6027\u68C0\u67E5\u7ED3\u679C"]),L("delivery.verify","DELIVERY","quality-ci-gate","validation-runner","REQUIRED","RUN","\u9488\u5BF9\u51BB\u7ED3\u7684\u5019\u9009\u7248\u672C\u6267\u884C\u5DF2\u58F0\u660E\u7684\u4EA4\u4ED8\u68C0\u67E5\u3002",["assurance.evidence"],["DESIGN","POLICY","IMPLEMENTATION","TEST","FIXTURE","PIPELINE","CANDIDATE"],["\u7ED1\u5B9A\u5019\u9009\u7248\u672C\u7684\u6301\u7EED\u96C6\u6210\u9A8C\u8BC1\u51B3\u5B9A"]),L("admission.repository","ADMISSION","quality-repository-gate","final-reviewer","REQUIRED","RUN","\u4F9D\u636E\u5F53\u524D\u4E0A\u6E38\u51B3\u5B9A\u548C\u7EC8\u6001\u8BC1\u660E\u4F5C\u51FA\u4ED3\u5E93\u51C6\u5165\u51B3\u5B9A\u3002",["delivery.verify"],["DESIGN","POLICY","IMPLEMENTATION","TEST","FIXTURE","PIPELINE","CANDIDATE"],["\u672C\u4F53\u7EC8\u6001\u8BC1\u660E","\u4ED3\u5E93\u51C6\u5165\u51B3\u5B9A"])],I=Te(e),h={schema:"dic.harness-plan.v1",profileHash:I,candidate:t,gates:p};return{schema:h.schema,planId:`hplan-${X(h).slice(0,16)}`,generatedAt:n,profileHash:I,candidate:t,gates:p}}function It(e,t=new Date().toISOString()){let n={planId:e.planId,candidateHash:e.candidate.contentHash,createdAt:t};return{schema:"dic.harness-run.v1",runId:`hrun-${X(n).slice(0,16)}`,planId:e.planId,candidateHash:e.candidate.contentHash,createdAt:t,updatedAt:t,gates:e.gates.map(s=>({gateId:s.id,status:"NOT_RUN",summary:"",evidence:[]}))}}function ln(e){return`hplan-${X({schema:e.schema,profileHash:e.profileHash,candidate:e.candidate,gates:e.gates}).slice(0,16)}`}function dn(e){return`hrun-${X({planId:e.planId,candidateHash:e.candidateHash,createdAt:e.createdAt}).slice(0,16)}`}function ft(e,t){let n=St(Q(t),Q(e));return n===""||!n.startsWith("..")&&!on(n)}async function Et(e,t){let n=Q(t,e);if(!ft(n,t))throw new Error(`\u8BC1\u636E\u8DEF\u5F84\u4F4D\u4E8E\u9879\u76EE\u76EE\u5F55\u4E4B\u5916\uFF1A${e}`);let[s,i]=await Promise.all([ut(t),ut(n)]);if(!ft(i,s))throw new Error(`\u8BC1\u636E\u8DEF\u5F84\u89E3\u6790\u540E\u4F4D\u4E8E\u9879\u76EE\u76EE\u5F55\u4E4B\u5916\uFF1A${e}`);if(!(await mt(i)).isFile())throw new Error(`\u8BC1\u636E\u4E0D\u662F\u6587\u4EF6\uFF1A${e}`);return{path:De(St(t,n)),contentHash:Ie(await yt(i))}}async function At({plan:e,run:t,candidate:n,gateId:s,status:i,summary:a,evidencePaths:r,projectRoot:l,profile:d,recordedAt:o=new Date().toISOString()}){if(t.planId!==e.planId)throw new Error("\u8FD0\u884C\u8BB0\u5F55\u4E0E\u95E8\u7981\u8BA1\u5212\u4E0D\u5339\u914D");if(n.contentHash!==e.candidate.contentHash||t.candidateHash!==e.candidate.contentHash)throw new Error("\u5019\u9009\u7248\u672C\u5DF2\u7ECF\u53D8\u5316\uFF1B\u8BF7\u91CD\u65B0\u521D\u59CB\u5316\u95E8\u7981\u8BA1\u5212\u548C\u8FD0\u884C\u8BB0\u5F55");if(d&&Te(d)!==e.profileHash)throw new Error("\u9879\u76EE\u753B\u50CF\u5DF2\u7ECF\u53D8\u5316\uFF1B\u8BF7\u91CD\u65B0\u521D\u59CB\u5316\u95E8\u7981\u8BA1\u5212\u548C\u8FD0\u884C\u8BB0\u5F55");let c=e.gates.find(m=>m.id===s);if(!c)throw new Error(`\u672A\u77E5\u95E8\u7981\uFF1A${s}`);if(!new Set(["RUNNING","PASS","PASS_WITH_FOLLOW_UP","BLOCKED","FAIL","SKIPPED"]).has(i))throw new Error(`\u4E0D\u652F\u6301\u7684\u95E8\u7981\u72B6\u6001\uFF1A${i}`);if(i==="SKIPPED"&&c.applicability!=="CONDITIONAL")throw new Error(`\u5FC5\u8DD1\u95E8\u7981\u4E0D\u80FD\u8DF3\u8FC7\uFF1A${s}`);if(i!=="RUNNING"&&!a.trim())throw new Error(`${i} \u5FC5\u987B\u63D0\u4F9B\u975E\u7A7A\u7ED3\u8BBA\u6458\u8981`);if(["PASS","PASS_WITH_FOLLOW_UP"].includes(i)&&r.length===0)throw new Error(`${i} \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u6301\u4E45\u5316\u8BC1\u636E\u6587\u4EF6`);let I=new Map(t.gates.map(m=>[m.gateId,m]));if(de.has(i)){let m=c.dependsOn.filter(g=>!de.has(I.get(g)?.status));if(m.length>0)throw new Error(`\u95E8\u7981\u4F9D\u8D56\u5C1A\u672A\u5B8C\u6210\uFF1A${m.join(", ")}`)}let h=[];for(let m of r)h.push(await Et(m,l));let S=I.get(s),y={gateId:s,status:i,summary:a.trim(),evidence:h,...S?.startedAt||i==="RUNNING"?{startedAt:S?.startedAt??o}:{},...["RUNNING"].includes(i)?{}:{completedAt:o}};return{...t,updatedAt:o,gates:t.gates.map(m=>m.gateId===s?y:m)}}async function je(e,t,n,s,i){let a=[];e?.schema!=="dic.harness-plan.v1"&&a.push("\u4E0D\u652F\u6301\u7684\u95E8\u7981\u8BA1\u5212\u683C\u5F0F"),t?.schema!=="dic.harness-run.v1"&&a.push("\u4E0D\u652F\u6301\u7684\u8FD0\u884C\u8BB0\u5F55\u683C\u5F0F"),e?.planId!==ln(e)&&a.push("\u95E8\u7981\u8BA1\u5212\u5185\u5BB9\u54C8\u5E0C\u4E0D\u5339\u914D"),t?.runId!==dn(t)&&a.push("\u8FD0\u884C\u8BB0\u5F55\u8EAB\u4EFD\u4E0D\u5339\u914D"),t?.planId!==e?.planId&&a.push("\u8FD0\u884C\u8BB0\u5F55\u7684\u8BA1\u5212\u6807\u8BC6\u4E0D\u5339\u914D"),t?.candidateHash!==e?.candidate?.contentHash&&a.push("\u8FD0\u884C\u8BB0\u5F55\u7684\u5019\u9009\u7248\u672C\u54C8\u5E0C\u4E0E\u95E8\u7981\u8BA1\u5212\u4E0D\u5339\u914D"),n.contentHash!==e?.candidate?.contentHash&&a.push("\u5F53\u524D\u5019\u9009\u7248\u672C\u4E0E\u95E8\u7981\u8BA1\u5212\u51BB\u7ED3\u7684\u5019\u9009\u7248\u672C\u4E0D\u4E00\u81F4"),i&&Te(i)!==e?.profileHash&&a.push("\u5F53\u524D\u9879\u76EE\u753B\u50CF\u4E0E\u95E8\u7981\u8BA1\u5212\u7ED1\u5B9A\u7684\u9879\u76EE\u753B\u50CF\u4E0D\u4E00\u81F4");let r=e.gates.map(y=>y.id),l=t.gates.map(y=>y.gateId);new Set(r).size!==r.length&&a.push("\u95E8\u7981\u8BA1\u5212\u4E2D\u7684\u95E8\u7981\u6807\u8BC6\u4E0D\u552F\u4E00"),new Set(l).size!==l.length&&a.push("\u8FD0\u884C\u8BB0\u5F55\u4E2D\u7684\u95E8\u7981\u6807\u8BC6\u4E0D\u552F\u4E00");for(let y of l)r.includes(y)||a.push(`\u8FD0\u884C\u8BB0\u5F55\u5305\u542B\u672A\u77E5\u95E8\u7981\uFF1A${y}`);let d=new Set(r);for(let y of e.gates)for(let m of y.dependsOn)d.has(m)||a.push(`${y.id}\uFF1A\u4F9D\u8D56\u65E0\u6CD5\u89E3\u6790\uFF1A${m}`),m===y.id&&a.push(`${y.id}\uFF1A\u95E8\u7981\u4E0D\u80FD\u4F9D\u8D56\u81EA\u8EAB`);let o=new Set,c=new Set,p=new Map(e.gates.map(y=>[y.id,y])),I=(y,m=[])=>{if(o.has(y)){a.push(`\u95E8\u7981\u8BA1\u5212\u5B58\u5728\u5FAA\u73AF\u4F9D\u8D56\uFF1A${[...m,y].join(" -> ")}`);return}if(!c.has(y)){o.add(y);for(let g of p.get(y)?.dependsOn??[])p.has(g)&&I(g,[...m,y]);o.delete(y),c.add(y)}};for(let y of r)I(y);let h=new Map(t.gates.map(y=>[y.gateId,y])),S=[];for(let y of e.gates){let m=h.get(y.id),g=[];if(!m)g.push("\u7F3A\u5C11\u95E8\u7981\u7ED3\u679C");else{de.has(m.status)||g.push(`\u95E8\u7981\u5C1A\u672A\u6210\u529F\u5173\u95ED\uFF1A${m.status}`),de.has(m.status)&&(typeof m.completedAt!="string"||Number.isNaN(Date.parse(m.completedAt)))&&g.push("\u7EC8\u6001\u95E8\u7981\u7F3A\u5C11\u6709\u6548\u5B8C\u6210\u65F6\u95F4"),m.status==="SKIPPED"&&(y.applicability!=="CONDITIONAL"&&g.push("\u5FC5\u8DD1\u95E8\u7981\u88AB\u8DF3\u8FC7"),m.summary.trim()||g.push("\u8DF3\u8FC7\u95E8\u7981\u65F6\u6CA1\u6709\u8BF4\u660E\u4E0D\u9002\u7528\u539F\u56E0")),["PASS","PASS_WITH_FOLLOW_UP"].includes(m.status)&&(m.summary.trim()||g.push("\u6210\u529F\u95E8\u7981\u7F3A\u5C11\u7ED3\u8BBA\u6458\u8981"),m.evidence.length===0&&g.push("\u6210\u529F\u95E8\u7981\u7F3A\u5C11\u8BC1\u636E"));for(let R of y.dependsOn){let f=h.get(R);de.has(f?.status)?m.completedAt&&f.completedAt&&Date.parse(f.completedAt)>Date.parse(m.completedAt)&&g.push(`\u4F9D\u8D56\u5B8C\u6210\u65F6\u95F4\u665A\u4E8E\u5F53\u524D\u95E8\u7981\uFF1A${R}`):g.push(`\u4F9D\u8D56\u5C1A\u672A\u6210\u529F\u5173\u95ED\uFF1A${R}`)}for(let R of m.evidence)try{(await Et(R.path,s)).contentHash!==R.contentHash&&g.push(`\u8BC1\u636E\u5185\u5BB9\u5DF2\u7ECF\u53D8\u5316\uFF1A${R.path}`)}catch(f){g.push(f.message)}}S.push({gateId:y.id,domain:y.domain,status:m?.status??"MISSING",valid:g.length===0,errors:g}),a.push(...g.map(R=>`${y.id}\uFF1A${R}`))}return{valid:a.length===0,deliveryStatus:a.length===0?"READY":"BLOCKED",planId:e.planId,runId:t.runId,candidateId:e.candidate.id,currentCandidateId:n.id,gates:S,errors:a}}function V(e){return String(e??"").replaceAll("|","\\|").replace(/\r?\n/gu," ")}function Ne(e){return`gate_${String(e).replace(/[^a-zA-Z0-9_]/gu,"_")}`}function ht(e){return{NOT_RUN:"\u672A\u8FD0\u884C",RUNNING:"\u8FD0\u884C\u4E2D",PASS:"\u901A\u8FC7",PASS_WITH_FOLLOW_UP:"\u901A\u8FC7\u5E76\u8DDF\u8E2A\u540E\u7EED\u4E8B\u9879",BLOCKED:"\u53D7\u963B",FAIL:"\u5931\u8D25",SKIPPED:"\u4E0D\u9002\u7528",STALE:"\u5DF2\u5931\u6548",MISSING:"\u7F3A\u5931"}[e]??String(e??"\u7F3A\u5931")}function gt(e){return{DESIGN:"\u8BBE\u8BA1",DELIVERY:"\u4EA4\u4ED8",DEVELOPMENT:"\u5F00\u53D1",TEST:"\u6D4B\u8BD5",ASSURANCE:"\u8D28\u91CF\u4FDD\u969C",ADMISSION:"\u51C6\u5165"}[e]??String(e)}function pn(e){let t=e.applicability==="REQUIRED"?"\u5FC5\u8DD1":"\u6761\u4EF6",n=e.defaultDisposition==="RUN"?"\u5EFA\u8BAE\u6267\u884C":"\u9700\u8981\u8BC4\u4F30";return`${t} / ${n}`}function vt(e,t,n){let s=new Map(t.gates.map(o=>[o.gateId,o])),a=["DESIGN","DELIVERY","DEVELOPMENT","TEST","ASSURANCE","ADMISSION"].map(o=>{let c=n.gates.filter(p=>p.domain===o);return{domain:o,total:c.length,passed:c.filter(p=>p.valid).length,blocked:c.filter(p=>!p.valid).length}}).filter(o=>o.total>0),r=o=>["PASS","PASS_WITH_FOLLOW_UP","SKIPPED"].includes(o)?"passed":["BLOCKED","FAIL","STALE"].includes(o)?"blocked":"pending",l=["flowchart LR"];for(let o of e.gates){let c=s.get(o.id);l.push(` ${Ne(o.id)}["${o.id}<br/>${ht(c?.status??"MISSING")}"]:::${r(c?.status)}`);for(let p of o.dependsOn)l.push(` ${Ne(p)} --> ${Ne(o.id)}`)}l.push(" classDef passed fill:#E8F5E9,stroke:#167D3F,color:#0B3D20;"," classDef pending fill:#FFF8E1,stroke:#B7791F,color:#5F370E;"," classDef blocked fill:#FDECEC,stroke:#C53030,color:#681313;");let d=n.gates.length===0?0:Math.round(n.gates.filter(o=>o.valid).length/n.gates.length*100);return["# QIHENG \u9AD8\u5C42\u4EA4\u4ED8\u4FDD\u969C\u9A7E\u9A76\u8231","",`> **\u4EA4\u4ED8\u51B3\u5B9A\uFF1A${n.deliveryStatus==="READY"?"\u5DF2\u5C31\u7EEA":"\u53D7\u963B"}** `,`> \u4FDD\u969C\u8986\u76D6\u7387\uFF1A**${d}%** | \u5019\u9009\u7248\u672C\uFF1A\`${e.candidate.id}\` | \u95E8\u7981\u8BA1\u5212\uFF1A\`${e.planId}\``,"","## \u6838\u5FC3\u7ED3\u8BBA","",`- **\u4EA4\u4ED8\u51B3\u5B9A\uFF1A** ${n.deliveryStatus==="READY"?"\u5DF2\u5C31\u7EEA":"\u53D7\u963B"}`,`- **\u5019\u9009\u7248\u672C\u5B8C\u6574\u6027\uFF1A** ${e.candidate.id===n.currentCandidateId?"\u4E00\u81F4":"\u5DF2\u6F02\u79FB"}`,`- **\u95E8\u7981\u5173\u95ED\u60C5\u51B5\uFF1A** ${n.gates.filter(o=>o.valid).length}/${n.gates.length}`,`- **\u963B\u65AD\u9879\u6570\u91CF\uFF1A** ${n.errors.length}`,`- **\u51BB\u7ED3\u65F6\u5DE5\u4F5C\u533A\uFF1A** ${e.candidate.clean?"\u5E72\u51C0":"\u5DF2\u5185\u5BB9\u5BFB\u5740\u7684\u975E\u5E72\u51C0\u5019\u9009\u7248\u672C"}`,"","## \u5019\u9009\u7248\u672C\u8EAB\u4EFD\u51ED\u8BC1","","| \u5B57\u6BB5 | \u5185\u5BB9 |","| --- | --- |",`| \u5019\u9009\u7248\u672C\u6807\u8BC6 | \`${V(e.candidate.id)}\` |`,`| Git \u5F15\u7528 | \`${V(e.candidate.ref)}\` |`,`| \u5185\u5BB9\u54C8\u5E0C | \`${V(e.candidate.contentHash)}\` |`,`| \u9879\u76EE\u753B\u50CF\u54C8\u5E0C | \`${V(e.profileHash)}\` |`,`| \u8FD0\u884C\u8BB0\u5F55 | \`${V(t.runId)}\` |`,`| \u6700\u540E\u66F4\u65B0\u65F6\u95F4 | ${V(t.updatedAt)} |`,"","## \u8D28\u91CF\u4FDD\u969C\u8303\u56F4","","| \u9886\u57DF | \u5DF2\u5173\u95ED | \u603B\u6570 | \u672A\u5173\u95ED\u6216\u53D7\u963B |","| --- | ---: | ---: | ---: |",...a.map(o=>`| ${gt(o.domain)} | ${o.passed} | ${o.total} | ${o.blocked} |`),"","## \u8BBE\u8BA1\u4EA4\u4ED8\u6570\u5B57\u4E3B\u7EBF","","```mermaid",...l,"```","","## \u95E8\u7981\u51B3\u7B56\u77E9\u9635","","| \u9886\u57DF | \u95E8\u7981 | Skill | \u9002\u7528\u6027 | \u72B6\u6001 | \u8BC1\u636E\u6570\u91CF | \u51B3\u5B9A\u6458\u8981 |","| --- | --- | --- | --- | --- | ---: | --- |",...e.gates.map(o=>{let c=s.get(o.id);return`| ${gt(o.domain)} | \`${o.id}\` | \`${o.skill}\` | ${pn(o)} | ${ht(c?.status??"MISSING")} | ${c?.evidence?.length??0} | ${V(c?.summary)} |`}),"","## \u4EA4\u4ED8\u963B\u65AD\u9879","",...n.errors.length>0?n.errors.map(o=>`- ${V(o)}`):["- \u65E0\u3002\u5019\u9009\u7248\u672C\u7EA6\u675F\u7684\u5168\u90E8\u95E8\u7981\u5DF2\u7ECF\u5173\u95ED\u3002"],"","## \u8D28\u91CF\u4FDD\u969C\u804C\u8D23\u4F53\u7CFB","","- **\u89C2\u6D4B\u57DF**\uFF1A\u786E\u8BA4\u6743\u5A01\u6E90\u3001\u5B9E\u73B0\u4E49\u52A1\u3001\u8BED\u4E49\u51B2\u7A81\u548C\u5F71\u54CD\u8303\u56F4\u3002","- **\u6784\u5EFA\u57DF**\uFF1A\u68C0\u67E5\u3001\u4FEE\u590D\u3001\u9A8C\u8BC1\u5E76\u6536\u655B\u5B9E\u73B0\u3002","- **\u88C1\u51B3\u57DF**\uFF1A\u8D28\u8BE2\u4E3B\u5F20\u3001\u5BA1\u8BA1\u8BC1\u636E\u5E76\u51B3\u5B9A\u51C6\u5165\u3002","","_\u672C\u62A5\u544A\u7531\u51BB\u7ED3\u7684\u95E8\u7981\u8BA1\u5212\u548C\u5185\u5BB9\u5BFB\u5740\u8FD0\u884C\u8BC1\u636E\u751F\u6210\uFF0C\u7981\u6B62\u624B\u5DE5\u4FEE\u6539\u3002_",""].join(`
|
|
5
|
+
`)}var Y="dic-workflow-kit",Rt=".dic-workflow-kit-install.json",gn="QIHENG",ue=b(B(hn(import.meta.url)),".."),yn=new Map([["codex","codex"],["claude","claude-code"],["claude-code","claude-code"],["opencode","opencode"],["mimo","mimo-code"],["mimocode","mimo-code"],["mimo-code","mimo-code"],["bitfun","bitfun"]]),mn=[".codex-plugin","adapters","agents","schemas","skills","INSTRUCTION.md"];function T(e,t,n){let s=e[t+1];if(!s)throw new Error(`${n} \u9700\u8981\u63D0\u4F9B\u503C`);return s}function Sn(e){let t=e[0]??"help",n="codex",s="user",i,a,r=process.cwd(),l=!1,d=!1,o=!1,c,p,I,h,S="",y="",m="",g="",R,f,v="",N="",G=[];for(let E=1;E<e.length;E+=1){let w=e[E];if(w==="--host"){let D=T(e,E,w).toLowerCase();if(n=yn.get(D),!n)throw new Error(`\u4E0D\u652F\u6301\u7684\u5BBF\u4E3B\uFF1A${D}\uFF1B\u53EF\u9009\u503C\u4E3A codex\u3001claude-code\u3001opencode\u3001mimo-code \u6216 bitfun`);E+=1}else if(w==="--scope"){if(s=T(e,E,w).toLowerCase(),!["user","project"].includes(s))throw new Error("--scope \u5FC5\u987B\u662F user \u6216 project");E+=1}else if(w==="--install-root")i=b(T(e,E,w)),E+=1;else if(w==="--project-root")r=b(T(e,E,w)),E+=1;else if(w==="--root")r=b(T(e,E,w)),E+=1;else if(w==="--snapshot")c=b(T(e,E,w)),E+=1;else if(w==="--action")p=b(T(e,E,w)),E+=1;else if(w==="--profile")I=b(T(e,E,w)),E+=1;else if(w==="--ledger")h=b(T(e,E,w)),E+=1;else if(w==="--status"){S=T(e,E,w).toUpperCase();let D=t==="harness-record"?["RUNNING","PASS","PASS_WITH_FOLLOW_UP","BLOCKED","FAIL","SKIPPED"]:["PASS","PARTIAL","BLOCKED","FAIL"];if(!D.includes(S))throw new Error(`--status \u5FC5\u987B\u662F\u4EE5\u4E0B\u503C\u4E4B\u4E00\uFF1A${D.join(", ")}`);E+=1}else if(w==="--query"){if(y=T(e,E,w).toLowerCase(),!["uncovered","gaps","unevidenced","impact"].includes(y))throw new Error("--query \u5FC5\u987B\u662F uncovered\u3001gaps\u3001unevidenced \u6216 impact");E+=1}else if(w==="--id")m=T(e,E,w),E+=1;else if(w==="--summary")g=T(e,E,w),E+=1;else if(w==="--output")R=b(T(e,E,w)),E+=1;else if(w==="--attestation")f=b(T(e,E,w)),E+=1;else if(w==="--expected-hash"){if(v=T(e,E,w).toLowerCase(),!/^[a-f0-9]{64}$/u.test(v))throw new Error("--expected-hash \u5FC5\u987B\u662F 64 \u4E2A\u5B57\u7B26\u7684 SHA-256 \u6458\u8981");E+=1}else if(w==="--gate")N=T(e,E,w),E+=1;else if(w==="--evidence")G.push(T(e,E,w)),E+=1;else if(w==="--marketplace-root")a=b(T(e,E,w)),E+=1;else if(w==="--dry-run")l=!0;else if(w==="--force")d=!0;else if(w==="--json")o=!0;else throw new Error(`\u672A\u77E5\u53C2\u6570\uFF1A${w}`)}if(n!=="codex"&&a)throw new Error("--marketplace-root \u4EC5\u9002\u7528\u4E8E --host codex");if(n==="codex"&&s==="project")throw new Error("Codex \u63D2\u4EF6\u4EC5\u652F\u6301\u7528\u6237\u8303\u56F4\u5B89\u88C5");return{command:t,host:n,scope:s,installRoot:i,marketplaceRoot:a,projectRoot:r,dryRun:l,force:d,json:o,snapshot:c,action:p,profile:I,ledger:h,status:S,query:y,id:m,summary:g,output:R,attestation:f,expectedHash:v,gate:N,evidence:G}}function Tt({host:e,scope:t,projectRoot:n}){if(t==="project"){let s={"claude-code":".claude",opencode:".opencode","mimo-code":".mimocode",bitfun:".bitfun"}[e];return A(n,s)}if(e==="claude-code")return A(F(),".claude");if(e==="opencode")return A(process.env.XDG_CONFIG_HOME||A(F(),".config"),"opencode");if(e==="mimo-code")return process.env.MIMOCODE_HOME?b(process.env.MIMOCODE_HOME):process.platform==="win32"&&process.env.LOCALAPPDATA?A(process.env.LOCALAPPDATA,"mimocode"):A(process.env.XDG_CONFIG_HOME||A(F(),".config"),"mimocode");if(e==="bitfun")throw new Error("BitFun \u7528\u6237\u8303\u56F4\u4F7F\u7528\u5E73\u53F0\u539F\u751F\u4E14\u5F7C\u6B64\u72EC\u7ACB\u7684\u6280\u80FD\u4E0E\u667A\u80FD\u4F53\u6839\u76EE\u5F55");return A(F(),".agents","plugins")}function wn(){let e,t;if(process.platform==="win32"){let n=process.env.APPDATA||A(F(),"AppData","Roaming");e=A(n,"BitFun","skills"),t=A(process.env.BITFUN_USER_ROOT?b(process.env.BITFUN_USER_ROOT):A(n,"bitfun"),"agents")}else if(process.platform==="darwin"){let n=A(F(),"Library","Application Support");e=A(n,"BitFun","skills"),t=A(process.env.BITFUN_USER_ROOT?b(process.env.BITFUN_USER_ROOT):A(n,"bitfun"),"agents")}else e=A(process.env.XDG_DATA_HOME||A(F(),".local","share"),"BitFun","skills"),t=A(process.env.BITFUN_USER_ROOT?b(process.env.BITFUN_USER_ROOT):A(process.env.XDG_CONFIG_HOME||A(F(),".config"),"bitfun"),"agents");return{skillsRoot:e,agentsRoot:t}}function In(e){if(e.installRoot)return{root:e.installRoot,skillsRoot:A(e.installRoot,"skills"),agentsRoot:A(e.installRoot,"agents")};if(e.host==="bitfun"&&e.scope==="user"){let n=wn();return{root:B(n.skillsRoot),...n}}let t=Tt(e);return{root:t,skillsRoot:A(t,"skills"),agentsRoot:A(t,"agents")}}function Dt(e){if(e.host==="codex"){let n=e.marketplaceRoot||e.installRoot||Tt(e),s=A(n,"plugins",Y);return{root:s,skillsRoot:A(s,"skills"),agentsRoot:A(s,"agents"),manifestPath:A(s,Rt),marketplaceRoot:n,marketplacePath:A(n,"marketplace.json")}}let t=In(e);return{...t,manifestPath:A(t.root,Rt)}}async function K(e){try{return await Pt(e),!0}catch(t){if(t?.code==="ENOENT")return!1;throw t}}function Ee(e){return bt("sha256").update(e).digest("hex")}async function jt(e){return Ee(await H(e))}async function En(){return JSON.parse(await H(A(ue,"package.json"),"utf8"))}async function qe(e,t){let n=`${e}.${process.pid}.tmp`;await Ae(B(e),{recursive:!0}),await ve(n,`${JSON.stringify(t,null,2)}
|
|
6
|
+
`,"utf8"),await Z(e,{force:!0}),await Le(n,e)}async function $t(e,t){try{return JSON.parse(await H(e,"utf8"))}catch(n){if(n?.code==="ENOENT"&&t!==void 0)return t;throw n}}async function He(e){let t=await $t(e,{name:"personal",interface:{displayName:"Personal"},plugins:[]});if(!t||typeof t!="object"||Array.isArray(t))throw new Error("marketplace.json \u5FC5\u987B\u5305\u542B\u4E00\u4E2A\u5BF9\u8C61");if(!Array.isArray(t.plugins))throw new Error("marketplace.json \u5FC5\u987B\u5305\u542B plugins \u6570\u7EC4");return t}function An(){return{name:Y,source:{source:"local",path:`./plugins/${Y}`},policy:{installation:"AVAILABLE",authentication:"ON_INSTALL"},category:"Developer Tools"}}function vn(e,t){let n=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);if(!n)return e;if(t==="bitfun"){let a=n[1],r=a.match(/^name:\s*(.+)$/m)?.[1]?.trim(),l=a.match(/^description:\s*(.+)$/m)?.[1]?.trim();if(!r||!l)throw new Error("BitFun \u5B50\u667A\u80FD\u4F53\u5FC5\u987B\u63D0\u4F9B\u540D\u79F0\u548C\u8BF4\u660E");let d=["code-repairer","validation-runner"].includes(r),o=["LS","Read","Glob","Grep","Skill"];return d&&o.push("Write","Edit","ExecCommand"),["---","schema_version: 1","kind: subagent",`id: ${r}`,`name: ${r}`,`description: ${l}`,`readonly: ${d?"false":"true"}`,"tools:",...o.map(c=>` - ${c}`),"---",e.slice(n[0].length)].join(`
|
|
7
|
+
`)}let s=t==="claude-code"?new Set(["name","description","tools","disallowedTools","model","permissionMode","skills","memory","background","isolation"]):new Set(["name","description","mode","model","temperature","top_p","tools","permission","steps","hidden","color"]);return`---
|
|
8
|
+
${n[1].split(/\r?\n/).filter(a=>{let r=a.match(/^([A-Za-z][A-Za-z0-9_-]*):/)?.[1];return!r||s.has(r)}).join(`
|
|
8
9
|
`)}
|
|
9
10
|
---
|
|
10
|
-
${e.slice(n[0].length)}`}async function
|
|
11
|
-
`);return}process.stdout.write(`${Object.entries(t).map(([n,
|
|
11
|
+
${e.slice(n[0].length)}`}async function Lt(e){let t=[],n=await kt(e,{withFileTypes:!0});for(let s of n){let i=A(e,s.name);s.isDirectory()?t.push(...await Lt(i)):s.isFile()&&t.push(i)}return t.sort()}async function Ct(e,t,n){if((await Pt(e)).isFile()){let r=await H(e);return[{source:n,destination:t,content:r,sha256:Ee(r)}]}let i=await Lt(e),a=[];for(let r of i){let l=Ot(e,r),d=await H(r);a.push({source:A(n,l),destination:A(t,l),content:d,sha256:Ee(d)})}return a}async function Rn(e,t){if(e.host==="codex"){let i=[];for(let a of mn)i.push(...await Ct(A(ue,a),A(t.root,a),a));return i}let n=await Ct(A(ue,"skills"),t.skillsRoot,"skills"),s=(await kt(A(ue,"agents"))).filter(i=>i.endsWith(".md"));for(let i of s.sort()){let a=A(ue,"agents",i),r=Buffer.from(vn(await H(a,"utf8"),e.host),"utf8");n.push({source:A("agents",i),destination:A(t.agentsRoot,i),content:r,sha256:Ee(r)})}return n}async function qt(e,t=!1){let n=await $t(e,null);if(!n){if(t)throw new Error(`\u672A\u627E\u5230\u5B89\u88C5\u6E05\u5355\uFF1A${e}`);return null}if(n.schemaVersion!==1||!Array.isArray(n.files)||typeof n.host!="string")throw new Error(`\u5B89\u88C5\u6E05\u5355\u65E0\u6548\uFF1A${e}`);return n}function xe(e,t){let n=Ot(b(t),b(e));return n===""||n!==".."&&!n.startsWith(`..${fn}`)&&!Nt(n)}function Ht(e,t){if(!(t.marketplacePath?[t.root]:[t.skillsRoot,t.agentsRoot]).some(s=>xe(e,s)))throw new Error(`\u6E05\u5355\u8DEF\u5F84\u8D85\u51FA\u53D7\u7BA1\u6839\u76EE\u5F55\uFF1A${e}`)}async function Cn(e,t){if(!xe(e.destination,t.skillsRoot)||!e.source.endsWith("SKILL.md"))return!1;let n=await H(e.destination,"utf8"),s=e.source.split(/[\\/]/).at(-2);return new RegExp(`^name:\\s*${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"m").test(n)&&/^(?: )?version:\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/m.test(n)}async function bn(e,t,n,s){let i=new Map((t?.files??[]).map(r=>[b(r.path),r.sha256])),a=[];for(let r of e){if(!await K(r.destination))continue;let l=await $e(r.destination);if(l.isSymbolicLink()){a.push(r.destination);continue}if(!l.isFile())throw new Error(`\u5B89\u88C5\u76EE\u6807\u4E0D\u662F\u666E\u901A\u6587\u4EF6\uFF1A${r.destination}`);let d=await jt(r.destination);d===r.sha256||i.get(b(r.destination))===d||n.host==="codex"||await Cn(r,s)||a.push(r.destination)}return a}async function kn(e,t){for(let n of e)await Ae(B(n.destination),{recursive:!0}),t&&await K(n.destination)&&(await $e(n.destination)).isSymbolicLink()&&await Z(n.destination,{force:!0}),await ve(n.destination,n.content)}async function Pn(e){let t=await He(e.marketplacePath),n=An(),s=t.plugins.findIndex(i=>i?.name===Y);s>=0?t.plugins[s]=n:t.plugins.push(n),await qe(e.marketplacePath,t)}async function Nn(e){if(!await K(e.marketplacePath))return;let t=await He(e.marketplacePath);t.plugins=t.plugins.filter(n=>n?.name!==Y),await qe(e.marketplacePath,t)}function k(e,t){if(e.json){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
12
|
+
`);return}process.stdout.write(`${Object.entries(t).map(([n,s])=>{let i=s!==null&&typeof s=="object"?JSON.stringify(s):s;return`${n.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase()}: ${i}`}).join(`
|
|
12
13
|
`)}
|
|
13
|
-
`)}async function
|
|
14
|
-
|
|
15
|
-
`),
|
|
16
|
-
`)
|
|
17
|
-
|
|
14
|
+
`)}async function On(e){let t=Dt(e),n=await Rn(e,t),s=await qt(t.manifestPath),i=await bn(n,s,e,t);if(i.length>0&&!e.force)throw new Error(`\u5B89\u88C5\u5C06\u8986\u76D6 ${i.length} \u4E2A\u672A\u53D7\u7BA1\u6216\u5DF2\u4FEE\u6539\u6587\u4EF6\uFF1A${i.join(", ")}\uFF1B\u786E\u8BA4\u540E\u624D\u80FD\u4F7F\u7528 --force \u91CD\u65B0\u6267\u884C`);let a=await En(),r={schemaVersion:1,packageName:a.name,packageVersion:a.version,host:e.host,scope:e.scope,installedAt:new Date().toISOString(),root:t.root,skillsRoot:t.skillsRoot,agentsRoot:t.agentsRoot,marketplacePath:t.marketplacePath,files:n.map(l=>({source:l.source,path:l.destination,sha256:l.sha256}))};e.dryRun||(await kn(n,e.force),e.host==="codex"&&await Pn(t),await qe(t.manifestPath,r)),k(e,{installed:!e.dryRun,dryRun:e.dryRun,host:e.host,scope:e.scope,version:a.version,root:t.root,skills:t.skillsRoot,subagents:t.agentsRoot,manifest:t.manifestPath,managedFiles:n.length,forcedConflicts:e.force?i.length:0,...t.marketplacePath?{marketplace:t.marketplacePath}:{}})}async function xt(e){let t=Dt(e),n=await qt(t.manifestPath,!0);if(n.host!==e.host||n.scope!==e.scope)throw new Error(`\u6E05\u5355\u76EE\u6807\u4E0D\u5339\u914D\uFF1A\u5B9E\u9645\u4E3A ${n.host}/${n.scope}\uFF0C\u8BF7\u6C42\u4E3A ${e.host}/${e.scope}`);let s=[],i=[];for(let r of n.files)if(Ht(r.path,t),!await K(r.path))s.push(r.path);else{let l=await $e(r.path);(!l.isFile()||l.isSymbolicLink()||await jt(r.path)!==r.sha256)&&i.push(r.path)}let a=!0;return e.host==="codex"&&(await K(t.marketplacePath)?a=(await He(t.marketplacePath)).plugins.some(l=>l?.name===Y&&l?.source?.path===`./plugins/${Y}`):a=!1),{context:t,manifest:n,missing:s,modified:i,registrationHealthy:a,healthy:s.length===0&&i.length===0&&a}}async function Tn(e){let t=await xt(e);k(e,{healthy:t.healthy,host:e.host,scope:e.scope,version:t.manifest.packageVersion,manifest:t.context.manifestPath,managedFiles:t.manifest.files.length,missingFiles:t.missing,modifiedFiles:t.modified,registrationHealthy:t.registrationHealthy}),t.healthy||(process.exitCode=1)}async function Dn(e,t){let n=new Set;for(let s of e){let i=B(s);for(;t.some(a=>xe(i,a))&&!t.some(a=>b(a)===b(i));)n.add(i),i=B(i)}for(let s of[...n].sort((i,a)=>a.length-i.length))try{await un(s)}catch(i){if(!["ENOENT","ENOTEMPTY","EEXIST"].includes(i?.code))throw i}}async function jn(e){let t=await xt(e);if(t.modified.length>0&&!e.force)throw new Error(`\u62D2\u7EDD\u79FB\u9664 ${t.modified.length} \u4E2A\u5DF2\u4FEE\u6539\u7684\u53D7\u7BA1\u6587\u4EF6\uFF1A${t.modified.join(", ")}\uFF1B\u4EC5\u5728\u786E\u8BA4\u53EF\u4E22\u5F03\u8FD9\u4E9B\u4FEE\u6539\u540E\u4F7F\u7528 --force \u91CD\u65B0\u6267\u884C`);if(!e.dryRun){for(let n of t.manifest.files)Ht(n.path,t.context),await Z(n.path,{force:!0});e.host==="codex"&&await Nn(t.context),await Z(t.context.manifestPath,{force:!0}),await Dn(t.manifest.files.map(n=>n.path),[t.context.skillsRoot,t.context.agentsRoot,t.context.root])}k(e,{uninstalled:!e.dryRun,dryRun:e.dryRun,host:e.host,scope:e.scope,version:t.manifest.packageVersion,manifest:t.context.manifestPath,removedFiles:t.manifest.files.length,forcedModifiedFiles:e.force?t.modified.length:0})}function $(e){return{snapshot:e.snapshot??A(e.projectRoot,"reports","ontology-snapshot.json"),action:e.action,profile:e.profile??A(e.projectRoot,"reports","project-profile.json"),ledger:e.ledger??A(e.projectRoot,"reports","ontology-actions.jsonl"),attestation:e.attestation??A(e.projectRoot,"reports","ontology-attestation.json"),report:e.output??A(e.projectRoot,"reports","ontology-report.md")}}function Re(e){return{profile:e.profile??A(e.projectRoot,"reports","project-profile.json"),plan:A(e.projectRoot,"reports","harness-plan.json"),run:A(e.projectRoot,"reports","harness-run.json"),report:e.output??A(e.projectRoot,"reports","harness-report.md")}}async function $n(e){let t=Re(e);if(!e.force&&(await K(t.plan)||await K(t.run)))throw new Error("\u95E8\u7981\u8BA1\u5212\u6216\u6267\u884C\u8BB0\u5F55\u5DF2\u5B58\u5728\uFF1B\u4EC5\u5728\u9700\u8981\u51BB\u7ED3\u65B0\u7684\u5019\u9009\u7248\u672C\u65F6\u4F7F\u7528 --force");let[n,s]=await Promise.all([C(t.profile),pe(e.projectRoot)]),i=wt(n,s),a=It(i);e.dryRun||await Promise.all([ee(t.plan,`${JSON.stringify(i,null,2)}
|
|
15
|
+
`),ee(t.run,`${JSON.stringify(a,null,2)}
|
|
16
|
+
`)]),k(e,{created:!e.dryRun,dryRun:e.dryRun,plan:t.plan,run:t.run,planId:i.planId,candidateId:s.id,candidateHash:s.contentHash,candidateClean:s.clean,gates:i.gates.length,recommendedRuns:i.gates.filter(r=>r.defaultDisposition==="RUN").map(r=>r.id),applicabilityRequired:i.gates.filter(r=>r.defaultDisposition==="ASSESS").map(r=>r.id)})}async function Ln(e){if(!e.gate)throw new Error("\u5FC5\u987B\u63D0\u4F9B --gate");if(!e.status)throw new Error("\u5FC5\u987B\u63D0\u4F9B --status");let t=Re(e),[n,s,i,a]=await Promise.all([C(t.plan),C(t.run),pe(e.projectRoot),C(t.profile)]),r=await At({plan:n,run:s,candidate:i,gateId:e.gate,status:e.status,summary:e.summary,evidencePaths:e.evidence,projectRoot:e.projectRoot,profile:a});e.dryRun||await ee(t.run,`${JSON.stringify(r,null,2)}
|
|
17
|
+
`);let l=r.gates.find(d=>d.gateId===e.gate);k(e,{recorded:!e.dryRun,dryRun:e.dryRun,run:t.run,gate:l.gateId,status:l.status,evidence:l.evidence.length,candidateId:i.id})}async function qn(e){let t=Re(e),[n,s,i,a]=await Promise.all([C(t.plan),C(t.run),pe(e.projectRoot),C(t.profile)]),r=await je(n,s,i,e.projectRoot,a);k(e,{...r,plan:t.plan,run:t.run}),r.valid||(process.exitCode=1)}async function Hn(e){let t=Re(e),[n,s,i,a]=await Promise.all([C(t.plan),C(t.run),pe(e.projectRoot),C(t.profile)]),r=await je(n,s,i,e.projectRoot,a),l=vt(n,s,r);e.dryRun||await ee(t.report,l),k(e,{created:!e.dryRun,dryRun:e.dryRun,report:t.report,deliveryStatus:r.deliveryStatus,candidateId:n.candidate.id,assuranceCoverage:`${r.gates.filter(d=>d.valid).length}/${r.gates.length}`,blockers:r.errors.length})}function q(e,t){let n=e?.projectRoot;return typeof n!="string"||!n?t:Nt(n)?b(n):b(t,n)}async function xn(e){let t=$(e),n=await C(t.snapshot),s=await Ue(n,e.status,e.projectRoot);k(e,{valid:s.failures.length===0,requestedStatus:e.status||"STRUCTURAL",snapshot:t.snapshot,failures:s.failures.map(i=>i.id),sourceDrift:s.sourceDrift,evidenceIntegrity:s.evidenceIntegrity,implementationIntegrity:s.implementationIntegrity,results:s.results}),s.failures.length>0&&(process.exitCode=1)}async function Ue(e,t,n){let s=q(e,n),i=ge(e,t),a=await re(e,s),[r,l]=await Promise.all([ce(e,s),le(e,s)]),d=a.filter(p=>p.status!=="UNCHANGED");i.push({id:"pass.sources.no-drift",status:t==="PASS"?d.length===0?"PASS":"FAIL":"NOT_APPLICABLE",severity:"blocking",message:"PASS requires every tracked design source to match its recorded revision.",objectIds:t==="PASS"?d.map(p=>p.id).sort():[]});let o=r.filter(p=>p.required&&p.status!=="UNCHANGED");i.push({id:"pass.evidence.artifacts-current",status:t==="PASS"?o.length===0?"PASS":"FAIL":"NOT_APPLICABLE",severity:"blocking",message:"PASS requires every required Evidence artifact to exist and match its recorded SHA-256 hash.",objectIds:t==="PASS"?o.map(p=>p.id).sort():[]});let c=l.filter(p=>p.required&&p.status!=="UNCHANGED");return i.push({id:"pass.implementation.artifacts-current",status:t==="PASS"?c.length===0?"PASS":"FAIL":"NOT_APPLICABLE",severity:"blocking",message:"PASS requires every required ImplementationUnit artifact to exist and match its recorded SHA-256 hash.",objectIds:t==="PASS"?c.map(p=>p.id).sort():[]}),{results:i,sourceDrift:a,evidenceIntegrity:r,implementationIntegrity:l,failures:i.filter(p=>p.status==="FAIL")}}async function Ut(e){let t=$(e);if(!t.action)throw new Error("\u5FC5\u987B\u63D0\u4F9B --action");let[n,s,i]=await Promise.all([C(t.action),C(t.snapshot),C(t.profile)]),a=ke(n,s,i,q(s,e.projectRoot));return a.push(...await it(n,q(s,e.projectRoot))),{paths:t,action:n,snapshot:s,errors:a}}async function Un(e){let t=await Ut(e);k(e,{valid:t.errors.length===0,action:t.paths.action,actionId:t.action.id,actionType:t.action.type,errors:t.errors}),t.errors.length>0&&(process.exitCode=1)}async function Gn(e){let t=await Ut(e);if(t.errors.length>0)throw new Error(`\u52A8\u4F5C\u88AB\u62D2\u7EDD\uFF1A${t.errors.join("\uFF1B")}`);e.dryRun||await Ae(B(t.paths.ledger),{recursive:!0});let n=await st(t.paths.ledger,t.action,{dryRun:e.dryRun,baseSnapshotRevision:t.snapshot.snapshotRevision,appliedActionIds:t.snapshot.appliedActionIds??[]});k(e,{...n,actionId:t.action.id,actionType:t.action.type,ledger:t.paths.ledger})}async function Mn(e){let t=$(e),[n,s,i]=await Promise.all([H(t.snapshot,"utf8"),C(t.profile),me(t.ledger)]),a=JSON.parse(n),r=Se(a,i,s,q(a,e.projectRoot));if(!e.dryRun&&r.applied>0){let l=`${t.snapshot}.tmp-${process.pid}`;try{if(await ve(l,`${JSON.stringify(r.snapshot,null,2)}
|
|
18
|
+
`,"utf8"),await H(t.snapshot,"utf8")!==n)throw new Error("\u534F\u8C03\u671F\u95F4\u672C\u4F53\u5FEB\u7167\u53D1\u751F\u53D8\u5316\uFF1B\u8BF7\u57FA\u4E8E\u6700\u65B0\u4FEE\u8BA2\u91CD\u65B0\u6267\u884C");await Le(l,t.snapshot)}catch(d){throw await Z(l,{force:!0}),d}}k(e,{reconciled:!e.dryRun,dryRun:e.dryRun,snapshot:t.snapshot,ledger:t.ledger,appliedActions:r.applied,skippedActions:r.skipped,totalActions:r.total})}async function _n(e){let t=$(e),n=await H(t.ledger,"utf8"),s=Pe(n),i=J(s);k(e,{valid:i.valid,ledger:t.ledger,records:i.recordCount,legacyRecords:s.filter(a=>a.schema==="dic.ontology-action-record.v1").length,chainedRecords:s.filter(a=>a.schema==="dic.ontology-action-record.v2").length,headHash:i.headHash,fileSha256:bt("sha256").update(n).digest("hex"),errors:i.errors}),i.valid||(process.exitCode=1)}async function Vn(e){let t=$(e),n=await C(t.snapshot),s=await ce(n,q(n,e.projectRoot)),i=s.filter(a=>a.required&&a.status!=="UNCHANGED");k(e,{valid:i.length===0,requiredArtifacts:s.filter(a=>a.required).length,invalidArtifacts:i.map(a=>a.id),evidence:s}),i.length>0&&(process.exitCode=1)}async function Fn(e){let t=$(e),n=await C(t.snapshot),s=ae(n),i=s.filter(a=>a.required&&a.status!=="CURRENT");k(e,{valid:i.length===0,requiredValidations:s.filter(a=>a.required).length,invalidValidations:i.map(a=>a.id),validations:s}),i.length>0&&(process.exitCode=1)}async function Bn(e){let t=$(e),n=await C(t.snapshot),s=await le(n,q(n,e.projectRoot)),i=s.filter(a=>a.required&&a.status!=="UNCHANGED");k(e,{valid:i.length===0,requiredArtifacts:s.filter(a=>a.required).length,invalidArtifacts:i.map(a=>a.id),implementations:s}),i.length>0&&(process.exitCode=1)}async function Wn(e){if(!e.query)throw new Error("\u5FC5\u987B\u63D0\u4F9B --query");let t=$(e),n=await C(t.snapshot),s=W(n,e.query,e.id);k(e,{query:e.query,startId:e.id||"",count:s.length,matches:s})}async function Jn(e){let t=$(e),n=await C(t.snapshot),s=await re(n,q(n,e.projectRoot)),i=s.filter(a=>a.status!=="UNCHANGED");k(e,{clean:i.length===0,trackedSources:s.filter(a=>a.status!=="UNTRACKED").length,driftedSources:i.length,sources:s}),i.length>0&&(process.exitCode=1)}async function Yn(e){let t=$(e),n=await C(t.snapshot),s=q(n,e.projectRoot),[i,a,r]=await Promise.all([re(n,s),le(n,s),ce(n,s)]),l=ot(n,i,a,r);k(e,l)}async function Kn(e){if(!e.id)throw new Error("\u5FC5\u987B\u63D0\u4F9B --id");let t=$(e),n=await C(t.snapshot);k(e,at(n,e.id))}function Gt(e,t){let n=new Set(t.map(i=>i.action?.id)),s=(e.appliedActionIds??[]).filter(i=>!n.has(i));if(s.length>0)throw new Error(`\u5FEB\u7167\u5F15\u7528\u4E86\u53F0\u8D26\u4E2D\u7F3A\u5931\u7684\u52A8\u4F5C\uFF1A${s.join(", ")}`)}async function ee(e,t){await Ae(B(e),{recursive:!0});let n=`${e}.tmp-${process.pid}`;try{await ve(n,t,"utf8"),await Le(n,e)}catch(s){throw await Z(n,{force:!0}),s}}async function zn(e){if(!e.status)throw new Error("\u5FC5\u987B\u63D0\u4F9B --status");if(!e.summary.trim())throw new Error("\u5FC5\u987B\u63D0\u4F9B --summary");let t=$(e),[n,s,i,a]=await Promise.all([C(t.snapshot),C(t.profile),me(t.ledger),H(t.ledger,"utf8")]);Gt(n,i);let r=Se(n,i,s,q(n,e.projectRoot));if(r.applied>0)throw new Error(`${r.applied} \u4E2A\u5DF2\u8BB0\u5F55\u52A8\u4F5C\u5C1A\u672A\u843D\u5165\u5FEB\u7167\uFF1B\u8BF7\u5148\u6267\u884C ontology-reconcile`);let l=await Ue(n,e.status,e.projectRoot);if(l.results.find(c=>c.id==="ontology.snapshot.revision")?.status!=="PASS")throw new Error("\u7B7E\u7F72\u8981\u6C42\u89C4\u8303\u7684 snapshotRevision\uFF1B\u8BF7\u5148\u521D\u59CB\u5316\u6216\u534F\u8C03\u5FEB\u7167");if(l.failures.length>0)throw new Error(`\u7B7E\u7F72\u88AB\u672C\u4F53\u95E8\u7981\u62D2\u7EDD\uFF1A${l.failures.map(c=>c.id).join(", ")}`);let o=lt({snapshot:n,ledgerText:a,ledgerHeadHash:J(i).headHash,status:e.status,summary:e.summary.trim(),sourceDrift:l.sourceDrift,evidenceIntegrity:l.evidenceIntegrity,implementationIntegrity:l.implementationIntegrity,invariants:l.results});e.dryRun||await ee(t.attestation,`${JSON.stringify(o,null,2)}
|
|
19
|
+
`),k(e,{created:!e.dryRun,dryRun:e.dryRun,attestation:t.attestation,attestationId:o.attestationId,contentHash:o.contentHash,status:o.status,snapshotRevision:o.snapshot.snapshotRevision,ledgerSha256:o.ledger.sha256,ledgerHeadHash:o.ledger.headHash})}async function Qn(e){let t=$(e),[n,s,i,a,r]=await Promise.all([C(t.attestation),C(t.snapshot),C(t.profile),me(t.ledger),H(t.ledger,"utf8")]);Gt(s,a);let l=Se(s,a,i,q(s,e.projectRoot));if(l.applied>0)throw new Error(`${l.applied} \u4E2A\u5DF2\u8BB0\u5F55\u52A8\u4F5C\u5C1A\u672A\u843D\u5165\u5FEB\u7167\uFF1B\u7B7E\u7F72\u5DF2\u7ECF\u5931\u6548`);let d=await Ue(s,n.status,e.projectRoot),o=dt({attestation:n,snapshot:s,ledgerText:r,ledgerHeadHash:J(a).headHash,sourceDrift:d.sourceDrift,evidenceIntegrity:d.evidenceIntegrity,implementationIntegrity:d.implementationIntegrity,invariants:d.results,expectedContentHash:e.expectedHash});k(e,{...o,attestation:t.attestation}),o.valid||(process.exitCode=1)}async function Xn(e){let t=$(e),n=await C(t.snapshot),[s,i,a]=await Promise.all([re(n,q(n,e.projectRoot)),ce(n,q(n,e.projectRoot)),le(n,q(n,e.projectRoot))]),r=pt(n,s,i,a,e.status);e.dryRun||await ee(t.report,r),k(e,{created:!e.dryRun,dryRun:e.dryRun,report:t.report,bytes:Buffer.byteLength(r),requestedStatus:e.status||"STRUCTURAL"})}function Zn(){process.stdout.write([`${gn} \u5019\u9009\u7248\u672C\u7EA6\u675F\u7684\u4EA4\u4ED8\u4FDD\u969C\u6267\u884C\u6846\u67B6`,"","\u7528\u6CD5\uFF1A"," qiheng <install|doctor|uninstall> [options]"," qiheng harness-init [--root <project>] [--force]"," qiheng harness-record --gate <id> --status <status> [--evidence <path>]"," qiheng harness-check [--root <project>]"," qiheng harness-report [--root <project>] [--output <path>]"," qiheng ontology-check [--root <project>] [--status PASS]"," qiheng ontology-reconcile [--root <project>] [--dry-run]"," qiheng ontology-ledger-check [--root <project>]"," qiheng ontology-evidence-check [--root <project>]"," qiheng ontology-validation-check [--root <project>]"," qiheng ontology-implementation-check [--root <project>]"," qiheng ontology-query --query <name> [--id <object-id>]"," qiheng ontology-drift [--root <project>]"," qiheng ontology-plan [--root <project>]"," qiheng ontology-explain --id <object-id>"," qiheng ontology-report [--root <project>] [--status PASS]"," qiheng ontology-attest --status <status> --summary <text>"," qiheng ontology-attestation-check [--root <project>]"," qiheng action-check --action <file> [--root <project>]"," qiheng action-record --action <file> [--root <project>]","","\u9009\u9879\uFF1A"," --host <host> \u76EE\u6807\u5BBF\u4E3B"," --scope user|project \u5B89\u88C5\u8303\u56F4"," --project-root <path> \u9879\u76EE\u8303\u56F4\u5BF9\u5E94\u7684\u4ED3\u5E93\u6839\u76EE\u5F55"," --root <path> \u9879\u76EE\u4E0E\u8BC1\u636E\u6839\u76EE\u5F55"," --snapshot <path> \u6307\u5B9A\u672C\u4F53\u5FEB\u7167\u8DEF\u5F84"," --profile <path> \u6307\u5B9A\u9879\u76EE\u753B\u50CF\u8DEF\u5F84"," --action <path> \u52A8\u4F5C\u8BF7\u6C42\u6587\u4EF6"," --ledger <path> \u6307\u5B9A\u53EA\u8FFD\u52A0\u52A8\u4F5C\u53F0\u8D26\u8DEF\u5F84"," --status <status> \u6307\u5B9A\u7EC8\u6001\u95E8\u7981\u72B6\u6001"," --query <name> \u67E5\u8BE2\u672A\u8986\u76D6\u9879\u3001\u5DEE\u8DDD\u3001\u65E0\u8BC1\u636E\u9879\u6216\u5F71\u54CD\u8303\u56F4"," --id <object-id> \u5F71\u54CD\u8303\u56F4\u67E5\u8BE2\u7684\u8D77\u59CB\u5BF9\u8C61"," --summary <text> \u6700\u7EC8\u7B7E\u7F72\u6458\u8981"," --output <path> \u6307\u5B9A\u751F\u6210\u62A5\u544A\u8DEF\u5F84"," --attestation <path> \u6307\u5B9A\u7B7E\u7F72\u51ED\u8BC1\u8DEF\u5F84"," --expected-hash <sha256> \u8981\u6C42\u5339\u914D\u5916\u90E8\u951A\u5B9A\u7684\u7B7E\u7F72\u6458\u8981\u503C"," --gate <id> \u8981\u66F4\u65B0\u7684\u95E8\u7981"," --evidence <path> \u53EF\u6301\u4E45\u5316\u95E8\u7981\u8BC1\u636E\uFF0C\u53EF\u91CD\u590D\u63D0\u4F9B"," --install-root <path> \u6307\u5B9A\u5BBF\u4E3B\u5B89\u88C5\u6839\u76EE\u5F55"," --marketplace-root <path> Codex \u4E2A\u4EBA\u5E02\u573A\u6839\u76EE\u5F55"," --dry-run \u4EC5\u9884\u89C8\uFF0C\u4E0D\u5199\u5165"," --force \u8986\u76D6\u6216\u79FB\u9664\u5DF2\u786E\u8BA4\u51B2\u7A81"," --json \u8F93\u51FA\u673A\u5668\u53EF\u8BFB\u7ED3\u679C","","\u652F\u6301\u5BBF\u4E3B\uFF1A"," codex (default), claude-code, opencode, mimo-code, bitfun","","\u793A\u4F8B\uFF1A"," qiheng install"," qiheng doctor --host bitfun --scope project"," qiheng uninstall --host opencode --scope project"," qiheng harness-init --root ."," qiheng harness-record --root . --gate design.authority --status PASS --summary \u5DF2\u6838\u9A8C --evidence reports/project-profile.json"," qiheng harness-check --root . --json"," qiheng harness-report --root ."," qiheng ontology-check --root . --status PASS"," qiheng ontology-reconcile --root ."," qiheng ontology-ledger-check --root . --json"," qiheng ontology-evidence-check --root . --json"," qiheng ontology-validation-check --root . --json"," qiheng ontology-implementation-check --root . --json"," qiheng ontology-query --root . --query uncovered"," qiheng ontology-drift --root ."," qiheng ontology-plan --root . --json"," qiheng ontology-explain --root . --id obl-example --json"," qiheng ontology-report --root . --status PASS"," qiheng ontology-attest --root . --status PASS --summary \u5DF2\u6838\u9A8C"," qiheng ontology-attestation-check --root ."," qiheng action-record --root . --action repair-action.json","","--marketplace-root \u662F\u4EC5\u4F9B Codex \u4F7F\u7528\u7684\u5411\u540E\u517C\u5BB9\u9009\u9879\u3002",""].join(`
|
|
20
|
+
`))}try{let e=Sn(process.argv.slice(2));if(e.command==="install")await On(e);else if(e.command==="doctor")await Tn(e);else if(e.command==="uninstall")await jn(e);else if(e.command==="harness-init")await $n(e);else if(e.command==="harness-record")await Ln(e);else if(e.command==="harness-check")await qn(e);else if(e.command==="harness-report")await Hn(e);else if(e.command==="ontology-check")await xn(e);else if(e.command==="ontology-reconcile")await Mn(e);else if(e.command==="ontology-ledger-check")await _n(e);else if(e.command==="ontology-evidence-check")await Vn(e);else if(e.command==="ontology-validation-check")await Fn(e);else if(e.command==="ontology-implementation-check")await Bn(e);else if(e.command==="ontology-query")await Wn(e);else if(e.command==="ontology-drift")await Jn(e);else if(e.command==="ontology-plan")await Yn(e);else if(e.command==="ontology-explain")await Kn(e);else if(e.command==="ontology-report")await Xn(e);else if(e.command==="ontology-attest")await zn(e);else if(e.command==="ontology-attestation-check")await Qn(e);else if(e.command==="action-check")await Un(e);else if(e.command==="action-record")await Gn(e);else if(e.command==="help"||e.command==="--help")Zn();else throw new Error(`\u672A\u77E5\u547D\u4EE4\uFF1A${e.command}`)}catch(e){process.argv.slice(2).includes("--json")?process.stderr.write(`${JSON.stringify({ok:!1,error:e.message},null,2)}
|
|
21
|
+
`):process.stderr.write(`\u9519\u8BEF\uFF1A${e.message}
|
|
18
22
|
`),process.exitCode=1}
|
package/package.json
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dic-workflow-kit",
|
|
3
|
-
"version": "1.1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.1.4",
|
|
4
|
+
"description": "QIHENG 候选版本约束的设计、开发、测试、证据与准入交付保障执行框架。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
|
+
"qiheng": "dist/dic-workflow-kit.mjs",
|
|
7
8
|
"dic-workflow-kit": "dist/dic-workflow-kit.mjs"
|
|
8
9
|
},
|
|
9
10
|
"files": [
|
|
@@ -23,6 +24,8 @@
|
|
|
23
24
|
"opencode",
|
|
24
25
|
"mimo-code",
|
|
25
26
|
"bitfun",
|
|
27
|
+
"qiheng",
|
|
28
|
+
"design-integrity",
|
|
26
29
|
"plugin",
|
|
27
30
|
"skills",
|
|
28
31
|
"subagents",
|
|
@@ -6,7 +6,22 @@
|
|
|
6
6
|
"required": ["schema", "status", "final", "summary", "artifacts"],
|
|
7
7
|
"properties": {
|
|
8
8
|
"schema": { "const": "dic.final-result.v1" },
|
|
9
|
-
"status": {
|
|
9
|
+
"status": {
|
|
10
|
+
"enum": ["PASS", "PARTIAL", "BLOCKED", "FAIL"],
|
|
11
|
+
"description": "Backward-compatible DIC consistency status. Prefer consistencyStatus for new output."
|
|
12
|
+
},
|
|
13
|
+
"consistencyStatus": {
|
|
14
|
+
"enum": ["PASS", "PARTIAL", "BLOCKED", "FAIL"],
|
|
15
|
+
"description": "Design-implementation consistency outcome. When present, it must not be treated as repository admission."
|
|
16
|
+
},
|
|
17
|
+
"qualityStatus": {
|
|
18
|
+
"enum": ["PASS", "PASS WITH FOLLOW-UP", "BLOCKED", "NOT_EVALUATED"],
|
|
19
|
+
"description": "Current aggregate decision across all applicable specialist quality gates."
|
|
20
|
+
},
|
|
21
|
+
"admissionStatus": {
|
|
22
|
+
"enum": ["ADMIT", "ADMIT WITH FOLLOW-UP", "REJECT", "NOT_EVALUATED"],
|
|
23
|
+
"description": "Pre-commit repository admission outcome for the frozen candidate."
|
|
24
|
+
},
|
|
10
25
|
"final": { "type": "boolean" },
|
|
11
26
|
"summary": { "type": "string" },
|
|
12
27
|
"artifacts": { "type": "array", "items": { "type": "string" } },
|