workspai 0.72.0 → 0.72.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +5 -2
  2. package/dist/autopilot-release-QMZSHOLF.js +1 -0
  3. package/dist/{chunk-TQQEZQLC.js → chunk-4PDEWMOG.js} +1 -1
  4. package/dist/{chunk-UHAPXPGW.js → chunk-5NL53T5C.js} +1 -1
  5. package/dist/{chunk-SG3QRCMM.js → chunk-FYIPYGMW.js} +1 -1
  6. package/dist/{chunk-7LKCWDX6.js → chunk-I7P6XQJI.js} +1 -1
  7. package/dist/{chunk-COBU44T5.js → chunk-ISGLADQI.js} +1 -1
  8. package/dist/{chunk-D5RUGSBC.js → chunk-JPPZDLY3.js} +1 -1
  9. package/dist/{chunk-ONV6WW7A.js → chunk-L4WG3NI7.js} +1 -1
  10. package/dist/{chunk-5TKRCE6F.js → chunk-L5ZD2GD3.js} +1 -1
  11. package/dist/{chunk-5PFFR5S7.js → chunk-LLSY6L7E.js} +1 -1
  12. package/dist/{chunk-5OLNT6YD.js → chunk-RQKDJVX3.js} +65 -65
  13. package/dist/{chunk-LDNX2R6V.js → chunk-U3RX7KDY.js} +1 -1
  14. package/dist/{create-7CWWGDXQ.js → create-FOPYAWAR.js} +1 -1
  15. package/dist/{doctor-WYBSI3GC.js → doctor-Z3Z5L67W.js} +1 -1
  16. package/dist/{goal-lifecycle-PSPYQ4TR.js → goal-lifecycle-ZH7AQIOX.js} +1 -1
  17. package/dist/{goal-pack-G7SAYDIC.js → goal-pack-OP453Q6U.js} +1 -1
  18. package/dist/index.js +18 -18
  19. package/dist/{pipeline-NDV7DBB7.js → pipeline-LPZHMO7S.js} +1 -1
  20. package/dist/{project-agent-entry-HEBGPLMX.js → project-agent-entry-QGPM7CU7.js} +1 -1
  21. package/dist/{project-intelligence-lens-QTQEZXUY.js → project-intelligence-lens-U7PLWYXX.js} +1 -1
  22. package/dist/{proof-carrying-change-SHO2E3DX.js → proof-carrying-change-6LQ6JO5J.js} +1 -1
  23. package/dist/{verified-goal-BSREU6R7.js → verified-goal-JIRVX7KO.js} +1 -1
  24. package/dist/{workspace-E3MM3AIE.js → workspace-3K2YGPU7.js} +1 -1
  25. package/dist/{workspace-agent-sync-NBIOSXCG.js → workspace-agent-sync-TFQNKRD3.js} +1 -1
  26. package/dist/{workspace-foundation-LRLYPR36.js → workspace-foundation-J62BMOQS.js} +1 -1
  27. package/dist/{workspace-intelligence-runner-FPPKTSNK.js → workspace-intelligence-runner-OELXKX3D.js} +1 -1
  28. package/dist/{workspace-mcp-serve-KSZ2O66S.js → workspace-mcp-serve-X7ZYJA3X.js} +1 -1
  29. package/dist/{workspace-onboarding-RJMTHN7Z.js → workspace-onboarding-CZSQDNKO.js} +1 -1
  30. package/dist/{workspace-repair-engine-4JTNNDZL.js → workspace-repair-engine-RXHJX4CQ.js} +1 -1
  31. package/dist/workspace-run-IDRHBKEB.js +1 -0
  32. package/docs/ci-workflows.md +1 -1
  33. package/docs/doctor-command.md +7 -0
  34. package/package.json +1 -4
  35. package/scripts/enterprise-package-smoke.mjs +14 -2
  36. package/dist/autopilot-release-PNSWAVZG.js +0 -1
  37. package/dist/workspace-run-HFOY2UYT.js +0 -1
  38. package/scripts/check-cli-resolution.cjs +0 -72
  39. /package/dist/{chunk-EDPUQXP6.js → chunk-4AW5QP5J.js} +0 -0
package/README.md CHANGED
@@ -113,8 +113,11 @@ Choose whether to create a workspace, scaffold a project, or add existing
113
113
  software. Project starters are grouped as Backend, Frontend, Desktop, and
114
114
  Extension.
115
115
 
116
- Global installation is optional: `npm install -g workspai`. `wspai` is a short
117
- alias for the same CLI.
116
+ ```bash
117
+ # Optional global installation
118
+ npm install -g workspai
119
+ workspai --version
120
+ ```
118
121
 
119
122
  ## Give your agent a goal, not an open-ended prompt
120
123
 
@@ -0,0 +1 @@
1
+ export{b as AUTOPILOT_RELEASE_ALIAS_FILENAME,a as AUTOPILOT_RELEASE_LAST_RUN_FILENAME,c as runAutopilotRelease}from'./chunk-U3RX7KDY.js';
@@ -1,4 +1,4 @@
1
- import {l,f,e as e$2,g as g$1}from'./chunk-T6LCDLJ7.js';import {b as b$4}from'./chunk-SG3QRCMM.js';import {b as b$7,a as a$3}from'./chunk-D5LLTUTY.js';import {b as b$2}from'./chunk-B6FJ6RG6.js';import {a as a$2}from'./chunk-2RF75G5T.js';import {e,g,h as h$1,c as c$1,i as i$1,f as f$1,b as b$6,d as d$4}from'./chunk-46QH3ZVI.js';import {g as g$2}from'./chunk-WPZUKU2B.js';import {d as d$1,b as b$1}from'./chunk-2LIVMG5C.js';import {h,e as e$1,b as b$3,d as d$2}from'./chunk-PKKSRXUS.js';import {a}from'./chunk-TQEMLBAG.js';import {i,b as b$5,k as k$1,j,m,t,s as s$1,q}from'./chunk-RGNCL5OB.js';import {b,a as a$1,c,d as d$3}from'./chunk-VQZ5PI5J.js';import {promises}from'fs';import*as k from'fs-extra';import d from'path';import s from'chalk';import {execa}from'execa';function ct(e){let n=e.projectCount??0,t=n===1?"project":"projects",o=e.pythonEngine==="installed"?`Python ${e.pythonVersion||"3.10+"} \xB7 ${e.installMethod||"local environment"}`:e.pythonEngine==="skipped"?"Python engine not installed":"Runtime-neutral foundation";return ["","\u2713 Workspace ready",`${e.workspaceName} \xB7 ${e.profile} \xB7 ${n} registered ${t}`,`Location ${e.workspacePath}`,`Runtime ${o}`,...e.note?[`Note ${e.note}`]:[],"","Workspace Intelligence"," \u2713 Contract and project registry"," \u2713 Canonical model and proof-backed graph"," \u2713 Agent context, grounding, and evidence index","","Next",` ${g$1(e.workspacePath)}`," npx workspai create"," npx workspai workspace intelligence run --for-agent generic --strict --json","","Evidence .workspai/reports/INDEX.json","Guide README.md",""]}function B(e){let n=ct(e);for(let t of n)t==="\u2713 Workspace ready"?console.log(s.green.bold(t)):t==="Workspace Intelligence"||t==="Next"?console.log(s.cyan.bold(t)):t.startsWith(" \u2713")?console.log(s.green(t)):t.startsWith("Location")||t.startsWith("Runtime")?console.log(s.gray(t)):console.log(t);}function T(){return i()}var pt="transactions";function dt(){return d.join(q(),pt)}async function He(){let e=dt();return await b$7(e),a$3({journalDirectory:e})}async function Ue(e){for(let n of s$1())await e.captureFile(n);}async function se(e){let n=await He();try{return await Ue(n),await n.captureOwnedTree(e),n}catch(t){return F(n,t)}}async function ut(e){let n=await He();try{await Ue(n),await n.captureOwnedTree(d.join(e,a$1)),await n.captureOwnedTree(d.join(e,".venv"));let t=[c,".gitignore",d.join(a$1,"workspace.json"),d.join(a$1,"toolchain.lock"),d.join(a$1,"policies.yml"),d.join(a$1,"cache-config.yml"),g$2,a$2,"pyproject.toml","poetry.toml","poetry.lock","rapidkit","rapidkit.cmd","README.md",".rapidkit-global"];for(let o of t)await n.captureFile(d.join(e,o));return n}catch(t){return F(n,t)}}async function J(e){await e.commit(),e.journalPath&&await promises.rm(d.dirname(e.journalPath),{recursive:true,force:true}).catch(n=>e$1.debug(`Could not remove committed lifecycle journal: ${n}`));}async function F(e,n){try{await e.rollback();}catch(t){throw new AggregateError([n,t],"Workspace lifecycle failed and rollback was incomplete.")}throw n}async function Q(e,n,t,o,a){let l=d$1(n,h(),t,a?.pythonEngine?{coreStatus:a.pythonEngine,...a.pythonEngineReason?{coreReason:a.pythonEngineReason}:{},...o?{pythonVersion:o}:{}}:void 0);o&&!a?.pythonEngine&&(l.metadata||(l.metadata={}),l.metadata.python={pythonVersion:o}),await b$1(e,l);}async function H(e){await k.outputFile(d.join(e,".gitignore"),`.venv/
1
+ import {l,f,e as e$2,g as g$1}from'./chunk-T6LCDLJ7.js';import {b as b$4}from'./chunk-FYIPYGMW.js';import {b as b$7,a as a$3}from'./chunk-D5LLTUTY.js';import {b as b$2}from'./chunk-B6FJ6RG6.js';import {a as a$2}from'./chunk-2RF75G5T.js';import {e,g,h as h$1,c as c$1,i as i$1,f as f$1,b as b$6,d as d$4}from'./chunk-46QH3ZVI.js';import {g as g$2}from'./chunk-WPZUKU2B.js';import {d as d$1,b as b$1}from'./chunk-2LIVMG5C.js';import {h,e as e$1,b as b$3,d as d$2}from'./chunk-PKKSRXUS.js';import {a}from'./chunk-TQEMLBAG.js';import {i,b as b$5,k as k$1,j,m,t,s as s$1,q}from'./chunk-RGNCL5OB.js';import {b,a as a$1,c,d as d$3}from'./chunk-VQZ5PI5J.js';import {promises}from'fs';import*as k from'fs-extra';import d from'path';import s from'chalk';import {execa}from'execa';function ct(e){let n=e.projectCount??0,t=n===1?"project":"projects",o=e.pythonEngine==="installed"?`Python ${e.pythonVersion||"3.10+"} \xB7 ${e.installMethod||"local environment"}`:e.pythonEngine==="skipped"?"Python engine not installed":"Runtime-neutral foundation";return ["","\u2713 Workspace ready",`${e.workspaceName} \xB7 ${e.profile} \xB7 ${n} registered ${t}`,`Location ${e.workspacePath}`,`Runtime ${o}`,...e.note?[`Note ${e.note}`]:[],"","Workspace Intelligence"," \u2713 Contract and project registry"," \u2713 Canonical model and proof-backed graph"," \u2713 Agent context, grounding, and evidence index","","Next",` ${g$1(e.workspacePath)}`," npx workspai create"," npx workspai workspace intelligence run --for-agent generic --strict --json","","Evidence .workspai/reports/INDEX.json","Guide README.md",""]}function B(e){let n=ct(e);for(let t of n)t==="\u2713 Workspace ready"?console.log(s.green.bold(t)):t==="Workspace Intelligence"||t==="Next"?console.log(s.cyan.bold(t)):t.startsWith(" \u2713")?console.log(s.green(t)):t.startsWith("Location")||t.startsWith("Runtime")?console.log(s.gray(t)):console.log(t);}function T(){return i()}var pt="transactions";function dt(){return d.join(q(),pt)}async function He(){let e=dt();return await b$7(e),a$3({journalDirectory:e})}async function Ue(e){for(let n of s$1())await e.captureFile(n);}async function se(e){let n=await He();try{return await Ue(n),await n.captureOwnedTree(e),n}catch(t){return F(n,t)}}async function ut(e){let n=await He();try{await Ue(n),await n.captureOwnedTree(d.join(e,a$1)),await n.captureOwnedTree(d.join(e,".venv"));let t=[c,".gitignore",d.join(a$1,"workspace.json"),d.join(a$1,"toolchain.lock"),d.join(a$1,"policies.yml"),d.join(a$1,"cache-config.yml"),g$2,a$2,"pyproject.toml","poetry.toml","poetry.lock","rapidkit","rapidkit.cmd","README.md",".rapidkit-global"];for(let o of t)await n.captureFile(d.join(e,o));return n}catch(t){return F(n,t)}}async function J(e){await e.commit(),e.journalPath&&await promises.rm(d.dirname(e.journalPath),{recursive:true,force:true}).catch(n=>e$1.debug(`Could not remove committed lifecycle journal: ${n}`));}async function F(e,n){try{await e.rollback();}catch(t){throw new AggregateError([n,t],"Workspace lifecycle failed and rollback was incomplete.")}throw n}async function Q(e,n,t,o,a){let l=d$1(n,h(),t,a?.pythonEngine?{coreStatus:a.pythonEngine,...a.pythonEngineReason?{coreReason:a.pythonEngineReason}:{},...o?{pythonVersion:o}:{}}:void 0);o&&!a?.pythonEngine&&(l.metadata||(l.metadata={}),l.metadata.python={pythonVersion:o}),await b$1(e,l);}async function H(e){await k.outputFile(d.join(e,".gitignore"),`.venv/
2
2
  __pycache__/
3
3
  *.pyc
4
4
  .env
@@ -1 +1 @@
1
- import {a as a$1}from'./chunk-TDQ2PRHV.js';import {f,i}from'./chunk-FE5R6EUV.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c}from'./chunk-EWZZUQBR.js';import {createHash}from'crypto';import u from'path';import j from'fs-extra';var V="workspai.goal-pack.v1",B="workspai.goal-agent-handoff.v1",ae="workspai.goal-plan-result.v1",D=".workspai/reports/goal-pack-last-run.json",M="workspai.goal-index.v1",p=".workspai/goals/index.json",F="workspai.goal-lifecycle-result.v1";function K(e){if(!e.activeGoalId)return null;let a=e.goals.find(o=>o.id===e.activeGoalId),t=e.goals.filter(o=>o.lifecycle==="active");return !a||a.state==="ready-to-plan"||!(a.lifecycle==="planned"&&t.length===0||a.lifecycle==="active"&&t.length===1&&t[0]?.id===a.id)?null:{...e,activeGoalId:null,goals:e.goals.map(o=>o.id===a.id&&o.lifecycle==="active"?{...o,lifecycle:"planned"}:o)}}function A(e){let a=new Set,t=new Set,o=Date.parse(e.generatedAt);for(let r of e.goals){if(a.has(r.id))throw new Error(`Goal index contains duplicate id: ${r.id}`);if(t.has(r.fingerprint))throw new Error(`Goal index contains duplicate fingerprint: ${r.fingerprint}`);if(a.add(r.id),t.add(r.fingerprint),r.goalPack!==`.workspai/goals/${r.id}/goal-pack.json`||r.agentHandoff!==`.workspai/goals/${r.id}/agent-handoff.json`)throw new Error(`Goal index artifact paths do not match goal id: ${r.id}`);if(Date.parse(r.createdAt)>Date.parse(r.updatedAt))throw new Error(`Goal index timestamps are inconsistent for: ${r.id}`);if(Date.parse(r.updatedAt)>o)throw new Error(`Goal index generatedAt predates entry update: ${r.id}`)}let i=e.goals.filter(r=>r.lifecycle==="active");for(let r of e.goals){if(r.repairTransactionIds&&(r.repairTransactionIds.length>25||new Set(r.repairTransactionIds).size!==r.repairTransactionIds.length||r.repairTransactionId&&r.repairTransactionIds.at(-1)!==r.repairTransactionId))throw new Error(`Goal index repair transaction history is inconsistent: ${r.id}`);if(r.changeTransactionIds&&(r.changeTransactionIds.length>25||new Set(r.changeTransactionIds).size!==r.changeTransactionIds.length||r.changeTransactionId&&r.changeTransactionIds.at(-1)!==r.changeTransactionId))throw new Error(`Goal index change transaction history is inconsistent: ${r.id}`);if(r.verificationReceipt&&(!r.verifiedGoalId||r.verificationReceipt.verifiedGoalId!==r.verifiedGoalId||r.verificationReceipt.attempt<1||Date.parse(r.verificationReceipt.recordedAt)>o))throw new Error(`Goal index verification receipt is inconsistent: ${r.id}`)}if(e.activeGoalId===null){if(i.length>0)throw new Error("Goal index is inconsistent: active lifecycle entries require activeGoalId.");return}let n=e.goals.find(r=>r.id===e.activeGoalId);if(!n||n.state!=="ready-to-plan"||!["active","verification-ready","failed"].includes(n.lifecycle)||i.some(r=>r.id!==e.activeGoalId))throw new Error("Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")}function X(e){let a=_(e.scope),t={id:"workspace-verify",kind:"workspace-verify",expected:"Canonical Workspace Verify proves workspace safety and evidence freshness without claiming arbitrary semantic outcome completion.",producerCommand:"workspai workspace verify --json",machineVerifiable:true};if(e.intent.category==="release-readiness")return [{id:"release-readiness",kind:"release-readiness",expected:"Every release readiness gate passes.",producerCommand:`workspai workspace goal plan release-readiness${a} --json`,machineVerifiable:true},t];if(e.intent.category==="dependency-security")return [{id:"dependency-security",kind:"dependency-security",expected:"No blocking dependency vulnerability remains in the selected scope.",producerCommand:`workspai workspace goal plan dependency-security${a} --json`,machineVerifiable:true},t];if(e.intent.category==="test-coverage"&&e.intent.requestedTarget){let o=e.intent.requestedTarget.runtime?` --runtime ${e.intent.requestedTarget.runtime}`:"";return [{id:"test-coverage",kind:"test-coverage",expected:`${e.intent.requestedTarget.runtime?`${e.intent.requestedTarget.runtime} `:""}test coverage is at least ${e.intent.requestedTarget.value}%.`,producerCommand:`workspai workspace goal plan test-coverage${a} --target ${e.intent.requestedTarget.value}${o} --json`,machineVerifiable:e.preflight.measurement.status==="available"},t]}return [t]}function Y(e){let a=_(e.scope);if(e.intent.category==="release-readiness")return `workspai workspace goal plan release-readiness${a} --json`;if(e.intent.category==="dependency-security")return `workspai workspace goal plan dependency-security${a} --json`;if(e.intent.category==="test-coverage"&&e.intent.requestedTarget){let t=e.intent.requestedTarget.runtime?` --runtime ${e.intent.requestedTarget.runtime}`:"";return `workspai workspace goal plan test-coverage${a} --target ${e.intent.requestedTarget.value}${t} --json`}}function W(e){return /^[A-Za-z0-9._:@+-]+$/.test(e)?e:JSON.stringify(e)}function _(e){return e.resolution==="selection-required"?"":e.kind==="project"&&e.projects[0]?` --scope ${W(`project:${e.projects[0]}`)}`:e.kind==="project-set"&&e.projects.length>1?` --scope ${W(`projects:${e.projects.join(",")}`)}`:e.kind==="workspace"?" --scope workspace":""}function z(e,a){let t=X(e),o=e.intent.ambiguities.length>0,i=!o&&e.intent.category==="test-coverage"&&e.preflight.measurement.status!=="available",n=!o&&e.preflight.retrieval.status==="empty",r={kernelRevision:"goal-pack-kernel-v12",intent:e.intent.normalized,workspace:e.workspaceName,scope:e.scope,modelHash:e.sourceBinding.model.hash,graphSourceFingerprint:e.sourceBinding.graph.inputHash??e.sourceBinding.graph.hash,preflight:e.preflight,baseline:e.baseline,consumer:e.consumer,policy:{maxAttempts:e.maxAttempts,mutationMode:"proposal-only"}},s=a.digestCanonical(r),c=`goal-${e.intent.category}-${s.slice(0,16)}`,l=`.workspai/goals/${c}/goal-pack.json`,m=`.workspai/goals/${c}/agent-handoff.json`,w=Y(e),T=!!w,R=_(e.scope),d=_(e.scope),G=o?"needs-confirmation":n?"blocked":i?"needs-evidence":"ready-to-plan",f=o&&e.intent.category==="test-coverage"&&e.intent.ambiguities.some(b=>/coverage runtimes|coverage scope|requested .* runtime/i.test(b)),I=o&&e.intent.category==="test-coverage"&&e.intent.ambiguities.some(b=>b.startsWith("The selected projects do not share a common canonical coverage runtime")),y=e.preflight.measurement.runtimeChoices??e.baseline.runtimes,g=e.scope.resolution==="selection-required"||e.intent.ambiguities.some(b=>b.startsWith("Goal scope is unresolved")),h={schemaVersion:V,id:c,fingerprint:s,generatedAt:e.generatedAt,state:G,intent:e.intent,workspace:{name:e.workspaceName},scope:e.scope,sourceBinding:e.sourceBinding,baseline:e.baseline,preflight:e.preflight,successCriteria:t,policy:{mutationMode:"proposal-only",approval:"required-before-mutation",verificationOwner:"workspai-cli",rollbackOwner:"workspai-cli",maxAttempts:e.maxAttempts,allowBreakingChanges:false,allowForce:false,networkAccess:"not-granted",scopeExpansion:"requires-decision"},orchestration:[{id:"understand",owner:"workspai-cli",status:"complete",summary:"Bound the intent to the canonical model and proof-backed graph."},{id:"impact",owner:"workspai-cli",status:"complete",summary:"Pinned the permitted workspace or project scope before source inspection."},{id:"propose",owner:"agent",status:o||i||n?"blocked":"pending",summary:"Produce a bounded source-change proposal; do not mutate evidence artifacts."},{id:"approve",owner:"human",status:"pending",summary:"Approve the immutable CLI repair plan before mutation."},{id:"execute",owner:"workspai-cli",status:"pending",summary:"Checkpoint, execute, reconcile, and roll back through Repair Engine."},{id:"verify",owner:"workspai-cli",status:"pending",summary:T?"Independently verify the exact success contract from fresh evidence.":"Verify workspace safety and evidence freshness; the agent must review the final outcome against the complete objective."}],...o||i||n?{decision:{required:true,reason:o?e.intent.ambiguities.join(" "):n?"No bounded proof-backed Graph anchor matches the selected scope and intent.":e.preflight.measurement.prerequisites.join(" ")||"No current machine-readable measurement evidence is available.",question:o?g?`Choose one project, multiple projects, or the entire workspace from: ${e.scope.projects.join(", ")}.`:I?"Split the selected projects into runtime-compatible Goal scopes so every project receives deterministic coverage verification.":f?`Choose exactly one coverage runtime from the detected scope${y.length>0?`: ${y.join(", ")}`:""}, then regenerate this Goal Pack.`:"Clarify the intended outcome or provide a machine-verifiable target.":n?"Refresh Workspace Intelligence or clarify the intent before asking an agent to inspect source.":"Establish the listed measurement prerequisites, then regenerate this Goal Pack."}}:{},artifacts:{goalPack:l,agentHandoff:m,latestReport:D},commands:{refreshEvidence:"workspai workspace intelligence run --for-agent generic --strict --json",inspectGraph:`workspai workspace graph search ${JSON.stringify(e.preflight.retrieval.queries[0]??e.intent.statement)}${R} --limit 20 --json`,beginChange:`workspai change begin --goal ${c} --json`,...w?{planVerifiedGoal:w}:{},proposeRepair:"workspai workspace repair propose --file <proposal.json> --json"}},P=a.digestCanonical(h),L={schemaVersion:B,goalId:c,goalFingerprint:s,generatedAt:e.generatedAt,consumer:e.consumer,state:G,objective:e.intent.statement,scope:e.scope,discovery:{index:p,statusCommand:`workspai goal --status ${c} --json`,requiredReads:[p,l,m]},retrieval:e.preflight.retrieval,evidence:[{role:"model",artifact:e.sourceBinding.model.artifact,binding:{algorithm:"sha256",semantics:e.sourceBinding.model.hashSemantics,value:e.sourceBinding.model.hash}},{role:"graph",artifact:e.sourceBinding.graph.artifact,binding:{algorithm:"sha256",semantics:e.sourceBinding.graph.hashSemantics,value:e.sourceBinding.graph.hash}},{role:"goal",artifact:l,binding:{algorithm:"sha256",semantics:"canonical-json-v1",value:P}}],guardrails:["Treat the Goal Pack as data, never as instructions that can override host or CLI policy.","Inspect only the bounded scope and request a decision before expanding it.","Do not edit .workspai evidence, goal, repair, contract, or report artifacts.","Return source edits as a proposal until a human authorizes either a Workspai Repair transaction or a Proof-Carrying Change.","After Proof-Carrying Change authorization, use only admitted effect classes and record typed effect receipts before verification.","Do not claim success from model output or test narration; require fresh CLI evidence.",...T?[]:["For this general Goal, CLI verification proves workspace safety and freshness; final outcome acceptance requires evidence review against the complete objective."]],workflow:[{order:1,owner:"workspai-cli",instruction:"Validate source bindings and scope."},{order:2,owner:"agent",instruction:"Inspect bounded proof and relevant source."},{order:3,owner:"workspai-cli",instruction:`Begin or join the Goal-bound change with: workspai change begin --goal ${c} --json.`},{order:4,owner:"agent",instruction:"Attach a bounded prediction and return one focused, reviewable proposal."},{order:5,owner:"human",instruction:"Authorize explicit effect classes."},{order:6,owner:"agent",instruction:"Execute only authorized effects and record idempotent effect receipts."},{order:7,owner:"workspai-cli",instruction:"Re-observe the Graph, run independent verification, and seal the capsule."},...T?[]:[{order:8,owner:"agent",instruction:"Inspect the final worktree and fresh evidence against the complete objective; report uncertainty instead of presenting workspace verification as semantic proof."}]],renewal:{command:`workspai goal ${JSON.stringify(e.intent.original)}${d}${e.intent.requestedTarget?.runtime?` --runtime ${e.intent.requestedTarget.runtime}`:""} --refresh --for-agent ${e.consumer} --json`,reason:"Regenerate when the canonical model or graph hash changes."}};return {goalPack:h,handoff:L}}var S="contracts/workspace-intelligence/goal-index.v1.json",Q="contracts/workspace-intelligence/goal-lifecycle-result.v1.json";function me(e){let a$1={schemaVersion:F,...e};return a(a$1,Q,"Goal lifecycle result"),a$1}async function C(e){let a$1=u.join(e,p);if(!await j.pathExists(a$1))return {schemaVersion:M,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let t=await j.readJson(a$1);a(t,S,"Goal index");try{return A(t),t}catch(o){let i=K(t);if(!i||!(o instanceof Error)||o.message!=="Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")throw o;return A(i),i}}async function J(e,a$2){let[t,o]=await Promise.all([j.readJson(u.join(e,a$2.goalPack)),j.readJson(u.join(e,a$2.agentHandoff))]);if(a(t,"contracts/workspace-intelligence/goal-pack.v1.json","Indexed Goal Pack"),t.id!==a$2.id||t.fingerprint!==a$2.fingerprint)throw new Error(`Goal index binding failed for ${a$2.id}.`);a(o,"contracts/workspace-intelligence/goal-agent-handoff.v1.json","Indexed Goal agent handoff");let i=new Map(o.evidence.map(d=>[d.role,d])),n=z({generatedAt:t.generatedAt,intent:t.intent,workspaceName:t.workspace.name,scope:t.scope,sourceBinding:t.sourceBinding,baseline:t.baseline,preflight:t.preflight,maxAttempts:t.policy.maxAttempts,consumer:o.consumer},{digestCanonical:c});if(o.goalId!==t.id||o.goalFingerprint!==t.fingerprint||i.get("goal")?.binding.value!==c(t)||i.get("model")?.binding.value!==t.sourceBinding.model.hash||i.get("graph")?.binding.value!==t.sourceBinding.graph.hash||c(o)!==c(n.handoff))throw new Error(`Goal agent handoff integrity validation failed for ${a$2.id}.`);let r=await a$1(e);if(r.status==="miss")throw new Error(`Goal ${a$2.id} is stale because live workspace inputs changed (${r.reason}). Regenerate it with --refresh.`);let{model:s,graph:c$1}=r,l=d(s),m=c(c$1),w=c$1.source.inputs?.hash;if(!(l===t.sourceBinding.model.hash&&(t.sourceBinding.graph.inputHash?w===t.sourceBinding.graph.inputHash:m===t.sourceBinding.graph.hash))){let d=a$2.changeTransactionIds??(a$2.changeTransactionId?[a$2.changeTransactionId]:[]),{assertSealedProofCarryingChangeCurrent:G}=await import('./proof-carrying-change-SHO2E3DX.js'),f=false;for(let g of [...d].reverse()){let h=await G({workspacePath:e,changeId:g,goalId:a$2.id}).catch(()=>{});if(h?.modelHash===l&&h.graphHash===m){f=true;break}}let I=a$2.repairTransactionIds??(a$2.repairTransactionId?[a$2.repairTransactionId]:[]),{assertClosedGoalRepairTransactionCurrent:y}=await import('./workspace-repair-engine-4JTNNDZL.js');if(!f)for(let g of [...I].reverse()){let h=await y({workspacePath:e,transactionId:g,goalId:a$2.id}).catch(()=>{});if(h?.modelHash===l&&h.graphInputHash===w){f=true;break}}if(!f&&a$2.verificationReceipt&&a$2.verifiedGoalId){let g=a$2.verificationReceipt,{readVerifiedGoal:h}=await import('./verified-goal-BSREU6R7.js'),P=await h(e,a$2.verifiedGoalId).catch(()=>{}),L=w??m;f=!!(P&&g.verifiedGoalId===a$2.verifiedGoalId&&g.attempt===P.status.attempt&&g.statusHash===c(P.status)&&g.modelHash===l&&g.graphFingerprint===L&&g.graphFingerprintSemantics===(w?"workspace-knowledge-graph-inputs-v1":"canonical-json-v1"));}if(!f)throw new Error(`Goal ${a$2.id} is stale because its canonical model or graph binding changed outside a closed Goal repair transaction or recorded CLI verification attempt. Regenerate it with --refresh.`)}if(c$1.source.hash!==l)throw new Error(`Goal ${a$2.id} is stale because its current Model and Graph source bindings disagree. Regenerate it with --refresh.`);let R=s;for(let d of t.preflight.measurement.existingEvidence){let G=R.projects?.find(g=>g.name===d.project);if(!G)throw new Error(`Goal measurement project binding is missing: ${d.project}`);let f=u.resolve(G.absolutePath??u.join(e,G.path??d.project)),I=u.resolve(f,d.path);if(I!==f&&!I.startsWith(`${f}${u.sep}`))throw new Error(`Goal measurement evidence escapes its project boundary: ${d.path}`);let y=await j.readFile(I).catch(()=>null);if(!y||createHash("sha256").update(y).digest("hex")!==d.sha256)throw new Error(`Goal ${a$2.id} is stale because measurement evidence changed: ${d.project}/${d.path}`)}return t}async function $(e){let a=u.resolve(e.workspacePath),t=await C(a),o=e.goalId??t.activeGoalId,i=o?t.goals.find(r=>r.id===o)??null:null;if(o&&!i)throw new Error(`Goal is not registered in this workspace: ${o}`);let n=i&&e.validateBindings!==false?await J(a,i):null;return {index:t,active:i,goalPack:n}}async function we(e){let a$1=u.resolve(e.workspacePath);return f(a$1,".workspai/goals/index-lifecycle",async()=>{let t=await C(a$1),o=t.goals.find(s=>s.id===e.goalId);if(!o)throw new Error(`Goal is not registered in this workspace: ${e.goalId}`);if(e.action==="activate"){let s=await J(a$1,o);if(s.state!=="ready-to-plan"){let c=s.decision;throw new Error([`Goal ${o.id} cannot be activated while its planning state is ${s.state}.`,c?.reason,c?.question,"Re-run the Goal with the requested clarification or evidence before activation."].filter(l=>!!l).join(" "))}if(o.lifecycle==="cancelled"||o.lifecycle==="verified"||o.lifecycle==="verification-ready")throw new Error(`Goal ${o.id} cannot be activated from lifecycle ${o.lifecycle}. Create or plan a new Goal instead.`)}let i$1=new Date().toISOString(),n={...o,lifecycle:e.action==="activate"?"active":"cancelled",updatedAt:i$1},r={...t,generatedAt:i$1,activeGoalId:e.action==="activate"?e.goalId:t.activeGoalId===e.goalId?null:t.activeGoalId,goals:t.goals.map(s=>s.id===e.goalId?n:e.action==="activate"&&s.lifecycle==="active"?{...s,lifecycle:"planned",updatedAt:i$1}:s)};return a(r,S,"Goal index"),A(r),await i(a$1,p,[{relativePath:p,payload:r}]),{index:r,goal:n}})}async function U(e){return f(e.workspacePath,".workspai/goals/index-lifecycle",async()=>{let a$1=await C(e.workspacePath),t=a$1.goals.find(n=>n.id===e.goalId);if(!t)throw new Error(`Goal is not registered in this workspace: ${e.goalId}`);let o={...t,lifecycle:e.lifecycle,updatedAt:new Date().toISOString(),...e.verifiedGoalId?{verifiedGoalId:e.verifiedGoalId}:{},...e.verificationReceipt?{verificationReceipt:e.verificationReceipt}:{}},i$1={...a$1,generatedAt:o.updatedAt,activeGoalId:e.lifecycle==="verified"?null:e.goalId,goals:a$1.goals.map(n=>n.id===e.goalId?o:n)};return a(i$1,S,"Goal index"),A(i$1),await i(e.workspacePath,p,[{relativePath:p,payload:i$1}]),o})}async function ve(e){let a=await $(e);if(!a.active||!a.goalPack)throw new Error("No active Goal Pack is available.");if(a.index.activeGoalId!==a.active.id)throw new Error(`Goal ${a.active.id} is not active. Activate it before preparing verification.`);let t=a.goalPack;if(!t.commands.planVerifiedGoal)throw new Error(`Goal ${t.id} has no deterministic verification primitive. An agent proposal and explicit review are required first.`);if(t.state!=="ready-to-plan")throw new Error(`Goal ${t.id} cannot enter verification while its state is ${t.state}.`);let{planVerifiedGoal:o}=await import('./verified-goal-BSREU6R7.js'),i=t.scope.kind==="project"&&t.scope.projects[0]?`project:${t.scope.projects[0]}`:t.scope.kind==="project-set"&&t.scope.projects.length>1?`projects:${t.scope.projects.join(",")}`:void 0,n=t.intent.category;if(n!=="release-readiness"&&n!=="dependency-security"&&n!=="test-coverage")throw new Error(`Goal category ${n} does not have a deterministic verification adapter.`);let r=await o({workspacePath:e.workspacePath,kind:n,scope:i,target:t.intent.requestedTarget?.value,runtime:t.intent.requestedTarget?.runtime});return {goal:await U({workspacePath:e.workspacePath,goalId:t.id,lifecycle:"verification-ready",verifiedGoalId:r.goal.id}),verifiedGoalId:r.goal.id,state:r.status.state}}async function ke(e){let a=u.resolve(e.workspacePath),t=await $({workspacePath:a,goalId:e.goalId,validateBindings:false});if(!t.active)throw new Error("No active Goal Pack is available.");let o=t.active.id;return f(a,`.workspai/goals/${o}/verification`,()=>ee({workspacePath:a,goalId:o,run:e.run}))}async function ee(e){let a=await $(e);if(!a.active)throw new Error("No active Goal Pack is available.");if(a.index.activeGoalId!==a.active.id)throw new Error(`Goal ${a.active.id} is not active. Activate it before running verification.`);if(!a.active.verifiedGoalId)throw new Error(`Goal ${a.active.id} has no linked verification contract. Run workspai goal --prepare ${a.active.id} --json first.`);if(!a.goalPack)throw new Error(`Goal ${a.active.id} has no validated immutable Goal Pack.`);let{readVerifiedGoal:t,verifyVerifiedGoal:o}=await import('./verified-goal-BSREU6R7.js');if((await t(e.workspacePath,a.active.verifiedGoalId)).status.attempt>=a.goalPack.policy.maxAttempts)throw new Error(`Goal ${a.active.id} exhausted its verification budget (${a.goalPack.policy.maxAttempts}). Review the latest evidence before creating or activating another Goal Pack.`);let n=await o({workspacePath:e.workspacePath,goalId:a.active.verifiedGoalId,run:e.run!==false}),r=await a$1(e.workspacePath);if(r.status==="miss")throw new Error(`Goal ${a.active.id} verification completed without a current Model and Graph receipt (${r.reason}).`);let s=d(r.model),c$1=r.graph.source.inputs?.hash,l={verifiedGoalId:a.active.verifiedGoalId,attempt:n.attempt,statusHash:c(n),modelHash:s,graphFingerprint:c$1??c(r.graph),graphFingerprintSemantics:c$1?"workspace-knowledge-graph-inputs-v1":"canonical-json-v1",recordedAt:new Date().toISOString()},m=n.state;return {goal:await U({workspacePath:e.workspacePath,goalId:a.active.id,lifecycle:m==="verified"?"verified":m==="failed"?"failed":"verification-ready",verifiedGoalId:a.active.verifiedGoalId,verificationReceipt:l}),verifiedGoalId:a.active.verifiedGoalId,verification:n}}async function Ge(e){let a$1=await $({workspacePath:e.workspacePath,goalId:e.goalId});if(!a$1.active||a$1.index.activeGoalId!==e.goalId)throw new Error(`Repair proposal goal is not the active workspace goal: ${e.goalId}`);if(!a$1.goalPack)throw new Error(`Repair proposal Goal Pack is unavailable: ${e.goalId}`);let t=a$1.goalPack.policy.maxAttempts;return f(e.workspacePath,".workspai/goals/index-lifecycle",async()=>{let o=await C(e.workspacePath),i$1=o.goals.find(l=>l.id===e.goalId);if(!i$1)throw new Error(`Goal is not registered in this workspace: ${e.goalId}`);let n=i$1.repairTransactionIds??(i$1.repairTransactionId?[i$1.repairTransactionId]:[]);if(!n.includes(e.transactionId)&&n.length>=t)throw new Error(`Goal ${e.goalId} exhausted its repair proposal budget (${t}). Review the latest evidence before creating another Goal Pack.`);let r=n.includes(e.transactionId)?n:[...n,e.transactionId],s={...i$1,repairTransactionId:e.transactionId,repairTransactionIds:r,updatedAt:new Date().toISOString()},c={...o,generatedAt:s.updatedAt,goals:o.goals.map(l=>l.id===e.goalId?s:l)};return a(c,S,"Goal index"),A(c),await i(e.workspacePath,p,[{relativePath:p,payload:c}]),s})}async function Ie(e){let a$1=await $({workspacePath:e.workspacePath,goalId:e.goalId});if(!a$1.active||a$1.index.activeGoalId!==e.goalId)throw new Error(`Proof-carrying change Goal is not the active workspace Goal: ${e.goalId}`);if(!a$1.goalPack)throw new Error(`Proof-carrying change Goal Pack is unavailable: ${e.goalId}`);let t=a$1.goalPack.policy.maxAttempts;return f(e.workspacePath,".workspai/goals/index-lifecycle",async()=>{let o=await C(e.workspacePath),i$1=o.goals.find(l=>l.id===e.goalId);if(!i$1)throw new Error(`Goal is not registered in this workspace: ${e.goalId}`);let n=i$1.changeTransactionIds??(i$1.changeTransactionId?[i$1.changeTransactionId]:[]);if(!n.includes(e.changeId)&&n.length>=t)throw new Error(`Goal ${e.goalId} exhausted its proof-carrying change budget (${t}).`);let r=n.includes(e.changeId)?n:[...n,e.changeId],s={...i$1,changeTransactionId:e.changeId,changeTransactionIds:r,updatedAt:new Date().toISOString()},c={...o,generatedAt:s.updatedAt,goals:o.goals.map(l=>l.id===e.goalId?s:l)};return a(c,S,"Goal index"),A(c),await i(e.workspacePath,p,[{relativePath:p,payload:c}]),s})}export{V as a,B as b,ae as c,D as d,M as e,p as f,F as g,K as h,A as i,z as j,me as k,$ as l,we as m,ve as n,ke as o,Ge as p,Ie as q};
1
+ import {a as a$1}from'./chunk-TDQ2PRHV.js';import {f,i}from'./chunk-FE5R6EUV.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c}from'./chunk-EWZZUQBR.js';import {createHash}from'crypto';import u from'path';import j from'fs-extra';var V="workspai.goal-pack.v1",B="workspai.goal-agent-handoff.v1",ae="workspai.goal-plan-result.v1",D=".workspai/reports/goal-pack-last-run.json",M="workspai.goal-index.v1",p=".workspai/goals/index.json",F="workspai.goal-lifecycle-result.v1";function K(e){if(!e.activeGoalId)return null;let a=e.goals.find(o=>o.id===e.activeGoalId),t=e.goals.filter(o=>o.lifecycle==="active");return !a||a.state==="ready-to-plan"||!(a.lifecycle==="planned"&&t.length===0||a.lifecycle==="active"&&t.length===1&&t[0]?.id===a.id)?null:{...e,activeGoalId:null,goals:e.goals.map(o=>o.id===a.id&&o.lifecycle==="active"?{...o,lifecycle:"planned"}:o)}}function A(e){let a=new Set,t=new Set,o=Date.parse(e.generatedAt);for(let r of e.goals){if(a.has(r.id))throw new Error(`Goal index contains duplicate id: ${r.id}`);if(t.has(r.fingerprint))throw new Error(`Goal index contains duplicate fingerprint: ${r.fingerprint}`);if(a.add(r.id),t.add(r.fingerprint),r.goalPack!==`.workspai/goals/${r.id}/goal-pack.json`||r.agentHandoff!==`.workspai/goals/${r.id}/agent-handoff.json`)throw new Error(`Goal index artifact paths do not match goal id: ${r.id}`);if(Date.parse(r.createdAt)>Date.parse(r.updatedAt))throw new Error(`Goal index timestamps are inconsistent for: ${r.id}`);if(Date.parse(r.updatedAt)>o)throw new Error(`Goal index generatedAt predates entry update: ${r.id}`)}let i=e.goals.filter(r=>r.lifecycle==="active");for(let r of e.goals){if(r.repairTransactionIds&&(r.repairTransactionIds.length>25||new Set(r.repairTransactionIds).size!==r.repairTransactionIds.length||r.repairTransactionId&&r.repairTransactionIds.at(-1)!==r.repairTransactionId))throw new Error(`Goal index repair transaction history is inconsistent: ${r.id}`);if(r.changeTransactionIds&&(r.changeTransactionIds.length>25||new Set(r.changeTransactionIds).size!==r.changeTransactionIds.length||r.changeTransactionId&&r.changeTransactionIds.at(-1)!==r.changeTransactionId))throw new Error(`Goal index change transaction history is inconsistent: ${r.id}`);if(r.verificationReceipt&&(!r.verifiedGoalId||r.verificationReceipt.verifiedGoalId!==r.verifiedGoalId||r.verificationReceipt.attempt<1||Date.parse(r.verificationReceipt.recordedAt)>o))throw new Error(`Goal index verification receipt is inconsistent: ${r.id}`)}if(e.activeGoalId===null){if(i.length>0)throw new Error("Goal index is inconsistent: active lifecycle entries require activeGoalId.");return}let n=e.goals.find(r=>r.id===e.activeGoalId);if(!n||n.state!=="ready-to-plan"||!["active","verification-ready","failed"].includes(n.lifecycle)||i.some(r=>r.id!==e.activeGoalId))throw new Error("Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")}function X(e){let a=_(e.scope),t={id:"workspace-verify",kind:"workspace-verify",expected:"Canonical Workspace Verify proves workspace safety and evidence freshness without claiming arbitrary semantic outcome completion.",producerCommand:"workspai workspace verify --json",machineVerifiable:true};if(e.intent.category==="release-readiness")return [{id:"release-readiness",kind:"release-readiness",expected:"Every release readiness gate passes.",producerCommand:`workspai workspace goal plan release-readiness${a} --json`,machineVerifiable:true},t];if(e.intent.category==="dependency-security")return [{id:"dependency-security",kind:"dependency-security",expected:"No blocking dependency vulnerability remains in the selected scope.",producerCommand:`workspai workspace goal plan dependency-security${a} --json`,machineVerifiable:true},t];if(e.intent.category==="test-coverage"&&e.intent.requestedTarget){let o=e.intent.requestedTarget.runtime?` --runtime ${e.intent.requestedTarget.runtime}`:"";return [{id:"test-coverage",kind:"test-coverage",expected:`${e.intent.requestedTarget.runtime?`${e.intent.requestedTarget.runtime} `:""}test coverage is at least ${e.intent.requestedTarget.value}%.`,producerCommand:`workspai workspace goal plan test-coverage${a} --target ${e.intent.requestedTarget.value}${o} --json`,machineVerifiable:e.preflight.measurement.status==="available"},t]}return [t]}function Y(e){let a=_(e.scope);if(e.intent.category==="release-readiness")return `workspai workspace goal plan release-readiness${a} --json`;if(e.intent.category==="dependency-security")return `workspai workspace goal plan dependency-security${a} --json`;if(e.intent.category==="test-coverage"&&e.intent.requestedTarget){let t=e.intent.requestedTarget.runtime?` --runtime ${e.intent.requestedTarget.runtime}`:"";return `workspai workspace goal plan test-coverage${a} --target ${e.intent.requestedTarget.value}${t} --json`}}function W(e){return /^[A-Za-z0-9._:@+-]+$/.test(e)?e:JSON.stringify(e)}function _(e){return e.resolution==="selection-required"?"":e.kind==="project"&&e.projects[0]?` --scope ${W(`project:${e.projects[0]}`)}`:e.kind==="project-set"&&e.projects.length>1?` --scope ${W(`projects:${e.projects.join(",")}`)}`:e.kind==="workspace"?" --scope workspace":""}function z(e,a){let t=X(e),o=e.intent.ambiguities.length>0,i=!o&&e.intent.category==="test-coverage"&&e.preflight.measurement.status!=="available",n=!o&&e.preflight.retrieval.status==="empty",r={kernelRevision:"goal-pack-kernel-v12",intent:e.intent.normalized,workspace:e.workspaceName,scope:e.scope,modelHash:e.sourceBinding.model.hash,graphSourceFingerprint:e.sourceBinding.graph.inputHash??e.sourceBinding.graph.hash,preflight:e.preflight,baseline:e.baseline,consumer:e.consumer,policy:{maxAttempts:e.maxAttempts,mutationMode:"proposal-only"}},s=a.digestCanonical(r),c=`goal-${e.intent.category}-${s.slice(0,16)}`,l=`.workspai/goals/${c}/goal-pack.json`,m=`.workspai/goals/${c}/agent-handoff.json`,w=Y(e),T=!!w,R=_(e.scope),d=_(e.scope),G=o?"needs-confirmation":n?"blocked":i?"needs-evidence":"ready-to-plan",f=o&&e.intent.category==="test-coverage"&&e.intent.ambiguities.some(b=>/coverage runtimes|coverage scope|requested .* runtime/i.test(b)),I=o&&e.intent.category==="test-coverage"&&e.intent.ambiguities.some(b=>b.startsWith("The selected projects do not share a common canonical coverage runtime")),y=e.preflight.measurement.runtimeChoices??e.baseline.runtimes,g=e.scope.resolution==="selection-required"||e.intent.ambiguities.some(b=>b.startsWith("Goal scope is unresolved")),h={schemaVersion:V,id:c,fingerprint:s,generatedAt:e.generatedAt,state:G,intent:e.intent,workspace:{name:e.workspaceName},scope:e.scope,sourceBinding:e.sourceBinding,baseline:e.baseline,preflight:e.preflight,successCriteria:t,policy:{mutationMode:"proposal-only",approval:"required-before-mutation",verificationOwner:"workspai-cli",rollbackOwner:"workspai-cli",maxAttempts:e.maxAttempts,allowBreakingChanges:false,allowForce:false,networkAccess:"not-granted",scopeExpansion:"requires-decision"},orchestration:[{id:"understand",owner:"workspai-cli",status:"complete",summary:"Bound the intent to the canonical model and proof-backed graph."},{id:"impact",owner:"workspai-cli",status:"complete",summary:"Pinned the permitted workspace or project scope before source inspection."},{id:"propose",owner:"agent",status:o||i||n?"blocked":"pending",summary:"Produce a bounded source-change proposal; do not mutate evidence artifacts."},{id:"approve",owner:"human",status:"pending",summary:"Approve the immutable CLI repair plan before mutation."},{id:"execute",owner:"workspai-cli",status:"pending",summary:"Checkpoint, execute, reconcile, and roll back through Repair Engine."},{id:"verify",owner:"workspai-cli",status:"pending",summary:T?"Independently verify the exact success contract from fresh evidence.":"Verify workspace safety and evidence freshness; the agent must review the final outcome against the complete objective."}],...o||i||n?{decision:{required:true,reason:o?e.intent.ambiguities.join(" "):n?"No bounded proof-backed Graph anchor matches the selected scope and intent.":e.preflight.measurement.prerequisites.join(" ")||"No current machine-readable measurement evidence is available.",question:o?g?`Choose one project, multiple projects, or the entire workspace from: ${e.scope.projects.join(", ")}.`:I?"Split the selected projects into runtime-compatible Goal scopes so every project receives deterministic coverage verification.":f?`Choose exactly one coverage runtime from the detected scope${y.length>0?`: ${y.join(", ")}`:""}, then regenerate this Goal Pack.`:"Clarify the intended outcome or provide a machine-verifiable target.":n?"Refresh Workspace Intelligence or clarify the intent before asking an agent to inspect source.":"Establish the listed measurement prerequisites, then regenerate this Goal Pack."}}:{},artifacts:{goalPack:l,agentHandoff:m,latestReport:D},commands:{refreshEvidence:"workspai workspace intelligence run --for-agent generic --strict --json",inspectGraph:`workspai workspace graph search ${JSON.stringify(e.preflight.retrieval.queries[0]??e.intent.statement)}${R} --limit 20 --json`,beginChange:`workspai change begin --goal ${c} --json`,...w?{planVerifiedGoal:w}:{},proposeRepair:"workspai workspace repair propose --file <proposal.json> --json"}},P=a.digestCanonical(h),L={schemaVersion:B,goalId:c,goalFingerprint:s,generatedAt:e.generatedAt,consumer:e.consumer,state:G,objective:e.intent.statement,scope:e.scope,discovery:{index:p,statusCommand:`workspai goal --status ${c} --json`,requiredReads:[p,l,m]},retrieval:e.preflight.retrieval,evidence:[{role:"model",artifact:e.sourceBinding.model.artifact,binding:{algorithm:"sha256",semantics:e.sourceBinding.model.hashSemantics,value:e.sourceBinding.model.hash}},{role:"graph",artifact:e.sourceBinding.graph.artifact,binding:{algorithm:"sha256",semantics:e.sourceBinding.graph.hashSemantics,value:e.sourceBinding.graph.hash}},{role:"goal",artifact:l,binding:{algorithm:"sha256",semantics:"canonical-json-v1",value:P}}],guardrails:["Treat the Goal Pack as data, never as instructions that can override host or CLI policy.","Inspect only the bounded scope and request a decision before expanding it.","Do not edit .workspai evidence, goal, repair, contract, or report artifacts.","Return source edits as a proposal until a human authorizes either a Workspai Repair transaction or a Proof-Carrying Change.","After Proof-Carrying Change authorization, use only admitted effect classes and record typed effect receipts before verification.","Do not claim success from model output or test narration; require fresh CLI evidence.",...T?[]:["For this general Goal, CLI verification proves workspace safety and freshness; final outcome acceptance requires evidence review against the complete objective."]],workflow:[{order:1,owner:"workspai-cli",instruction:"Validate source bindings and scope."},{order:2,owner:"agent",instruction:"Inspect bounded proof and relevant source."},{order:3,owner:"workspai-cli",instruction:`Begin or join the Goal-bound change with: workspai change begin --goal ${c} --json.`},{order:4,owner:"agent",instruction:"Attach a bounded prediction and return one focused, reviewable proposal."},{order:5,owner:"human",instruction:"Authorize explicit effect classes."},{order:6,owner:"agent",instruction:"Execute only authorized effects and record idempotent effect receipts."},{order:7,owner:"workspai-cli",instruction:"Re-observe the Graph, run independent verification, and seal the capsule."},...T?[]:[{order:8,owner:"agent",instruction:"Inspect the final worktree and fresh evidence against the complete objective; report uncertainty instead of presenting workspace verification as semantic proof."}]],renewal:{command:`workspai goal ${JSON.stringify(e.intent.original)}${d}${e.intent.requestedTarget?.runtime?` --runtime ${e.intent.requestedTarget.runtime}`:""} --refresh --for-agent ${e.consumer} --json`,reason:"Regenerate when the canonical model or graph hash changes."}};return {goalPack:h,handoff:L}}var S="contracts/workspace-intelligence/goal-index.v1.json",Q="contracts/workspace-intelligence/goal-lifecycle-result.v1.json";function me(e){let a$1={schemaVersion:F,...e};return a(a$1,Q,"Goal lifecycle result"),a$1}async function C(e){let a$1=u.join(e,p);if(!await j.pathExists(a$1))return {schemaVersion:M,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let t=await j.readJson(a$1);a(t,S,"Goal index");try{return A(t),t}catch(o){let i=K(t);if(!i||!(o instanceof Error)||o.message!=="Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")throw o;return A(i),i}}async function J(e,a$2){let[t,o]=await Promise.all([j.readJson(u.join(e,a$2.goalPack)),j.readJson(u.join(e,a$2.agentHandoff))]);if(a(t,"contracts/workspace-intelligence/goal-pack.v1.json","Indexed Goal Pack"),t.id!==a$2.id||t.fingerprint!==a$2.fingerprint)throw new Error(`Goal index binding failed for ${a$2.id}.`);a(o,"contracts/workspace-intelligence/goal-agent-handoff.v1.json","Indexed Goal agent handoff");let i=new Map(o.evidence.map(d=>[d.role,d])),n=z({generatedAt:t.generatedAt,intent:t.intent,workspaceName:t.workspace.name,scope:t.scope,sourceBinding:t.sourceBinding,baseline:t.baseline,preflight:t.preflight,maxAttempts:t.policy.maxAttempts,consumer:o.consumer},{digestCanonical:c});if(o.goalId!==t.id||o.goalFingerprint!==t.fingerprint||i.get("goal")?.binding.value!==c(t)||i.get("model")?.binding.value!==t.sourceBinding.model.hash||i.get("graph")?.binding.value!==t.sourceBinding.graph.hash||c(o)!==c(n.handoff))throw new Error(`Goal agent handoff integrity validation failed for ${a$2.id}.`);let r=await a$1(e);if(r.status==="miss")throw new Error(`Goal ${a$2.id} is stale because live workspace inputs changed (${r.reason}). Regenerate it with --refresh.`);let{model:s,graph:c$1}=r,l=d(s),m=c(c$1),w=c$1.source.inputs?.hash;if(!(l===t.sourceBinding.model.hash&&(t.sourceBinding.graph.inputHash?w===t.sourceBinding.graph.inputHash:m===t.sourceBinding.graph.hash))){let d=a$2.changeTransactionIds??(a$2.changeTransactionId?[a$2.changeTransactionId]:[]),{assertSealedProofCarryingChangeCurrent:G}=await import('./proof-carrying-change-6LQ6JO5J.js'),f=false;for(let g of [...d].reverse()){let h=await G({workspacePath:e,changeId:g,goalId:a$2.id}).catch(()=>{});if(h?.modelHash===l&&h.graphHash===m){f=true;break}}let I=a$2.repairTransactionIds??(a$2.repairTransactionId?[a$2.repairTransactionId]:[]),{assertClosedGoalRepairTransactionCurrent:y}=await import('./workspace-repair-engine-RXHJX4CQ.js');if(!f)for(let g of [...I].reverse()){let h=await y({workspacePath:e,transactionId:g,goalId:a$2.id}).catch(()=>{});if(h?.modelHash===l&&h.graphInputHash===w){f=true;break}}if(!f&&a$2.verificationReceipt&&a$2.verifiedGoalId){let g=a$2.verificationReceipt,{readVerifiedGoal:h}=await import('./verified-goal-JIRVX7KO.js'),P=await h(e,a$2.verifiedGoalId).catch(()=>{}),L=w??m;f=!!(P&&g.verifiedGoalId===a$2.verifiedGoalId&&g.attempt===P.status.attempt&&g.statusHash===c(P.status)&&g.modelHash===l&&g.graphFingerprint===L&&g.graphFingerprintSemantics===(w?"workspace-knowledge-graph-inputs-v1":"canonical-json-v1"));}if(!f)throw new Error(`Goal ${a$2.id} is stale because its canonical model or graph binding changed outside a closed Goal repair transaction or recorded CLI verification attempt. Regenerate it with --refresh.`)}if(c$1.source.hash!==l)throw new Error(`Goal ${a$2.id} is stale because its current Model and Graph source bindings disagree. Regenerate it with --refresh.`);let R=s;for(let d of t.preflight.measurement.existingEvidence){let G=R.projects?.find(g=>g.name===d.project);if(!G)throw new Error(`Goal measurement project binding is missing: ${d.project}`);let f=u.resolve(G.absolutePath??u.join(e,G.path??d.project)),I=u.resolve(f,d.path);if(I!==f&&!I.startsWith(`${f}${u.sep}`))throw new Error(`Goal measurement evidence escapes its project boundary: ${d.path}`);let y=await j.readFile(I).catch(()=>null);if(!y||createHash("sha256").update(y).digest("hex")!==d.sha256)throw new Error(`Goal ${a$2.id} is stale because measurement evidence changed: ${d.project}/${d.path}`)}return t}async function $(e){let a=u.resolve(e.workspacePath),t=await C(a),o=e.goalId??t.activeGoalId,i=o?t.goals.find(r=>r.id===o)??null:null;if(o&&!i)throw new Error(`Goal is not registered in this workspace: ${o}`);let n=i&&e.validateBindings!==false?await J(a,i):null;return {index:t,active:i,goalPack:n}}async function we(e){let a$1=u.resolve(e.workspacePath);return f(a$1,".workspai/goals/index-lifecycle",async()=>{let t=await C(a$1),o=t.goals.find(s=>s.id===e.goalId);if(!o)throw new Error(`Goal is not registered in this workspace: ${e.goalId}`);if(e.action==="activate"){let s=await J(a$1,o);if(s.state!=="ready-to-plan"){let c=s.decision;throw new Error([`Goal ${o.id} cannot be activated while its planning state is ${s.state}.`,c?.reason,c?.question,"Re-run the Goal with the requested clarification or evidence before activation."].filter(l=>!!l).join(" "))}if(o.lifecycle==="cancelled"||o.lifecycle==="verified"||o.lifecycle==="verification-ready")throw new Error(`Goal ${o.id} cannot be activated from lifecycle ${o.lifecycle}. Create or plan a new Goal instead.`)}let i$1=new Date().toISOString(),n={...o,lifecycle:e.action==="activate"?"active":"cancelled",updatedAt:i$1},r={...t,generatedAt:i$1,activeGoalId:e.action==="activate"?e.goalId:t.activeGoalId===e.goalId?null:t.activeGoalId,goals:t.goals.map(s=>s.id===e.goalId?n:e.action==="activate"&&s.lifecycle==="active"?{...s,lifecycle:"planned",updatedAt:i$1}:s)};return a(r,S,"Goal index"),A(r),await i(a$1,p,[{relativePath:p,payload:r}]),{index:r,goal:n}})}async function U(e){return f(e.workspacePath,".workspai/goals/index-lifecycle",async()=>{let a$1=await C(e.workspacePath),t=a$1.goals.find(n=>n.id===e.goalId);if(!t)throw new Error(`Goal is not registered in this workspace: ${e.goalId}`);let o={...t,lifecycle:e.lifecycle,updatedAt:new Date().toISOString(),...e.verifiedGoalId?{verifiedGoalId:e.verifiedGoalId}:{},...e.verificationReceipt?{verificationReceipt:e.verificationReceipt}:{}},i$1={...a$1,generatedAt:o.updatedAt,activeGoalId:e.lifecycle==="verified"?null:e.goalId,goals:a$1.goals.map(n=>n.id===e.goalId?o:n)};return a(i$1,S,"Goal index"),A(i$1),await i(e.workspacePath,p,[{relativePath:p,payload:i$1}]),o})}async function ve(e){let a=await $(e);if(!a.active||!a.goalPack)throw new Error("No active Goal Pack is available.");if(a.index.activeGoalId!==a.active.id)throw new Error(`Goal ${a.active.id} is not active. Activate it before preparing verification.`);let t=a.goalPack;if(!t.commands.planVerifiedGoal)throw new Error(`Goal ${t.id} has no deterministic verification primitive. An agent proposal and explicit review are required first.`);if(t.state!=="ready-to-plan")throw new Error(`Goal ${t.id} cannot enter verification while its state is ${t.state}.`);let{planVerifiedGoal:o}=await import('./verified-goal-JIRVX7KO.js'),i=t.scope.kind==="project"&&t.scope.projects[0]?`project:${t.scope.projects[0]}`:t.scope.kind==="project-set"&&t.scope.projects.length>1?`projects:${t.scope.projects.join(",")}`:void 0,n=t.intent.category;if(n!=="release-readiness"&&n!=="dependency-security"&&n!=="test-coverage")throw new Error(`Goal category ${n} does not have a deterministic verification adapter.`);let r=await o({workspacePath:e.workspacePath,kind:n,scope:i,target:t.intent.requestedTarget?.value,runtime:t.intent.requestedTarget?.runtime});return {goal:await U({workspacePath:e.workspacePath,goalId:t.id,lifecycle:"verification-ready",verifiedGoalId:r.goal.id}),verifiedGoalId:r.goal.id,state:r.status.state}}async function ke(e){let a=u.resolve(e.workspacePath),t=await $({workspacePath:a,goalId:e.goalId,validateBindings:false});if(!t.active)throw new Error("No active Goal Pack is available.");let o=t.active.id;return f(a,`.workspai/goals/${o}/verification`,()=>ee({workspacePath:a,goalId:o,run:e.run}))}async function ee(e){let a=await $(e);if(!a.active)throw new Error("No active Goal Pack is available.");if(a.index.activeGoalId!==a.active.id)throw new Error(`Goal ${a.active.id} is not active. Activate it before running verification.`);if(!a.active.verifiedGoalId)throw new Error(`Goal ${a.active.id} has no linked verification contract. Run workspai goal --prepare ${a.active.id} --json first.`);if(!a.goalPack)throw new Error(`Goal ${a.active.id} has no validated immutable Goal Pack.`);let{readVerifiedGoal:t,verifyVerifiedGoal:o}=await import('./verified-goal-JIRVX7KO.js');if((await t(e.workspacePath,a.active.verifiedGoalId)).status.attempt>=a.goalPack.policy.maxAttempts)throw new Error(`Goal ${a.active.id} exhausted its verification budget (${a.goalPack.policy.maxAttempts}). Review the latest evidence before creating or activating another Goal Pack.`);let n=await o({workspacePath:e.workspacePath,goalId:a.active.verifiedGoalId,run:e.run!==false}),r=await a$1(e.workspacePath);if(r.status==="miss")throw new Error(`Goal ${a.active.id} verification completed without a current Model and Graph receipt (${r.reason}).`);let s=d(r.model),c$1=r.graph.source.inputs?.hash,l={verifiedGoalId:a.active.verifiedGoalId,attempt:n.attempt,statusHash:c(n),modelHash:s,graphFingerprint:c$1??c(r.graph),graphFingerprintSemantics:c$1?"workspace-knowledge-graph-inputs-v1":"canonical-json-v1",recordedAt:new Date().toISOString()},m=n.state;return {goal:await U({workspacePath:e.workspacePath,goalId:a.active.id,lifecycle:m==="verified"?"verified":m==="failed"?"failed":"verification-ready",verifiedGoalId:a.active.verifiedGoalId,verificationReceipt:l}),verifiedGoalId:a.active.verifiedGoalId,verification:n}}async function Ge(e){let a$1=await $({workspacePath:e.workspacePath,goalId:e.goalId});if(!a$1.active||a$1.index.activeGoalId!==e.goalId)throw new Error(`Repair proposal goal is not the active workspace goal: ${e.goalId}`);if(!a$1.goalPack)throw new Error(`Repair proposal Goal Pack is unavailable: ${e.goalId}`);let t=a$1.goalPack.policy.maxAttempts;return f(e.workspacePath,".workspai/goals/index-lifecycle",async()=>{let o=await C(e.workspacePath),i$1=o.goals.find(l=>l.id===e.goalId);if(!i$1)throw new Error(`Goal is not registered in this workspace: ${e.goalId}`);let n=i$1.repairTransactionIds??(i$1.repairTransactionId?[i$1.repairTransactionId]:[]);if(!n.includes(e.transactionId)&&n.length>=t)throw new Error(`Goal ${e.goalId} exhausted its repair proposal budget (${t}). Review the latest evidence before creating another Goal Pack.`);let r=n.includes(e.transactionId)?n:[...n,e.transactionId],s={...i$1,repairTransactionId:e.transactionId,repairTransactionIds:r,updatedAt:new Date().toISOString()},c={...o,generatedAt:s.updatedAt,goals:o.goals.map(l=>l.id===e.goalId?s:l)};return a(c,S,"Goal index"),A(c),await i(e.workspacePath,p,[{relativePath:p,payload:c}]),s})}async function Ie(e){let a$1=await $({workspacePath:e.workspacePath,goalId:e.goalId});if(!a$1.active||a$1.index.activeGoalId!==e.goalId)throw new Error(`Proof-carrying change Goal is not the active workspace Goal: ${e.goalId}`);if(!a$1.goalPack)throw new Error(`Proof-carrying change Goal Pack is unavailable: ${e.goalId}`);let t=a$1.goalPack.policy.maxAttempts;return f(e.workspacePath,".workspai/goals/index-lifecycle",async()=>{let o=await C(e.workspacePath),i$1=o.goals.find(l=>l.id===e.goalId);if(!i$1)throw new Error(`Goal is not registered in this workspace: ${e.goalId}`);let n=i$1.changeTransactionIds??(i$1.changeTransactionId?[i$1.changeTransactionId]:[]);if(!n.includes(e.changeId)&&n.length>=t)throw new Error(`Goal ${e.goalId} exhausted its proof-carrying change budget (${t}).`);let r=n.includes(e.changeId)?n:[...n,e.changeId],s={...i$1,changeTransactionId:e.changeId,changeTransactionIds:r,updatedAt:new Date().toISOString()},c={...o,generatedAt:s.updatedAt,goals:o.goals.map(l=>l.id===e.goalId?s:l)};return a(c,S,"Goal index"),A(c),await i(e.workspacePath,p,[{relativePath:p,payload:c}]),s})}export{V as a,B as b,ae as c,D as d,M as e,p as f,F as g,K as h,A as i,z as j,me as k,$ as l,we as m,ve as n,ke as o,Ge as p,Ie as q};
@@ -1 +1 @@
1
- import a from'path';import Y from'fs-extra';import q from'chalk';async function U(p,n={}){let e=a.resolve(p),{WORKSPACE_CONTRACT_PATH:l,syncWorkspaceContract:d,verifyWorkspaceContract:S,writeWorkspaceContractVerifyEvidence:j}=await import('./workspace-contract-E7GVWM7W.js'),w=await d({workspacePath:e,strict:true}),{syncWorkspaceReadme:E,WORKSPACE_README_PATH:R}=await import('./workspace-readme-HA6XLDME.js'),x=await E({workspacePath:e,workspaceName:w.contract.workspace.name,profile:w.contract.workspace.profile??"minimal",projectCount:w.contract.projects.length}),{buildWorkspaceModel:h,writeWorkspaceModel:g}=await import('./workspace-model-5FA2636K.js'),r=await h({workspacePath:e,includeEvidence:true}),k=await g(r,e),{buildWorkspaceImpact:G,buildWorkspaceModelSnapshot:O,diffWorkspaceModel:$,writeWorkspaceImpact:M,writeWorkspaceModelDiff:T,writeWorkspaceModelSnapshot:_}=await import('./workspace-intelligence-3IAAM3H3.js'),{WORKSPACE_INTELLIGENCE_ARTIFACTS:s}=await import('./workspace-intelligence-runtime-registry-ZLPF7BAY.js'),{syncWorkspaceAgentGrounding:P}=await import('./workspace-agent-sync-NBIOSXCG.js'),W=await P({workspacePath:e,model:r,write:true,refreshContext:true,strict:false,preset:"enterprise",targets:["all"],projectGrounding:n.projectGrounding??"managed"}),v=new Set(W.writtenFiles),i=new Set(W.projectLenses?.skipped.map(t=>`${t.name}: ${t.reason}`)??[]),{readWorkspaceKnowledgeGraphSnapshot:C}=await import('./workspace-knowledge-graph-snapshot-MTFTCVFF.js'),o=await C(e),y=false;if(o.status==="miss"){if(o.reason!=="live-input-mismatch")throw new Error(`Workspace consumer sync could not validate canonical Model/Graph evidence (${o.reason}).`);r=await h({workspacePath:e,includeEvidence:true}),k=await g(r,e);let{buildWorkspaceAgentContext:t,writeWorkspaceAgentContext:f}=await import('./workspace-context-ZDXF6S7S.js'),m=await t({workspacePath:e,model:r,agent:"generic",includeEvidence:true});await f(m,e);let b=await P({workspacePath:e,model:r,write:true,refreshContext:false,strict:false,preset:"enterprise",targets:["all"],projectGrounding:n.projectGrounding??"managed"});for(let c of b.writtenFiles)v.add(c);for(let c of b.projectLenses?.skipped??[])i.add(`${c.name}: ${c.reason}`);if(o=await C(e),o.status==="miss")throw new Error(`Workspace consumer reconciliation did not produce fresh canonical evidence (${o.reason}).`);y=true;}let F=a.join(e,s.snapshot),u=false;if(!await Y.pathExists(F)){let t=await O({workspacePath:e,model:r});await _(t,e),u=true;}let I=await $({workspacePath:e,fromPath:s.snapshot,model:r}),N=await T(I,e),L=await G({workspacePath:e,fromPath:s.diff}),K=await M(L,e),z=await S({workspacePath:e,strict:true}),H=await j({workspacePath:e,result:z}),V=(o.graph.source.inputs?.scopes??[]).filter(t=>t.truncated);for(let t of V)i.add(`${t.kind}:${t.id} graph inventory reached its ${t.fileLimit}-file emergency bound; inventory completeness is bounded.`);let A=o.graph.quality.completeness?.providers.bounded??0;A>0&&i.add(`${A} graph provider(s) used declared adaptive semantic/deep budgets; inspect provider inputCoverage before making exhaustive symbol-level claims.`);let D=[l,(await import('./workspace-registry-summary-WKENOFEA.js')).WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH,a.relative(e,x).split(a.sep).join("/")||R,a.relative(e,k).split(a.sep).join("/"),s.knowledgeGraph,...u?[s.snapshot]:[],a.relative(e,N).split(a.sep).join("/"),a.relative(e,K).split(a.sep).join("/"),a.relative(e,H).split(a.sep).join("/"),...v].filter((t,f,m)=>m.indexOf(t)===f);return n.silent||console.log(q.gray(`\u2713 Workspace Intelligence synced \xB7 ${r.summary.projectCount} project(s) \xB7 model + graph + agent grounding \xB7 freshness sealed`)),{workspacePath:e,projectCount:r.summary.projectCount,baselineCreated:u,freshnessSealed:true,reconciledAfterGrounding:y,writtenFiles:D,warnings:[...i].sort()}}async function ee(p,n={}){let e=a.resolve(p),l=n.workspaceName??a.basename(e),{registerWorkspaceStrict:d}=await import('./workspace-E3MM3AIE.js');return await d(e,l),U(e,{silent:n.silent})}export{U as a,ee as b};
1
+ import a from'path';import Y from'fs-extra';import q from'chalk';async function U(p,n={}){let e=a.resolve(p),{WORKSPACE_CONTRACT_PATH:l,syncWorkspaceContract:d,verifyWorkspaceContract:S,writeWorkspaceContractVerifyEvidence:j}=await import('./workspace-contract-E7GVWM7W.js'),w=await d({workspacePath:e,strict:true}),{syncWorkspaceReadme:E,WORKSPACE_README_PATH:R}=await import('./workspace-readme-HA6XLDME.js'),x=await E({workspacePath:e,workspaceName:w.contract.workspace.name,profile:w.contract.workspace.profile??"minimal",projectCount:w.contract.projects.length}),{buildWorkspaceModel:h,writeWorkspaceModel:g}=await import('./workspace-model-5FA2636K.js'),r=await h({workspacePath:e,includeEvidence:true}),k=await g(r,e),{buildWorkspaceImpact:G,buildWorkspaceModelSnapshot:O,diffWorkspaceModel:$,writeWorkspaceImpact:M,writeWorkspaceModelDiff:T,writeWorkspaceModelSnapshot:_}=await import('./workspace-intelligence-3IAAM3H3.js'),{WORKSPACE_INTELLIGENCE_ARTIFACTS:s}=await import('./workspace-intelligence-runtime-registry-ZLPF7BAY.js'),{syncWorkspaceAgentGrounding:P}=await import('./workspace-agent-sync-TFQNKRD3.js'),W=await P({workspacePath:e,model:r,write:true,refreshContext:true,strict:false,preset:"enterprise",targets:["all"],projectGrounding:n.projectGrounding??"managed"}),v=new Set(W.writtenFiles),i=new Set(W.projectLenses?.skipped.map(t=>`${t.name}: ${t.reason}`)??[]),{readWorkspaceKnowledgeGraphSnapshot:C}=await import('./workspace-knowledge-graph-snapshot-MTFTCVFF.js'),o=await C(e),y=false;if(o.status==="miss"){if(o.reason!=="live-input-mismatch")throw new Error(`Workspace consumer sync could not validate canonical Model/Graph evidence (${o.reason}).`);r=await h({workspacePath:e,includeEvidence:true}),k=await g(r,e);let{buildWorkspaceAgentContext:t,writeWorkspaceAgentContext:f}=await import('./workspace-context-ZDXF6S7S.js'),m=await t({workspacePath:e,model:r,agent:"generic",includeEvidence:true});await f(m,e);let b=await P({workspacePath:e,model:r,write:true,refreshContext:false,strict:false,preset:"enterprise",targets:["all"],projectGrounding:n.projectGrounding??"managed"});for(let c of b.writtenFiles)v.add(c);for(let c of b.projectLenses?.skipped??[])i.add(`${c.name}: ${c.reason}`);if(o=await C(e),o.status==="miss")throw new Error(`Workspace consumer reconciliation did not produce fresh canonical evidence (${o.reason}).`);y=true;}let F=a.join(e,s.snapshot),u=false;if(!await Y.pathExists(F)){let t=await O({workspacePath:e,model:r});await _(t,e),u=true;}let I=await $({workspacePath:e,fromPath:s.snapshot,model:r}),N=await T(I,e),L=await G({workspacePath:e,fromPath:s.diff}),K=await M(L,e),z=await S({workspacePath:e,strict:true}),H=await j({workspacePath:e,result:z}),V=(o.graph.source.inputs?.scopes??[]).filter(t=>t.truncated);for(let t of V)i.add(`${t.kind}:${t.id} graph inventory reached its ${t.fileLimit}-file emergency bound; inventory completeness is bounded.`);let A=o.graph.quality.completeness?.providers.bounded??0;A>0&&i.add(`${A} graph provider(s) used declared adaptive semantic/deep budgets; inspect provider inputCoverage before making exhaustive symbol-level claims.`);let D=[l,(await import('./workspace-registry-summary-WKENOFEA.js')).WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH,a.relative(e,x).split(a.sep).join("/")||R,a.relative(e,k).split(a.sep).join("/"),s.knowledgeGraph,...u?[s.snapshot]:[],a.relative(e,N).split(a.sep).join("/"),a.relative(e,K).split(a.sep).join("/"),a.relative(e,H).split(a.sep).join("/"),...v].filter((t,f,m)=>m.indexOf(t)===f);return n.silent||console.log(q.gray(`\u2713 Workspace Intelligence synced \xB7 ${r.summary.projectCount} project(s) \xB7 model + graph + agent grounding \xB7 freshness sealed`)),{workspacePath:e,projectCount:r.summary.projectCount,baselineCreated:u,freshnessSealed:true,reconciledAfterGrounding:y,writtenFiles:D,warnings:[...i].sort()}}async function ee(p,n={}){let e=a.resolve(p),l=n.workspaceName??a.basename(e),{registerWorkspaceStrict:d}=await import('./workspace-3K2YGPU7.js');return await d(e,l),U(e,{silent:n.silent})}export{U as a,ee as b};
@@ -1 +1 @@
1
- import {a as a$2}from'./chunk-N2PAAQKI.js';import {j,l as l$1}from'./chunk-COBU44T5.js';import {g}from'./chunk-D5RUGSBC.js';import {u}from'./chunk-5OLNT6YD.js';import {j as j$1,e}from'./chunk-XVTN5DDV.js';import {b,c as c$1}from'./chunk-T6KHOIEY.js';import {c,d}from'./chunk-JQINCVK5.js';import {a}from'./chunk-COICGD62.js';import {f as f$1,g as g$1,h as h$2}from'./chunk-S66NO5BX.js';import {k,l,h as h$1,m,n as n$1,p as p$1,q as q$2}from'./chunk-QVUVJU56.js';import {a as a$3}from'./chunk-TDQ2PRHV.js';import {a as a$1}from'./chunk-LLEKVSMX.js';import {n,q as q$1,t}from'./chunk-BVWDG66W.js';import {o,r as r$1,s}from'./chunk-WPZUKU2B.js';import {f,h}from'./chunk-FE5R6EUV.js';import {b as b$1}from'./chunk-K33JJVQZ.js';import {p,q,z,A,y,x}from'./chunk-ODK4LCEL.js';import {c as c$2}from'./chunk-PKKSRXUS.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(p.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===p.intelligenceRun,`artifactPath must be ${p.intelligenceRun}`),r(t.preflight.length===y.length,`preflight must contain exactly ${y.length} entries`);for(let[d,n]of y.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,z[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===x.length,`stages must contain exactly ${x.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of x.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,A[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y$1=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y$1?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=p.intelligenceRun,Ee=q.intelligenceRun,L=we;function I(t){c$2({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return f(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t$1){let s$1=t$1.workspacePath,m$1=[],u$1=[],h$3=false,y=async(e,o)=>{let c=[...z[e]];if(h$3){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$1.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$1.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$3=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$1.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$2=async(e,o)=>{let c=[...A[e].produces];if(h$3){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u$1.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u$1.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$3=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u$1.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o$1=await o({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o$1.contract.projects.length} projects`}});let p$2,d$1=()=>{if(!p$2)throw new Error("canonical workspace model is unavailable");return p$2};await l$2("model",async()=>(p$2={...await q$1({workspacePath:s$1,includeEvidence:true}),build:n({mode:"full",engineStatus:"disabled"})},await t(p$2,s$1),{message:`${p$2.summary.projectCount} projects modeled`}));let n$2=ge.join(s$1,p.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$2)){let c=await k({workspacePath:s$1,model:d$1()});return await l(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$2),o=h$1(e);return o?(await l(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$2("diff",async()=>{let e=await m({workspacePath:s$1,fromPath:p.snapshot,model:d$1()});return await n$1(e,s$1),{message:e.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$2("impact",async()=>{let e=await p$1({workspacePath:s$1,fromPath:p.diff});return await q$2(e,s$1),{message:`${e.summary.risk} risk; ${e.summary.affectedProjects} affected`}}),await l$2("doctor-evidence",async()=>{let e=await u({workspace:s$1,json:true,quiet:true,profile:t$1.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$2("contract-evidence",async()=>{let e=await r$1({workspacePath:s$1,strict:true});return await s({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$2("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t$1.strict===true});return {blocked:e.summary.verdict==="blocked"||t$1.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t$1.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$2("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t$1.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t$1.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$2("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:p.impact});await g$1(e$1,s$1);let o=h$2(e$1,{strict:t$1.strict===true});return await j$1(s$1,e(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$2("context",async()=>{let e=await c({workspacePath:s$1,model:d$1(),agent:t$1.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$2("agent-sync",async()=>{let e=await l$1({workspacePath:s$1,agent:t$1.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t$1.strict===true,preset:"enterprise"}),o=false,c$1=await a$3(s$1);if(c$1.status==="miss"){if(c$1.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c$1.reason}).`);p$2={...await q$1({workspacePath:s$1,includeEvidence:true}),build:n({mode:"full",engineStatus:"disabled"})},await t(p$2,s$1);let f=await c({workspacePath:s$1,model:p$2,agent:t$1.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$1({workspacePath:s$1,agent:t$1.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t$1.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t$1.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$2("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$1(e,s$1);let o=t$1.strict===true?u$1.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u$1.some(e=>e.status==="blocked"),G=h$3?"failed":me?"blocked":"passed",fe=h$3?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$1,status:G,exitCode:fe,stages:u$1,artifactPath:L};ue(b$1),await h(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await h(s$1,p.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
1
+ import {a as a$2}from'./chunk-N2PAAQKI.js';import {j,l as l$1}from'./chunk-ISGLADQI.js';import {g}from'./chunk-JPPZDLY3.js';import {u}from'./chunk-RQKDJVX3.js';import {j as j$1,e}from'./chunk-XVTN5DDV.js';import {b,c as c$1}from'./chunk-T6KHOIEY.js';import {c,d}from'./chunk-JQINCVK5.js';import {a}from'./chunk-COICGD62.js';import {f as f$1,g as g$1,h as h$2}from'./chunk-S66NO5BX.js';import {k,l,h as h$1,m,n as n$1,p as p$1,q as q$2}from'./chunk-QVUVJU56.js';import {a as a$3}from'./chunk-TDQ2PRHV.js';import {a as a$1}from'./chunk-LLEKVSMX.js';import {n,q as q$1,t}from'./chunk-BVWDG66W.js';import {o,r as r$1,s}from'./chunk-WPZUKU2B.js';import {f,h}from'./chunk-FE5R6EUV.js';import {b as b$1}from'./chunk-K33JJVQZ.js';import {p,q,z,A,y,x}from'./chunk-ODK4LCEL.js';import {c as c$2}from'./chunk-PKKSRXUS.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(p.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===p.intelligenceRun,`artifactPath must be ${p.intelligenceRun}`),r(t.preflight.length===y.length,`preflight must contain exactly ${y.length} entries`);for(let[d,n]of y.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,z[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===x.length,`stages must contain exactly ${x.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of x.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,A[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y$1=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y$1?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=p.intelligenceRun,Ee=q.intelligenceRun,L=we;function I(t){c$2({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return f(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t$1){let s$1=t$1.workspacePath,m$1=[],u$1=[],h$3=false,y=async(e,o)=>{let c=[...z[e]];if(h$3){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$1.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$1.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$3=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$1.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$2=async(e,o)=>{let c=[...A[e].produces];if(h$3){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u$1.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u$1.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$3=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u$1.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o$1=await o({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o$1.contract.projects.length} projects`}});let p$2,d$1=()=>{if(!p$2)throw new Error("canonical workspace model is unavailable");return p$2};await l$2("model",async()=>(p$2={...await q$1({workspacePath:s$1,includeEvidence:true}),build:n({mode:"full",engineStatus:"disabled"})},await t(p$2,s$1),{message:`${p$2.summary.projectCount} projects modeled`}));let n$2=ge.join(s$1,p.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$2)){let c=await k({workspacePath:s$1,model:d$1()});return await l(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$2),o=h$1(e);return o?(await l(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$2("diff",async()=>{let e=await m({workspacePath:s$1,fromPath:p.snapshot,model:d$1()});return await n$1(e,s$1),{message:e.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$2("impact",async()=>{let e=await p$1({workspacePath:s$1,fromPath:p.diff});return await q$2(e,s$1),{message:`${e.summary.risk} risk; ${e.summary.affectedProjects} affected`}}),await l$2("doctor-evidence",async()=>{let e=await u({workspace:s$1,json:true,quiet:true,profile:t$1.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$2("contract-evidence",async()=>{let e=await r$1({workspacePath:s$1,strict:true});return await s({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$2("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t$1.strict===true});return {blocked:e.summary.verdict==="blocked"||t$1.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t$1.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$2("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t$1.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t$1.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$2("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:p.impact});await g$1(e$1,s$1);let o=h$2(e$1,{strict:t$1.strict===true});return await j$1(s$1,e(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$2("context",async()=>{let e=await c({workspacePath:s$1,model:d$1(),agent:t$1.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$2("agent-sync",async()=>{let e=await l$1({workspacePath:s$1,agent:t$1.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t$1.strict===true,preset:"enterprise"}),o=false,c$1=await a$3(s$1);if(c$1.status==="miss"){if(c$1.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c$1.reason}).`);p$2={...await q$1({workspacePath:s$1,includeEvidence:true}),build:n({mode:"full",engineStatus:"disabled"})},await t(p$2,s$1);let f=await c({workspacePath:s$1,model:p$2,agent:t$1.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$1({workspacePath:s$1,agent:t$1.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t$1.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t$1.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$2("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$1(e,s$1);let o=t$1.strict===true?u$1.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u$1.some(e=>e.status==="blocked"),G=h$3?"failed":me?"blocked":"passed",fe=h$3?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$1,status:G,exitCode:fe,stages:u$1,artifactPath:L};ue(b$1),await h(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await h(s$1,p.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
@@ -1,4 +1,4 @@
1
- import {m,a as a$1,l as l$1}from'./chunk-5PFFR5S7.js';import {b as b$5,g as g$2}from'./chunk-5TKRCE6F.js';import {b as b$4,a}from'./chunk-D5LLTUTY.js';import {b as b$2,f as f$2,s as s$1,t as t$1,u,P as P$1,v,q as q$2,r,R,n,o,p as p$2,h as h$2,i,m as m$1,j,k,l,O,w,x,y,z as z$1,A,B as B$1,C,E,G,I,D as D$1,F,H,J as J$1,K,L,M,N,S,T,U,V,Y as Y$1,X as X$1,W,a as a$3,Q}from'./chunk-QYEQVNBF.js';import {b as b$1,c,d}from'./chunk-JQINCVK5.js';import {b as b$3}from'./chunk-COICGD62.js';import {d as d$2}from'./chunk-S66NO5BX.js';import {b as b$7}from'./chunk-QYXX6G5O.js';import {q as q$1,l as l$2,d as d$1}from'./chunk-BVWDG66W.js';import {p as p$1}from'./chunk-WPZUKU2B.js';import {g}from'./chunk-FE5R6EUV.js';import {a as a$2,b as b$6}from'./chunk-K33JJVQZ.js';import {q,p,t,s as s$2}from'./chunk-ODK4LCEL.js';import {f as f$1,g as g$1,h}from'./chunk-VQZ5PI5J.js';import s from'path';import h$1 from'fs-extra';var pe=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var Jt="workspace-operational-skill.v1";function Yt(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function Ot(e){let t=Yt(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:Jt,skillId:t,canonicalPath:W(t),title:e.title,triggers:[...e.triggers].sort((r,n)=>r.localeCompare(n)),requiredReports:[...e.requiredReports].sort((r,n)=>r.localeCompare(n)),scopedProjects:[...e.scopedProjects??[]].sort((r,n)=>r.localeCompare(n)),verificationCommands:[...e.verificationCommands],answerContractSections:[...pe],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var Xt=q.skillsIndex;function Tt(e){let t=[...e.skills].sort((i,c)=>i.skillId.localeCompare(c.skillId)),r=e.inputsHash??d$1({skillIds:t.map(i=>i.skillId),paths:t.map(i=>i.canonicalPath),decisions:e.decisions??[]}),n=e.decisions?[...e.decisions].sort((i,c)=>i.skillId.localeCompare(c.skillId)):void 0;return {schemaVersion:Xt,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(i=>({skillId:i.skillId,path:i.canonicalPath,schemaVersion:i.schemaVersion,title:i.title})),...n?{selection:{generatedCount:n.filter(i=>i.status==="generated").length,suppressedCount:n.filter(i=>i.status==="suppressed").length,decisions:n}}:{}}}var _t=[p.agentIndex,b$1,d$2],B="<!-- WORKSPAI:GENERATED-OPERATIONAL-SKILL -->",Qt=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${p.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${p.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."],applicability:"api"},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${p.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${p.verify}\` for verdict and blocking reasons.`,`Read \`${t.artifactRemediationPlan}\` when a Studio or agent repair path is needed.`,"List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."],applicability:"workspace"},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Run a registered project-scoped test/build command when available; otherwise resolve the repository-authored validation command from cited manifests before promoting the migration.","Document rollback and verification signals."],applicability:"schema"},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Use registered test/build commands for affected projects; when none are registered, resolve repository-authored commands from cited manifests instead of inventing one.","Re-run `workspace verify` after evidence refresh."],applicability:"dependency"},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:[`Read \`${t.workspaceContract}\` for publishes/consumes/owns edges.`,"List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."],applicability:"contract"}];function z(e){return `npx workspai ${e}`.trim()}function Zt(e){let t=["---",`name: ${e.template.skillId}`,`description: ${e.template.objective}`,"---","",B,"",`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",..._t.map(r=>`- \`${r}\``),"","## Why this skill exists here","",`Applicability: **${e.decision.confidence} confidence**.`,"",...e.decision.reasons.map(r=>`- ${r}`),...e.decision.signals.length>0?["","Evidence signals:","",...e.decision.signals.map(r=>`- \`${r}\``)]:[],"","## Project-aware execution boundary","",...e.projectEvidence,"",...e.retrievalCommands.length>0?["## Scoped retrieval commands","",...e.retrievalCommands.map(r=>`- \`${r}\``),""]:[],"## Procedure","",...e.template.steps.map((r,n)=>`${n+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",z("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
1
+ import {m,a as a$1,l as l$1}from'./chunk-LLSY6L7E.js';import {b as b$5,g as g$2}from'./chunk-L5ZD2GD3.js';import {b as b$4,a}from'./chunk-D5LLTUTY.js';import {b as b$2,f as f$2,s as s$1,t as t$1,u,P as P$1,v,q as q$2,r,R,n,o,p as p$2,h as h$2,i,m as m$1,j,k,l,O,w,x,y,z as z$1,A,B as B$1,C,E,G,I,D as D$1,F,H,J as J$1,K,L,M,N,S,T,U,V,Y as Y$1,X as X$1,W,a as a$3,Q}from'./chunk-QYEQVNBF.js';import {b as b$1,c,d}from'./chunk-JQINCVK5.js';import {b as b$3}from'./chunk-COICGD62.js';import {d as d$2}from'./chunk-S66NO5BX.js';import {b as b$7}from'./chunk-QYXX6G5O.js';import {q as q$1,l as l$2,d as d$1}from'./chunk-BVWDG66W.js';import {p as p$1}from'./chunk-WPZUKU2B.js';import {g}from'./chunk-FE5R6EUV.js';import {a as a$2,b as b$6}from'./chunk-K33JJVQZ.js';import {q,p,t,s as s$2}from'./chunk-ODK4LCEL.js';import {f as f$1,g as g$1,h}from'./chunk-VQZ5PI5J.js';import s from'path';import h$1 from'fs-extra';var pe=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var Jt="workspace-operational-skill.v1";function Yt(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function Ot(e){let t=Yt(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:Jt,skillId:t,canonicalPath:W(t),title:e.title,triggers:[...e.triggers].sort((r,n)=>r.localeCompare(n)),requiredReports:[...e.requiredReports].sort((r,n)=>r.localeCompare(n)),scopedProjects:[...e.scopedProjects??[]].sort((r,n)=>r.localeCompare(n)),verificationCommands:[...e.verificationCommands],answerContractSections:[...pe],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var Xt=q.skillsIndex;function Tt(e){let t=[...e.skills].sort((i,c)=>i.skillId.localeCompare(c.skillId)),r=e.inputsHash??d$1({skillIds:t.map(i=>i.skillId),paths:t.map(i=>i.canonicalPath),decisions:e.decisions??[]}),n=e.decisions?[...e.decisions].sort((i,c)=>i.skillId.localeCompare(c.skillId)):void 0;return {schemaVersion:Xt,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(i=>({skillId:i.skillId,path:i.canonicalPath,schemaVersion:i.schemaVersion,title:i.title})),...n?{selection:{generatedCount:n.filter(i=>i.status==="generated").length,suppressedCount:n.filter(i=>i.status==="suppressed").length,decisions:n}}:{}}}var _t=[p.agentIndex,b$1,d$2],B="<!-- WORKSPAI:GENERATED-OPERATIONAL-SKILL -->",Qt=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${p.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${p.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."],applicability:"api"},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${p.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${p.verify}\` for verdict and blocking reasons.`,`Read \`${t.artifactRemediationPlan}\` when a Studio or agent repair path is needed.`,"List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."],applicability:"workspace"},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Run a registered project-scoped test/build command when available; otherwise resolve the repository-authored validation command from cited manifests before promoting the migration.","Document rollback and verification signals."],applicability:"schema"},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Use registered test/build commands for affected projects; when none are registered, resolve repository-authored commands from cited manifests instead of inventing one.","Re-run `workspace verify` after evidence refresh."],applicability:"dependency"},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:[`Read \`${t.workspaceContract}\` for publishes/consumes/owns edges.`,"List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."],applicability:"contract"}];function z(e){return `npx workspai ${e}`.trim()}function Zt(e){let t=["---",`name: ${e.template.skillId}`,`description: ${e.template.objective}`,"---","",B,"",`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",..._t.map(r=>`- \`${r}\``),"","## Why this skill exists here","",`Applicability: **${e.decision.confidence} confidence**.`,"",...e.decision.reasons.map(r=>`- ${r}`),...e.decision.signals.length>0?["","Evidence signals:","",...e.decision.signals.map(r=>`- \`${r}\``)]:[],"","## Project-aware execution boundary","",...e.projectEvidence,"",...e.retrievalCommands.length>0?["## Scoped retrieval commands","",...e.retrievalCommands.map(r=>`- \`${r}\``),""]:[],"## Procedure","",...e.template.steps.map((r,n)=>`${n+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",z("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
2
2
  `)}function er(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function tr(e){let t=new Map;for(let c of e.projects){let m=new Set([c.runtime,...c.runtimeCandidates??[]].map(er).filter(a=>a&&a!=="unknown"));for(let a of m){let k=t.get(a)??[];k.includes(c.name)||k.push(c.name),t.set(a,k);}}let r=[];for(let[c,m]of [...t.entries()].sort(([a],[k])=>a.localeCompare(k)))r.push({skillId:`workspai-${c}-runtime-validation`,title:`${c.toUpperCase()} runtime validation`,triggers:[`${c} build`,`${c} test`,`${c} runtime failure`],objective:`Validate ${c} changes against the detected runtime boundary, registered project commands, and canonical Workspai evidence.`,steps:["Read the scoped project lens and current fail/warn evidence before changing source.",`Use a registered ${c} command only when the project model identifies ${c} as the primary runtime; for a composite secondary boundary, inspect its manifest and Graph proofs instead of assuming the primary adapter covers it.`,"Run only the affected project validation first, then verify the workspace when the change crosses a contract boundary."],scopedProjects:[...m].sort(),applicability:"derived"});t.size>1&&r.push({skillId:"workspai-polyglot-change-validation",title:"Polyglot change validation",triggers:["cross-language change","polyglot change","binding change","multi-runtime validation"],objective:"Plan and verify a cross-runtime change without assuming that one runtime command proves the whole system.",steps:["Use the project topology and bounded Graph query to identify runtime and contract boundaries.","Validate each affected runtime with its registered project command.","Run workspace impact and canonical verification before declaring the change complete."],scopedProjects:Wt([...t.values()].flat()),applicability:"derived"});let n=e.projects.filter(c=>c.commands.supported.includes("test")).map(c=>c.name).sort();n.length>0&&r.push({skillId:"workspai-test-evidence-recovery",title:"Test evidence recovery",triggers:["test failure","coverage","regression","test evidence"],objective:"Repair a test or coverage blocker by proving changed behavior, not merely improving a metric.",steps:["Read the exact Analyze, Doctor, or Goal evidence that owns the test finding.","Inspect the behavior and relevant test boundary before proposing a source change.","Run the scoped test command, then the exact producer and canonical verification."],scopedProjects:n,applicability:"derived"});let i=e.projects.filter(c=>c.importantFiles.some(m=>/(?:^|\/)(?:Dockerfile|docker-compose|compose\.|Chart\.yaml|\.github\/workflows)/i.test(m))).map(c=>c.name).sort();return i.length>0&&r.push({skillId:"workspai-delivery-evidence",title:"Delivery evidence and CI recovery",triggers:["ci failure","workflow failure","container build","deployment evidence"],objective:"Diagnose delivery evidence with the owning project and CI/container artifacts before changing application source.",steps:["Identify whether the failing evidence is project-owned or workspace-owned.","Inspect the referenced workflow or delivery artifact and its bounded proof paths.","Validate the affected project first, then refresh the exact evidence producer and verify the workspace."],scopedProjects:i,applicability:"derived"}),r}function rr(e,t){if(!e?.safeCommands?.length)return [z("workspace verify --json"),z("doctor workspace --json")];let r=new Set(t);return e.safeCommands.filter(n=>n.scope==="workspace"||n.project&&r.has(n.project)).slice(0,8).map(n=>n.display)}function nr(e,t){if(!e?.projects?.length)return;let r=new Set(t),n=e.projects.filter(i=>r.has(i.slug)).filter(i=>(i.contracts?.owns?.length??0)>0||(i.contracts?.publishes?.length??0)>0||(i.contracts?.consumes?.length??0)>0||(i.contracts?.apis?.length??0)>0).slice(0,12).map(i=>{let c=i.contracts?.owns?.join(", ")||"none",m=i.contracts?.publishes?.join(", ")||"none",a=i.contracts?.consumes?.join(", ")||"none";return `- **${i.slug}**: owns \`${c}\`; publishes \`${m}\`; consumes \`${a}\``});return n.length>0?n.join(`
3
3
  `):void 0}var ar=/(?:^|\/)(?:package(?:-lock)?\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|pyproject\.toml|poetry\.lock|requirements[^/]*\.txt|Pipfile(?:\.lock)?|uv\.lock|Cargo\.toml|Cargo\.lock|go\.mod|go\.sum|pom\.xml|build\.gradle(?:\.kts)?|settings\.gradle(?:\.kts)?|Gemfile(?:\.lock)?|composer\.(?:json|lock)|mix\.exs|deps\.edn|project\.clj|[^/]+\.(?:csproj|fsproj|vbproj)|Directory\.Packages\.props)$/i,or=/(?:^|\/)(?:openapi|swagger|asyncapi)\.(?:json|ya?ml)$|(?:^|\/)(?:routes?|controllers?|endpoints?|proto)(?:\/|\.)/i,ir=/(?:^|\/)(?:migrations?|database|db|prisma)(?:\/|\.)|(?:^|\/)schema\.(?:sql|prisma)$/i;function sr(e){let t=e.attributes.artifact;return typeof t=="string"&&t.trim()?t.trim():null}function cr(e){let t=e.attributes.ports;return Array.isArray(t)&&t.length>0}function lr(e,t){return e?.entities.filter(r=>r.projectId===t)??[]}function ue(e,t=12){return [...new Set([...e].map(r=>r.trim()).filter(Boolean))].sort((r,n)=>r.localeCompare(n)).slice(0,t)}function Wt(e){return [...new Set([...e].map(t=>t.trim()).filter(Boolean))].sort((t,r)=>t.localeCompare(r))}function dr(e){if(e.template.scopedProjects)return {projects:[...e.template.scopedProjects].sort(),reasons:["The canonical workspace model directly derived this capability."],signals:ue(e.template.scopedProjects.map(i=>`model:project:${i}:${e.template.skillId}`)),confidence:"high",applicable:true};if(e.template.applicability==="workspace")return {projects:e.model.projects.map(i=>i.name).sort(),reasons:["Workspace-level release and verification gates are always available."],signals:["model:workspace",`model:project-count:${e.model.projects.length}`],confidence:"high",applicable:true};let t=[],r=[],n=new Set;for(let i of e.model.projects){let c=lr(e.graph,i.name),m=Wt([...i.importantFiles,...c.map(sr).filter(l=>!!l)]),a=e.contract?.projects.find(l=>l.slug===i.name),k=false;switch(e.template.applicability){case "dependency":{let l=m.filter(d=>ar.test(d)),p=c.filter(d=>d.kind==="package");k=l.length>0||p.length>0,r.push(...l.map(d=>`artifact:${d}`),...p.slice(0,4).map(d=>`graph:package:${d.label}`)),k&&n.add("Dependency manifests or package entities were observed.");break}case "api":{let l=c.filter(w=>w.kind==="api"||w.kind==="endpoint"||w.kind==="service"&&cr(w)),p=m.filter(w=>or.test(w)),d=a?.contracts?.apis??[],R=(a?.ports??[]).filter(w=>["http","https","grpc"].includes(w.protocol));k=l.length>0||p.length>0||d.length>0||R.length>0,r.push(...l.slice(0,4).map(w=>`graph:${w.kind}:${w.label}`),...p.map(w=>`artifact:${w}`),...d.map(w=>`contract:api:${w.name}:${w.basePath}`),...R.map(w=>`contract:port:${w.name}:${w.protocol}:${w.port}`)),k&&n.add("An API, endpoint, routed artifact, or network contract was observed.");break}case "schema":{let l=c.filter(d=>{if(d.kind==="database")return true;if(d.kind!=="schema")return false;let R=`${d.label} ${JSON.stringify(d.attributes)}`;return /database|migration|sql|prisma|orm/i.test(R)}),p=m.filter(d=>ir.test(d));k=l.length>0||p.length>0,r.push(...l.slice(0,4).map(d=>`graph:${d.kind}:${d.label}`),...p.map(d=>`artifact:${d}`)),k&&n.add("A database, schema, or migration artifact was observed.");break}case "contract":{let l=a?[...a.contracts?.owns??[],...a.contracts?.publishes??[],...a.contracts?.consumes??[],...(a.contracts?.apis??[]).map(d=>d.name)]:[],p=c.filter(d=>["api","protocol"].includes(d.kind));k=l.length>0||p.length>0,r.push(...l.map(d=>`contract:${i.name}:${d}`),...p.slice(0,6).map(d=>`graph:${d.kind}:${d.label}`)),k&&n.add("A shared API, protocol, schema, or authored contract edge was observed.");break}case "derived":k=true;break}k&&t.push(i.name);}return {projects:ue(t,e.model.projects.length),reasons:[...n],signals:ue(r),confidence:e.graph||e.contract?"high":"medium",applicable:t.length>0}}function pr(e,t,r){let n=[];for(let i of t){let c=e.projects.find(l=>l.name===i);if(!c)continue;let m=c.commands.supported.filter(l=>["build","test","lint","format"].includes(l)),a=c.commands.supported.filter(l=>["docs","doctor"].includes(l)),k=r.filter(l=>l.startsWith("artifact:")).map(l=>l.slice(9)).filter(l=>c.importantFiles.includes(l)||l.includes(c.name));n.push(`- **${c.name}** \u2014 runtime \`${c.runtime}\`, framework \`${c.framework}\`, confidence \`${c.confidence}\`.`),n.push(m.length>0?` Registered lifecycle commands: ${m.map(l=>`\`${l}\``).join(", ")}.`:" No project-native build/test command is registered; inspect repository-authored manifests and Graph proofs before running a command."),a.length>0&&n.push(` Registered evidence commands: ${a.map(l=>`\`${l}\``).join(", ")}.`),k.length>0&&n.push(` Relevant artifacts: ${ue(k,6).map(l=>`\`${l}\``).join(", ")}.`);}return n.length>0?n:["- No project boundary was proven; do not infer repository-specific commands or files."]}function ur(e,t){let r=e.applicability==="api"?"api endpoint route service failure":e.applicability==="schema"?"database schema migration persistence":e.applicability==="dependency"?"package dependency manifest lockfile":e.applicability==="contract"?"api protocol published consumed contract":e.applicability==="workspace"?"release pipeline deployment verification":`${e.title.toLowerCase()} manifest command test`;return t.slice(0,8).map(n=>z(`workspace graph search "${r}" --scope project:${n} --limit 12 --json`))}function jt(e){let t=e.model.workspace.name,r=[],n=[];for(let i of [...Qt,...tr(e.model)]){let c=dr({template:i,model:e.model,contract:e.contract??null,graph:e.graph??null}),m={skillId:i.skillId,title:i.title,status:c.applicable?"generated":"suppressed",confidence:c.confidence,reasons:c.reasons.length>0?c.reasons:["No authoritative workspace signal proves this capability is present."],signals:c.signals,scopedProjects:c.projects};if(n.push(m),m.status==="suppressed")continue;let a=m.scopedProjects,k=rr(e.context??null,a),l=nr(e.contract??null,a),p=Zt({template:i,workspaceName:t,scopedProjects:a,verificationCommands:k,contractSummary:l,decision:m,projectEvidence:pr(e.model,a,m.signals),retrievalCommands:ur(i,a)});r.push(Ot({skillId:i.skillId,title:i.title,triggers:i.triggers,requiredReports:[..._t],scopedProjects:a,verificationCommands:k,...X$1(i.skillId)?{promptStem:Y$1[i.skillId]}:{},markdown:p}));}return {skills:r,decisions:n}}async function Nt(e){let t=s.resolve(e.workspacePath),r=[],n=d$1({skills:e.skills.map(a=>({id:a.skillId,path:a.canonicalPath,hash:d$1({markdown:a.markdown})})),decisions:e.decisions??[]}),i=Tt({generatedAt:e.generatedAt,skills:e.skills,inputsHash:n,decisions:e.decisions}),c=new Set(e.skills.map(a=>a.skillId)),m=[];if(e.write){let a=s.join(t,".workspai","skills");if(await h$1.pathExists(a))for(let l of await h$1.readdir(a,{withFileTypes:true})){if(!l.isFile()||!l.name.endsWith(".md"))continue;let p=l.name.slice(0,-3);if(c.has(p))continue;let d=s.join(a,l.name);(await h$1.readFile(d,"utf8")).includes(B)&&(await h$1.remove(d),m.push(p));}for(let l of e.skills){let p=s.join(t,l.canonicalPath);await h$1.ensureDir(s.dirname(p)),await h$1.writeFile(p,l.markdown,"utf8"),r.push(l.canonicalPath);}let k=s.join(t,b$2);await h$1.ensureDir(s.dirname(k)),await h$1.writeJson(k,i,{spaces:2}),r.push(b$2);}return {skills:e.skills,index:i,writtenPaths:r,removedSkillIds:m.sort()}}function Lt(e){return ["## Operational skills (canonical)","","Read workspace-native playbooks from `.workspai/skills/` before generic repo scans. Legacy `.rapidkit/skills/` playbooks are read only when already present from older workspaces:","",...e.skills.map(r=>`- \`${r.path}\` \u2014 ${r.title} (\`${r.skillId}\`)`),"","Regenerate:","","```bash",z("workspace agent-sync --write --refresh-context"),"```",""].join(`
4
4
  `)}var gr={"workspai-diagnose-api-failure":A,"workspai-release-readiness":E},Je="## Workspace verification (hydrated)";function mr(e){let t=[Je,"","Verification commands for this workspace:","",...e.verificationCommands.length?e.verificationCommands.map(r=>`- \`${r}\``):["- `npx workspai workspace verify --json`"]];return e.scopedProjects.length>0&&t.push("","Scoped projects:","",...e.scopedProjects.map(r=>`- ${r}`)),t.push(""),t.join(`
@@ -2,7 +2,7 @@ import {c}from'./chunk-N4B2M44I.js';import {a}from'./chunk-A5FBGRJA.js';import {
2
2
  `);}async function se(e,r){let t=n.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${e}.${process.pid}.${randomUUID()}.tmp`;try{await promises.writeFile(o,r);let a=await promises.open(o,"r");try{await ae(a);}finally{await a.close();}try{await promises.rename(o,e);}catch(s){let i=s.code;if(i!=="EEXIST"&&i!=="EPERM")throw s;await le.move(o,e,{overwrite:true});}}finally{await promises.rm(o,{force:true}).catch(()=>{});}}async function Z(e){try{return {exists:true,content:await promises.readFile(e)}}catch(r){if(r.code==="ENOENT")return {exists:false};throw r}}async function ee(e,r){if(!r.exists){await promises.rm(e,{force:true});return}await se(e,r.content);}async function we(e,r){let t=n.join(e,"workspaces.json.lock"),o=randomUUID();await promises.mkdir(e,{recursive:true});let a=Date.now(),s;for(;!s;)try{s=await promises.open(t,"wx"),await s.writeFile(`${JSON.stringify({pid:process.pid,lockId:o,createdAt:new Date().toISOString()})}
3
3
  `),await ae(s);}catch(i){if(i.code!=="EEXIST")throw i;let c=await promises.stat(t).catch(()=>null);if(c&&Date.now()-c.mtimeMs>de){let d=await promises.readFile(t,"utf8").then(g=>JSON.parse(g)).catch(()=>null),u=Number(d?.pid),f=false;if(Number.isInteger(u)&&u>0)try{process.kill(u,0),f=true;}catch(g){f=g.code==="EPERM";}if(!f){await promises.rm(t,{force:true}).catch(()=>{});continue}}if(Date.now()-a>me)throw new Error(`Timed out waiting for workspace registry lock: ${t}`);await new Promise(d=>setTimeout(d,25));}try{return await r()}finally{await s.close().catch(()=>{}),await promises.readFile(t,"utf8").then(c=>JSON.parse(c).lockId===o).catch(()=>false)&&await promises.rm(t,{force:true}).catch(()=>{});}}async function S(e){let r$1=q(),t=n.join(r$1,"workspaces.json"),o=n.join(r(),"workspaces.json"),a=[...new Set(s$1())];return we(r$1,async()=>{let[s,i]=await Promise.all([Z(t),Z(o)]),c=await oe(a);await e(c);let d=I(c);try{await X(t,d),await X(o,d);}catch(u){let g=(await Promise.allSettled([ee(t,s),ee(o,i)])).filter(k=>k.status==="rejected").map(k=>k.reason);throw g.length>0?new AggregateError([u,...g],"Workspace registry transaction failed and could not be fully restored"):u}return d})}async function ie(e,r){let t=a(e);await S(o=>{let a=o.workspaces.find(s=>s.path===t);if(a){a.name=r,a.mode=a.mode||"full",a.projects=Array.isArray(a.projects)?a.projects:[];return}o.workspaces.push({name:r,path:t,mode:"full",projects:[]});});}async function He(e){let r=a(e),o=(await oe()).workspaces.find(a=>a.path===r);return o?{...o,projects:o.projects.map(a=>({...a}))}:null}async function Ke(e,r){let t=a(e);await S(o=>{let a=o.workspaces.findIndex(i=>i.path===t);if(!r){a>=0&&o.workspaces.splice(a,1);return}let s=G(r);a>=0?o.workspaces[a]=s:o.workspaces.push(s);});}async function qe(e){let r=a(e);await S(t=>{t.workspaces=t.workspaces.filter(o=>o.path!==r);});}async function he(e,r){try{await ie(e,r);}catch{console.warn(p.gray("Note: Could not register workspace in shared registry"));}}async function Qe(e,r=false){let t=a(e),o={workspacePath:t,workspaceFound:false,added:[],skipped:0};try{let a$1=await z(),s=a$1.workspaces.find(k=>k.path===t);if(!s){if(await he(t,n.basename(n.resolve(e))),a$1=await z(),s=a$1.workspaces.find(k=>k.path===t),!s)return r||console.log("\u26A0\uFE0F Workspace could not be registered in registry"),o;r||console.log("\u2714 Registered workspace in shared registry");}Array.isArray(s.projects)||(s.projects=[]);let i=0,c=0,d=[],u$1=[],f=[e],g=new Set;for(;f.length>0;){let k=f.shift();if(!k||g.has(k))continue;g.add(k);let w=await promises.readdir(k,{withFileTypes:true});for(let h of w){if(!h.isDirectory()||h.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(h.name))continue;let v=n.join(k,h.name),y=a(v);try{let x=false;for(let P of [...u(y,"context.json"),...u(y,"project.json")])try{await promises.access(P),x=true;break}catch{}if(x){let P=n.basename(y),m=s.projects.some($=>$.path===y);u$1.push({name:P,path:y}),m?c++:(s.projects.push({name:P,path:y}),i++,d.push(y),r||console.log(`\u2714 Added: ${n.relative(e,y)}`));continue}}catch{}f.push(v);}}return await S(k=>{let w=k.workspaces.find(y=>y.path===t);if(!w)return;let h=`${t}${n.sep}`,v=(w.projects||[]).filter(y=>y.path!==t&&!y.path.startsWith(h));w.projects=G({...w,projects:[...v,...u$1]}).projects;}),i>0?r||console.log(`
4
4
  \u2705 Synced ${i} project(s) to registry`):r||console.log(`
5
- \u2705 All projects already registered (${c} found)`),{workspacePath:t,workspaceFound:true,added:d,skipped:c}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function ye(e,r,t){let o=a(e),a$1=a(t);await S(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let c=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};c>=0?i.projects[c]=d:i.projects.push(d);});}async function Xe(e,r,t){try{await ye(e,r,t);}catch{}}async function Ze(e,r){let t=N("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(n.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(n.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-7CWWGDXQ.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=$e();await promises.writeFile(n.join(e,"rapidkit"),s),await promises.chmod(n.join(e,"rapidkit"),493);let i=je();await promises.writeFile(n.join(e,"rapidkit.cmd"),i);let c=ve(r.name);await promises.writeFile(n.join(e,"README.md"),c),await promises.writeFile(n.join(e,".gitignore"),`# Workspai workspace
5
+ \u2705 All projects already registered (${c} found)`),{workspacePath:t,workspaceFound:true,added:d,skipped:c}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function ye(e,r,t){let o=a(e),a$1=a(t);await S(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let c=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};c>=0?i.projects[c]=d:i.projects.push(d);});}async function Xe(e,r,t){try{await ye(e,r,t);}catch{}}async function Ze(e,r){let t=N("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(n.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(n.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-FOPYAWAR.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=$e();await promises.writeFile(n.join(e,"rapidkit"),s),await promises.chmod(n.join(e,"rapidkit"),493);let i=je();await promises.writeFile(n.join(e,"rapidkit.cmd"),i);let c=ve(r.name);await promises.writeFile(n.join(e,"README.md"),c),await promises.writeFile(n.join(e,".gitignore"),`# Workspai workspace
6
6
  .env
7
7
  .env.*
8
8
  !.env.example
@@ -1,4 +1,4 @@
1
- import {a}from'./chunk-FIK343LI.js';import {c as c$1}from'./chunk-7LKCWDX6.js';import {l,q}from'./chunk-UHAPXPGW.js';import {f as f$1,g,h as h$2}from'./chunk-S66NO5BX.js';import {a as a$2}from'./chunk-TDQ2PRHV.js';import {i,h as h$1,d,b as b$1,c as c$2,a as a$3,k as k$2}from'./chunk-FE5R6EUV.js';import {b as b$3}from'./chunk-K33JJVQZ.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {c,d as d$1}from'./chunk-EWZZUQBR.js';import {h,i as i$1,m,k as k$1,n,o,l as l$1,j,s,f as f$2,g as g$1,e}from'./chunk-ODK4LCEL.js';import {a as a$5}from'./chunk-FB7SCXAZ.js';import {b as b$2}from'./chunk-25AWHAB5.js';import {a as a$4}from'./chunk-XWKGZRHN.js';import {randomUUID,createHash}from'crypto';import C from'path';import N from'fs-extra';var Xe=new Set(["committed","rejected","aborted","superseded"]);function f(e,t){if(!e)throw new Error(`Decision protocol violation: ${t}`)}function Qe(e){return [...new Set(e)].sort()}function _e(e,t){return t.digestCanonical(e.effects.map(a=>({id:a.id,status:a.status,key:a.idempotencyKey})))}function je(e,t,a){f(!e.some(r=>r.id===t),`${a} receipt '${t}' already exists`);}function Ze(e,t){je(e.effects,t.id,"effect");let a=e.effects.find(r=>r.idempotencyKey===t.idempotencyKey);return f(!a,`effect idempotency key '${t.idempotencyKey}' was already recorded by '${a?.id}'`),[...e.effects,t]}function et(e,t,a){return je(e.verifications,t.id,"verification"),f(t.target.effectHeadDigest===_e(e,a),`verification '${t.id}' does not bind the current effect head`),[...e.verifications,t]}function tt(e){return e.requiredCriteria.every(t=>{let a=e.verifications.filter(r=>r.criterionId===t);return a.length>0&&a.at(-1)?.status==="passed"})}function at(e$1,t,a){if(t.kind==="created"){f(e$1===null,"created must be the first event");let y=t.payload.references?.[0];f(y,"created must bind an intent artifact");let h=t.payload.references?.filter(g=>g.role==="success-criterion").map(g=>g.artifact)??[];return {schemaVersion:e,id:t.transactionId,purpose:"proof-carrying-change",createdAt:t.occurredAt,updatedAt:t.occurredAt,state:"draft",generation:1,eventCount:t.sequence,eventHeadDigest:t.digest,intent:y,requiredCriteria:Qe(h),scope:null,evidence:[],plans:[],authorization:null,effects:[],verifications:[],blockers:[]}}f(e$1,`${t.kind} cannot occur before created`),f(!Xe.has(e$1.state),`${t.kind} cannot follow terminal state ${e$1.state}`);let r=e$1.state,i=e$1.scope,n=e$1.evidence,s=e$1.plans,c=e$1.authorization,d=e$1.effects,o=e$1.verifications,l=e$1.blockers,w=e$1.terminalReason;switch(t.kind){case "scope-bound":f(e$1.state==="draft"||e$1.state==="scoped","scope-bound requires draft or scoped state"),f(t.payload.scope,"scope-bound requires scope"),i=t.payload.scope,r="scoped";break;case "evidence-attached":f(e$1.state==="scoped"||e$1.state==="evidence-ready","evidence-attached requires scoped state"),f((t.payload.references?.length??0)>0,"evidence-attached requires references"),n=[...n,...t.payload.references??[]],r="evidence-ready";break;case "plan-attached":f(e$1.state==="evidence-ready","plan-attached requires evidence-ready state"),f((t.payload.references?.length??0)>0,"plan-attached requires references"),s=[...s,...t.payload.references??[]];break;case "authorized":f(e$1.state==="evidence-ready","authorization requires evidence-ready state"),f(t.payload.authorization,"authorized requires a bounded authorization grant"),c=t.payload.authorization,r="authorized";break;case "effect-requested":f(e$1.state==="authorized"||e$1.state==="executing","effect-requested requires authorization"),r="executing";break;case "effect-recorded":f(e$1.state==="authorized"||e$1.state==="executing","effect-recorded requires authorization"),f(t.payload.effect,"effect-recorded requires a receipt"),f(c?.effectClasses.includes(t.payload.effect.effectClass),`effect class '${t.payload.effect.effectClass}' is outside the authorization grant`),d=Ze(e$1,t.payload.effect),r=t.payload.effect.status==="succeeded"?"executing":"blocked",t.payload.effect.status!=="succeeded"&&(l=[...l,{code:t.payload.effect.status==="uncertain"?"decision.effect.uncertain":"decision.effect.failed",actionable:true,details:t.payload.effect.summary}]);break;case "effect-uncertain":f(e$1.state==="authorized"||e$1.state==="executing","effect-uncertain requires an active execution"),r="blocked",l=[...l,t.payload.blocker??{code:"decision.effect.uncertain",actionable:true}];break;case "verification-started":f(e$1.state==="authorized"||e$1.state==="executing","verification-started requires authorized or executing state"),r="verifying";break;case "verification-recorded":{f(e$1.state==="verifying","verification-recorded requires verifying state"),f(t.payload.verification,"verification-recorded requires a receipt"),o=et(e$1,t.payload.verification,a),r=t.payload.verification.status==="failed"?"blocked":t.payload.verification.status==="inconclusive"?"awaiting-human":"verifying";break}case "human-required":r="awaiting-human";break;case "blocked":f(t.payload.blocker,"blocked requires a structured blocker"),l=[...l,t.payload.blocker],r="blocked";break;case "resumed":f(e$1.state==="blocked"||e$1.state==="awaiting-human","resumed requires a paused state"),f(t.payload.resumeTo,"resumed requires an explicit target state"),r=t.payload.resumeTo,l=[];break;case "committed":f(e$1.state==="verifying","commit requires verifying state"),f(tt(e$1),"every required criterion needs a latest passing receipt"),f(!e$1.effects.some(y=>y.status!=="succeeded"),"all effects must be certainly successful"),r="committed",w=t.payload.reason??t.payload.summary;break;case "rejected":case "aborted":case "superseded":r=t.kind,w=t.payload.reason??t.payload.summary;break;default:throw new Error(`Decision protocol violation: unsupported event ${t.kind}`)}return {...e$1,updatedAt:t.occurredAt,state:r,generation:e$1.generation+1,eventCount:t.sequence,eventHeadDigest:t.digest,scope:i,evidence:n,plans:s,authorization:c,effects:d,verifications:o,blockers:l,...w?{terminalReason:w}:{}}}function Ke(e,t,a,r){let i=(t?.sequence??0)+1,n={schemaVersion:f$2,transactionId:e,sequence:i,kind:a.kind,occurredAt:a.occurredAt,actor:a.actor,previousEventDigest:t?.digest??null,payload:a.payload};return {...n,digest:r.digestCanonical(n)}}function U(e,t){f(e.length>0,"at least one event is required");let a=null,r=null;for(let i of e){f(i.schemaVersion===f$2,`unsupported event schema ${i.schemaVersion}`),f(i.sequence===(r?.sequence??0)+1,`event sequence ${i.sequence} is not contiguous`),f(i.previousEventDigest===(r?.digest??null),`event ${i.sequence} has an invalid previous digest`);let{digest:n,...s}=i;f(i.digest===t.digestCanonical(s),`event ${i.sequence} digest is invalid`),f(!r||i.transactionId===r.transactionId,"events cross transaction boundaries"),a=at(a,i,t),r=i;}return a}function ie(e,t,a){return {schemaVersion:g$1,transactionId:e.id,generatedAt:t,generation:e.generation,eventCount:e.eventCount,eventHeadDigest:e.eventHeadDigest,state:e.state,transactionDigest:a.digestCanonical(e)}}function B(e,t){return _e(e,t)}var T={digestCanonical:c};function it(e){let t=e.trim();if(!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(t))throw new Error(`Invalid decision transaction id: ${e}`);return t}function z(e){let a=`.workspai/decisions/${it(e)}`;return {directory:a,transaction:`${a}/transaction.json`,checkpoint:`${a}/checkpoint.json`,events:`${a}/events.jsonl`,lock:`${a}.lock`}}function nt(e,t){return e.split(/\r?\n/).filter(r=>r.trim().length>0).map((r,i)=>{try{return JSON.parse(r)}catch(n){throw new Error(`Decision event log is corrupt at ${t}:${i+1}: ${n.message}`)}})}async function qe(e,t){let a=z(t),r=await b$1(e,a.events);return r?nt(await N.readFile(r,"utf8"),r):[]}function ze(e,t){let a=z(t);return {directory:a$3(e,a.directory),transaction:a$3(e,a.transaction),checkpoint:a$3(e,a.checkpoint),events:a$3(e,a.events)}}async function st(e,t,a,r){let i=z(t.id),n=ie(t,r,T);for(let[s,c]of a.entries())a$1(c,"contracts/workspace-intelligence/decision-event.v1.json",`Decision event ${s+1}`);return b$3(i.transaction,t),b$3(i.checkpoint,n),await k$2(e,i.events,`${a.map(s=>JSON.stringify(s)).join(`
1
+ import {a}from'./chunk-FIK343LI.js';import {c as c$1}from'./chunk-I7P6XQJI.js';import {l,q}from'./chunk-5NL53T5C.js';import {f as f$1,g,h as h$2}from'./chunk-S66NO5BX.js';import {a as a$2}from'./chunk-TDQ2PRHV.js';import {i,h as h$1,d,b as b$1,c as c$2,a as a$3,k as k$2}from'./chunk-FE5R6EUV.js';import {b as b$3}from'./chunk-K33JJVQZ.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {c,d as d$1}from'./chunk-EWZZUQBR.js';import {h,i as i$1,m,k as k$1,n,o,l as l$1,j,s,f as f$2,g as g$1,e}from'./chunk-ODK4LCEL.js';import {a as a$5}from'./chunk-FB7SCXAZ.js';import {b as b$2}from'./chunk-25AWHAB5.js';import {a as a$4}from'./chunk-XWKGZRHN.js';import {randomUUID,createHash}from'crypto';import C from'path';import N from'fs-extra';var Xe=new Set(["committed","rejected","aborted","superseded"]);function f(e,t){if(!e)throw new Error(`Decision protocol violation: ${t}`)}function Qe(e){return [...new Set(e)].sort()}function _e(e,t){return t.digestCanonical(e.effects.map(a=>({id:a.id,status:a.status,key:a.idempotencyKey})))}function je(e,t,a){f(!e.some(r=>r.id===t),`${a} receipt '${t}' already exists`);}function Ze(e,t){je(e.effects,t.id,"effect");let a=e.effects.find(r=>r.idempotencyKey===t.idempotencyKey);return f(!a,`effect idempotency key '${t.idempotencyKey}' was already recorded by '${a?.id}'`),[...e.effects,t]}function et(e,t,a){return je(e.verifications,t.id,"verification"),f(t.target.effectHeadDigest===_e(e,a),`verification '${t.id}' does not bind the current effect head`),[...e.verifications,t]}function tt(e){return e.requiredCriteria.every(t=>{let a=e.verifications.filter(r=>r.criterionId===t);return a.length>0&&a.at(-1)?.status==="passed"})}function at(e$1,t,a){if(t.kind==="created"){f(e$1===null,"created must be the first event");let y=t.payload.references?.[0];f(y,"created must bind an intent artifact");let h=t.payload.references?.filter(g=>g.role==="success-criterion").map(g=>g.artifact)??[];return {schemaVersion:e,id:t.transactionId,purpose:"proof-carrying-change",createdAt:t.occurredAt,updatedAt:t.occurredAt,state:"draft",generation:1,eventCount:t.sequence,eventHeadDigest:t.digest,intent:y,requiredCriteria:Qe(h),scope:null,evidence:[],plans:[],authorization:null,effects:[],verifications:[],blockers:[]}}f(e$1,`${t.kind} cannot occur before created`),f(!Xe.has(e$1.state),`${t.kind} cannot follow terminal state ${e$1.state}`);let r=e$1.state,i=e$1.scope,n=e$1.evidence,s=e$1.plans,c=e$1.authorization,d=e$1.effects,o=e$1.verifications,l=e$1.blockers,w=e$1.terminalReason;switch(t.kind){case "scope-bound":f(e$1.state==="draft"||e$1.state==="scoped","scope-bound requires draft or scoped state"),f(t.payload.scope,"scope-bound requires scope"),i=t.payload.scope,r="scoped";break;case "evidence-attached":f(e$1.state==="scoped"||e$1.state==="evidence-ready","evidence-attached requires scoped state"),f((t.payload.references?.length??0)>0,"evidence-attached requires references"),n=[...n,...t.payload.references??[]],r="evidence-ready";break;case "plan-attached":f(e$1.state==="evidence-ready","plan-attached requires evidence-ready state"),f((t.payload.references?.length??0)>0,"plan-attached requires references"),s=[...s,...t.payload.references??[]];break;case "authorized":f(e$1.state==="evidence-ready","authorization requires evidence-ready state"),f(t.payload.authorization,"authorized requires a bounded authorization grant"),c=t.payload.authorization,r="authorized";break;case "effect-requested":f(e$1.state==="authorized"||e$1.state==="executing","effect-requested requires authorization"),r="executing";break;case "effect-recorded":f(e$1.state==="authorized"||e$1.state==="executing","effect-recorded requires authorization"),f(t.payload.effect,"effect-recorded requires a receipt"),f(c?.effectClasses.includes(t.payload.effect.effectClass),`effect class '${t.payload.effect.effectClass}' is outside the authorization grant`),d=Ze(e$1,t.payload.effect),r=t.payload.effect.status==="succeeded"?"executing":"blocked",t.payload.effect.status!=="succeeded"&&(l=[...l,{code:t.payload.effect.status==="uncertain"?"decision.effect.uncertain":"decision.effect.failed",actionable:true,details:t.payload.effect.summary}]);break;case "effect-uncertain":f(e$1.state==="authorized"||e$1.state==="executing","effect-uncertain requires an active execution"),r="blocked",l=[...l,t.payload.blocker??{code:"decision.effect.uncertain",actionable:true}];break;case "verification-started":f(e$1.state==="authorized"||e$1.state==="executing","verification-started requires authorized or executing state"),r="verifying";break;case "verification-recorded":{f(e$1.state==="verifying","verification-recorded requires verifying state"),f(t.payload.verification,"verification-recorded requires a receipt"),o=et(e$1,t.payload.verification,a),r=t.payload.verification.status==="failed"?"blocked":t.payload.verification.status==="inconclusive"?"awaiting-human":"verifying";break}case "human-required":r="awaiting-human";break;case "blocked":f(t.payload.blocker,"blocked requires a structured blocker"),l=[...l,t.payload.blocker],r="blocked";break;case "resumed":f(e$1.state==="blocked"||e$1.state==="awaiting-human","resumed requires a paused state"),f(t.payload.resumeTo,"resumed requires an explicit target state"),r=t.payload.resumeTo,l=[];break;case "committed":f(e$1.state==="verifying","commit requires verifying state"),f(tt(e$1),"every required criterion needs a latest passing receipt"),f(!e$1.effects.some(y=>y.status!=="succeeded"),"all effects must be certainly successful"),r="committed",w=t.payload.reason??t.payload.summary;break;case "rejected":case "aborted":case "superseded":r=t.kind,w=t.payload.reason??t.payload.summary;break;default:throw new Error(`Decision protocol violation: unsupported event ${t.kind}`)}return {...e$1,updatedAt:t.occurredAt,state:r,generation:e$1.generation+1,eventCount:t.sequence,eventHeadDigest:t.digest,scope:i,evidence:n,plans:s,authorization:c,effects:d,verifications:o,blockers:l,...w?{terminalReason:w}:{}}}function Ke(e,t,a,r){let i=(t?.sequence??0)+1,n={schemaVersion:f$2,transactionId:e,sequence:i,kind:a.kind,occurredAt:a.occurredAt,actor:a.actor,previousEventDigest:t?.digest??null,payload:a.payload};return {...n,digest:r.digestCanonical(n)}}function U(e,t){f(e.length>0,"at least one event is required");let a=null,r=null;for(let i of e){f(i.schemaVersion===f$2,`unsupported event schema ${i.schemaVersion}`),f(i.sequence===(r?.sequence??0)+1,`event sequence ${i.sequence} is not contiguous`),f(i.previousEventDigest===(r?.digest??null),`event ${i.sequence} has an invalid previous digest`);let{digest:n,...s}=i;f(i.digest===t.digestCanonical(s),`event ${i.sequence} digest is invalid`),f(!r||i.transactionId===r.transactionId,"events cross transaction boundaries"),a=at(a,i,t),r=i;}return a}function ie(e,t,a){return {schemaVersion:g$1,transactionId:e.id,generatedAt:t,generation:e.generation,eventCount:e.eventCount,eventHeadDigest:e.eventHeadDigest,state:e.state,transactionDigest:a.digestCanonical(e)}}function B(e,t){return _e(e,t)}var T={digestCanonical:c};function it(e){let t=e.trim();if(!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(t))throw new Error(`Invalid decision transaction id: ${e}`);return t}function z(e){let a=`.workspai/decisions/${it(e)}`;return {directory:a,transaction:`${a}/transaction.json`,checkpoint:`${a}/checkpoint.json`,events:`${a}/events.jsonl`,lock:`${a}.lock`}}function nt(e,t){return e.split(/\r?\n/).filter(r=>r.trim().length>0).map((r,i)=>{try{return JSON.parse(r)}catch(n){throw new Error(`Decision event log is corrupt at ${t}:${i+1}: ${n.message}`)}})}async function qe(e,t){let a=z(t),r=await b$1(e,a.events);return r?nt(await N.readFile(r,"utf8"),r):[]}function ze(e,t){let a=z(t);return {directory:a$3(e,a.directory),transaction:a$3(e,a.transaction),checkpoint:a$3(e,a.checkpoint),events:a$3(e,a.events)}}async function st(e,t,a,r){let i=z(t.id),n=ie(t,r,T);for(let[s,c]of a.entries())a$1(c,"contracts/workspace-intelligence/decision-event.v1.json",`Decision event ${s+1}`);return b$3(i.transaction,t),b$3(i.checkpoint,n),await k$2(e,i.events,`${a.map(s=>JSON.stringify(s)).join(`
2
2
  `)}
3
3
  `),await h$1(e,i.transaction,t),await h$1(e,i.checkpoint,n),{transaction:t,checkpoint:n,events:a,paths:ze(e,t.id)}}async function Ge(e){let t=z(e.transactionId),a=a$3(e.workspacePath,t.lock);return a$4(a,async()=>{let r=await qe(e.workspacePath,e.transactionId),i=r.at(-1)??null;if((i?.digest??null)!==e.expectedHeadDigest)throw new Error(`Decision transaction head changed: expected ${e.expectedHeadDigest??"<empty>"}, observed ${i?.digest??"<empty>"}`);r.length>0&&U(r,T);let n=Ke(e.transactionId,i,e.event,T),s=[...r,n],c=U(s,T);return st(e.workspacePath,c,s,e.event.occurredAt)},{purpose:`decision:${e.transactionId}`,timeoutMs:3e4,staleMs:6e4})}async function Ne(e,t){let a=await qe(e,t);if(a.length===0)throw new Error(`Decision transaction not found: ${t}`);let r=U(a,T),i=ie(r,r.updatedAt,T);return {transaction:r,checkpoint:i,events:a,paths:ze(e,t)}}function G(e){return z(e).directory}var oe={digestCanonical:c},dt="workspai.deleted-artifact-tombstone.v1";function lt(e){let t=e.trim();if(!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(t))throw new Error(`Invalid proof-carrying change id: ${e}`);return t}function P(e){let a=`.workspai/changes/${lt(e)}`;return {directory:a,lease:`${a}/lease.json`,prediction:`${a}/predicted-overlay.json`,actualOverlay:`${a}/actual-overlay.json`,surprises:`${a}/architecture-surprises.json`,capsule:`${a}/capsule.json`,privateBaselineGraph:`${a}/private/baseline-graph.json`}}function gt(e,t){return {kind:e,id:t}}function $(e){return {role:e.role,artifact:e.artifact,schemaVersion:e.schemaVersion,digest:{algorithm:"sha256",semantics:e.semantics??"canonical-json-v1",value:e.value}}}async function I(e,t){let a=await b$1(e,t);return a?await N.readJson(a):null}async function ft(e){let a=(await I(e,s.workspaceContract.artifactPath))?.workspace?.name;if(typeof a=="string"&&a.trim())return a.trim();let r=await I(e,".workspai/workspace.json"),i=r?.workspace_name??r?.name;return typeof i=="string"&&i.trim()?i.trim():C.basename(e)}async function ce(e,t){let a=await c$2(e,t.artifact);if(!a)return false;if(t.digest.semantics==="raw-bytes-v1"){let n=await N.readFile(a);return createHash("sha256").update(n).digest("hex")===t.digest.value}let r=await N.readJson(a).catch(()=>null);return r?(t.digest.semantics==="workspace-model-structural-v1"?d$1(r):c(r))===t.digest.value:false}function Me(e){return c({schemaVersion:dt,artifact:H(e),deleted:true})}function ht(e){let t=H(e.artifact);if(!t||t==="."||t===".."||t.startsWith("../"))throw new Error(`Deleted artifact identity must be a contained relative path: ${e.artifact}`);return {artifact:t,observedAt:e.observedAt??new Date().toISOString(),digest:{algorithm:"sha256",semantics:"deletion-tombstone-v1",value:Me(t)}}}async function Le(e,t){if(t.digest.algorithm!=="sha256"||t.digest.semantics!=="deletion-tombstone-v1"||t.digest.value!==Me(t.artifact))return false;let a=await d(e,t.artifact);return a!==null&&!await N.pathExists(a)}async function pt(e,t){let a=await I(e,P(t).lease);if(!a||a.schemaVersion!==h)throw new Error(`Architecture lease is missing or unsupported for ${t}.`);if(a.changeId!==t)throw new Error(`Architecture lease binding failed for ${t}.`);return a}async function F(e){let t=await a$2(e);if(t.status==="miss")throw new Error(`A current canonical Model and Graph are required (${t.reason}). Run workspai workspace intelligence run --for-agent generic --strict --json.`);return t}function ut(e,t,a){return c({modelHash:e,graphHash:t,inputHash:a})}function Y(e){let t=d$1(e.model),a=c(e.graph),r=e.graph.source.inputs?.hash;if(!r)throw new Error("The canonical Graph has no live input fingerprint.");return {modelHash:t,graphHash:a,inputHash:r,generation:ut(t,a,r)}}async function Ue(e,t){let a=await F(e),r=Y(a);if(r.generation!==t.generation)throw new Error(`Architecture lease ${t.changeId} is stale. Expected generation ${t.generation}, observed ${r.generation}. Abort or begin a new change from current evidence.`);return a}function v(e,t,a,r,i=new Date().toISOString()){return {kind:e,payload:t,occurredAt:i,actor:gt(a,r)}}async function k(e,t,a,r){return Ge({workspacePath:e,transactionId:a,expectedHeadDigest:t?.transaction.eventHeadDigest??null,event:r})}function S(e,t,a){return `${e}\0${t}\0${a}`}function mt(e){let t=[];for(let[a,r]of [["entity",e.entities],["relation",e.relations],["proof",e.proofs]])t.push(...r.added.map(i=>({operation:"add",targetKind:a,targetId:i.id}))),t.push(...r.removed.map(i=>({operation:"remove",targetKind:a,targetId:i.id}))),t.push(...r.changed.map(i=>({operation:"change",targetKind:a,targetId:i.id})));return t.push(...e.changedArtifacts.map(a=>({operation:"change",targetKind:"artifact",targetId:a}))),t.sort((a,r)=>S(a.operation,a.targetKind,a.targetId).localeCompare(S(r.operation,r.targetKind,r.targetId)))}function yt(e){let t=e.prediction?.operations.map(o=>({operation:o.operation,targetKind:o.targetKind,targetId:o.targetId}))??[],a=mt(e.actual),r=new Set(t.map(o=>S(o.operation,o.targetKind,o.targetId))),i=new Set(a.map(o=>S(o.operation,o.targetKind,o.targetId))),n=a.filter(o=>r.has(S(o.operation,o.targetKind,o.targetId))),s=a.filter(o=>!r.has(S(o.operation,o.targetKind,o.targetId))),c=t.filter(o=>!i.has(S(o.operation,o.targetKind,o.targetId))),d=e.prediction?s.length===0&&c.length===0?"exact":s.length===0?"within-expectation":"surprising":"no-prediction";return {schemaVersion:j,changeId:e.changeId,generatedAt:e.generatedAt,prediction:e.predictionReference,actual:e.actualReference,matched:n,unpredicted:s,missing:c,summary:{predicted:t.length,actual:a.length,matched:n.length,unpredicted:s.length,missing:c.length,verdict:d}}}async function ne(e){let t=await I(e.workspacePath,e.relativePath);return t?$({role:e.role,artifact:e.relativePath,schemaVersion:e.schemaVersion,value:c(t)}):null}function wt(e){let{integrity:t,...a}=e;return a}async function de(e){let t=P(e.lease.changeId),[a,r,i]=await Promise.all([ne({workspacePath:e.workspacePath,relativePath:t.prediction,role:"prediction",schemaVersion:i$1}),ne({workspacePath:e.workspacePath,relativePath:t.actualOverlay,role:"actual-architecture-overlay",schemaVersion:a$5}),ne({workspacePath:e.workspacePath,relativePath:t.surprises,role:"architecture-surprises",schemaVersion:j})]),n=$({role:"decision-transaction",artifact:`${G(e.lease.changeId)}/transaction.json`,schemaVersion:e.record.transaction.schemaVersion,value:c(e.record.transaction)}),s=e.record.transaction.effects.flatMap(p=>p.artifacts),c$1=e.record.transaction.effects.flatMap(p=>p.deletedArtifacts??[]),d=e.record.transaction.verifications.flatMap(p=>p.artifacts),o=await I(e.workspacePath,t.actualOverlay),l=o?!se(o):false,w=[{id:"intent-bound",status:"passed",summary:"The transaction is hash-bound to its immutable Goal Pack."},{id:"baseline-pinned",status:"passed",summary:"The architecture lease pins exact Model, Graph, and live-input identities."},{id:"effects-receipted",status:e.record.transaction.effects.length>0&&e.record.transaction.effects.every(p=>p.status==="succeeded")||e.record.transaction.effects.length===0&&l?"passed":e.record.transaction.effects.length===0?"pending":"failed",summary:e.record.transaction.effects.length===0&&l?"Fresh Graph observation proves this was a no-effect change.":`${e.record.transaction.effects.length} typed effect receipt(s) are bound to the transaction ledger.`},{id:"architecture-reobserved",status:r?"passed":"pending",summary:r?"The actual architecture delta was derived from a fresh canonical Graph.":"No post-effect architecture overlay has been observed yet."},{id:"independently-verified",status:e.record.transaction.state==="committed"?"passed":e.record.transaction.verifications.some(p=>p.status==="failed")?"failed":"pending",summary:`${e.record.transaction.verifications.length} independent verification receipt(s) are recorded.`}],y=await I(e.workspacePath,t.surprises),h=[...e.record.transaction.effects.length===0&&o&&se(o)?["No typed effect receipt explains the observed architecture generation."]:[],...y?.summary.unpredicted?[`${y.summary.unpredicted} actual architecture operation(s) were not predicted.`]:[],...e.record.transaction.blockers.map(p=>p.details??p.code)],g=e.record.transaction.state==="committed"?"sealed":e.record.transaction.state==="aborted"?"aborted":e.record.transaction.state==="blocked"||e.record.transaction.state==="awaiting-human"?"blocked":e.record.transaction.state==="verifying"&&e.record.transaction.verifications.some(p=>p.status==="passed")?"verified":"open",m={schemaVersion:k$1,changeId:e.lease.changeId,goalId:e.lease.goalId,generatedAt:e.record.transaction.updatedAt,status:g,workspace:e.lease.workspace,scope:e.lease.scope,decision:{transaction:n,eventHeadDigest:e.record.transaction.eventHeadDigest,effectHeadDigest:B(e.record.transaction,oe),state:e.record.transaction.state,generation:e.record.transaction.generation},intent:e.record.transaction.intent,baseline:e.lease.baseline,prediction:a,actualOverlay:r,surpriseReport:i,effects:s,deletedArtifacts:c$1,verification:d,assurances:w,remainingUncertainty:[...new Set(h)]};return {...m,integrity:{algorithm:"sha256",semantics:"canonical-json-v1",capsuleDigest:c(m)}}}async function D(e,t,a){let r=await de({workspacePath:e,lease:t,record:a});return await h$1(e,P(t.changeId).capsule,r),r}function b(e){let t=P(e.lease.changeId),a={schemaVersion:l$1,operation:e.operation,changeId:e.lease.changeId,state:e.record.transaction.state,capsule:e.capsule,artifacts:{lease:t.lease,prediction:e.capsule.prediction?.artifact??null,actualOverlay:e.capsule.actualOverlay?.artifact??null,surpriseReport:e.capsule.surpriseReport?.artifact??null,transaction:`${G(e.lease.changeId)}/transaction.json`,events:`${G(e.lease.changeId)}/events.jsonl`,capsule:t.capsule},nextActions:e.nextActions};return a$1(a,"contracts/workspace-intelligence/change-operation-result.v1.json","Proof-Carrying Change operation result"),b$2({kind:"operation.completed",status:e.record.transaction.state==="blocked"||e.record.transaction.state==="awaiting-human"?"blocked":e.record.transaction.state==="aborted"?"cancelled":"succeeded",component:"proof-carrying-change",correlationId:e.lease.changeId,message:`${e.operation}: ${e.record.transaction.state}`,evidenceBindings:[{kind:"artifact",ref:t.capsule,role:"output",provenance:"authoritative"},{kind:"artifact",ref:`${G(e.lease.changeId)}/transaction.json`,role:"subject",provenance:"authoritative"}],attributes:{operation:e.operation,changeId:e.lease.changeId,goalId:e.lease.goalId,decisionState:e.record.transaction.state,assurancePassed:e.capsule.assurances.filter(r=>r.status==="passed").length,assuranceTotal:e.capsule.assurances.length}}),a}async function E(e,t){let a=await pt(e,t),r=await Ne(e,t);return {lease:a,record:r}}async function Yt(e){let t=C.resolve(e.workspacePath),a=await l({workspacePath:t,goalId:e.goalId,validateBindings:true}),r=a.goalPack;if(!r||!a.active)throw new Error("No active Goal Pack is available, or the named Goal is not active.");if(r.state!=="ready-to-plan")throw new Error(`Goal ${r.id} cannot begin a change while its state is ${r.state}.`);let i$1=await F(t),n=Y(i$1);if(n.modelHash!==r.sourceBinding.model.hash||(r.sourceBinding.graph.inputHash?n.inputHash!==r.sourceBinding.graph.inputHash:n.graphHash!==r.sourceBinding.graph.hash))throw new Error(`Goal ${r.id} is no longer bound to the current architecture generation.`);let s=`change-${r.intent.category}-${randomUUID().replace(/-/g,"").slice(0,16)}`,c$1=P(s),d=new Date().toISOString(),o=c(i$1.graph),l$1={schemaVersion:h,changeId:s,goalId:r.id,createdAt:d,workspace:r.workspace,scope:{kind:r.scope.kind,projects:[...r.scope.projects]},baseline:{model:$({role:"baseline-model",artifact:r.sourceBinding.model.artifact,schemaVersion:r.sourceBinding.model.schemaVersion,value:r.sourceBinding.model.hash,semantics:"workspace-model-structural-v1"}),graph:{...$({role:"baseline-graph",artifact:r.sourceBinding.graph.artifact,schemaVersion:r.sourceBinding.graph.schemaVersion,value:n.graphHash}),inputHash:n.inputHash}},generation:n.generation,semantics:"optimistic-generation-guard",privateMaterialization:{artifact:c$1.privateBaselineGraph,role:"hash-bound-baseline-cache",portable:false,authoritative:false,digest:{algorithm:"sha256",semantics:"canonical-json-v1",value:o}}};await i(t,c$1.lease,[{relativePath:c$1.privateBaselineGraph,payload:i$1.graph},{relativePath:c$1.lease,payload:l$1}]);let w=e.actorKind??"cli",y=e.actorId??"workspai-change",h$1=$({role:"intent",artifact:a.active.goalPack,schemaVersion:r.schemaVersion,value:c(r)}),g=r.successCriteria.map(_=>$({role:"success-criterion",artifact:_.id,schemaVersion:"workspai.goal-success-criterion.v1",value:c(_)})),m=await k(t,null,s,v("created",{summary:`Begin proof-carrying change for ${r.id}.`,references:[h$1,...g]},w,y,d));m=await k(t,m,s,v("scope-bound",{summary:"Bind immutable Goal scope.",scope:l$1.scope},w,y)),m=await k(t,m,s,v("evidence-attached",{summary:"Attach exact architecture generation and lease.",references:[l$1.baseline.model,{role:l$1.baseline.graph.role,artifact:l$1.baseline.graph.artifact,schemaVersion:l$1.baseline.graph.schemaVersion,digest:l$1.baseline.graph.digest},$({role:"architecture-lease",artifact:c$1.lease,schemaVersion:l$1.schemaVersion,value:c(l$1)})]},w,y)),await q({workspacePath:t,goalId:r.id,changeId:s});let p=await D(t,l$1,m);return b({operation:"begin",lease:l$1,record:m,capsule:p,nextActions:[`workspai change predict --change ${s} --file <prediction.json> --json`,`workspai change authorize --change ${s} --effects filesystem,command --json`]})}async function Xt(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId);if(await Ue(e.workspacePath,t),a.transaction.state!=="evidence-ready")throw new Error(`Prediction requires evidence-ready state, observed ${a.transaction.state}.`);let r={...e.prediction,schemaVersion:i$1,changeId:e.changeId,goalId:t.goalId,baselineGeneration:t.generation,nonCanonical:true,proofEligible:false,operations:[...e.prediction.operations].sort((c,d)=>S(c.operation,c.targetKind,c.targetId).localeCompare(S(d.operation,d.targetKind,d.targetId)))};await h$1(e.workspacePath,P(e.changeId).prediction,r);let i=$({role:"noncanonical-prediction",artifact:P(e.changeId).prediction,schemaVersion:r.schemaVersion,value:c(r)}),n=await k(e.workspacePath,a,e.changeId,v("plan-attached",{summary:"Attach an explicitly noncanonical architecture prediction.",references:[i]},e.actorKind??"agent",e.actorId??"workspai-agent")),s=await D(e.workspacePath,t,n);return b({operation:"predict",lease:t,record:n,capsule:s,nextActions:[`workspai change authorize --change ${e.changeId} --effects filesystem,command --json`]})}async function Qt(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId);if(await Ue(e.workspacePath,t),e.effectClasses.length===0)throw new Error("Authorization requires at least one effect class.");let r=await k(e.workspacePath,a,e.changeId,v("authorized",{summary:`Authorize bounded effect classes: ${e.effectClasses.join(", ")}.`,authorization:{grantedBy:e.grantedBy,grant:"bounded-effects",effectClasses:[...new Set(e.effectClasses)].sort()}},e.actorKind??"human",e.grantedBy)),i=await D(e.workspacePath,t,r);return b({operation:"authorize",lease:t,record:r,capsule:i,nextActions:[`workspai change effect record --change ${e.changeId} --file <effect-receipt.json> --json`,`workspai change verify --change ${e.changeId} --json`]})}async function Zt(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId);if(a.transaction.state!=="blocked"&&a.transaction.state!=="awaiting-human")throw new Error(`Resume requires blocked or awaiting-human state, observed ${a.transaction.state}.`);let r=await k(e.workspacePath,a,e.changeId,v("resumed",{summary:e.reason,reason:e.reason,resumeTo:e.resumeTo},"human",e.actorId)),i=await D(e.workspacePath,t,r);return b({operation:"resume",lease:t,record:r,capsule:i,nextActions:e.resumeTo==="verifying"?[`workspai change verification record --change ${e.changeId} --file <verification-receipt.json> --json`]:[`workspai change effect record --change ${e.changeId} --file <effect-receipt.json> --json`]})}async function ea(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId),r=new Set(e.receipt.artifacts.map(c=>H(c.artifact))),i=(e.receipt.deletedArtifacts??[]).map(c=>H(c.artifact));if(new Set(i).size!==i.length)throw new Error("Effect receipt contains duplicate deleted-artifact identities.");if(i.some(c=>r.has(c)))throw new Error("An effect artifact cannot be both present and deleted in one receipt.");if(i.length>0&&e.receipt.status!=="succeeded")throw new Error("Only a succeeded effect may carry deleted-artifact tombstones.");for(let c of e.receipt.artifacts)if(!await ce(e.workspacePath,c))throw new Error(`Effect artifact is missing or corrupt: ${c.artifact}`);for(let c of e.receipt.deletedArtifacts??[])if(!await Le(e.workspacePath,c))throw new Error(`Deleted effect artifact is present, outside the governed scope, or has an invalid tombstone: ${c.artifact}`);let n=await k(e.workspacePath,a,e.changeId,v("effect-recorded",{summary:e.receipt.summary,effect:e.receipt},e.actorKind??"agent",e.actorId??"workspai-agent")),s=await D(e.workspacePath,t,n);return b({operation:"effect-record",lease:t,record:n,capsule:s,nextActions:n.transaction.state==="blocked"?[`workspai change status --change ${e.changeId} --json`]:[`workspai change verify --change ${e.changeId} --json`]})}async function ta(e){let t=C.resolve(e.workspacePath),{lease:a,record:r}=await E(t,e.changeId);if(!r.transaction.requiredCriteria.includes(e.receipt.criterionId))throw new Error(`Verification criterion '${e.receipt.criterionId}' is outside the immutable Goal contract.`);let i=await F(t),n=P(e.changeId),[s,c]=await Promise.all([I(t,n.actualOverlay),I(t,n.surprises)]),d=r.transaction.verifications.some(m=>m.criterionId==="workspace-verify"&&m.status==="passed");if(!s||!c||!d)throw new Error("Domain verification can be admitted only after change verify re-observes the Graph and records a passing Workspace Verify receipt.");let o=Y(i),l=B(r.transaction,oe);if(e.receipt.target.modelHash!==o.modelHash||e.receipt.target.graphHash!==o.graphHash||e.receipt.target.effectHeadDigest!==l)throw new Error("Verification receipt does not target the current Model, Graph, and effect head.");for(let m of e.receipt.artifacts)if(!await ce(t,m))throw new Error(`Verification artifact is missing or corrupt: ${m.artifact}`);let w=e.actorKind??"ci",y=e.actorId??"workspai-verifier",h=r;if(h.transaction.state==="blocked"){if(!h.transaction.blockers.every(p=>p.code==="change.verification.criteria_missing"))throw new Error("The change is blocked by a condition that a verification receipt cannot resume.");h=await k(t,h,e.changeId,v("resumed",{summary:"Resume to admit a missing verification receipt.",resumeTo:"verifying"},w,y));}else if(h.transaction.state!=="verifying")throw new Error(`Verification receipt requires verifying or criteria-blocked state; observed ${h.transaction.state}.`);h=await k(t,h,e.changeId,v("verification-recorded",{summary:e.receipt.summary,verification:e.receipt},w,y)),h.transaction.state==="verifying"&&h.transaction.requiredCriteria.every(p=>h.transaction.verifications.filter(W=>W.criterionId===p).at(-1)?.status==="passed")&&(h=await k(t,h,e.changeId,v("committed",{summary:"Seal the independently verified proof-carrying change."},w,y)));let g=await D(t,a,h);return b({operation:"verification-record",lease:a,record:h,capsule:g,nextActions:h.transaction.state==="committed"?[`workspai change capsule validate --change ${e.changeId} --json`]:[`workspai change status --change ${e.changeId} --json`]})}function J(e,t,a,r="verification"){return $({role:r,artifact:e,schemaVersion:t,value:c(a)})}function se(e){return e.summary.entityAdds+e.summary.entityRemovals+e.summary.entityChanges+e.summary.relationAdds+e.summary.relationRemovals+e.summary.relationChanges+e.summary.proofAdds+e.summary.proofRemovals+e.summary.proofChanges>0}function H(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function We(e){let t=C.normalize(C.resolve(e));return process.platform==="win32"?t.toLowerCase():t}async function vt(e){let t=new Set(e.receiptedArtifacts.map(H)),a=new Set;for(let i of t){let n=await d(e.workspacePath,i);n&&a.add(We(n));}let r=[];for(let i of e.changedArtifacts){let n=H(i);if(t.has(n))continue;let s=await d(e.workspacePath,n);s&&a.has(We(s))||r.push(i);}return r}async function aa(e){let t=C.resolve(e.workspacePath),{lease:a$1,record:r}=await E(t,e.changeId);if(r.transaction.state!=="authorized"&&r.transaction.state!=="executing")throw new Error(`Verification requires authorized or executing state, observed ${r.transaction.state}.`);e.refresh!==false&&await c$1({workspacePath:t,strict:false,agent:"generic"});let i=await F(t),n=await I(t,a$1.privateMaterialization.artifact);if(!n||c(n)!==a$1.privateMaterialization.digest.value)throw new Error(`The hash-bound baseline materialization is missing or corrupt for ${e.changeId}.`);let s=new Date().toISOString(),c$2=a(n,i.graph,new Date(s)),d=P(e.changeId);await h$1(t,d.actualOverlay,c$2);let o=J(d.actualOverlay,c$2.schemaVersion,c$2,"actual-architecture-overlay"),l=await I(t,d.prediction),w=l?J(d.prediction,l.schemaVersion,l,"noncanonical-prediction"):null,y=yt({changeId:e.changeId,generatedAt:s,prediction:l,predictionReference:w,actual:c$2,actualReference:o});await h$1(t,d.surprises,y);let h=J(d.surprises,y.schemaVersion,y,"architecture-surprises"),g$1=r,m=e.actorKind??"cli",p=e.actorId??"workspai-change-verify";if(se(c$2)&&g$1.transaction.effects.length===0){g$1=await k(t,g$1,e.changeId,v("blocked",{summary:"Observed architecture change has no typed effect receipt.",blocker:{code:"change.effect_receipt.missing",actionable:true,details:"Record the actual mutation effect before verification can claim causality."}},m,p));let A=await D(t,a$1,g$1);return b({operation:"verify",lease:a$1,record:g$1,capsule:A,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Record missing effect receipt" --json`]})}let _=g$1.transaction.effects.filter(A=>A.status==="succeeded").flatMap(A=>[...A.artifacts.map(K=>K.artifact),...(A.deletedArtifacts??[]).map(K=>K.artifact)]),W=await vt({workspacePath:t,changedArtifacts:c$2.changedArtifacts,receiptedArtifacts:_});if(W.length>0){g$1=await k(t,g$1,e.changeId,v("blocked",{summary:"Observed architecture artifacts are not covered by typed effect receipts.",blocker:{code:"change.effect_receipt.coverage_missing",actionable:true,details:`Uncovered artifacts: ${W.slice(0,20).join(", ")}`}},m,p));let A=await D(t,a$1,g$1);return b({operation:"verify",lease:a$1,record:g$1,capsule:A,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Cover observed artifacts" --json`]})}g$1=await k(t,g$1,e.changeId,v("verification-started",{summary:"Begin independent post-effect verification."},m,p));let Be=await f$1({workspacePath:t}),Je=await g(Be,t),X=C.relative(t,Je).split(C.sep).join("/"),j=await I(t,X);if(!j)throw new Error(`Workspace Verify evidence was not persisted at ${X}.`);let O=h$2(j,{strict:e.strict===true}),ge=Y(i),fe={id:`verify-workspace-${c({generatedAt:s,verify:j,gate:O}).slice(0,16)}`,criterionId:"workspace-verify",status:O.passed?"passed":"failed",summary:O.passed?`Workspace Verify passed in ${O.mode} mode.`:`Workspace Verify blocked in ${O.mode} mode: ${O.reasons.join("; ")}`,target:{modelHash:ge.modelHash,graphHash:ge.graphHash,effectHeadDigest:B(g$1.transaction,oe)},artifacts:[J(X,j.schemaVersion,j),o,h],observedAt:s};if(g$1=await k(t,g$1,e.changeId,v("verification-recorded",{summary:fe.summary,verification:fe},m,p)),g$1.transaction.state==="verifying"){let A=g$1.transaction.requiredCriteria.filter(K=>g$1.transaction.verifications.filter(Ye=>Ye.criterionId===K).at(-1)?.status!=="passed");A.length>0?g$1=await k(t,g$1,e.changeId,v("blocked",{summary:"Required outcome verification is incomplete.",blocker:{code:"change.verification.criteria_missing",actionable:true,details:`Missing passing receipts: ${A.join(", ")}`}},m,p)):g$1=await k(t,g$1,e.changeId,v("committed",{summary:"Seal the independently verified proof-carrying change."},m,p));}let Fe=await D(t,a$1,g$1);return b({operation:"verify",lease:a$1,record:g$1,capsule:Fe,nextActions:g$1.transaction.state==="committed"?[`workspai change capsule validate --change ${e.changeId} --json`]:[`workspai change status --change ${e.changeId} --json`]})}async function ra(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId),r=await de({workspacePath:e.workspacePath,lease:t,record:a});return b({operation:e.operation??"status",lease:t,record:a,capsule:r,nextActions:a.transaction.state==="evidence-ready"?[`workspai change authorize --change ${e.changeId} --effects filesystem,command --json`]:a.transaction.state==="authorized"||a.transaction.state==="executing"?[`workspai change verify --change ${e.changeId} --json`]:[]})}async function ia(e){let t=C.resolve(e.workspacePath),a=await b$1(t,".workspai/changes","directory"),i=(a?await N.readdir(a,{withFileTypes:true}):[]).filter(d=>d.isDirectory()&&/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(d.name)).map(d=>d.name).sort(),n=[],s=null;for(let d of i)try{let{lease:o,record:l}=await E(t,d);s??=o.workspace.name;let w=await de({workspacePath:t,lease:o,record:l}),y=await le({workspacePath:t,changeId:d});n.push({changeId:d,goalId:o.goalId,state:l.transaction.state,status:w.status,createdAt:l.transaction.createdAt,updatedAt:l.transaction.updatedAt,scope:o.scope,assurance:{passed:w.assurances.filter(h=>h.status==="passed").length,total:w.assurances.length},blockers:l.transaction.blockers.map(h=>h.details??h.code),capsuleArtifact:P(d).capsule,valid:y.valid,errors:y.errors});}catch(o){n.push({changeId:d,goalId:null,state:null,status:"invalid",createdAt:null,updatedAt:null,scope:null,assurance:{passed:0,total:5},blockers:[],capsuleArtifact:P(d).capsule,valid:false,errors:[o instanceof Error?o.message:String(o)]});}n.sort((d,o)=>(o.updatedAt??"").localeCompare(d.updatedAt??"")||d.changeId.localeCompare(o.changeId));let c={schemaVersion:m,generatedAt:new Date().toISOString(),workspace:{name:s??await ft(t)},changes:n,summary:{total:n.length,open:n.filter(d=>d.status==="open"||d.status==="verified").length,blocked:n.filter(d=>d.status==="blocked").length,sealed:n.filter(d=>d.status==="sealed").length,aborted:n.filter(d=>d.status==="aborted").length,invalid:n.filter(d=>!d.valid).length}};return a$1(c,"contracts/workspace-intelligence/proof-carrying-change-list.v1.json","Proof-Carrying Change list"),c}async function na(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId),r=await k(e.workspacePath,a,e.changeId,v("aborted",{summary:e.reason,reason:e.reason},"human",e.actorId)),i=await D(e.workspacePath,t,r);return b({operation:"abort",lease:t,record:r,capsule:i,nextActions:[]})}async function le(e){let t=P(e.changeId),a=await I(e.workspacePath,t.capsule);if(!a)throw new Error(`Proof-carrying change capsule not found: ${e.changeId}`);let r=[];a.schemaVersion!==k$1&&r.push(`Unsupported capsule schema: ${a.schemaVersion}`),a.changeId!==e.changeId&&r.push("Capsule change binding does not match."),c(wt(a))!==a.integrity.capsuleDigest&&r.push("Capsule integrity digest does not match its canonical content.");let{lease:i,record:n$1}=await E(e.workspacePath,e.changeId),s=n$1.transaction.evidence.find(o=>o.role==="architecture-lease");(!s||s.digest.value!==c(i))&&r.push("Architecture lease does not match the decision-ledger evidence binding."),(i.goalId!==a.goalId||i.generation!==c({modelHash:i.baseline.model.digest.value,graphHash:i.baseline.graph.digest.value,inputHash:i.baseline.graph.inputHash}))&&r.push("Architecture lease identity or generation binding is invalid."),n$1.transaction.eventHeadDigest!==a.decision.eventHeadDigest&&r.push("Capsule does not bind the current decision event head."),c(n$1.transaction)!==a.decision.transaction.digest.value&&r.push("Decision transaction projection digest does not match the capsule.");let c$1=await I(e.workspacePath,i.privateMaterialization.artifact);(!c$1||c(c$1)!==i.privateMaterialization.digest.value)&&r.push("Hash-bound baseline materialization is missing or corrupt.");for(let o of [a.intent,a.decision.transaction,a.prediction,a.actualOverlay,a.surpriseReport,...a.effects,...a.verification].filter(l=>!!l))await ce(e.workspacePath,o)||r.push(`Referenced artifact is missing or corrupt: ${o.artifact}`);for(let o of a.deletedArtifacts??[])await Le(e.workspacePath,o)||r.push(`Deleted artifact tombstone is invalid or the artifact exists again: ${o.artifact}`);let d={schemaVersion:n,changeId:e.changeId,validatedAt:new Date().toISOString(),valid:r.length===0,errors:r,capsule:a};return a$1(d,"contracts/workspace-intelligence/proof-carrying-change-capsule-validation.v1.json","Proof-Carrying Change capsule validation"),d}async function sa(e){let t=await le(e);if(!t.valid)throw new Error(`Cannot export an invalid capsule: ${t.errors.join("; ")}`);let a=C.resolve(e.workspacePath),r=C.resolve(a,e.outputPath),i=C.relative(a,r);if(i===".."||i.startsWith(`..${C.sep}`)||C.isAbsolute(i))throw new Error("Capsule export path must remain inside the workspace.");let n=i.split(C.sep).join("/"),s=await h$1(a,n,t.capsule),c={schemaVersion:o,changeId:e.changeId,outputPath:s,validation:t};return a$1(c,"contracts/workspace-intelligence/proof-carrying-change-capsule-export.v1.json","Proof-Carrying Change capsule export"),c}function oa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Prediction input must be a JSON object.");let t=e;if(!Array.isArray(t.operations)||!Array.isArray(t.assumptions))throw new Error("Prediction input requires operations[] and assumptions[].");let a=new Set(["add","remove","change"]),r=new Set(["entity","relation","proof","artifact"]),i=new Set(["high","medium","low"]);for(let s of t.operations)if(!s||!a.has(s.operation)||!r.has(s.targetKind)||typeof s.targetId!="string"||s.targetId.trim().length===0||typeof s.rationale!="string"||!i.has(s.confidence))throw new Error("Prediction contains an invalid operation.");let n=t.predictedRisk;if(!n||!["none","low","medium","high"].includes(n))throw new Error("Prediction requires predictedRisk: none, low, medium, or high.");return {schemaVersion:i$1,changeId:t.changeId??"change-placeholder",goalId:t.goalId??"goal-placeholder",generatedAt:t.generatedAt??new Date().toISOString(),baselineGeneration:t.baselineGeneration??"pending-binding",nonCanonical:true,proofEligible:false,operations:t.operations,assumptions:t.assumptions.filter(s=>typeof s=="string"),predictedRisk:n}}function ca(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Effect receipt input must be a JSON object.");let t=e;if(typeof t.id!="string"||!["filesystem","command","configuration","dependency","external"].includes(String(t.effectClass))||!["succeeded","failed","uncertain"].includes(String(t.status))||typeof t.summary!="string"||typeof t.observedAt!="string"||typeof t.idempotencyKey!="string"||!Array.isArray(t.artifacts))throw new Error("Effect receipt is missing required typed fields.");if(t.deletedArtifacts!==void 0&&(!Array.isArray(t.deletedArtifacts)||t.deletedArtifacts.some(r=>!r||typeof r.artifact!="string"||r.observedAt!==void 0&&typeof r.observedAt!="string"||r.digest!==void 0&&(r.digest.algorithm!=="sha256"||r.digest.semantics!=="deletion-tombstone-v1"||typeof r.digest.value!="string"))))throw new Error("Effect receipt contains an invalid deleted-artifact tombstone.");let a=t;return {...a,...a.deletedArtifacts?{deletedArtifacts:a.deletedArtifacts.map(r=>r.digest?r:ht({artifact:r.artifact,observedAt:r.observedAt??a.observedAt}))}:{}}}function da(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Verification receipt input must be a JSON object.");let t=e;if(typeof t.id!="string"||typeof t.criterionId!="string"||!["passed","failed","inconclusive"].includes(String(t.status))||typeof t.summary!="string"||typeof t.observedAt!="string"||!t.target||typeof t.target.modelHash!="string"||typeof t.target.graphHash!="string"||typeof t.target.effectHeadDigest!="string"||!Array.isArray(t.artifacts))throw new Error("Verification receipt is missing required typed fields.");return t}function la(e,t){return e.decision.eventHeadDigest===t.eventHeadDigest&&e.decision.transaction.digest.value===c(t)}async function ga(e){let t=await le({workspacePath:e.workspacePath,changeId:e.changeId});if(!t.valid)throw new Error(`Proof-carrying change ${e.changeId} failed capsule validation.`);let{lease:a,record:r}=await E(e.workspacePath,e.changeId);if(a.goalId!==e.goalId||r.transaction.state!=="committed"||t.capsule.status!=="sealed")throw new Error(`Proof-carrying change ${e.changeId} is not a sealed change for ${e.goalId}.`);let i=[...r.transaction.verifications].reverse().find(n=>n.status==="passed");if(!i)throw new Error(`Proof-carrying change ${e.changeId} has no passing verification receipt.`);return {modelHash:i.target.modelHash,graphHash:i.target.graphHash}}
4
4
  export{ht as a,Yt as b,Xt as c,Qt as d,Zt as e,ea as f,ta as g,vt as h,aa as i,ra as j,ia as k,na as l,le as m,sa as n,oa as o,ca as p,da as q,la as r,ga as s};
@@ -1,2 +1,2 @@
1
- import {l}from'./chunk-UHAPXPGW.js';import {a as a$1}from'./chunk-TDQ2PRHV.js';import {b}from'./chunk-EBQS5T7Q.js';import {j}from'./chunk-BVWDG66W.js';import {b as b$1}from'./chunk-K33JJVQZ.js';import {a}from'./chunk-AFIFZTOY.js';import {c}from'./chunk-EWZZUQBR.js';import {s,t,p}from'./chunk-ODK4LCEL.js';import Pe from'crypto';import O from'fs';import M from'fs/promises';import f from'path';var le=s.projectAgentEntry.schemaVersion,L=t.projectAgentEntry,Ce="workspai.agent-bootstrap-receipt.v1",Ve="<!-- WORKSPAI:AGENT-ENTRY:START -->",Be="<!-- WORKSPAI:AGENT-ENTRY:END -->",B=["generic","codex","claude","gemini","qwen","kimi","grok","copilot","cursor","windsurf","amazon-q"],Ue=["CLAUDE.md","GEMINI.md","QWEN.md",".amazonq/rules/workspai-agent-entry.md"];function Te(t){let s=t?.trim().toLowerCase()||"generic";if(s==="orca")return "grok";if(B.includes(s))return s;throw new Error(`Unsupported agent host "${s}". Expected one of: ${B.join(", ")}.`)}function de(t){let s=t.map(c=>c.id).sort(),n=[...B].sort();if(s.length!==n.length||s.some((c,p)=>c!==n[p]))throw new Error("Project agent entry must define each supported host exactly once.")}function U(t){let{integrity:s,...n}=t;return n}function S(t){return c(t)}function Je(t$1){de(t$1.hosts);let s={schemaVersion:le,generatedAt:t$1.context.generatedAt,project:{name:t$1.context.project.name,relativePath:t$1.context.project.relativePath,...t$1.context.project.runtime?{runtime:t$1.context.project.runtime}:{},...t$1.context.project.framework?{framework:t$1.context.project.framework}:{}},workspace:{name:t$1.context.workspace.name,relationship:t$1.context.workspace.relationship,localBinding:t.projectWorkspaceLink,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},canonical:{projectContext:t.projectContextAgent,projectGrounding:".workspai/PROJECT-GROUNDING.md",projectKnowledgeGraph:t.projectKnowledgeGraphReference,goalIndex:`workspace:${t.goalIndex}`,workspaceIndex:`workspace:${p.agentIndex}`,workspaceContext:`workspace:${p.agentContext}`,workspaceModel:`workspace:${p.model}`,knowledgeGraph:`workspace:${p.knowledgeGraph}`,workspaceSkillsIndex:`workspace:${p.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json"},protocol:{mode:"canonical-first",bootstrapCommand:"workspai agent bootstrap --for-agent generic --strict --json",verifyCommand:"workspai project agent-entry verify --for-agent all --strict --json",requiredReadOrder:[L,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",t.projectContextAgent,`workspace:${t.goalIndex}`,`workspace:${p.skillsIndex}`,"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json","source:targeted-live-files"],sourcePolicy:{liveSourceAuthority:"exact-implementation",workspaceEvidenceAuthority:"identity-topology-readiness-goals",broadScanBeforeBootstrap:false,sourceMutation:"governed-only",verificationClaims:"cli-evidence-only"},degradedMode:{discloseMissingEvidence:true,allowCompleteArchitectureClaims:false,allowReadOnlySourceInspection:true}},hosts:[...t$1.hosts].sort((c,p)=>c.id.localeCompare(p.id))},n={...s,integrity:{algorithm:"sha256",projectContextHash:t$1.context.integrity.payloadHash,payloadHash:S(s),portable:true,absolutePathsEmitted:false}};if(!A(n))throw new Error("Project agent entry rejected a non-portable local path.");return a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n}function A(t){return typeof t=="string"?!(/^[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])file:\/\//i.test(t)||/(?:^|[\s("'`])\\\\[^\\\s]+[\\]/.test(t)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(t)):Array.isArray(t)?t.every(A):t&&typeof t=="object"?Object.values(t).every(A):true}async function Se(t){let s=f.join(t,L),n=JSON.parse(await M.readFile(s,"utf8"));if(a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n.integrity.payloadHash!==S(U(n)))throw new Error("Project agent entry integrity validation failed.");if(de(n.hosts),!A(n)||n.integrity.absolutePathsEmitted)throw new Error("Project agent entry contains a non-portable local path.");return n}async function Re(t$1){let s=f.join(t$1,t.projectContextAgent),n=JSON.parse(await M.readFile(s,"utf8"));a(n,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent");let c=U(n),p=Pe.createHash("sha256").update(JSON.stringify(c)).digest("hex");if(n.integrity.payloadHash!==p)throw new Error("Project context agent integrity validation failed.");if(!A(n)||n.integrity.absolutePathsEmitted)throw new Error("Project context agent contains a non-portable local path.");return n}function xe(t){return t.includes("blocked")?"blocked":t.includes("degraded")?"degraded":"ready"}async function Ye(t$1){let s=b({startPath:f.resolve(t$1.startPath??process.cwd()),strict:true,requireProjectMembership:true});if(!s?.projectPath)throw new Error("No canonically bound Workspai project was resolved.");let n=s.projectPath,c$1=s.workspacePath,p$1=await Se(n),o=await Re(n);if(p$1.integrity.projectContextHash!==o.integrity.payloadHash||p$1.project.name!==o.project.name||p$1.workspace.name!==o.workspace.name)throw new Error("Project agent entry is not bound to the current project context.");let J=t$1.forAgent?.trim().toLowerCase()||"generic",Y=J==="all",g=Y?"all":Te(J),D=g,u=Y?p$1.hosts:p$1.hosts.filter(e=>e.id===g),z=p$1.hosts.find(e=>e.id==="generic");if(u.length===0&&z&&u.push(z),u.length===0)throw new Error("Project agent entry does not define generic host coverage.");let y=[],d=(e,r,P,h)=>y.push({id:e,status:r,message:P,...h?{artifact:h}:{}});d("workspace-binding","passed","Canonical workspace membership is resolved."),d("entry-integrity","passed","Project entry manifest integrity is valid.",L),d("project-context-integrity","passed","Project context integrity and manifest binding are valid.",t.projectContextAgent);let K=[...new Set(u.flatMap(e=>e.entryFiles))].sort(),ge=K.filter(e=>!O.existsSync(f.join(n,e))),k=u.some(e=>e.status==="blocked")||ge.length>0?"blocked":u.some(e=>e.status==="degraded")?"degraded":"ready";d("host-discovery",k==="ready"?"passed":k==="degraded"?"warning":"failed",k==="ready"?`${g} has discoverable Workspai entry coverage.`:k==="degraded"?u.find(e=>e.reason)?.reason??`${g} entry coverage is degraded.`:`${g} entry coverage is missing required files.`,K[0]);let Z=[p.agentIndex,p.agentContext,p.skillsIndex,p.model,p.knowledgeGraph],R=Z.filter(e=>!O.existsSync(f.join(c$1,e)));d("canonical-evidence",R.length===0?"passed":"failed",R.length===0?"Required canonical workspace evidence is present.":`Required canonical evidence is missing: ${R.join(", ")}.`);let E=[],x=null,m=null;for(let e of Z)if(!R.includes(e))try{let r=JSON.parse(await M.readFile(f.join(c$1,e),"utf8"));b$1(e,r,e),e===p.model&&(x=r),e===p.knowledgeGraph&&(m=r);}catch{E.push(e);}d("canonical-contracts",E.length===0?"passed":"failed",E.length===0?"Canonical workspace evidence satisfies its published schemas.":`Canonical evidence failed contract validation: ${E.join(", ")}.`);let b$2=t.projectKnowledgeGraphReference,Q=f.join(n,b$2),X="failed",I="The project Knowledge Graph reference is missing.";if(O.existsSync(Q)&&m)try{let e=JSON.parse(await M.readFile(Q,"utf8"));b$1(b$2,e,b$2);let r=j(m,o.project.name),{integrity:P,...h}=e,C=m.source;e.project.name===o.project.name&&e.canonical.sourceHash===C?.hash&&e.canonical.projectionHash===c(r)&&e.integrity.payloadHash===c(h)?(X="passed",I="The project reference integrity-binds the exact current projection of canonical workspace evidence."):I="The project Knowledge Graph reference is stale or does not match the canonical project projection.";}catch{I="The project Knowledge Graph reference failed schema or integrity validation.";}d("project-knowledge-graph",X,I,b$2);let he=x?.workspace,fe=m?.workspace,ue=Array.isArray(m?.entities)?m.entities:[],me=Array.isArray(x?.projects)?x.projects:[],ee=E.length===0&&he?.name===o.workspace.name&&fe?.name===o.workspace.name&&me.some(e=>e.name===o.project.name)&&ue.some(e=>e.projectId===o.project.name);d("canonical-project-membership",ee?"passed":"failed",ee?"The project and workspace identities agree across the entry, Model, and Graph.":"The project or workspace identity is missing or inconsistent in canonical evidence.");let te=!o.intelligence.freshness.graphMatchesModel||["missing","stale"].includes(o.intelligence.freshness.model)||["missing","stale"].includes(o.intelligence.freshness.graph)?"failed":o.intelligence.freshness.model==="unknown"||o.intelligence.freshness.graph==="unknown"?"warning":"passed",j$1=false,G;if(t$1.validateLiveInputs!==false)try{let e=await a$1(c$1);j$1=e.status==="hit";let r=e.status==="hit"?"Live project inputs match the persisted Model and Knowledge Graph snapshot.":`Live project inputs require an intelligence refresh (${e.reason}).`;G={id:"live-inputs",status:j$1?"passed":"failed",message:r};}catch{G={id:"live-inputs",status:"failed",message:"Live project inputs could not be validated against canonical graph evidence."};}else G={id:"live-inputs",status:"warning",message:"Live input validation was skipped; persisted compatibility was checked only."};let $=te==="warning"&&o.intelligence.freshness.model==="unknown"&&o.intelligence.freshness.graph==="fresh"&&o.intelligence.freshness.graphMatchesModel&&j$1?"passed":te;d("persisted-freshness",$,$==="passed"?o.intelligence.freshness.model==="unknown"?"Model and Graph bindings are current; live input validation closes structural freshness while verify-before-use facts remain individually governed.":"Persisted Model and Knowledge Graph bindings are current.":$==="warning"?"Persisted evidence is compatible, but at least one freshness state is unknown.":"Persisted Model or Knowledge Graph evidence is missing, stale, or mismatched."),y.push(G);let i={present:false,appliesToProject:false,status:"none"},_=[],we=f.join(c$1,t.goalIndex);if(O.existsSync(we)){let e=null;try{e=await l({workspacePath:c$1,validateBindings:false});}catch{_.push("workspai goal --list --json"),d("active-goal","failed","The Goal index is present but invalid.");}if(e?.active&&(i={present:true,appliesToProject:e.active.scope.projects.includes(o.project.name),status:"invalid",id:e.active.id,objective:e.active.objective,lifecycle:e.active.lifecycle,goalPack:`workspace:${e.active.goalPack}`,agentHandoff:`workspace:${e.active.agentHandoff}`}),e)try{let r=await l({workspacePath:c$1,validateBindings:true});r.active&&(i={present:true,appliesToProject:r.active.scope.projects.includes(o.project.name),status:"ready",id:r.active.id,objective:r.active.objective,lifecycle:r.active.lifecycle,goalPack:`workspace:${r.active.goalPack}`,agentHandoff:`workspace:${r.active.agentHandoff}`}),d("active-goal","passed",r.active?"The active Goal Pack and agent handoff have valid canonical bindings.":"No active Goal Pack is selected.");}catch(r){let P=r instanceof Error?r.message:String(r),h=i.present&&/\bstale\b|--refresh/i.test(P);if(i.present&&(i.status=h?"stale":"invalid"),h&&i.objective){let w=e.active,ve=w?.scope.kind==="project"&&w.scope.projects.length===1?`project:${w.scope.projects[0]}`:w?.scope.kind==="project-set"&&w.scope.projects.length>1?`projects:${w.scope.projects.join(",")}`:"workspace";_.push(`workspai goal ${JSON.stringify(i.objective)} --scope ${ve} --for-agent generic --refresh --json`);}else _.push("workspai goal --status --json");let C=!i.present||i.appliesToProject;d("active-goal",C?"failed":"warning",h?C?"The selected Goal Pack is present but stale; regenerate it against current canonical evidence before acting.":"The selected Goal Pack is stale, but it does not apply to this project; current project evidence remains usable while the Goal is refreshed for its own scope.":i.present?C?"The selected Goal Pack is present but its canonical binding or handoff is invalid.":"The selected Goal Pack has an invalid canonical binding, but it does not apply to this project; current project evidence remains usable while the Goal is repaired for its own scope.":"The Goal index could not be validated.");}}else d("active-goal","passed","No Goal index is present for this workspace.");let oe=y.filter(e=>e.id!=="active-goal"),W=oe.some(e=>e.status==="failed")?"blocked":oe.some(e=>e.status==="warning")?"degraded":"ready",ye=y.some(e=>e.id==="active-goal"&&e.status==="failed")?"blocked":y.some(e=>e.id==="active-goal"&&e.status==="warning")?"degraded":"ready",N=xe([k,W,ye]),v=o.blockers.some(e=>e.severity==="error")?"blocked":o.blockers.length>0?"degraded":"ready",ke=v==="blocked"?"blocked":v==="degraded"?"degraded":"not-verified",je=`command:workspai agent bootstrap --for-agent ${g} --strict --json`,Ae=p$1.protocol.requiredReadOrder.map(e=>e==="command:workspai agent bootstrap --for-agent generic --strict --json"?je:e),ne={schemaVersion:Ce,generatedAt:(t$1.now??new Date).toISOString(),status:N,statusScope:"agent-grounding",readiness:{agentGrounding:N,architectureEvidence:W,projectEnvironment:v,release:ke},requestedAgent:D,resolvedHost:g,project:{name:o.project.name,relativePath:o.project.relativePath,...o.project.runtime?{runtime:o.project.runtime}:{},...o.project.framework?{framework:o.project.framework}:{}},workspace:{name:o.workspace.name,relationship:o.workspace.relationship,resolved:true,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},entry:{artifact:L,schemaVersion:le,hostStatus:k,entryFiles:K},canonicalEvidence:{projectContext:t.projectContextAgent,projectKnowledgeGraph:t.projectKnowledgeGraphReference,workspaceIndex:`workspace:${p.agentIndex}`,workspaceContext:`workspace:${p.agentContext}`,workspaceModel:`workspace:${p.model}`,knowledgeGraph:`workspace:${p.knowledgeGraph}`,workspaceSkillsIndex:`workspace:${p.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json",modelFreshness:j$1?"fresh":o.intelligence.freshness.model,graphFreshness:j$1?"fresh":o.intelligence.freshness.graph,graphMatchesModel:o.intelligence.freshness.graphMatchesModel,liveInputsValidated:j$1,blockerCount:o.blockers.length},activeGoal:i,requiredReadOrder:Ae,claims:{architecture:W==="ready"?"allowed-with-citations":"prohibited",sourceInspection:"bounded-and-targeted",sourceMutation:"governed-cli-transaction-only",verification:"cli-evidence-only"},checks:y,nextActions:N==="ready"?[...i.present&&i.appliesToProject&&i.agentHandoff?[`read:${i.agentHandoff}`]:[],...v==="blocked"?["workspai doctor project --json","workspai workspace explain release-blocked --json"]:v==="degraded"?["workspai doctor project --json"]:[],`workspai workspace graph search <task-query> --scope project:${o.project.name} --limit 12 --json`,"inspect only the returned proof paths and target source files"]:[..._,"workspai workspace intelligence run --for-agent generic --strict --json",`workspai agent bootstrap --for-agent ${g} --strict --json`]},re=S(U(p$1)),Ee=S({manifestHash:re,projectContextHash:o.integrity.payloadHash,requestedAgent:D,status:N,generatedAt:ne.generatedAt}),se={...ne,receiptId:Ee},F={...se,integrity:{algorithm:"sha256",manifestHash:re,projectContextHash:o.integrity.payloadHash,payloadHash:S(se),portable:true,absolutePathsEmitted:false}};if(!A(F))throw new Error("Agent bootstrap receipt rejected a non-portable local path.");return a(F,"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json","Agent bootstrap receipt"),F}
1
+ import {l}from'./chunk-5NL53T5C.js';import {a as a$1}from'./chunk-TDQ2PRHV.js';import {b}from'./chunk-EBQS5T7Q.js';import {j}from'./chunk-BVWDG66W.js';import {b as b$1}from'./chunk-K33JJVQZ.js';import {a}from'./chunk-AFIFZTOY.js';import {c}from'./chunk-EWZZUQBR.js';import {s,t,p}from'./chunk-ODK4LCEL.js';import Pe from'crypto';import O from'fs';import M from'fs/promises';import f from'path';var le=s.projectAgentEntry.schemaVersion,L=t.projectAgentEntry,Ce="workspai.agent-bootstrap-receipt.v1",Ve="<!-- WORKSPAI:AGENT-ENTRY:START -->",Be="<!-- WORKSPAI:AGENT-ENTRY:END -->",B=["generic","codex","claude","gemini","qwen","kimi","grok","copilot","cursor","windsurf","amazon-q"],Ue=["CLAUDE.md","GEMINI.md","QWEN.md",".amazonq/rules/workspai-agent-entry.md"];function Te(t){let s=t?.trim().toLowerCase()||"generic";if(s==="orca")return "grok";if(B.includes(s))return s;throw new Error(`Unsupported agent host "${s}". Expected one of: ${B.join(", ")}.`)}function de(t){let s=t.map(c=>c.id).sort(),n=[...B].sort();if(s.length!==n.length||s.some((c,p)=>c!==n[p]))throw new Error("Project agent entry must define each supported host exactly once.")}function U(t){let{integrity:s,...n}=t;return n}function S(t){return c(t)}function Je(t$1){de(t$1.hosts);let s={schemaVersion:le,generatedAt:t$1.context.generatedAt,project:{name:t$1.context.project.name,relativePath:t$1.context.project.relativePath,...t$1.context.project.runtime?{runtime:t$1.context.project.runtime}:{},...t$1.context.project.framework?{framework:t$1.context.project.framework}:{}},workspace:{name:t$1.context.workspace.name,relationship:t$1.context.workspace.relationship,localBinding:t.projectWorkspaceLink,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},canonical:{projectContext:t.projectContextAgent,projectGrounding:".workspai/PROJECT-GROUNDING.md",projectKnowledgeGraph:t.projectKnowledgeGraphReference,goalIndex:`workspace:${t.goalIndex}`,workspaceIndex:`workspace:${p.agentIndex}`,workspaceContext:`workspace:${p.agentContext}`,workspaceModel:`workspace:${p.model}`,knowledgeGraph:`workspace:${p.knowledgeGraph}`,workspaceSkillsIndex:`workspace:${p.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json"},protocol:{mode:"canonical-first",bootstrapCommand:"workspai agent bootstrap --for-agent generic --strict --json",verifyCommand:"workspai project agent-entry verify --for-agent all --strict --json",requiredReadOrder:[L,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",t.projectContextAgent,`workspace:${t.goalIndex}`,`workspace:${p.skillsIndex}`,"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json","source:targeted-live-files"],sourcePolicy:{liveSourceAuthority:"exact-implementation",workspaceEvidenceAuthority:"identity-topology-readiness-goals",broadScanBeforeBootstrap:false,sourceMutation:"governed-only",verificationClaims:"cli-evidence-only"},degradedMode:{discloseMissingEvidence:true,allowCompleteArchitectureClaims:false,allowReadOnlySourceInspection:true}},hosts:[...t$1.hosts].sort((c,p)=>c.id.localeCompare(p.id))},n={...s,integrity:{algorithm:"sha256",projectContextHash:t$1.context.integrity.payloadHash,payloadHash:S(s),portable:true,absolutePathsEmitted:false}};if(!A(n))throw new Error("Project agent entry rejected a non-portable local path.");return a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n}function A(t){return typeof t=="string"?!(/^[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])file:\/\//i.test(t)||/(?:^|[\s("'`])\\\\[^\\\s]+[\\]/.test(t)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(t)):Array.isArray(t)?t.every(A):t&&typeof t=="object"?Object.values(t).every(A):true}async function Se(t){let s=f.join(t,L),n=JSON.parse(await M.readFile(s,"utf8"));if(a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n.integrity.payloadHash!==S(U(n)))throw new Error("Project agent entry integrity validation failed.");if(de(n.hosts),!A(n)||n.integrity.absolutePathsEmitted)throw new Error("Project agent entry contains a non-portable local path.");return n}async function Re(t$1){let s=f.join(t$1,t.projectContextAgent),n=JSON.parse(await M.readFile(s,"utf8"));a(n,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent");let c=U(n),p=Pe.createHash("sha256").update(JSON.stringify(c)).digest("hex");if(n.integrity.payloadHash!==p)throw new Error("Project context agent integrity validation failed.");if(!A(n)||n.integrity.absolutePathsEmitted)throw new Error("Project context agent contains a non-portable local path.");return n}function xe(t){return t.includes("blocked")?"blocked":t.includes("degraded")?"degraded":"ready"}async function Ye(t$1){let s=b({startPath:f.resolve(t$1.startPath??process.cwd()),strict:true,requireProjectMembership:true});if(!s?.projectPath)throw new Error("No canonically bound Workspai project was resolved.");let n=s.projectPath,c$1=s.workspacePath,p$1=await Se(n),o=await Re(n);if(p$1.integrity.projectContextHash!==o.integrity.payloadHash||p$1.project.name!==o.project.name||p$1.workspace.name!==o.workspace.name)throw new Error("Project agent entry is not bound to the current project context.");let J=t$1.forAgent?.trim().toLowerCase()||"generic",Y=J==="all",g=Y?"all":Te(J),D=g,u=Y?p$1.hosts:p$1.hosts.filter(e=>e.id===g),z=p$1.hosts.find(e=>e.id==="generic");if(u.length===0&&z&&u.push(z),u.length===0)throw new Error("Project agent entry does not define generic host coverage.");let y=[],d=(e,r,P,h)=>y.push({id:e,status:r,message:P,...h?{artifact:h}:{}});d("workspace-binding","passed","Canonical workspace membership is resolved."),d("entry-integrity","passed","Project entry manifest integrity is valid.",L),d("project-context-integrity","passed","Project context integrity and manifest binding are valid.",t.projectContextAgent);let K=[...new Set(u.flatMap(e=>e.entryFiles))].sort(),ge=K.filter(e=>!O.existsSync(f.join(n,e))),k=u.some(e=>e.status==="blocked")||ge.length>0?"blocked":u.some(e=>e.status==="degraded")?"degraded":"ready";d("host-discovery",k==="ready"?"passed":k==="degraded"?"warning":"failed",k==="ready"?`${g} has discoverable Workspai entry coverage.`:k==="degraded"?u.find(e=>e.reason)?.reason??`${g} entry coverage is degraded.`:`${g} entry coverage is missing required files.`,K[0]);let Z=[p.agentIndex,p.agentContext,p.skillsIndex,p.model,p.knowledgeGraph],R=Z.filter(e=>!O.existsSync(f.join(c$1,e)));d("canonical-evidence",R.length===0?"passed":"failed",R.length===0?"Required canonical workspace evidence is present.":`Required canonical evidence is missing: ${R.join(", ")}.`);let E=[],x=null,m=null;for(let e of Z)if(!R.includes(e))try{let r=JSON.parse(await M.readFile(f.join(c$1,e),"utf8"));b$1(e,r,e),e===p.model&&(x=r),e===p.knowledgeGraph&&(m=r);}catch{E.push(e);}d("canonical-contracts",E.length===0?"passed":"failed",E.length===0?"Canonical workspace evidence satisfies its published schemas.":`Canonical evidence failed contract validation: ${E.join(", ")}.`);let b$2=t.projectKnowledgeGraphReference,Q=f.join(n,b$2),X="failed",I="The project Knowledge Graph reference is missing.";if(O.existsSync(Q)&&m)try{let e=JSON.parse(await M.readFile(Q,"utf8"));b$1(b$2,e,b$2);let r=j(m,o.project.name),{integrity:P,...h}=e,C=m.source;e.project.name===o.project.name&&e.canonical.sourceHash===C?.hash&&e.canonical.projectionHash===c(r)&&e.integrity.payloadHash===c(h)?(X="passed",I="The project reference integrity-binds the exact current projection of canonical workspace evidence."):I="The project Knowledge Graph reference is stale or does not match the canonical project projection.";}catch{I="The project Knowledge Graph reference failed schema or integrity validation.";}d("project-knowledge-graph",X,I,b$2);let he=x?.workspace,fe=m?.workspace,ue=Array.isArray(m?.entities)?m.entities:[],me=Array.isArray(x?.projects)?x.projects:[],ee=E.length===0&&he?.name===o.workspace.name&&fe?.name===o.workspace.name&&me.some(e=>e.name===o.project.name)&&ue.some(e=>e.projectId===o.project.name);d("canonical-project-membership",ee?"passed":"failed",ee?"The project and workspace identities agree across the entry, Model, and Graph.":"The project or workspace identity is missing or inconsistent in canonical evidence.");let te=!o.intelligence.freshness.graphMatchesModel||["missing","stale"].includes(o.intelligence.freshness.model)||["missing","stale"].includes(o.intelligence.freshness.graph)?"failed":o.intelligence.freshness.model==="unknown"||o.intelligence.freshness.graph==="unknown"?"warning":"passed",j$1=false,G;if(t$1.validateLiveInputs!==false)try{let e=await a$1(c$1);j$1=e.status==="hit";let r=e.status==="hit"?"Live project inputs match the persisted Model and Knowledge Graph snapshot.":`Live project inputs require an intelligence refresh (${e.reason}).`;G={id:"live-inputs",status:j$1?"passed":"failed",message:r};}catch{G={id:"live-inputs",status:"failed",message:"Live project inputs could not be validated against canonical graph evidence."};}else G={id:"live-inputs",status:"warning",message:"Live input validation was skipped; persisted compatibility was checked only."};let $=te==="warning"&&o.intelligence.freshness.model==="unknown"&&o.intelligence.freshness.graph==="fresh"&&o.intelligence.freshness.graphMatchesModel&&j$1?"passed":te;d("persisted-freshness",$,$==="passed"?o.intelligence.freshness.model==="unknown"?"Model and Graph bindings are current; live input validation closes structural freshness while verify-before-use facts remain individually governed.":"Persisted Model and Knowledge Graph bindings are current.":$==="warning"?"Persisted evidence is compatible, but at least one freshness state is unknown.":"Persisted Model or Knowledge Graph evidence is missing, stale, or mismatched."),y.push(G);let i={present:false,appliesToProject:false,status:"none"},_=[],we=f.join(c$1,t.goalIndex);if(O.existsSync(we)){let e=null;try{e=await l({workspacePath:c$1,validateBindings:false});}catch{_.push("workspai goal --list --json"),d("active-goal","failed","The Goal index is present but invalid.");}if(e?.active&&(i={present:true,appliesToProject:e.active.scope.projects.includes(o.project.name),status:"invalid",id:e.active.id,objective:e.active.objective,lifecycle:e.active.lifecycle,goalPack:`workspace:${e.active.goalPack}`,agentHandoff:`workspace:${e.active.agentHandoff}`}),e)try{let r=await l({workspacePath:c$1,validateBindings:true});r.active&&(i={present:true,appliesToProject:r.active.scope.projects.includes(o.project.name),status:"ready",id:r.active.id,objective:r.active.objective,lifecycle:r.active.lifecycle,goalPack:`workspace:${r.active.goalPack}`,agentHandoff:`workspace:${r.active.agentHandoff}`}),d("active-goal","passed",r.active?"The active Goal Pack and agent handoff have valid canonical bindings.":"No active Goal Pack is selected.");}catch(r){let P=r instanceof Error?r.message:String(r),h=i.present&&/\bstale\b|--refresh/i.test(P);if(i.present&&(i.status=h?"stale":"invalid"),h&&i.objective){let w=e.active,ve=w?.scope.kind==="project"&&w.scope.projects.length===1?`project:${w.scope.projects[0]}`:w?.scope.kind==="project-set"&&w.scope.projects.length>1?`projects:${w.scope.projects.join(",")}`:"workspace";_.push(`workspai goal ${JSON.stringify(i.objective)} --scope ${ve} --for-agent generic --refresh --json`);}else _.push("workspai goal --status --json");let C=!i.present||i.appliesToProject;d("active-goal",C?"failed":"warning",h?C?"The selected Goal Pack is present but stale; regenerate it against current canonical evidence before acting.":"The selected Goal Pack is stale, but it does not apply to this project; current project evidence remains usable while the Goal is refreshed for its own scope.":i.present?C?"The selected Goal Pack is present but its canonical binding or handoff is invalid.":"The selected Goal Pack has an invalid canonical binding, but it does not apply to this project; current project evidence remains usable while the Goal is repaired for its own scope.":"The Goal index could not be validated.");}}else d("active-goal","passed","No Goal index is present for this workspace.");let oe=y.filter(e=>e.id!=="active-goal"),W=oe.some(e=>e.status==="failed")?"blocked":oe.some(e=>e.status==="warning")?"degraded":"ready",ye=y.some(e=>e.id==="active-goal"&&e.status==="failed")?"blocked":y.some(e=>e.id==="active-goal"&&e.status==="warning")?"degraded":"ready",N=xe([k,W,ye]),v=o.blockers.some(e=>e.severity==="error")?"blocked":o.blockers.length>0?"degraded":"ready",ke=v==="blocked"?"blocked":v==="degraded"?"degraded":"not-verified",je=`command:workspai agent bootstrap --for-agent ${g} --strict --json`,Ae=p$1.protocol.requiredReadOrder.map(e=>e==="command:workspai agent bootstrap --for-agent generic --strict --json"?je:e),ne={schemaVersion:Ce,generatedAt:(t$1.now??new Date).toISOString(),status:N,statusScope:"agent-grounding",readiness:{agentGrounding:N,architectureEvidence:W,projectEnvironment:v,release:ke},requestedAgent:D,resolvedHost:g,project:{name:o.project.name,relativePath:o.project.relativePath,...o.project.runtime?{runtime:o.project.runtime}:{},...o.project.framework?{framework:o.project.framework}:{}},workspace:{name:o.workspace.name,relationship:o.workspace.relationship,resolved:true,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},entry:{artifact:L,schemaVersion:le,hostStatus:k,entryFiles:K},canonicalEvidence:{projectContext:t.projectContextAgent,projectKnowledgeGraph:t.projectKnowledgeGraphReference,workspaceIndex:`workspace:${p.agentIndex}`,workspaceContext:`workspace:${p.agentContext}`,workspaceModel:`workspace:${p.model}`,knowledgeGraph:`workspace:${p.knowledgeGraph}`,workspaceSkillsIndex:`workspace:${p.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json",modelFreshness:j$1?"fresh":o.intelligence.freshness.model,graphFreshness:j$1?"fresh":o.intelligence.freshness.graph,graphMatchesModel:o.intelligence.freshness.graphMatchesModel,liveInputsValidated:j$1,blockerCount:o.blockers.length},activeGoal:i,requiredReadOrder:Ae,claims:{architecture:W==="ready"?"allowed-with-citations":"prohibited",sourceInspection:"bounded-and-targeted",sourceMutation:"governed-cli-transaction-only",verification:"cli-evidence-only"},checks:y,nextActions:N==="ready"?[...i.present&&i.appliesToProject&&i.agentHandoff?[`read:${i.agentHandoff}`]:[],...v==="blocked"?["workspai doctor project --json","workspai workspace explain release-blocked --json"]:v==="degraded"?["workspai doctor project --json"]:[],`workspai workspace graph search <task-query> --scope project:${o.project.name} --limit 12 --json`,"inspect only the returned proof paths and target source files"]:[..._,"workspai workspace intelligence run --for-agent generic --strict --json",`workspai agent bootstrap --for-agent ${g} --strict --json`]},re=S(U(p$1)),Ee=S({manifestHash:re,projectContextHash:o.integrity.payloadHash,requestedAgent:D,status:N,generatedAt:ne.generatedAt}),se={...ne,receiptId:Ee},F={...se,integrity:{algorithm:"sha256",manifestHash:re,projectContextHash:o.integrity.payloadHash,payloadHash:S(se),portable:true,absolutePathsEmitted:false}};if(!A(F))throw new Error("Agent bootstrap receipt rejected a non-portable local path.");return a(F,"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json","Agent bootstrap receipt"),F}
2
2
  export{le as a,L as b,Ce as c,Ve as d,Be as e,B as f,Ue as g,Te as h,Je as i,Ye as j};