workspai 0.78.0 → 0.79.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 (75) hide show
  1. package/README.md +117 -236
  2. package/contracts/create-planner-capabilities.v1.json +1 -1
  3. package/dist/analyze-SKOIUD6F.js +1 -0
  4. package/dist/autopilot-release-E7ADQH2B.js +1 -0
  5. package/dist/{chunk-5FVREPQC.js → chunk-2ZVE7VE2.js} +1 -1
  6. package/dist/{chunk-4KAYWMNE.js → chunk-3O344BX3.js} +1 -1
  7. package/dist/{chunk-HMWZWT7B.js → chunk-5MRDPZU7.js} +1 -1
  8. package/dist/{chunk-RJESUJQF.js → chunk-5NS322HT.js} +28 -28
  9. package/dist/{chunk-B6FJ6RG6.js → chunk-6CZQXEZ7.js} +1 -1
  10. package/dist/{chunk-75WJOYWT.js → chunk-CAGOLU4Q.js} +1 -1
  11. package/dist/{chunk-2CUT4GLE.js → chunk-DYSFGHV5.js} +1 -1
  12. package/dist/{chunk-4AAXIWYY.js → chunk-ETTZXKAS.js} +1 -1
  13. package/dist/{chunk-FLAGHVSH.js → chunk-FJMUBFXO.js} +1 -1
  14. package/dist/{chunk-RHF2IZOW.js → chunk-GIP7YFWR.js} +1 -1
  15. package/dist/{chunk-YWC5MKIL.js → chunk-IF2OWXNY.js} +1 -1
  16. package/dist/{chunk-UVIBPWOG.js → chunk-L3O2QXKH.js} +2 -2
  17. package/dist/{chunk-ONUFNCRN.js → chunk-LQYMYRGI.js} +1 -1
  18. package/dist/{chunk-YHQK4S3H.js → chunk-MJYWGRCY.js} +1 -1
  19. package/dist/{chunk-MN5S462C.js → chunk-MNZAJ6PP.js} +1 -1
  20. package/dist/{chunk-VRZAN3WS.js → chunk-NZQKHGPE.js} +1 -1
  21. package/dist/{chunk-QDM6TWFK.js → chunk-O4TZKLEC.js} +1 -1
  22. package/dist/{chunk-5OKNWBAN.js → chunk-R7R5FX4B.js} +1 -1
  23. package/dist/{chunk-HB3ZYG2Z.js → chunk-RRZQPFFR.js} +69 -60
  24. package/dist/{chunk-VEMGICT4.js → chunk-SKHRUHXO.js} +1 -1
  25. package/dist/{chunk-AMGIXK6Z.js → chunk-TQW2SZHH.js} +1 -1
  26. package/dist/{chunk-TJRVWVAZ.js → chunk-U5WP4HDH.js} +1 -1
  27. package/dist/{chunk-QMNJTI65.js → chunk-VT4WPXTO.js} +1 -1
  28. package/dist/chunk-WJKQTX4V.js +2 -0
  29. package/dist/{chunk-MD4CHXV3.js → chunk-WU5M6UP7.js} +1 -1
  30. package/dist/{chunk-IQJL3LBM.js → chunk-ZONAHZBG.js} +1 -1
  31. package/dist/{chunk-ZQ36CTLF.js → chunk-ZXYTWF2R.js} +1 -1
  32. package/dist/{create-WB5YQ7C6.js → create-2ETTECFU.js} +1 -1
  33. package/dist/{doctor-HOSHQ7II.js → doctor-3F7OUVYQ.js} +1 -1
  34. package/dist/{goal-interactive-selection-6YJOK4WC.js → goal-interactive-selection-EMHAM5TM.js} +1 -1
  35. package/dist/{goal-lifecycle-UEJMTUFV.js → goal-lifecycle-PR5O7T6B.js} +1 -1
  36. package/dist/{goal-pack-YGZMG3RQ.js → goal-pack-TEK2PHAV.js} +1 -1
  37. package/dist/index.js +159 -159
  38. package/dist/{pipeline-Z4JOJ4PX.js → pipeline-E6YY65GU.js} +1 -1
  39. package/dist/{project-agent-entry-ZMDQWJ6I.js → project-agent-entry-MXAHZSQR.js} +1 -1
  40. package/dist/{project-intelligence-lens-FSWQKY3E.js → project-intelligence-lens-IUM66OV2.js} +1 -1
  41. package/dist/{proof-carrying-change-M2RNYQ7E.js → proof-carrying-change-XA5HRGSB.js} +1 -1
  42. package/dist/{verified-goal-UAUCEDZZ.js → verified-goal-V5OVULY7.js} +1 -1
  43. package/dist/{workspace-J5QYWAE3.js → workspace-XVPKQG5W.js} +1 -1
  44. package/dist/{workspace-agent-sync-GLG36KQZ.js → workspace-agent-sync-46L7ZOQQ.js} +1 -1
  45. package/dist/{workspace-context-BZV4ZFKZ.js → workspace-context-VVZARI5K.js} +1 -1
  46. package/dist/{workspace-contract-XDNIB5JX.js → workspace-contract-N2BJCAJ7.js} +1 -1
  47. package/dist/{workspace-explain-V3XDMONQ.js → workspace-explain-5WKK6ENK.js} +1 -1
  48. package/dist/{workspace-foundation-EDTKW2RB.js → workspace-foundation-PZNZWUJ4.js} +1 -1
  49. package/dist/{workspace-graph-stream-UPASFCAF.js → workspace-graph-stream-26ME2JJS.js} +1 -1
  50. package/dist/{workspace-intelligence-24MZRG2S.js → workspace-intelligence-ZTET7JHS.js} +1 -1
  51. package/dist/{workspace-intelligence-runner-HISKHQLG.js → workspace-intelligence-runner-NZFRFCPN.js} +1 -1
  52. package/dist/{workspace-knowledge-graph-5EECTGXQ.js → workspace-knowledge-graph-4RSZTEFJ.js} +1 -1
  53. package/dist/workspace-knowledge-graph-snapshot-UTJHALST.js +1 -0
  54. package/dist/{workspace-mcp-serve-S3TWO4RI.js → workspace-mcp-serve-TIYCW364.js} +1 -1
  55. package/dist/{workspace-model-J757KSDE.js → workspace-model-LBICKRVI.js} +1 -1
  56. package/dist/{workspace-onboarding-3TLME4HP.js → workspace-onboarding-WUO6KCLF.js} +1 -1
  57. package/dist/{workspace-registry-summary-ZC5CFZXP.js → workspace-registry-summary-3PXZENLC.js} +1 -1
  58. package/dist/{workspace-repair-engine-C26C7OIB.js → workspace-repair-engine-V4Z7TJGS.js} +1 -1
  59. package/dist/workspace-run-T65CCZIN.js +1 -0
  60. package/dist/{workspace-verify-KFBWQ37C.js → workspace-verify-UQWAFGNQ.js} +1 -1
  61. package/dist/{workspace-watch-LNP5JPD4.js → workspace-watch-BKIZQ2SM.js} +1 -1
  62. package/docs/README.md +48 -116
  63. package/docs/agent-framework-adapters.md +32 -26
  64. package/docs/ci-workflows.md +8 -2
  65. package/docs/commands-reference.md +13 -12
  66. package/docs/create-planner-capabilities.md +1 -1
  67. package/docs/creating-workspaces-and-projects.md +29 -22
  68. package/docs/model-gateways.md +23 -23
  69. package/package.json +2 -2
  70. package/dist/analyze-X76YV667.js +0 -1
  71. package/dist/autopilot-release-6OV2FLRS.js +0 -1
  72. package/dist/chunk-3PGXGAHC.js +0 -2
  73. package/dist/workspace-knowledge-graph-snapshot-T6ZJGWLC.js +0 -1
  74. package/dist/workspace-run-2KBTMGG7.js +0 -1
  75. /package/dist/{chunk-QLHRGWUW.js → chunk-GOOY7I36.js} +0 -0
@@ -1,2 +1,2 @@
1
- import {r,m,n,l}from'./chunk-QDM6TWFK.js';import {a}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {d as d$1}from'./chunk-MD4CHXV3.js';import {h as h$1}from'./chunk-BLEIUQL6.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {e,d,b as b$1}from'./chunk-EWZZUQBR.js';import {q,p}from'./chunk-ODK4LCEL.js';import k from'path';import V from'fs-extra';import {spawnSync}from'child_process';function ue(){let e={...process.env};return delete e.GIT_DIR,delete e.GIT_WORK_TREE,delete e.GIT_INDEX_FILE,delete e.GIT_PREFIX,e}function x(e,t,a){let r=spawnSync("git",t,{cwd:e,env:ue(),encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(r.status!==0)return {ok:false,stdout:""};let i=r.stdout??"";return {ok:true,stdout:a?.preserveWhitespace?i:i.trim()}}function ge(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return t===".workspai/AGENT-GROUNDING.md"?true:[".workspai/reports/",".workspai/cache/",".rapidkit/reports/",".rapidkit/cache/"].some(a=>t.startsWith(a))}function ke(e){let t=[],a=[],r=[];for(let i of e.split(`
1
+ import {r,m,n,l}from'./chunk-O4TZKLEC.js';import {a}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {d as d$1}from'./chunk-WU5M6UP7.js';import {h as h$1}from'./chunk-BLEIUQL6.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {e,d,b as b$1}from'./chunk-EWZZUQBR.js';import {q,p}from'./chunk-ODK4LCEL.js';import k from'path';import V from'fs-extra';import {spawnSync}from'child_process';function ue(){let e={...process.env};return delete e.GIT_DIR,delete e.GIT_WORK_TREE,delete e.GIT_INDEX_FILE,delete e.GIT_PREFIX,e}function x(e,t,a){let r=spawnSync("git",t,{cwd:e,env:ue(),encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(r.status!==0)return {ok:false,stdout:""};let i=r.stdout??"";return {ok:true,stdout:a?.preserveWhitespace?i:i.trim()}}function ge(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return t===".workspai/AGENT-GROUNDING.md"?true:[".workspai/reports/",".workspai/cache/",".rapidkit/reports/",".rapidkit/cache/"].some(a=>t.startsWith(a))}function ke(e){let t=[],a=[],r=[];for(let i of e.split(`
2
2
  `)){if(!i.trim())continue;let n=i.slice(0,2),c=i.slice(3).trim();if(c&&!ge(c)){if(n==="??"){a.push(c);continue}n.includes("D")&&r.push(c),t.push(c);}}return {changedFiles:[...new Set(t)].sort(),untrackedFiles:[...new Set(a)].sort(),deletedFiles:[...new Set(r)].sort()}}function Q(e,t){let a={available:false,dirty:false,changedFiles:[],untrackedFiles:[],deletedFiles:[]},r=x(e,["rev-parse","--is-inside-work-tree"]);if(!r.ok||r.stdout!=="true")return a;let i=x(e,["rev-parse","--abbrev-ref","HEAD"]),n=x(e,["rev-parse","HEAD"]),c=x(e,["status","--porcelain=v1","--untracked-files=all"],{preserveWhitespace:true}),p=ke(c.stdout),m=p.changedFiles.length>0||p.untrackedFiles.length>0||p.deletedFiles.length>0;return {available:true,branch:i.ok?i.stdout:void 0,commit:n.ok?n.stdout:void 0,ref:t?.ref,dirty:m,changedFiles:p.changedFiles,untrackedFiles:p.untrackedFiles,deletedFiles:p.deletedFiles}}var oe=q.snapshot,L=q.diff,T=p.snapshot,ae=p.diff,he=q.impact,we=p.impact;function ye(e$1){if(e$1.model.projectTopology||!e$1.model.graph||e$1.modelHash!==e(e$1.model))return null;let t={...e$1.model,projectTopology:e$1.model.graph,graph:e$1.model.graph};return {...e$1,modelHash:d(t),model:t}}function ne(e){let t=e.trim().toLowerCase();return t==="git"||t.startsWith("git:")}function We(e){let t=e.trim();return t.toLowerCase()==="git"?"HEAD":t.toLowerCase().startsWith("git:")&&t.slice(4).trim()||"HEAD"}function se(e,t){return k.isAbsolute(t)?t:k.join(e,t)}async function be(e){let t=await V.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace model input is not a JSON object: ${e}`);let a=t;if(a.schemaVersion===oe){a$1(t,"contracts/workspace-intelligence/workspace-model-snapshot.v1.json",`Workspace model snapshot ${e}`);let r=a;if(!r.model||r.model.schemaVersion!==l)throw new Error(`Invalid workspace model snapshot: ${e}`);let i=d(r.model);if(r.modelHash!==i){let n=ye(r);if(!n)throw new Error(`Workspace model snapshot hash mismatch: ${e}`);return {model:n.model,hash:n.modelHash}}return {model:r.model,hash:r.modelHash}}if(a.schemaVersion===l){a$1(t,"contracts/workspace-intelligence/workspace-model.v1.json",`Workspace model ${e}`);let r=a;return {model:r,hash:d(r)}}throw a.schemaVersion===L?new Error(`workspace diff --from received a diff report (${k.basename(e)}). Use a workspace model snapshot or model report as baseline, e.g. ${T}. To analyze an existing diff report, run: npx workspai workspace impact --from ${k.basename(e)} --json`):new Error(`Unsupported workspace model input schema: ${String(a.schemaVersion)}`)}async function ve(e){let t=await V.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace diff input is not a JSON object: ${e}`);let a=t;if(a.schemaVersion!==L)return null;a$1(t,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Workspace model diff ${e}`);let r=a;if(!r.currentModel||r.currentModel.schemaVersion!==l||!r.summary||!Array.isArray(r.changes))throw new Error(`Invalid workspace model diff report: ${e}`);if(r.toHash!==d(r.currentModel))throw new Error(`Workspace model diff current-model hash mismatch: ${e}`);return r}async function Ye(e){let t=e.model??await r({workspacePath:e.workspacePath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {schemaVersion:oe,generatedAt:(e.now??new Date).toISOString(),modelHash:d(t),modelRef:m,model:t}}async function Qe(e,t){return h$1(t,T,d$1(e))}function F(e){let{evidence:t,...a}=e;return a}function h(e,t){e.push(t);}function je(e,t){let a=[],r=["name","profile","type"],i=["workspaceType","surfaces","runtimeFamilies","businessCapabilities"];for(let n of r){let c=e.workspace[n],p=t.workspace[n];b$1(c)!==b$1(p)&&h(a,{type:"workspace.changed",severity:"info",target:`workspace.${n}`,message:`Workspace metadata field changed: ${String(n)}`,before:c,after:p});}for(let n of i){let c=e.identity[n],p=t.identity[n];b$1(c)!==b$1(p)&&h(a,{type:"workspace.changed",severity:"info",target:`identity.${n}`,message:`Workspace identity field changed: ${String(n)}`,before:c,after:p});}return b$1(e.policies)!==b$1(t.policies)&&h(a,{type:"workspace.changed",severity:"warning",target:"policies",message:"Workspace policy summary changed.",before:e.policies,after:t.policies}),b$1(e.discovery)!==b$1(t.discovery)&&h(a,{type:"workspace.changed",severity:"info",target:"discovery",message:"Workspace discovery settings changed.",before:e.discovery,after:t.discovery}),e.contracts.exists!==t.contracts.exists&&h(a,{type:"workspace.changed",severity:t.contracts.exists?"info":"warning",target:t.contracts.workspaceContractPath,message:"Workspace contract presence changed.",before:e.contracts.exists,after:t.contracts.exists}),a}function Me(e,t){let a=e.validation??null,r=t.validation??null;return b$1(a)===b$1(r)?[]:[{type:"validation.changed",severity:r?.status==="failed"?"critical":"warning",target:"validation",message:"Workspace model validation changed.",before:a,after:r}]}function Ie(e,t){let a=[],r=new Map(e.projects.map(n=>[n.path,n])),i=new Map(t.projects.map(n=>[n.path,n]));for(let[n,c]of i.entries()){let p=r.get(n);if(!p){h(a,{type:"project.added",severity:"info",target:n,message:`Project added: ${c.name}`,after:F(c)});continue}let m=F(p),l=F(c);if(b$1(m)!==b$1(l)){let u=p.runtime!==c.runtime||p.framework!==c.framework;h(a,{type:"project.changed",severity:u?"warning":"info",target:n,message:`Project changed: ${c.name}`,before:m,after:l});}}for(let[n,c]of r.entries())i.has(n)||h(a,{type:"project.removed",severity:"warning",target:n,message:`Project removed: ${c.name}`,before:F(c)});return a.sort((n,c)=>`${n.type}:${n.target}`.localeCompare(`${c.type}:${c.target}`))}async function Pe(e){let t=k.resolve(e.workspacePath),a=ne(e.fromPath),r$1=a?We(e.fromPath):void 0,i=e.fromPath;if(a){let f=k.join(t,T);if(!await V.pathExists(f))throw new Error("Git-aware workspace diff requires an existing snapshot at .workspai/reports/workspace-model-snapshot.json. Run: npx workspai workspace snapshot --json");i=T;}let n=se(t,i),c=await be(n),p=e.model??await r({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),m$1=d(p),l=[...je(c.model,p),...Ie(c.model,p),...Me(c.model,p)],u;e.includeGitObservation!==false&&(u=e.gitObservation??Q(t,{ref:r$1}),u.available&&Se(l,u,p));let v=c.hash!==m$1;v&&!l.some(f=>!f.type.startsWith("git."))&&h(l,{type:"workspace.changed",severity:"warning",target:"model.structural-hash",message:"Workspace structural identity changed outside the currently classified diff fields.",before:c.hash,after:m$1});let P=l.filter(f=>f.type.startsWith("git.")).length,w=a?`git:${r$1??"HEAD"}`:k.relative(t,n).split(k.sep).join("/");return {schemaVersion:L,generatedAt:(e.now??new Date).toISOString(),fromRef:w,toRef:m,fromHash:c.hash,toHash:m$1,summary:{changed:v||P>0,addedProjects:l.filter(f=>f.type==="project.added").length,removedProjects:l.filter(f=>f.type==="project.removed").length,changedProjects:l.filter(f=>f.type==="project.changed").length,workspaceChanges:l.filter(f=>f.type==="workspace.changed").length,validationChanges:l.filter(f=>f.type==="validation.changed").length,gitChangedFiles:P},git:u?.available?Oe(u,r$1):{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:l,currentModel:p}}async function Ze(e,t){return h$1(t,ae,d$1(e))}function I(e){return {none:0,low:1,medium:2,high:3,critical:4}[e]}function Z(e){return e.reduce((t,a)=>I(a)>I(t)?a:t,"none")}var N=["none","low","medium","high","critical"];function Re(e){let t=Math.max(1,I(e)-1);return N[t]}function Ce(e){let t=Math.min(N.length-1,I(e)+1);return N[t]}function ee(e){return e.join(" ")}function b(e,t,a,r){return {id:e,label:t,scope:r.scope,project:r.project,display:ee(["npx","workspai",...a]),execute:ee(["npx","--yes","--package","workspai","workspai",...a]),required:r.required!==false}}function te(e){let t=`project:${e.name}`,a=e.commands.fleetStages,r={init:`Run init for ${e.name}`,test:`Run tests for ${e.name}`,build:`Run build for ${e.name}`,start:`Run start for ${e.name}`};return ["init","test","build","start"].filter(i=>a.includes(i)).map(i=>b(`project.${e.name}.${i}`,r[i],["workspace","run",i,"--scope",t,"--json"],{scope:"project",project:e.name}))}function _(){return [b("workspace.doctor","Run workspace doctor",["doctor","workspace","--json"],{scope:"workspace"}),b("workspace.contract.verify","Verify workspace contract",["workspace","contract","verify","--json"],{scope:"workspace"}),b("workspace.readiness","Run release readiness",["readiness","--json"],{scope:"workspace"}),b("workspace.analyze","Run workspace analyze",["analyze","--json"],{scope:"workspace",required:false}),b("workspace.pipeline","Run governance pipeline",["pipeline","--json"],{scope:"workspace",required:false}),b("workspace.doctor-fix","Verify doctor fix result",["doctor","workspace","--fix","--json"],{scope:"workspace",required:false})]}function Ee(e,t){let a=t.split(k.sep).join("/");return e.projects.filter(i=>{let n=i.path.split(k.sep).join("/");return a===n||a.startsWith(`${n}/`)}).sort((i,n)=>n.path.length-i.path.length)[0]}function Se(e,t,a){let r=new Set(e.map(n=>n.target)),i=(n,c)=>{let p=c.split(k.sep).join("/"),m=`git:${p}`;if(r.has(m))return;let l=Ee(a,p),u=l?`${l.name} (${l.path})`:"workspace";h(e,{type:n,severity:n==="git.deleted"?"warning":"info",target:m,message:`Git ${n==="git.untracked"?"untracked":n==="git.deleted"?"deleted":"changed"} file affects ${u}: ${p}`,after:{path:p,project:l?.name,projectPath:l?.path}}),r.add(m);};for(let n of t.changedFiles)i("git.file.changed",n);for(let n of t.untrackedFiles)i("git.untracked",n);for(let n of t.deletedFiles)i("git.deleted",n);}function Oe(e,t){return {available:true,ref:t??e.ref,branch:e.branch,commit:e.commit,dirty:e.dirty,changedFiles:e.changedFiles.length,untrackedFiles:e.untrackedFiles.length,deletedFiles:e.deletedFiles.length}}function Ae(e){let t=new Set,a=[];for(let r of e){let i=`${r.scope}:${r.project??""}:${r.display}`;t.has(i)||(t.add(i),a.push(r));}return a}function De(e){return e.type==="project.removed"?"high":e.severity==="critical"?"critical":e.severity==="warning"?"high":("medium")}function $e(e,t){return e.severity==="critical"?"critical":e.target==="policies"||e.target.includes("contract")?"high":e.type==="validation.changed"?(t?.projectCount??0)===0?"low":"high":e.target==="evidence"?"low":e.severity==="warning"?"medium":"low"}function xe(e){return e.affectedProjects>0||e.projectCount>0||!e.changes.every(a=>a.severity==="critical"?false:a.type.startsWith("git.")||a.type==="validation.changed")?e.risk:I(e.risk)>=I("high")||e.risk==="medium"?"low":e.risk}function re(e,t){if(!e||e==="workspace")return true;let a=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return [t.name,t.path,k.basename(t.path),t.absolutePath].filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase()).includes(a)}function Fe(e){if(!e.changed)return {headline:"No workspace model impact detected.",bullets:["The current workspace model matches the provided snapshot/report."],unsafeAssumptions:["Do not claim runtime verification passed unless a report exists."]};let t=e.affectedProjects.map(a=>a.project?.name??a.target);return {headline:`Workspace impact risk: ${e.risk}.`,bullets:[`Affected projects: ${t.length?t.join(", "):"none"}.`,`Workspace-level items: ${e.workspaceImpact.length}.`,"Use the verification plan before recommending apply, rollback, or release actions."],unsafeAssumptions:["Do not infer test/build success from impact alone.","Do not apply fixes without project scope and verification evidence.","Use display commands for users and execute commands for automation."]}}async function et(e){let t=k.resolve(e.workspacePath),a$1=ne(e.fromPath),r=e.diff;if(!r&&!a$1){let o=se(t,e.fromPath);r=await ve(o)??void 0;}r||(r=await Pe({workspacePath:t,fromPath:e.fromPath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,includeGitObservation:e.includeGitObservation,gitObservation:e.gitObservation,now:e.now,model:e.model}));let i=new Map(r.currentModel.projects.map(o=>[o.path,o])),n$1=new Map(r.currentModel.projects.map(o=>[o.name,o])),c$1=r.changes.filter(o=>o.type.startsWith("project.")),p=new Map;for(let o of c$1){let d=(i.get(o.target)??(typeof o.before?.name=="string"?n$1.get(o.before.name):void 0))?.path??o.target,y=p.get(d)??[];y.push(o),p.set(d,y);}let m=[];for(let[o,s]of p.entries()){let d=i.get(o);if(d&&!re(e.scope,d))continue;let y=Z(s.map(De)),C=d?.name??(typeof s[0]?.before?.name=="string"?String(s[0].before.name):o);m.push({id:`project:${C}`,scope:"project",target:o,title:`Project impact: ${C}`,summary:s.map(j=>j.message).join(" "),risk:y,reasons:s.map(j=>`${j.type}: ${j.message}`),project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?te(d):_()});}let l=n(r.currentModel),u=l?a(l):void 0,v=new Set(m.map(o=>o.project?.name).filter(o=>typeof o=="string")),P=new Map;for(let o of m)if(o.project?.name){let s=u?.byId.get(o.project.name);s&&(o.centrality={fanIn:s.fanIn,fanOut:s.fanOut,reach:s.reach,betweenness:s.betweenness,isHotspot:s.isHotspot},s.isHotspot&&(o.risk=Ce(o.risk),o.reasons=[...o.reasons,`graph.hotspot: critical-path project with ${s.reach} transitive dependent(s); risk escalated.`])),o.origin="direct",o.distance=0,P.set(o.project.name,o.risk);}let w=[],f=0;if(l&&v.size>0){let o=c(l,v);for(let s of o.values()){if(s.distance===0||v.has(s.id))continue;let d=n$1.get(s.id);if(d&&!re(e.scope,d))continue;let y=s.path[0],C=s.path[s.path.length-2]??y,j=P.get(y)??"medium",de=Re(j),M=u?.byId.get(s.id);f=Math.max(f,s.distance),w.push({id:`transitive:${s.id}`,scope:"project",target:d?.path??s.id,title:`Transitive impact: ${s.id}`,summary:`Depends on changed project ${y}${s.via?` via ${s.via}`:""} (distance ${s.distance}).`,risk:de,reasons:[`graph.dependent: depends on ${C}${s.via?` via ${s.via}`:""} (path ${s.path.join(" -> ")})`],project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?te(d):_(),origin:"transitive",distance:s.distance,path:s.path,via:s.via,...M?{centrality:{fanIn:M.fanIn,fanOut:M.fanOut,reach:M.reach,betweenness:M.betweenness,isHotspot:M.isHotspot}}:{}});}}w.sort((o,s)=>o.target.localeCompare(s.target));let ie=u?u.hotspots.flatMap(o=>{let s=u.byId.get(o);return s?[{project:o,fanIn:s.fanIn,fanOut:s.fanOut,reach:s.reach,betweenness:s.betweenness}]:[]}):[],ce=r.changes.filter(o=>!o.type.startsWith("project.")),K=r.currentModel.summary?.projectCount??r.currentModel.projects.length,R=ce.map(o=>({id:`workspace:${o.target}`,scope:"workspace",target:o.target,title:`Workspace impact: ${o.target}`,summary:o.message,risk:$e(o,{projectCount:K}),reasons:[`${o.type}: ${o.message}`],verification:_()})),B=Ae([...m.flatMap(o=>o.verification),...w.flatMap(o=>o.verification),...R.flatMap(o=>o.verification),...r.summary.changed?_():[]]).filter(o=>o.required),pe=Z([...m.map(o=>o.risk),...w.map(o=>o.risk),...R.map(o=>o.risk)]),z=xe({risk:pe,affectedProjects:m.length,projectCount:K,changes:r.changes}),q={changed:r.summary.changed,risk:z,affectedProjects:m.length,workspaceItems:R.length,recommendedCommands:B.length,blastRadius:{directlyAffected:m.length,transitivelyAffected:w.length,maxDistance:f,graphEdges:l?.edges.length??0}};return {schemaVersion:he,generatedAt:(e.now??new Date).toISOString(),fromRef:r.fromRef,diffRef:ae,workspace:{name:r.currentModel.workspace.name,profile:r.currentModel.workspace.profile,type:r.currentModel.workspace.type},summary:q,affectedProjects:m.sort((o,s)=>o.target.localeCompare(s.target)),transitiveImpact:w,criticalPathHotspots:ie,workspaceImpact:R.sort((o,s)=>o.target.localeCompare(s.target)),verificationPlan:B,agentBrief:Fe({changed:q.changed,risk:z,affectedProjects:m,workspaceImpact:R}),diff:r}}async function tt(e,t){return h$1(t,we,d$1(e))}export{Q as a,oe as b,L as c,T as d,ae as e,he as f,we as g,ye as h,ne as i,We as j,Ye as k,Qe as l,Pe as m,Ze as n,_ as o,et as p,tt as q};
@@ -1,4 +1,4 @@
1
- import {f,e}from'./chunk-XF65LQ6M.js';import {a as a$1,b as b$2}from'./chunk-X7FYEKLI.js';import {c,d as d$2}from'./chunk-N4B2M44I.js';import {a,b}from'./chunk-SVO2GGTV.js';import {j,i}from'./chunk-7HV4U2OV.js';import {d}from'./chunk-ROOPODG6.js';import {a as a$2,h as h$1}from'./chunk-BLEIUQL6.js';import {b as b$1}from'./chunk-VN2MKTQO.js';import {t}from'./chunk-VQZ5PI5J.js';import {q as q$1,p as p$1}from'./chunk-ODK4LCEL.js';import p from'chalk';import d$1 from'fs';import h from'path';var H=p$1.readiness;function U(n){return n.vulnerableDependencies>0?`${n.vulnerableDependencies} known dependency vulnerability finding(s) reported`:`${n.blockingFindings} blocking dependency/security finding(s) reported`}var q=q$1.readiness;function B(n){let t=A(n,"workspace.contract.json");if(!d$1.existsSync(t))return [];try{let e=JSON.parse(d$1.readFileSync(t,"utf-8"));return (Array.isArray(e.projects)?e.projects:[]).map(i=>{let c=m(i),o=typeof c.externalPath=="string"?c.externalPath.trim():"",s=typeof c.relativePath=="string"?c.relativePath.trim():"",r=o||s;return r?d(n,s||r,o?{absolutePath:o}:{}):""}).filter(Boolean)}catch{return []}}function Q(n,t){let e=h.resolve(n);if(!b(e))return e;let a=A(t,"workspace.contract.json");if(d$1.existsSync(a))try{let o=JSON.parse(d$1.readFileSync(a,"utf-8")),s=Array.isArray(o.projects)?o.projects:[];for(let r of s){let f=m(r),y=typeof f.externalPath=="string"?f.externalPath.trim():"",g=typeof f.relativePath=="string"?f.relativePath.trim():"";if(y||g)return d(t,g||y,y?{absolutePath:y}:{})}}catch{}let i=T(t),c=Array.isArray(i.payload?.projects)?i.payload.projects:[];for(let o of c){let s=m(o),r=typeof s.path=="string"?s.path.trim():"";if(r)return h.resolve(r)}return e}function _(n){let t=j(n);return i(t,n)}function J(n,t){if(!d$1.existsSync(n))return null;let e=d$1.readdirSync(n).filter(a=>a.endsWith(".json")&&t.some(i=>i.test(a))).map(a=>h.join(n,a));return e.length===0?null:(e.sort((a,i)=>d$1.statSync(i).mtimeMs-d$1.statSync(a).mtimeMs),e[0])}function m(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function M(n){for(let t of n)if(d$1.existsSync(t))return t;return null}function A(n,...t$1){let e=t(n,...t$1);return M(e)??e[0]}function E(n,t){let e=a$2(n,`.workspai/reports/${t}`);return M([e,h.join(n,".rapidkit","reports",t)])??e}async function X(n){let{readWorkspaceRegistrySummary:t,resolveWorkspaceRegisteredProjects:e}=await import('./workspace-registry-summary-ZC5CFZXP.js'),a=await t(n);return a?a.projectCount:(await e(n)).summary.projectCount}function Y(n,t,e){let a=A(n,"toolchain.lock");if(!d$1.existsSync(a))return {gate:"env",status:"fail",summary:"toolchain.lock is missing",details:["Run workspai bootstrap to pin runtime versions and generate a reproducible toolchain."],evidencePath:a};try{let i=JSON.parse(d$1.readFileSync(a,"utf-8")),c=m(i.runtime),o=["python","node","go","java","dotnet","rust","php"],s=o.filter(l=>{let u=m(c[l]);return typeof u.version=="string"&&u.version.trim().length>0});if(s.length===0)return {gate:"env",status:"fail",summary:"No runtime versions are pinned in toolchain.lock",details:["Pin at least one runtime version via workspai setup <runtime> and re-run bootstrap."],evidencePath:a};let r=[...new Set((Array.isArray(t)?t:[t]).filter(l=>l!=="unknown"))],f=r.filter(l=>o.includes(l)),y=r.filter(l=>!o.includes(l)),g=f.filter(l=>{let u=m(c[l]);return typeof u.version!="string"||u.version.trim().length===0});return g.length>0?{gate:"env",status:"fail",summary:`${e?.hasRegisteredProjects?"Project runtime":"Workspace"}${g.length===1?"":"s"} (${g.join(", ")}) ${g.length===1?"is":"are"} not pinned in toolchain.lock`,details:g.map(u=>`Run workspai setup ${u} and workspai bootstrap to lock ${u} for this workspace.`),evidencePath:a}:y.length>0?{gate:"env",status:"warn",summary:`${e?.hasRegisteredProjects?"Project runtime":"Workspace"}${y.length===1?"":"s"} (${y.join(", ")}) cannot be verified by toolchain.lock`,details:[`Pinned Workspai runtimes (${s.join(", ")}) do not prove the ${y.join(", ")} compiler or runtime toolchain.`,"Declare and verify this runtime or toolchain through the project command contract or organization CI policy."],evidencePath:a}:{gate:"env",status:"pass",summary:`Pinned runtimes: ${s.join(", ")}`,details:[],evidencePath:a}}catch{return {gate:"env",status:"fail",summary:"toolchain.lock is invalid JSON",details:["Regenerate lockfile with workspai bootstrap."],evidencePath:a}}}function T(n){let t=E(n,"doctor-last-run.json");if(!d$1.existsSync(t))return {payload:null,path:t};try{let e=JSON.parse(d$1.readFileSync(t,"utf-8"));return c(e,"workspace")?(d$2(e),{payload:e,path:t}):{payload:null,path:t}}catch{return {payload:null,path:t}}}function Z(n){let t=T(n);if(!t.payload)return {gate:{gate:"doctor",status:"fail",summary:"Doctor evidence is missing",details:["Run workspai doctor workspace --json before release readiness checks."],evidencePath:t.path},payload:null};let e=a$1(t.payload);if(e.hasSystemErrors)return {gate:{gate:"doctor",status:"fail",summary:"Doctor reported system errors",details:["Resolve system-level doctor errors before proceeding."],evidencePath:t.path},payload:t.payload};if(e.blockingFindings>0)return {gate:{gate:"doctor",status:"fail",summary:`Doctor reported ${e.blockingFindings} blocking finding(s)`,details:["Resolve the canonical Doctor findings and regenerate fresh Doctor evidence."],evidencePath:t.path},payload:t.payload};let a=[...e.advisoryFindings>0?[`${e.advisoryFindings} advisory finding(s)`]:[],...e.unknownFindings>0?[`${e.unknownFindings} unknown finding(s)`]:[],...e.contradictionCount>0?[`${e.contradictionCount} evidence contradiction(s)`]:[],...e.missingDiagnosisProjects>0?[`${e.missingDiagnosisProjects} project(s) without canonical diagnosis`]:[],...e.staleEvidence?["stale Doctor evidence"]:[],...e.unknownFreshness?["unknown Doctor evidence freshness"]:[],...e.minimumDiagnosisCompleteness<100?[`diagnosis completeness ${e.minimumDiagnosisCompleteness}%`]:[]];return a.length>0?{gate:{gate:"doctor",status:"warn",summary:"Doctor evidence requires attention",details:a,evidencePath:t.path},payload:t.payload}:{gate:{gate:"doctor",status:"pass",summary:"Doctor checks passed without issues",details:[],evidencePath:t.path},payload:t.payload}}function ee(n){let t=E(n,"analyze-last-run.json");if(!d$1.existsSync(t))return {gate:"analyze",status:"fail",summary:"Analyze evidence is missing",details:["Run workspai analyze --json before release readiness checks."],evidencePath:t};try{let e=JSON.parse(d$1.readFileSync(t,"utf-8"));b$1(p$1.analyze,e,t);let a=m(e.summary),i=String(a.verdict??"").toLowerCase(),c=Number(a.score??0),o=m(a.findings),s=Number(o.fail??0);return i==="blocked"||s>0?{gate:"analyze",status:"fail",summary:`Analyze verdict is blocked (score ${c}/100)`,details:["Resolve analyze findings and regenerate analyze-last-run.json."],evidencePath:t}:i==="needs-attention"?{gate:"analyze",status:"warn",summary:`Analyze needs attention (score ${c}/100)`,details:["Review analyze warnings before release."],evidencePath:t}:{gate:"analyze",status:"pass",summary:`Analyze passed (score ${c}/100)`,details:[],evidencePath:t}}catch{return {gate:"analyze",status:"fail",summary:"Analyze evidence is invalid or violates its contract",details:["Re-run workspai analyze --json to regenerate evidence."],evidencePath:t}}}function te(n){try{let t=JSON.parse(d$1.readFileSync(n,"utf-8")),e=String(t.status??"").toLowerCase(),a=m(t.summary),i=Number(a.failedChecks??0);return e==="fail"||i>0?{gate:"verify",status:"fail",summary:"Verify-pack contract reports failed checks",details:["Fix failed verify checks and regenerate verify-pack contract evidence."],evidencePath:n}:e==="pass"?{gate:"verify",status:"pass",summary:"Verify-pack contract passed",details:[],evidencePath:n}:{gate:"verify",status:"warn",summary:"Verify-pack contract status is not explicit",details:["Ensure contract status is pass/fail and keep schema aligned with v1 contract."],evidencePath:n}}catch{return {gate:"verify",status:"fail",summary:"Verify-pack contract is invalid JSON",details:["Regenerate verify-pack contract artifact."],evidencePath:n}}}async function ne(n,t){if(t.skipVerify)return {gate:"verify",status:"pass",summary:"Verify gate skipped (--skip-verify)",details:["Verification was explicitly skipped for this readiness run."]};let e=[a$2(n,".workspai/reports"),h.join(n,".rapidkit","reports")],a=e[0],i=e.map(s=>J(s,[/verify-pack-contract/i,/^verify.*\.json$/i])).find(s=>typeof s=="string")??null;if(i)return te(i);let c=a$2(n,p$1.contractVerify),o=e.map(s=>J(s,[/workspace-contract-verify-last-run/i,/workspace-contract-verify/i])).find(s=>typeof s=="string")??null;if(o)try{let s=JSON.parse(d$1.readFileSync(o,"utf-8")),r=String(s.status??"").toLowerCase();if(r==="passed"||r==="pass")return {gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI cache)",details:[],evidencePath:o};if(r==="failed"||r==="fail")return {gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI cache)",details:(Array.isArray(s.violations)?s.violations:[]).slice(0,5),evidencePath:o}}catch{}try{let{verifyWorkspaceContract:s}=await import('./workspace-contract-XDNIB5JX.js'),r=await s({workspacePath:n}),f={schemaVersion:"v1",source:"cli",generatedAt:new Date().toISOString(),status:r.status,contractPath:r.contractPath,projectCount:r.projectCount,checks:r.checks,violations:r.violations};return await h$1(n,p$1.contractVerify,f),r.status==="failed"?{gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI)",details:r.violations.slice(0,5),evidencePath:c}:{gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI)",details:[],evidencePath:c}}catch(s){return {gate:"verify",status:"fail",summary:"No verify evidence and workspace contract verification unavailable",details:["Run workspai workspace contract verify --json or export verify-pack contract from CI.",s instanceof Error?s.message:String(s)],evidencePath:h.join(a,"*verify*.json")}}}function ae(n,t){let e=E(t,"doctor-last-run.json");if(!n)return {gate:"dependency",status:"warn",summary:"Dependency risk check skipped (doctor evidence missing)",details:["Run workspai doctor workspace --json to include dependency findings."],evidencePath:e};let a=b$2(n);return a.blockingFindings>0||a.vulnerableDependencies>0?{gate:"dependency",status:"fail",summary:U(a),details:["Resolve the typed dependency/security findings and regenerate focused audit evidence."],evidencePath:e}:a.auditFailed>0?{gate:"dependency",status:"fail",summary:`${a.auditFailed} dependency audit(s) failed`,details:["Repair the audit runner or dependency environment; failed audits are not clean."],evidencePath:e}:a.missingDependencies>0||a.auditUnavailable>0||a.unknownFindings>0||a.advisoryFindings>0?{gate:"dependency",status:"warn",summary:"Dependency evidence is incomplete or requires attention",details:[...a.missingDependencies>0?[`${a.missingDependencies} project(s) have no materialized dependency tree.`]:[],...a.auditUnavailable>0?[`${a.auditUnavailable} audit provider(s) are unavailable or unsupported.`]:[],...a.unknownFindings>0?[`${a.unknownFindings} dependency/security finding(s) remain unknown.`]:[],...a.advisoryFindings>0?[`${a.advisoryFindings} dependency/security advisory finding(s) remain.`]:[]],evidencePath:e}:{gate:"dependency",status:"pass",summary:"No dependency vulnerabilities reported",details:[],evidencePath:e}}function se(n){return n.some(t=>t.status==="fail")?"fail":n.some(t=>t.status==="warn")?"warn":"pass"}async function re(n,t){return h$1(n,H,t)}async function ie(n={}){let t=h.resolve(n.startPath??process.cwd()),e$1=a(t)??t,a$1=await X(e$1)>0,i=a$1&&b(t)?e$1:Q(t,e$1),c=i===e$1?"unknown":_(i),o=a$1?c:"unknown";if(a$1&&i===e$1){let{resolveWorkspaceRegisteredProjects:v}=await import('./workspace-registry-summary-ZC5CFZXP.js'),K=await v(e$1),C=B(e$1);o=(C.length>0?C:K.summary.projects.map(S=>d(e$1,S.relativePath))).map(S=>_(S));}let s=Y(e$1,o,{hasRegisteredProjects:a$1}),r=Z(e$1),f$1=ee(e$1),y=await ne(e$1,{skipVerify:n.skipVerify}),g=ae(r.payload,e$1),l=[s,r.gate,f$1,y,g],u=se(l),k={schemaVersion:q,generatedAt:new Date().toISOString(),workspacePath:e$1,projectPath:i,action:n.action,overallStatus:u,blocking:u==="fail",blockingReasons:l.filter(v=>v.status==="fail").map(v=>`${v.gate}: ${v.summary}`),gates:l};if(n.writeReport!==false){let v=f(k,{commandId:"workspaceReadiness",exitCode:u==="fail"?2:u==="warn"?1:0,generatedAt:k.generatedAt,blockers:k.blockingReasons,runId:e()});k.evidencePath=await re(e$1,v);}return k}function oe(n){return n==="pass"?p.green("PASS"):n==="warn"?p.yellow("WARN"):p.red("FAIL")}function ce(n){return n==="pass"?p.green("PASS"):n==="warn"?p.yellow("WARN"):p.red("FAIL")}async function je(n){let t=await ie({startPath:n.workspace,writeReport:true,skipVerify:n.skipVerify===true});if(n.json)console.log(JSON.stringify(t,null,2));else {console.log(p.bold.cyan(`
1
+ import {f,e}from'./chunk-XF65LQ6M.js';import {a as a$1,b as b$2}from'./chunk-X7FYEKLI.js';import {c,d as d$2}from'./chunk-N4B2M44I.js';import {a,b}from'./chunk-SVO2GGTV.js';import {j,i}from'./chunk-7HV4U2OV.js';import {d}from'./chunk-ROOPODG6.js';import {a as a$2,h as h$1}from'./chunk-BLEIUQL6.js';import {b as b$1}from'./chunk-VN2MKTQO.js';import {t}from'./chunk-VQZ5PI5J.js';import {q as q$1,p as p$1}from'./chunk-ODK4LCEL.js';import p from'chalk';import d$1 from'fs';import h from'path';var H=p$1.readiness;function U(n){return n.vulnerableDependencies>0?`${n.vulnerableDependencies} known dependency vulnerability finding(s) reported`:`${n.blockingFindings} blocking dependency/security finding(s) reported`}var q=q$1.readiness;function B(n){let t=A(n,"workspace.contract.json");if(!d$1.existsSync(t))return [];try{let e=JSON.parse(d$1.readFileSync(t,"utf-8"));return (Array.isArray(e.projects)?e.projects:[]).map(i=>{let c=m(i),o=typeof c.externalPath=="string"?c.externalPath.trim():"",s=typeof c.relativePath=="string"?c.relativePath.trim():"",r=o||s;return r?d(n,s||r,o?{absolutePath:o}:{}):""}).filter(Boolean)}catch{return []}}function Q(n,t){let e=h.resolve(n);if(!b(e))return e;let a=A(t,"workspace.contract.json");if(d$1.existsSync(a))try{let o=JSON.parse(d$1.readFileSync(a,"utf-8")),s=Array.isArray(o.projects)?o.projects:[];for(let r of s){let f=m(r),y=typeof f.externalPath=="string"?f.externalPath.trim():"",g=typeof f.relativePath=="string"?f.relativePath.trim():"";if(y||g)return d(t,g||y,y?{absolutePath:y}:{})}}catch{}let i=T(t),c=Array.isArray(i.payload?.projects)?i.payload.projects:[];for(let o of c){let s=m(o),r=typeof s.path=="string"?s.path.trim():"";if(r)return h.resolve(r)}return e}function _(n){let t=j(n);return i(t,n)}function J(n,t){if(!d$1.existsSync(n))return null;let e=d$1.readdirSync(n).filter(a=>a.endsWith(".json")&&t.some(i=>i.test(a))).map(a=>h.join(n,a));return e.length===0?null:(e.sort((a,i)=>d$1.statSync(i).mtimeMs-d$1.statSync(a).mtimeMs),e[0])}function m(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function M(n){for(let t of n)if(d$1.existsSync(t))return t;return null}function A(n,...t$1){let e=t(n,...t$1);return M(e)??e[0]}function E(n,t){let e=a$2(n,`.workspai/reports/${t}`);return M([e,h.join(n,".rapidkit","reports",t)])??e}async function X(n){let{readWorkspaceRegistrySummary:t,resolveWorkspaceRegisteredProjects:e}=await import('./workspace-registry-summary-3PXZENLC.js'),a=await t(n);return a?a.projectCount:(await e(n)).summary.projectCount}function Y(n,t,e){let a=A(n,"toolchain.lock");if(!d$1.existsSync(a))return {gate:"env",status:"fail",summary:"toolchain.lock is missing",details:["Run workspai bootstrap to pin runtime versions and generate a reproducible toolchain."],evidencePath:a};try{let i=JSON.parse(d$1.readFileSync(a,"utf-8")),c=m(i.runtime),o=["python","node","go","java","dotnet","rust","php"],s=o.filter(l=>{let u=m(c[l]);return typeof u.version=="string"&&u.version.trim().length>0});if(s.length===0)return {gate:"env",status:"fail",summary:"No runtime versions are pinned in toolchain.lock",details:["Pin at least one runtime version via workspai setup <runtime> and re-run bootstrap."],evidencePath:a};let r=[...new Set((Array.isArray(t)?t:[t]).filter(l=>l!=="unknown"))],f=r.filter(l=>o.includes(l)),y=r.filter(l=>!o.includes(l)),g=f.filter(l=>{let u=m(c[l]);return typeof u.version!="string"||u.version.trim().length===0});return g.length>0?{gate:"env",status:"fail",summary:`${e?.hasRegisteredProjects?"Project runtime":"Workspace"}${g.length===1?"":"s"} (${g.join(", ")}) ${g.length===1?"is":"are"} not pinned in toolchain.lock`,details:g.map(u=>`Run workspai setup ${u} and workspai bootstrap to lock ${u} for this workspace.`),evidencePath:a}:y.length>0?{gate:"env",status:"warn",summary:`${e?.hasRegisteredProjects?"Project runtime":"Workspace"}${y.length===1?"":"s"} (${y.join(", ")}) cannot be verified by toolchain.lock`,details:[`Pinned Workspai runtimes (${s.join(", ")}) do not prove the ${y.join(", ")} compiler or runtime toolchain.`,"Declare and verify this runtime or toolchain through the project command contract or organization CI policy."],evidencePath:a}:{gate:"env",status:"pass",summary:`Pinned runtimes: ${s.join(", ")}`,details:[],evidencePath:a}}catch{return {gate:"env",status:"fail",summary:"toolchain.lock is invalid JSON",details:["Regenerate lockfile with workspai bootstrap."],evidencePath:a}}}function T(n){let t=E(n,"doctor-last-run.json");if(!d$1.existsSync(t))return {payload:null,path:t};try{let e=JSON.parse(d$1.readFileSync(t,"utf-8"));return c(e,"workspace")?(d$2(e),{payload:e,path:t}):{payload:null,path:t}}catch{return {payload:null,path:t}}}function Z(n){let t=T(n);if(!t.payload)return {gate:{gate:"doctor",status:"fail",summary:"Doctor evidence is missing",details:["Run workspai doctor workspace --json before release readiness checks."],evidencePath:t.path},payload:null};let e=a$1(t.payload);if(e.hasSystemErrors)return {gate:{gate:"doctor",status:"fail",summary:"Doctor reported system errors",details:["Resolve system-level doctor errors before proceeding."],evidencePath:t.path},payload:t.payload};if(e.blockingFindings>0)return {gate:{gate:"doctor",status:"fail",summary:`Doctor reported ${e.blockingFindings} blocking finding(s)`,details:["Resolve the canonical Doctor findings and regenerate fresh Doctor evidence."],evidencePath:t.path},payload:t.payload};let a=[...e.advisoryFindings>0?[`${e.advisoryFindings} advisory finding(s)`]:[],...e.unknownFindings>0?[`${e.unknownFindings} unknown finding(s)`]:[],...e.contradictionCount>0?[`${e.contradictionCount} evidence contradiction(s)`]:[],...e.missingDiagnosisProjects>0?[`${e.missingDiagnosisProjects} project(s) without canonical diagnosis`]:[],...e.staleEvidence?["stale Doctor evidence"]:[],...e.unknownFreshness?["unknown Doctor evidence freshness"]:[],...e.minimumDiagnosisCompleteness<100?[`diagnosis completeness ${e.minimumDiagnosisCompleteness}%`]:[]];return a.length>0?{gate:{gate:"doctor",status:"warn",summary:"Doctor evidence requires attention",details:a,evidencePath:t.path},payload:t.payload}:{gate:{gate:"doctor",status:"pass",summary:"Doctor checks passed without issues",details:[],evidencePath:t.path},payload:t.payload}}function ee(n){let t=E(n,"analyze-last-run.json");if(!d$1.existsSync(t))return {gate:"analyze",status:"fail",summary:"Analyze evidence is missing",details:["Run workspai analyze --json before release readiness checks."],evidencePath:t};try{let e=JSON.parse(d$1.readFileSync(t,"utf-8"));b$1(p$1.analyze,e,t);let a=m(e.summary),i=String(a.verdict??"").toLowerCase(),c=Number(a.score??0),o=m(a.findings),s=Number(o.fail??0);return i==="blocked"||s>0?{gate:"analyze",status:"fail",summary:`Analyze verdict is blocked (score ${c}/100)`,details:["Resolve analyze findings and regenerate analyze-last-run.json."],evidencePath:t}:i==="needs-attention"?{gate:"analyze",status:"warn",summary:`Analyze needs attention (score ${c}/100)`,details:["Review analyze warnings before release."],evidencePath:t}:{gate:"analyze",status:"pass",summary:`Analyze passed (score ${c}/100)`,details:[],evidencePath:t}}catch{return {gate:"analyze",status:"fail",summary:"Analyze evidence is invalid or violates its contract",details:["Re-run workspai analyze --json to regenerate evidence."],evidencePath:t}}}function te(n){try{let t=JSON.parse(d$1.readFileSync(n,"utf-8")),e=String(t.status??"").toLowerCase(),a=m(t.summary),i=Number(a.failedChecks??0);return e==="fail"||i>0?{gate:"verify",status:"fail",summary:"Verify-pack contract reports failed checks",details:["Fix failed verify checks and regenerate verify-pack contract evidence."],evidencePath:n}:e==="pass"?{gate:"verify",status:"pass",summary:"Verify-pack contract passed",details:[],evidencePath:n}:{gate:"verify",status:"warn",summary:"Verify-pack contract status is not explicit",details:["Ensure contract status is pass/fail and keep schema aligned with v1 contract."],evidencePath:n}}catch{return {gate:"verify",status:"fail",summary:"Verify-pack contract is invalid JSON",details:["Regenerate verify-pack contract artifact."],evidencePath:n}}}async function ne(n,t){if(t.skipVerify)return {gate:"verify",status:"pass",summary:"Verify gate skipped (--skip-verify)",details:["Verification was explicitly skipped for this readiness run."]};let e=[a$2(n,".workspai/reports"),h.join(n,".rapidkit","reports")],a=e[0],i=e.map(s=>J(s,[/verify-pack-contract/i,/^verify.*\.json$/i])).find(s=>typeof s=="string")??null;if(i)return te(i);let c=a$2(n,p$1.contractVerify),o=e.map(s=>J(s,[/workspace-contract-verify-last-run/i,/workspace-contract-verify/i])).find(s=>typeof s=="string")??null;if(o)try{let s=JSON.parse(d$1.readFileSync(o,"utf-8")),r=String(s.status??"").toLowerCase();if(r==="passed"||r==="pass")return {gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI cache)",details:[],evidencePath:o};if(r==="failed"||r==="fail")return {gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI cache)",details:(Array.isArray(s.violations)?s.violations:[]).slice(0,5),evidencePath:o}}catch{}try{let{verifyWorkspaceContract:s}=await import('./workspace-contract-N2BJCAJ7.js'),r=await s({workspacePath:n}),f={schemaVersion:"v1",source:"cli",generatedAt:new Date().toISOString(),status:r.status,contractPath:r.contractPath,projectCount:r.projectCount,checks:r.checks,violations:r.violations};return await h$1(n,p$1.contractVerify,f),r.status==="failed"?{gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI)",details:r.violations.slice(0,5),evidencePath:c}:{gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI)",details:[],evidencePath:c}}catch(s){return {gate:"verify",status:"fail",summary:"No verify evidence and workspace contract verification unavailable",details:["Run workspai workspace contract verify --json or export verify-pack contract from CI.",s instanceof Error?s.message:String(s)],evidencePath:h.join(a,"*verify*.json")}}}function ae(n,t){let e=E(t,"doctor-last-run.json");if(!n)return {gate:"dependency",status:"warn",summary:"Dependency risk check skipped (doctor evidence missing)",details:["Run workspai doctor workspace --json to include dependency findings."],evidencePath:e};let a=b$2(n);return a.blockingFindings>0||a.vulnerableDependencies>0?{gate:"dependency",status:"fail",summary:U(a),details:["Resolve the typed dependency/security findings and regenerate focused audit evidence."],evidencePath:e}:a.auditFailed>0?{gate:"dependency",status:"fail",summary:`${a.auditFailed} dependency audit(s) failed`,details:["Repair the audit runner or dependency environment; failed audits are not clean."],evidencePath:e}:a.missingDependencies>0||a.auditUnavailable>0||a.unknownFindings>0||a.advisoryFindings>0?{gate:"dependency",status:"warn",summary:"Dependency evidence is incomplete or requires attention",details:[...a.missingDependencies>0?[`${a.missingDependencies} project(s) have no materialized dependency tree.`]:[],...a.auditUnavailable>0?[`${a.auditUnavailable} audit provider(s) are unavailable or unsupported.`]:[],...a.unknownFindings>0?[`${a.unknownFindings} dependency/security finding(s) remain unknown.`]:[],...a.advisoryFindings>0?[`${a.advisoryFindings} dependency/security advisory finding(s) remain.`]:[]],evidencePath:e}:{gate:"dependency",status:"pass",summary:"No dependency vulnerabilities reported",details:[],evidencePath:e}}function se(n){return n.some(t=>t.status==="fail")?"fail":n.some(t=>t.status==="warn")?"warn":"pass"}async function re(n,t){return h$1(n,H,t)}async function ie(n={}){let t=h.resolve(n.startPath??process.cwd()),e$1=a(t)??t,a$1=await X(e$1)>0,i=a$1&&b(t)?e$1:Q(t,e$1),c=i===e$1?"unknown":_(i),o=a$1?c:"unknown";if(a$1&&i===e$1){let{resolveWorkspaceRegisteredProjects:v}=await import('./workspace-registry-summary-3PXZENLC.js'),K=await v(e$1),C=B(e$1);o=(C.length>0?C:K.summary.projects.map(S=>d(e$1,S.relativePath))).map(S=>_(S));}let s=Y(e$1,o,{hasRegisteredProjects:a$1}),r=Z(e$1),f$1=ee(e$1),y=await ne(e$1,{skipVerify:n.skipVerify}),g=ae(r.payload,e$1),l=[s,r.gate,f$1,y,g],u=se(l),k={schemaVersion:q,generatedAt:new Date().toISOString(),workspacePath:e$1,projectPath:i,action:n.action,overallStatus:u,blocking:u==="fail",blockingReasons:l.filter(v=>v.status==="fail").map(v=>`${v.gate}: ${v.summary}`),gates:l};if(n.writeReport!==false){let v=f(k,{commandId:"workspaceReadiness",exitCode:u==="fail"?2:u==="warn"?1:0,generatedAt:k.generatedAt,blockers:k.blockingReasons,runId:e()});k.evidencePath=await re(e$1,v);}return k}function oe(n){return n==="pass"?p.green("PASS"):n==="warn"?p.yellow("WARN"):p.red("FAIL")}function ce(n){return n==="pass"?p.green("PASS"):n==="warn"?p.yellow("WARN"):p.red("FAIL")}async function je(n){let t=await ie({startPath:n.workspace,writeReport:true,skipVerify:n.skipVerify===true});if(n.json)console.log(JSON.stringify(t,null,2));else {console.log(p.bold.cyan(`
2
2
  \u{1F6A6} Workspai Release Readiness
3
3
  `)),console.log(p.bold(`Workspace: ${p.cyan(h.basename(t.workspacePath))}`)),console.log(p.gray(`Path: ${t.workspacePath}`)),console.log(`Overall: ${ce(t.overallStatus)}`);for(let e of t.gates){console.log(` - ${e.gate}: ${oe(e.status)} ${e.summary}`);for(let a of e.details)console.log(p.gray(` ${a}`));e.evidencePath&&console.log(p.gray(` evidence: ${e.evidencePath}`));}t.evidencePath&&console.log(p.gray(`
4
4
  Evidence saved: ${t.evidencePath}`));}n.strict&&t.overallStatus!=="pass"&&process.exit(1);}export{ie as a,je as b};
@@ -1,2 +1,2 @@
1
- import {b as b$1}from'./chunk-COICGD62.js';import {b}from'./chunk-5OKNWBAN.js';import {r,f,g}from'./chunk-QDM6TWFK.js';import {d}from'./chunk-MD4CHXV3.js';import {h,g as g$1}from'./chunk-BLEIUQL6.js';import {q,p}from'./chunk-ODK4LCEL.js';import E from'path';import A from'fs-extra';var re=q.agentContext,se=p.agentContext;function ne(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="gemini"||t==="qwen"||t==="kimi"||t==="grok"||t==="copilot"||t==="windsurf"||t==="amazon-q"||t==="orca"?t:"generic"}function G(e){return `npx --yes --package workspai workspai ${e}`.trim()}function x(e){return `npx workspai ${e}`.trim()}async function C(e,t,i){let s=E.join(e,t);if(!await A.pathExists(s))return null;try{let n=await A.readJson(s);return typeof n!="object"||n===null||!("schemaVersion"in n)||n.schemaVersion!==i?null:n}catch{return null}}function m(e){return {id:e.id,scope:e.scope,display:x(e.args),execute:G(e.args),description:e.description,...e.project?{project:e.project}:{},freshness:f({id:`command.${e.id}`,label:`${e.id} command`,scope:"command",value:{display:x(e.args),execute:G(e.args)},...e.project?{project:e.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e.generatedAt,now:e.now,sourceArtifact:p.model,sourcePath:`safeCommands.${e.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function L(e,t){return `workspace run ${t} --scope project:${e.name}`}function ae(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function ie(e,t,i){let s={generatedAt:e.generatedAt,now:i},n=[m({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),m({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),m({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),m({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),m({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),m({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),m({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),m({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=t?[t]:e.projects;for(let a of c)a.commands.fleetStages.includes("test")&&n.push(m({id:`project.${a.name}.test`,scope:"project",project:a.name,args:L(a,"test"),description:`Run tests for ${a.name} through workspace orchestration.`,...s})),a.commands.fleetStages.includes("build")&&n.push(m({id:`project.${a.name}.build`,scope:"project",project:a.name,args:L(a,"build"),description:`Build ${a.name} through workspace orchestration.`,...s}));return n}function ce(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function pe(e,t){if(!t?.startsWith("project:"))return;let i=ae(t);if(i)return e.projects.find(s=>oe(s).includes(i))}function de(e,t,i){let s=[...e.validation?.issues??[]];t?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let n=s.filter(a=>a.severity==="error").length,c=s.filter(a=>a.severity==="warning").length;return {status:n>0?"failed":c>0?"warning":"passed",errors:n,warnings:c,issues:s}}async function me(e,t){let i=[],s=[];for(let[n,c]of Object.entries(e.evidence))c&&await g$1(t,c.path)!==null?i.push(`${n}: ${c.path}`):s.push(n);return {available:i.sort(),missing:s.sort()}}function le(e){let t=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${i}, and ${s}.`}function ge(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),((e.summary.extendedProjects??0)>0||e.summary.observedProjects>0)&&t.push("Some projects use extended or observed support tiers; command coverage may be partial."),t}async function We(e){let t=e.model??await r({workspacePath:e.workspacePath,includeEvidence:e.includeEvidence===true,observableScanDepth:e.observableScanDepth,now:e.now}),i=ne(e.agent),s=pe(t,e.scope),n=de(t,e.scope,s);if(e.strict===true&&n.status!=="passed"){let r=n.issues.map(g=>`${g.severity}:${g.code}:${g.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${r}`)}let c=e.now??new Date,a=t.facts??[],K=new Set((s?[s]:t.projects).map(r=>r.name)),R=a.filter(r=>r.project?K.has(r.project):true),H=(s?[s]:t.projects).map(r=>{let g=R.filter(p=>p.project===r.name);return {name:r.name,path:r.path,kind:r.kind,category:r.category,runtime:r.runtime,framework:r.frameworkDisplayName,...r.generator?{generator:r.generator}:{},createCapability:r.createCapability,supportTier:r.supportTier,...r.governance?{governance:r.governance}:{},safeCommands:ce(r),importantFiles:r.importantFiles,facts:g}}),S=await me(t,e.workspacePath),F=E.join(e.workspacePath,p.knowledgeGraph),u=await A.pathExists(F)?await A.readJson(F).catch(()=>null):null,N=false;if(u?.schemaVersion===q.knowledgeGraph)try{b(u,t),N=true;}catch{}let $=le(t),M=ie(t,s,c),b$2=await C(e.workspacePath,p.impact,q.impact),l=await C(e.workspacePath,p.doctor,q.doctor),v=await C(e.workspacePath,p.analyze,q.analyze),k=await C(e.workspacePath,p.readiness,q.readiness),h=await C(e.workspacePath,p.verify,q.verify),w=await C(e.workspacePath,p.explain,q.explain),f$1=await C(e.workspacePath,p.diff,q.diff),B=b$2?.summary?{changed:b$2.summary.changed,risk:b$2.summary.risk,affectedProjects:b$2.summary.affectedProjects,blastRadius:b$2.summary.blastRadius,recommendedCommands:b$2.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let r=Array.isArray(l.projects)?l.projects:[],g=[];for(let p of r.slice(0,6)){let te=Array.isArray(p.probes)?p.probes:[];for(let y of te.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&g.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return g.slice(0,8)})()}:void 0,J=v?.summary?{score:v.summary.score,verdict:v.summary.verdict,findingCounts:v.summary.findings,topFindings:(Array.isArray(v.findings)?v.findings:[]).filter(p=>p?.severity==="fail"||p?.severity==="warn").slice(0,8).map(p=>({severity:p.severity,title:p.title,target:p.target,remediation:p.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(r=>({gate:r.gate,status:r.status,summary:r.summary})):void 0}:void 0,Q=h?.summary?{verdict:h.summary.verdict,exitCode:h.summary.exitCode,stepsFailed:h.summary.stepsFailed,stepsMissing:h.summary.stepsMissing,blockingReasons:h.blockingReasons,missingEvidence:h.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(r=>({id:r.id,title:r.title,body:r.body})):void 0}:void 0,Z=f$1?.summary?{changed:f$1.summary.changed,addedProjects:f$1.summary.addedProjects,removedProjects:f$1.summary.removedProjects,changedProjects:f$1.summary.changedProjects,workspaceChanges:f$1.summary.workspaceChanges,validationChanges:f$1.summary.validationChanges,gitChangedFiles:f$1.summary.gitChangedFiles}:void 0,ee=M.map(r=>f({id:`context.command.${r.id}`,label:`${r.id} safe command`,scope:"command",value:{display:r.display,execute:r.execute,scope:r.scope},...r.project?{project:r.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:c,sourceArtifact:p.agentContext,sourcePath:`safeCommands.${r.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),I=[...R,...ee],W=g({facts:I,generatedAt:c.toISOString(),now:c}),j=b$1();return {schemaVersion:re,generatedAt:c.toISOString(),agent:i,workspaceSummary:$,modelRef:p.model,knowledgeGraph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,available:N,...typeof u?.quality?.entityCount=="number"?{entityCount:u.quality.entityCount}:{},...typeof u?.quality?.relationCount=="number"?{relationCount:u.quality.relationCount}:{},...typeof u?.quality?.proofCount=="number"?{proofCount:u.quality.proofCount}:{},queryCommands:[x("workspace graph search <query> --limit 12 --json"),x("workspace graph entities [kind] --json"),x("workspace graph evidence <entity-or-relation> --json"),x("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:j.schemaVersion,contractPath:j.contractPath,currentStep:"context",canonicalReadOrder:[...j.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:`workspace:${t.workspace.name}`,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:M,facts:I,factFreshness:W,evidence:S,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:n,agentInstructions:[`Read \`${p.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${p.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ge(t),...W.verifyBeforeUseFacts>0?[`${W.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[$,`Evidence available: ${S.available.length}. Missing evidence groups: ${S.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
1
+ import {b as b$1}from'./chunk-COICGD62.js';import {b}from'./chunk-R7R5FX4B.js';import {r,f,g}from'./chunk-O4TZKLEC.js';import {d}from'./chunk-WU5M6UP7.js';import {h,g as g$1}from'./chunk-BLEIUQL6.js';import {q,p}from'./chunk-ODK4LCEL.js';import E from'path';import A from'fs-extra';var re=q.agentContext,se=p.agentContext;function ne(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="gemini"||t==="qwen"||t==="kimi"||t==="grok"||t==="copilot"||t==="windsurf"||t==="amazon-q"||t==="orca"?t:"generic"}function G(e){return `npx --yes --package workspai workspai ${e}`.trim()}function x(e){return `npx workspai ${e}`.trim()}async function C(e,t,i){let s=E.join(e,t);if(!await A.pathExists(s))return null;try{let n=await A.readJson(s);return typeof n!="object"||n===null||!("schemaVersion"in n)||n.schemaVersion!==i?null:n}catch{return null}}function m(e){return {id:e.id,scope:e.scope,display:x(e.args),execute:G(e.args),description:e.description,...e.project?{project:e.project}:{},freshness:f({id:`command.${e.id}`,label:`${e.id} command`,scope:"command",value:{display:x(e.args),execute:G(e.args)},...e.project?{project:e.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e.generatedAt,now:e.now,sourceArtifact:p.model,sourcePath:`safeCommands.${e.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function L(e,t){return `workspace run ${t} --scope project:${e.name}`}function ae(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function ie(e,t,i){let s={generatedAt:e.generatedAt,now:i},n=[m({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),m({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),m({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),m({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),m({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),m({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),m({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),m({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=t?[t]:e.projects;for(let a of c)a.commands.fleetStages.includes("test")&&n.push(m({id:`project.${a.name}.test`,scope:"project",project:a.name,args:L(a,"test"),description:`Run tests for ${a.name} through workspace orchestration.`,...s})),a.commands.fleetStages.includes("build")&&n.push(m({id:`project.${a.name}.build`,scope:"project",project:a.name,args:L(a,"build"),description:`Build ${a.name} through workspace orchestration.`,...s}));return n}function ce(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function pe(e,t){if(!t?.startsWith("project:"))return;let i=ae(t);if(i)return e.projects.find(s=>oe(s).includes(i))}function de(e,t,i){let s=[...e.validation?.issues??[]];t?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let n=s.filter(a=>a.severity==="error").length,c=s.filter(a=>a.severity==="warning").length;return {status:n>0?"failed":c>0?"warning":"passed",errors:n,warnings:c,issues:s}}async function me(e,t){let i=[],s=[];for(let[n,c]of Object.entries(e.evidence))c&&await g$1(t,c.path)!==null?i.push(`${n}: ${c.path}`):s.push(n);return {available:i.sort(),missing:s.sort()}}function le(e){let t=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${i}, and ${s}.`}function ge(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),((e.summary.extendedProjects??0)>0||e.summary.observedProjects>0)&&t.push("Some projects use extended or observed support tiers; command coverage may be partial."),t}async function We(e){let t=e.model??await r({workspacePath:e.workspacePath,includeEvidence:e.includeEvidence===true,observableScanDepth:e.observableScanDepth,now:e.now}),i=ne(e.agent),s=pe(t,e.scope),n=de(t,e.scope,s);if(e.strict===true&&n.status!=="passed"){let r=n.issues.map(g=>`${g.severity}:${g.code}:${g.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${r}`)}let c=e.now??new Date,a=t.facts??[],K=new Set((s?[s]:t.projects).map(r=>r.name)),R=a.filter(r=>r.project?K.has(r.project):true),H=(s?[s]:t.projects).map(r=>{let g=R.filter(p=>p.project===r.name);return {name:r.name,path:r.path,kind:r.kind,category:r.category,runtime:r.runtime,framework:r.frameworkDisplayName,...r.generator?{generator:r.generator}:{},createCapability:r.createCapability,supportTier:r.supportTier,...r.governance?{governance:r.governance}:{},safeCommands:ce(r),importantFiles:r.importantFiles,facts:g}}),S=await me(t,e.workspacePath),F=E.join(e.workspacePath,p.knowledgeGraph),u=await A.pathExists(F)?await A.readJson(F).catch(()=>null):null,N=false;if(u?.schemaVersion===q.knowledgeGraph)try{b(u,t),N=true;}catch{}let $=le(t),M=ie(t,s,c),b$2=await C(e.workspacePath,p.impact,q.impact),l=await C(e.workspacePath,p.doctor,q.doctor),v=await C(e.workspacePath,p.analyze,q.analyze),k=await C(e.workspacePath,p.readiness,q.readiness),h=await C(e.workspacePath,p.verify,q.verify),w=await C(e.workspacePath,p.explain,q.explain),f$1=await C(e.workspacePath,p.diff,q.diff),B=b$2?.summary?{changed:b$2.summary.changed,risk:b$2.summary.risk,affectedProjects:b$2.summary.affectedProjects,blastRadius:b$2.summary.blastRadius,recommendedCommands:b$2.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let r=Array.isArray(l.projects)?l.projects:[],g=[];for(let p of r.slice(0,6)){let te=Array.isArray(p.probes)?p.probes:[];for(let y of te.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&g.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return g.slice(0,8)})()}:void 0,J=v?.summary?{score:v.summary.score,verdict:v.summary.verdict,findingCounts:v.summary.findings,topFindings:(Array.isArray(v.findings)?v.findings:[]).filter(p=>p?.severity==="fail"||p?.severity==="warn").slice(0,8).map(p=>({severity:p.severity,title:p.title,target:p.target,remediation:p.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(r=>({gate:r.gate,status:r.status,summary:r.summary})):void 0}:void 0,Q=h?.summary?{verdict:h.summary.verdict,exitCode:h.summary.exitCode,stepsFailed:h.summary.stepsFailed,stepsMissing:h.summary.stepsMissing,blockingReasons:h.blockingReasons,missingEvidence:h.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(r=>({id:r.id,title:r.title,body:r.body})):void 0}:void 0,Z=f$1?.summary?{changed:f$1.summary.changed,addedProjects:f$1.summary.addedProjects,removedProjects:f$1.summary.removedProjects,changedProjects:f$1.summary.changedProjects,workspaceChanges:f$1.summary.workspaceChanges,validationChanges:f$1.summary.validationChanges,gitChangedFiles:f$1.summary.gitChangedFiles}:void 0,ee=M.map(r=>f({id:`context.command.${r.id}`,label:`${r.id} safe command`,scope:"command",value:{display:r.display,execute:r.execute,scope:r.scope},...r.project?{project:r.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:c,sourceArtifact:p.agentContext,sourcePath:`safeCommands.${r.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),I=[...R,...ee],W=g({facts:I,generatedAt:c.toISOString(),now:c}),j=b$1();return {schemaVersion:re,generatedAt:c.toISOString(),agent:i,workspaceSummary:$,modelRef:p.model,knowledgeGraph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,available:N,...typeof u?.quality?.entityCount=="number"?{entityCount:u.quality.entityCount}:{},...typeof u?.quality?.relationCount=="number"?{relationCount:u.quality.relationCount}:{},...typeof u?.quality?.proofCount=="number"?{proofCount:u.quality.proofCount}:{},queryCommands:[x("workspace graph search <query> --limit 12 --json"),x("workspace graph entities [kind] --json"),x("workspace graph evidence <entity-or-relation> --json"),x("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:j.schemaVersion,contractPath:j.contractPath,currentStep:"context",canonicalReadOrder:[...j.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:`workspace:${t.workspace.name}`,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:M,facts:I,factFreshness:W,evidence:S,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:n,agentInstructions:[`Read \`${p.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${p.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ge(t),...W.verifyBeforeUseFacts>0?[`${W.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[$,`Evidence available: ${S.available.length}. Missing evidence groups: ${S.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
2
2
  `),impactSummary:B,doctorSummary:U,analyzeSummary:J,readinessSummary:X,verifySummary:Q,explainSummary:Y,diffSummary:Z}}async function je(e,t){return h(t,se,d(e))}export{re as a,se as b,We as c,je as d};
@@ -1,4 +1,4 @@
1
- import {f,e,h as h$1,g}from'./chunk-XF65LQ6M.js';import {a,b}from'./chunk-SVO2GGTV.js';import {b as b$1,c as c$1}from'./chunk-RQXZF7BZ.js';import {a as a$1}from'./chunk-NMXGSVMD.js';import {p,a as a$2}from'./chunk-MD4CHXV3.js';import {k as k$2,m,l}from'./chunk-7EMG3C3H.js';import {h}from'./chunk-BLEIUQL6.js';import {k,t,u}from'./chunk-VQZ5PI5J.js';import {p as p$1,q}from'./chunk-ODK4LCEL.js';import k$1 from'fs';import c from'path';import s from'chalk';var ee=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function E(e){try{return await k$1.promises.access(e,k$1.constants.F_OK),true}catch{return false}}async function F(e){try{let n=JSON.parse(await k$1.promises.readFile(e,"utf-8"));return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function C(e){try{return await k$1.promises.readFile(e,"utf-8")}catch{return ""}}function re(e){return a(e)}async function oe(e,n){return await ne([...u(e,"project.json"),...u(e,"context.json")])?true:b(e)?false:c.resolve(e)===c.resolve(n)?k$2(e).length>0:k$2(e).length>0}async function ie(e){let n=await a$1(e,{skipDirs:ee,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:oe}),o=(await a$2(e)).filter(i=>i.relationship==="adopted"||i.source==="adopted-local").map(i=>c.resolve(i.path)).filter(i=>k$1.existsSync(i)),r=[...new Set([...n.map(i=>c.resolve(i)),...o])];return r.length>0?r:b(e)?[]:k$2(e).length>0?[e]:[]}function ae(e,n){return c.relative(e,n).replace(/\\/g,"/")||"."}async function T(e,n){for(let t of n)if(await E(c.join(e,t)))return true;return false}async function se(e,n,t=4){let o=async(r,i)=>{if(i>t)return false;let l;try{l=await k$1.promises.readdir(r,{withFileTypes:true});}catch{return false}for(let a of l)if(a.isFile()&&n.has(a.name.toLowerCase())||a.isDirectory()&&!a.isSymbolicLink()&&!ee.has(a.name)&&await o(c.join(r,a.name),i+1))return true;return false};return o(e,0)}async function ne(e){for(let n of e)if(await E(n))return true;return false}async function te(e){for(let n of e){let t=await F(n);if(t)return t}return null}async function ce(e,n){if(await T(e,[".env",".env.local"]))return true;let t=n?.contracts&&typeof n.contracts=="object"?n.contracts:null;if(Array.isArray(t?.env)&&t.env.length>0)return true;let o=await F(c.join(e,"package.json")),r={...o?.dependencies??{},...o?.devDependencies??{}};if(Object.keys(r).some(a=>/^(?:dotenv|dotenv-flow|env-cmd)$/iu.test(a)))return true;let i=await C(c.join(e,"pyproject.toml"));if(/\b(?:python-dotenv|pydantic-settings)\b/iu.test(i))return true;let l=[await C(c.join(e,"compose.yaml")),await C(c.join(e,"compose.yml")),await C(c.join(e,"docker-compose.yml")),await C(c.join(e,"docker-compose.yaml"))].join(`
1
+ import {f,e,h as h$1,g}from'./chunk-XF65LQ6M.js';import {a,b}from'./chunk-SVO2GGTV.js';import {b as b$1,c as c$1}from'./chunk-RQXZF7BZ.js';import {a as a$1}from'./chunk-NMXGSVMD.js';import {p,a as a$2}from'./chunk-WU5M6UP7.js';import {k as k$2,m,l}from'./chunk-7EMG3C3H.js';import {h}from'./chunk-BLEIUQL6.js';import {k,t,u}from'./chunk-VQZ5PI5J.js';import {p as p$1,q}from'./chunk-ODK4LCEL.js';import k$1 from'fs';import c from'path';import s from'chalk';var ee=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function E(e){try{return await k$1.promises.access(e,k$1.constants.F_OK),true}catch{return false}}async function F(e){try{let n=JSON.parse(await k$1.promises.readFile(e,"utf-8"));return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function C(e){try{return await k$1.promises.readFile(e,"utf-8")}catch{return ""}}function re(e){return a(e)}async function oe(e,n){return await ne([...u(e,"project.json"),...u(e,"context.json")])?true:b(e)?false:c.resolve(e)===c.resolve(n)?k$2(e).length>0:k$2(e).length>0}async function ie(e){let n=await a$1(e,{skipDirs:ee,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:oe}),o=(await a$2(e)).filter(i=>i.relationship==="adopted"||i.source==="adopted-local").map(i=>c.resolve(i.path)).filter(i=>k$1.existsSync(i)),r=[...new Set([...n.map(i=>c.resolve(i)),...o])];return r.length>0?r:b(e)?[]:k$2(e).length>0?[e]:[]}function ae(e,n){return c.relative(e,n).replace(/\\/g,"/")||"."}async function T(e,n){for(let t of n)if(await E(c.join(e,t)))return true;return false}async function se(e,n,t=4){let o=async(r,i)=>{if(i>t)return false;let l;try{l=await k$1.promises.readdir(r,{withFileTypes:true});}catch{return false}for(let a of l)if(a.isFile()&&n.has(a.name.toLowerCase())||a.isDirectory()&&!a.isSymbolicLink()&&!ee.has(a.name)&&await o(c.join(r,a.name),i+1))return true;return false};return o(e,0)}async function ne(e){for(let n of e)if(await E(n))return true;return false}async function te(e){for(let n of e){let t=await F(n);if(t)return t}return null}async function ce(e,n){if(await T(e,[".env",".env.local"]))return true;let t=n?.contracts&&typeof n.contracts=="object"?n.contracts:null;if(Array.isArray(t?.env)&&t.env.length>0)return true;let o=await F(c.join(e,"package.json")),r={...o?.dependencies??{},...o?.devDependencies??{}};if(Object.keys(r).some(a=>/^(?:dotenv|dotenv-flow|env-cmd)$/iu.test(a)))return true;let i=await C(c.join(e,"pyproject.toml"));if(/\b(?:python-dotenv|pydantic-settings)\b/iu.test(i))return true;let l=[await C(c.join(e,"compose.yaml")),await C(c.join(e,"compose.yml")),await C(c.join(e,"docker-compose.yml")),await C(c.join(e,"docker-compose.yaml"))].join(`
2
2
  `);return /^\s*(?:env_file|environment)\s*:/imu.test(l)}async function de(e){return (await g(e)).detected}async function le(e){let n=await F(c.join(e,"package.json")),t=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return Object.keys(t).sort()}function w(e,n,t,o,r,i,l){return {id:e,severity:n,target:t,title:o,detail:r,remediation:i,...l&&l.length>0?{files:[...l]}:{}}}function pe(e){let n=e.reduce((t,o)=>o.severity==="fail"?t+28:o.severity==="warn"?t+12:t+3,0);return Math.max(0,100-n)}async function ue(e,n,t){let o=await te(u(n,"project.json")),r=m(n,o),i=l(n),l$1=r.runtime==="unknown"?i[0]||"unknown":r.runtime,a=[l$1,...i.filter(G=>G!==l$1)],u$1=r.key==="unknown"&&new Set(a.filter(G=>G!=="unknown")).size>1,b=await b$1(n,o,{runtime:l$1,framework:r.key}),m$1=["backend","service","worker","agent"].includes(b),h=["backend","service","worker"].includes(b),v=m$1&&/^(?:fastapi|django|flask|nestjs|express|fastify|springboot|gofiber|gogin|dotnet-webapi|laravel|rails|phoenix|axum|actix|rocket)$/u.test(r.key),j=ae(e,n),f=j,$=await le(n),P=await ne([...u(n,"project.json"),...u(n,"context.json")]),x=await de(n),R=await T(n,["Dockerfile","dockerfile"]),g=await T(n,[".env.example","env.example","config/env.example"])||await se(n,new Set([".env.example","env.example"])),p=await ce(n,o),d=await c$1({projectPath:n,declaration:t?.governance}),z=d.ci.status==="repository",D=await h$1(n),y=[];return r.key==="unknown"&&y.push(w(u$1?"project.stack.aggregate":"project.stack.unknown",u$1?"info":"fail",f,u$1?"Multi-runtime aggregate boundary detected":"Project stack is unknown",u$1?`Workspai detected multiple runtimes (${a.join(", ")}) and intentionally did not promote one nested framework as the aggregate project identity.`:"Workspai cannot confidently classify this backend project.",u$1?"Adopt independently operated nested projects when they need separate lifecycle, ownership, or release evidence.":"Add .workspai/project.json metadata or import the project with `workspai import`.")),P||y.push(w("project.marker.missing","warn",f,"Workspai marker is missing","The project can be detected by files, but it is not registered with Workspai metadata.","Run `workspai import <path>` from a workspace or create the project through Workspai.")),x||y.push(w("project.tests.missing","warn",f,"Test entrypoint is missing","No common test folder, config, or package test script was found.","Add a test command so `workspai workspace run test --affected` can gate changes.")),m$1&&p&&!g&&y.push(w("project.env.example.missing","info",f,"Environment example is missing","No .env.example or env.example file was found.","Add an env example for onboarding and CI secret documentation.",[".env.example"])),d.ci.status==="unknown"?y.push(w("project.ci.missing","warn",f,"CI governance is not proven","No repository CI surface or canonical external CI declaration was found for this project.","Add repository CI configuration or declare the external CI authority in the workspace contract.",[".github/workflows/ci.yml"])):d.ci.status==="external-observed"&&y.push(w("project.ci.external-observed","info",f,"Continuous integration appears externally managed",`Repository documentation references an external CI control plane (${d.ci.evidence.join(", ")}).`,"Declare the external CI provider in the canonical workspace contract when authoritative release gating depends on it.")),v&&!D&&y.push(w("project.health.missing","info",f,"Health or readiness probe is missing","The project has no obvious health or readiness endpoint to support automated deployment and runtime checks.","Add a simple health endpoint and document it for readiness gates and observability.")),h&&!R&&y.push(w("project.container.missing","info",f,"Container recipe is missing","No Dockerfile was found for this project.","Add a Dockerfile when the service is intended for containerized deployment.",["Dockerfile"])),{name:typeof o?.name=="string"&&o.name.trim()?o.name.trim():c.basename(n),path:n,relativePath:j,runtime:l$1,runtimeCandidates:a,framework:r.key,confidence:r.confidence,supportTier:r.supportTier,hasRapidKitMarker:P,hasTests:x,hasDockerfile:R,hasEnvExample:g,hasCiConfig:z,governance:d,hasHealthEndpoint:D,scripts:$,findings:y,score:pe(y)}}function me(e){return e.name.toLowerCase()}async function fe(e){let n=new Map(e.map(r=>[me(r),r])),t=[];for(let r of e){let i=await F(c.join(r.path,"package.json")),l={...i?.dependencies??{},...i?.devDependencies??{},...i?.peerDependencies??{}};for(let u of Object.keys(l)){let b=u.replace(/^@[^/]+\//,"").toLowerCase(),m=n.get(b);m&&m.relativePath!==r.relativePath&&t.push({from:r.relativePath,to:m.relativePath,kind:"package"});}let a=await C(c.join(r.path,"pyproject.toml"));for(let u of e)u.relativePath!==r.relativePath&&a.includes(u.name)&&t.push({from:r.relativePath,to:u.relativePath,kind:"workspace-reference"});}let o=new Set;return t.filter(r=>{let i=`${r.from}\0${r.to}\0${r.kind}`;return o.has(i)?false:(o.add(i),true)})}function ge(e,n){let t=new Map;for(let o of e)t.set(o.relativePath,{project:o.relativePath,directDependents:0,directDependencies:0});for(let o of n){let r=t.get(o.from),i=t.get(o.to);r&&(r.directDependencies+=1),i&&(i.directDependents+=1);}return Array.from(t.values()).sort((o,r)=>r.directDependents-o.directDependents||r.directDependencies-o.directDependencies)}async function ye(e){let n=await te(t(e,"workspace.json"));return typeof n?.profile=="string"?n.profile:null}function we(e){return {fail:e.filter(n=>n.severity==="fail").length,warn:e.filter(n=>n.severity==="warn").length,info:e.filter(n=>n.severity==="info").length}}function ke(e){if(e.projectCount===0)return e.workspaceDetected?["Add your first project: npx workspai create project <name> --kit <kit>","Import an existing service: npx workspai import <path>"]:["Create a Workspai workspace: npx workspai create workspace my-workspace --profile polyglot","Import an existing service: npx workspai import ../service"];let n=[];return e.findings.some(t=>t.id==="workspace.marker.missing")&&n.push("Initialize workspace metadata with `workspai bootstrap --profile polyglot`."),e.findings.some(t=>t.id==="project.marker.missing")&&n.push("Register detected projects with `workspai import <path>` or recreate them via `workspai create project`."),e.findings.some(t=>t.id==="project.tests.missing")&&n.push("Add test entrypoints, then gate changes with `workspai workspace run test --affected --strict`."),e.findings.some(t=>t.id==="project.ci.missing")&&n.push("Add CI/CD configuration to catch regressions early and make workspace health checks actionable."),e.findings.some(t=>t.id==="project.health.missing")&&n.push("Add a health/readiness endpoint so runtime probes and deployment checks can verify service health."),e.hasCanonicalGraph||n.push("Generate canonical topology with `workspai workspace model --write --include-evidence`."),n.push("Run `workspai autopilot release --mode audit --json` before release."),Array.from(new Set(n))}async function Te(e$1={}){let n=c.resolve(e$1.workspacePath||process.cwd());if(!await E(n))throw new Error(`Workspace path does not exist: ${n}`);let t=re(n)??n,o=k(t),r=await ye(t),i=await ie(t),l;try{l=(await p({workspacePath:t})).contract;}catch{}let a=await Promise.all(i.map(p=>{let d=l?.projects.find(z=>{let D=z.externalPath??z.relativePath;return c.resolve(t,D)===c.resolve(p)});return ue(t,p,d)})),u=await fe(a),b=ge(a,u),m=[];o||m.push(w("workspace.marker.missing","warn",".","Workspace metadata is missing","The directory can be analyzed, but it is not a registered Workspai workspace.","Run `workspai create workspace` or `workspai bootstrap --profile polyglot` in a workspace root.")),a.length===0&&m.push(w("workspace.projects.missing","warn",".","No backend projects detected","Workspai did not find runtime markers or project metadata under this root.","Create a project with `workspai create project` or import one with `workspai import <path>`."));let h$1=[...m,...a.flatMap(p=>p.findings)],v=we(h$1),j={};for(let p of a)for(let d of p.runtimeCandidates)j[d]=(j[d]||0)+1;let f$1=a.length>0?Math.round(a.reduce((p,d)=>p+d.score,0)/a.length):0,$=m.reduce((p,d)=>p+(d.severity==="fail"?20:d.severity==="warn"?8:2),0),P=Math.max(0,f$1-$),x=a.length===0&&v.fail===0&&h$1.length>0&&h$1.every(p=>p.id==="workspace.projects.missing"&&p.severity==="warn"),R=v.fail>0||e$1.strict&&v.warn>0&&!x?"blocked":v.warn>0?"needs-attention":"ready",g={schemaVersion:q.analyze,generatedAt:new Date().toISOString(),workspacePath:t,workspaceDetected:o,profile:r,summary:{statusScope:"source-structure",releaseReadiness:"not-evaluated",score:P,verdict:R,projectCount:a.length,runtimeCount:Object.keys(j).length,findings:v},runtimes:j,projects:a,dependencyGraph:{status:u.length>0?"generated":"empty",edges:u,topImpactedProjects:b.slice(0,5)},findings:h$1,nextActions:ke({findings:h$1,projectCount:a.length,hasCanonicalGraph:await E(c.join(t,p$1.knowledgeGraph)),workspaceDetected:o}),enterpriseControls:{jsonReady:true,ciGateCommand:"workspai analyze --json --strict",releaseGateCommand:"workspai autopilot release --mode enforce --json",evidencePath:p$1.analyze}};if(e$1.output&&(await k$1.promises.mkdir(c.dirname(c.resolve(e$1.output)),{recursive:true}),await k$1.promises.writeFile(c.resolve(e$1.output),`${JSON.stringify(g,null,2)}
3
3
  `)),!e$1.output&&o){let p=f(g,{commandId:"workspaceAnalyze",exitCode:g.summary.verdict==="blocked"?2:g.summary.verdict==="needs-attention"?1:0,generatedAt:g.generatedAt,blockers:g.findings.filter(d=>d.severity==="fail").map(d=>d.title).slice(0,12),runId:e()});await h(t,p$1.analyze,p);}return g}function Ne(e){let n=e.summary.verdict==="ready"?s.green:e.summary.verdict==="needs-attention"?s.yellow:s.red;if(console.log(s.bold(`
4
4
  Workspai Workspace Analysis
@@ -0,0 +1,2 @@
1
+ import {b}from'./chunk-6CZQXEZ7.js';import {N,M,k,q,G,I as I$1,O}from'./chunk-RRZQPFFR.js';import {c}from'./chunk-7HV4U2OV.js';import {e,f}from'./chunk-EFHSRPW7.js';import {b as b$1}from'./chunk-UJXE4UAX.js';import {m,l}from'./chunk-VQZ5PI5J.js';import {AsyncLocalStorage}from'async_hooks';import {promises}from'fs';import d from'path';import B,{homedir}from'os';import {pathToFileURL}from'url';import h from'process';import ue from'fs-extra';var C={schemaVersion:"workspai.model-gateway-qualification.v1",workspaiReleaseAuthority:"source-ready",attach:"unsupported",adapters:[{adapterId:"openrouter-typescript",status:"source-ready",platforms:[]},{adapterId:"openrouter-python",status:"source-ready",platforms:[]}]};var L=["ubuntu-latest","macos-latest","windows-latest"];function ee(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Model gateway qualification document must be an object.");let t=e;if(!Array.isArray(t.adapters)||t.adapters.length===0)throw new Error("Model gateway qualification document contains no adapters.");let r=new Set;for(let a of t.adapters){if(!a||typeof a.adapterId!="string")throw new Error("Model gateway qualification adapter is missing adapterId.");if(r.has(a.adapterId))throw new Error(`Duplicate model gateway qualification adapter: ${a.adapterId}`);r.add(a.adapterId);let s=N(a.adapterId);if(!s)throw new Error(`Qualification adapter ${a.adapterId} is not in the version baseline.`);if(a.status!=="source-ready"&&a.status!=="qualified")throw new Error(`Invalid qualification status for ${a.adapterId}.`);if(!Array.isArray(a.platforms))throw new Error(`Qualification platforms missing for ${a.adapterId}.`);if(a.status==="source-ready"){if(a.platforms.length!==0)throw new Error(`Source-ready adapter ${a.adapterId} must not record platform qualification.`);continue}let c=new Set;for(let o of a.platforms){if(!o||!L.includes(o.os)||o.result!=="pass"||o.skippedRequiredStage!==false||o.sdkVersion!==s.sdkVersion)throw new Error(`Qualified adapter ${a.adapterId} is missing a valid platform record bound to ${s.sdkVersion}.`);if(c.has(o.os))throw new Error(`Duplicate platform ${o.os} for ${a.adapterId}.`);c.add(o.os);}for(let o of L)if(!c.has(o))throw new Error(`Qualified adapter ${a.adapterId} is missing ${o} evidence.`)}for(let a of M)if(!r.has(a.adapterId))throw new Error(`Baseline adapter ${a.adapterId} has no qualification record.`);let n=t.adapters.every(a=>a.status==="qualified");if(n)throw new Error("All adapters are qualified; release authority must match.")}ee(C);var y=C,F=Object.freeze({schemaVersion:y.schemaVersion,workspaiReleaseAuthority:y.workspaiReleaseAuthority,attach:y.attach,adapters:Object.freeze(y.adapters.map(e=>Object.freeze({...e,platforms:Object.freeze(e.platforms.map(t=>Object.freeze(t)))})))}),te=F.workspaiReleaseAuthority;function Q(e){return `${e} \xB7 ${te}`}var A=["backend","frontend","desktop","agent","gateway","extension","gaming"],re=[{id:"backend",label:"Backend",hint:"APIs and services"},{id:"frontend",label:"Frontend",hint:"Web applications"},{id:"desktop",label:"Desktop",hint:"Native desktop applications"},{id:"agent",label:"AI Agent",hint:"Governed agent runtimes"},{id:"gateway",label:"AI Gateway",hint:"Unified model access and routing"},{id:"extension",label:"Extension",hint:"Editor and platform extensions"},{id:"gaming",label:"Gaming",hint:"Game runtimes and tooling"}];function oe(e){let r=e.label.indexOf(" \u2014 ");return r>=0?e.label.slice(r+3).trim():e.label.trim()}function ae(e){return A.includes(e.category)?e.category:null}function V(e){let t=c().flatMap(o=>{let i=ae(o);return i?[{value:o.id,label:`${U(i)} \xB7 ${oe(o)}`,hint:`${o.runtime} \xB7 tested baseline`,name:o.label,category:i}]:[]}),r=k().map(o=>({value:o.kitId,label:`Frontend \xB7 ${o.displayName}`,hint:"official \xB7 latest stable",name:`${o.displayName} \u2014 ${o.framework}`,category:"frontend"})),n=q().map(o=>({value:o.kitId,label:`${U(o.category)} \xB7 ${o.displayName}`,hint:`${o.runtimeCandidates.join(" + ")} \xB7 official latest stable`,name:`${o.displayName} \u2014 ${o.category}`,category:o.category})),a=G().map(o=>({value:o.id,label:`AI Agent \xB7 ${o.label}`,hint:`${o.runtime} \xB7 ${I$1(o)?"release-admitted baseline":`${o.stability} \xB7 awaiting release admission`}`,name:o.label,category:"agent"})),s=O().map(o=>({value:o.id,label:`AI Gateway \xB7 ${o.label}`,hint:Q(o.runtime),name:o.label,category:"gateway"})),c$1=[...t,...r,...n,...a,...s].filter(o=>!e||o.category===e).sort((o,i)=>{let l=A.indexOf(o.category),k=A.indexOf(i.category);return l-k||(o.label??"").localeCompare(i.label??"")});return Y(c$1),c$1}function Pe(){let e=new Set(V().map(t=>t.category));return re.filter(t=>e.has(t.id)).map(t=>({value:t.id,label:t.label,hint:t.hint}))}function U(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Y(e){let t=new Set,r=new Set;for(let n of e){let a=n.label??n.name??String(n.value),s=String(n.value);if(t.has(a))throw new Error(`Duplicate kit picker label: ${a}`);if(r.has(s))throw new Error(`Duplicate kit picker value: ${s}`);t.add(a),r.add(s);}}var E="__workspai_create_back__",g=class extends Error{},w=new AsyncLocalStorage;async function tt(e){if(w.getStore())return e();let t={history:[],cursor:0,active:true};return w.run(t,async()=>{for(;;){t.cursor=0;try{return await e()}catch(r){if(!(r instanceof g)||!t.active)throw r}}})}function rt(e){return e instanceof g}function ot(){let e=w.getStore();e&&(e.active=false,e.history=[]);}async function _(e,t=b){let r=w.getStore();if(!r?.active)return t(e);if(e.length>1){let i={};for(let l of e)l.when===false||typeof l.when=="function"&&!l.when(i)||Object.assign(i,await _([{...l,when:void 0}],t));return i}let n=JSON.stringify(e.map(({name:i,type:l,choices:k})=>[i,l,k?.map(({value:P})=>P)])),a=r.history[r.cursor];if(a?.key===n)return r.cursor+=1,a.answers;r.history.length=r.cursor;let s=r.cursor>0,c=e.map(i=>s?i.type==="list"||i.type==="rawlist"?{...i,choices:[...i.choices??[],{label:"\u2190 Back",value:E,hint:"Return to the previous step"}]}:i.type==="confirm"?{...i,type:"rawlist",default:i.default===true?"__create_yes__":"__create_no__",choices:[{label:"Yes",value:"__create_yes__"},{label:"No",value:"__create_no__"},{label:"\u2190 Back",value:E,hint:"Return to the previous step"}]}:i.type==="input"?{...i,message:`${i.message??i.name} (type /back to return)`,initialValue:"",validate:l=>l.trim()==="/back"||(i.validate?.(l)??true)}:i:i),o=await t(c);if(s&&c.some(i=>{let l=o[i.name];return l===E||i.type==="input"&&typeof l=="string"&&l.trim()==="/back"}))throw r.history.length=r.cursor-1,new g;for(let i of e)if(i.type==="confirm"){let l=o[i.name];(l==="__create_yes__"||l==="__create_no__")&&(o[i.name]=l==="__create_yes__");}return r.history.push({key:n,answers:o}),r.cursor+=1,o}var se=".workspairc.json",ce=".rapidkitrc.json",le=["workspai.config.js","workspai.config.mjs","workspai.config.cjs","rapidkit.config.js","rapidkit.config.mjs","rapidkit.config.cjs"],de=["workspai.config.json","rapidkit.config.json"];function H(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function I(e,t){let r=t instanceof Error?t.message:String(t),n=e.endsWith(".js")&&/module is not defined in ES module scope/i.test(r)?' CommonJS syntax in a .js config is not valid when the project package uses "type": "module"; rename the file to .cjs or use export default.':"";return `Failed to load Workspai config at ${e}.${n} Cause: ${r}`}async function pt(){for(let e$1 of [d.join(B.homedir(),se),d.join(B.homedir(),ce)])try{let t=await promises.readFile(e$1,"utf-8"),r=JSON.parse(t);return e.debug(`Loaded config from ${e$1}`),r}catch{}return e.debug("No user config found, using defaults"),{}}async function ft(e$1=process.cwd(),t={}){let r=e$1,n=d.parse(r).root;for(;r!==n;){for(let a of de){let s=d.join(r,a);try{let c=await promises.readFile(s,"utf-8"),o=JSON.parse(c);if(!o||typeof o!="object"||Array.isArray(o))throw new Error("configuration root must be a JSON object");return e.debug(`Loaded data-only Workspai config from ${a}`),o}catch(c){if(H(c))continue;throw new Error(I(s,c))}}for(let a of le){let s=d.join(r,a);try{await promises.access(s);}catch(c){if(H(c))continue;throw new Error(I(s,c))}if(e.debug(`Found config file: ${s}`),!t.trustExecutableConfig)throw new Error(`Refusing to execute Workspai config at ${s} without explicit trust. Use a data-only workspai.config.json file, pass --trust-config, or set WORKSPAI_TRUST_CONFIG=1.`);try{let o=await import(pathToFileURL(s).href),i=o.default||o;return e.debug(`Loaded Workspai config from ${a}`),i}catch(c){throw new Error(I(s,c))}}r=d.dirname(r);}return e.debug("No Workspai config file found, using defaults"),{}}function mt(e,t,r){return {author:r.author||t.workspace?.defaultAuthor||e.author,pythonVersion:r.pythonVersion||t.workspace?.pythonVersion||e.pythonVersion,defaultInstallMethod:r.defaultInstallMethod||t.workspace?.installMethod||e.defaultInstallMethod,defaultKit:r.defaultKit||t.projects?.defaultKit||e.defaultKit,skipGit:r.skipGit??t.projects?.skipGit??e.skipGit,license:r.license||e.license,testRapidKitPath:r.testRapidKitPath||e.testRapidKitPath}}function gt(e){return f("DEV_PATH")||e.testRapidKitPath||void 0}var v=class extends Error{constructor(r,n){super(["Workspai workspaces cannot be nested.",`Target: ${r}`,`Containing workspace: ${n}`,"Choose Managed home or pass --output <path> with a location outside the current workspace."].join(`
2
+ `));this.targetPath=r;this.containingWorkspacePath=n;this.name="NestedWorkspaceCreationError";}targetPath;containingWorkspacePath;code="WORKSPACE_NESTING_NOT_SUPPORTED"};async function pe(e){try{return !!await ue.stat(e)}catch{return false}}function fe(e,t){let r=e.indexOf(t);if(r>=0&&r+1<e.length)return e[r+1];let n=e.find(a=>a.startsWith(`${t}=`));if(n)return n.slice(t.length+1)}function me(e){return e.includes("--here")}async function J(e){let t=d.resolve(e);for(;;){let r=[d.join(t,".workspai-workspace"),d.join(t,".rapidkit-workspace"),d.join(t,".workspai","workspace.json"),d.join(t,".rapidkit","workspace.json")];if((await Promise.all(r.map(pe))).some(Boolean))return t;let n=d.dirname(t);if(n===t)return;t=n;}}async function It(e){let t=d.resolve(e),r=await J(d.dirname(t));if(r)throw new v(t,r)}async function ge(e,t=homedir()){let n=[{value:"managed",label:"Managed home",hint:l(t)}];return await J(e)||n.push({value:"here",label:"Current directory",hint:e}),n}function z(e,t=h.cwd()){if(me(e))return d.resolve(t);let r=fe(e,"--output");if(r)return d.resolve(r)}function xt(e,t=h.cwd()){let r=d.resolve(e),n=d.resolve(t),a=d.relative(n,r);return a.length>0&&!a.startsWith("..")&&!d.isAbsolute(a)?`cd ${a}`:`cd ${r}`}function vt(e,t={}){let r=t.argv??[],n=t.outputParent??z(r,h.cwd());return m(e.trim(),{homeDir:t.homeDir,outputDir:n})}function Pt(e,t,r={}){return e?d.resolve(e)===d.resolve(t)?true:r.outputParent===void 0:false}async function St(e,t={}){let r=t.cwd??h.cwd(),n=t.homeDir??homedir(),a=z(e,r);if(a!==void 0)return a;let s=t.hasYes??(e.includes("--yes")||e.includes("-y"));if(!(t.interactive??(!s&&!!h.stdin.isTTY&&!b$1())))return;let o=await ge(r,n);if(o.length===1)return;let{location:i}=await _([{type:"rawlist",name:"location",message:"Where should the workspace be created?",choices:o,default:0}]);if(i==="here")return d.resolve(r)}export{V as a,Pe as b,tt as c,rt as d,ot as e,_ as f,pt as g,ft as h,mt as i,gt as j,It as k,xt as l,vt as m,Pt as n,St as o};
@@ -1,2 +1,2 @@
1
- import {a as a$2,D as D$1}from'./chunk-7HV4U2OV.js';import {d}from'./chunk-ROOPODG6.js';import {j,m,i}from'./chunk-7EMG3C3H.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$3,g,f as f$1,h}from'./chunk-BLEIUQL6.js';import {b}from'./chunk-VN2MKTQO.js';import {a}from'./chunk-XWKGZRHN.js';import {a as a$4}from'./chunk-252EKOR6.js';import {l}from'./chunk-OCGZNSOE.js';import {c}from'./chunk-64XWHDZ3.js';import {t as t$1,u,q as q$1}from'./chunk-VQZ5PI5J.js';import {t,p,s,q}from'./chunk-ODK4LCEL.js';import*as f from'path';import f__default from'path';import k from'fs-extra';import Re from'crypto';var Ae="unknown-run";function de(e){let t=c();return !t||t===Ae?e:{...e,runId:t}}async function ue(e,t){await k.ensureDir(f.dirname(e));let r=`${e}.${process.pid}.${Date.now()}.${Re.randomUUID()}.tmp`;try{await k.writeJSON(r,t,{spaces:2}),await k.move(r,e,{overwrite:true});}finally{await k.remove(r).catch(()=>{});}}function le(e){return q$1(e,"imported-projects.json")}async function I(e){let t=(await Promise.all(t$1(e,"imported-projects.json").map(async r=>await k.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!t)return [];try{let r=await k.readJSON(t);if(!r||typeof r!="object"||r.version!==1||!Array.isArray(r.projects))throw new Error("expected a version 1 registry with a projects array");let o=r.projects,n=o.filter(i=>{if(!i||typeof i!="object")return false;let c=i;return typeof c.name=="string"&&typeof c.path=="string"&&typeof c.stack=="string"&&typeof c.confidence=="string"&&typeof c.importedAt=="string"});if(n.length!==o.length)throw new Error("one or more project entries are invalid");return n}catch(r){throw new Error(`Imported-project registry is invalid: ${t}`,{cause:r})}}async function Xe(e,t){if(t.length===0)return;let r=le(e);await a(`${r}.lock`,async()=>{let o=await I(e),n=new Map;for(let c of o)n.set(c.path,c);for(let c of t)n.set(c.path,c);let i=Array.from(n.values()).sort((c,l)=>c.name.localeCompare(l.name)).map(c=>({...c}));await ue(r,{version:1,updatedAt:new Date().toISOString(),projects:i});},{timeoutMs:3e4,staleMs:6e4,purpose:"imported-projects-registry-upsert"});}async function et(e,t){if(t.length===0)return;let r=le(e);await a(`${r}.lock`,async()=>{let o=await I(e),n=new Set(t.map(c=>f.resolve(c))),i=o.filter(c=>!n.has(f.resolve(c.path)));await ue(r,{version:1,updatedAt:new Date().toISOString(),projects:i});},{timeoutMs:3e4,staleMs:6e4,purpose:"imported-projects-registry-remove"});}var ot="workspace-dependency-graph.v1",me=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],ge=["inferred","contract","manual"];var v=t.workspaceContract,xe=p.contractVerify,G=s.workspaceContract.schemaVersion,_e=q.contractVerify,D=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function Pe(e){return e.replace(/\\/g,"/")}function z(e){let t=Pe(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function fe(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function ye(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Ge(e){return [...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function Oe(e){let t=e.contracts;return !t||typeof t!="object"||Array.isArray(t)?[]:ye(t.env)}function Ce(e){let t=(e||"").toLowerCase();return t.includes("vscode-extension")||t.includes("desktop.electron")||t.startsWith("extension.")||t.startsWith("desktop.")&&!t.includes("tauri")||t.startsWith("agent.")}function he(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(i=>{if(!i||typeof i!="object"||Array.isArray(i))return null;let c=i,l=Number(c.port);if(!Number.isInteger(l)||l<1||l>65535)return null;let m=c.protocol==="https"||c.protocol==="grpc"||c.protocol==="tcp"||c.protocol==="udp"?c.protocol:"http";return {name:typeof c.name=="string"&&c.name.trim()?c.name:"http",port:l,protocol:m}}).filter(i=>i!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,n=Number(e.port??o?.default_port);return Number.isInteger(n)&&n>=1&&n<=65535?[{name:"http",port:n,protocol:"http"}]:[]}async function Ne(e){let t=f__default.join(e,"Dockerfile");if(!await k.pathExists(t))return [];try{let r=await k.readFile(t,"utf8"),o=new Map;for(let n of r.matchAll(/^\s*EXPOSE\s+(.+)$/gim))for(let i of n[1].split(/\s+/)){let c=i.match(/^(\d{1,5})(?:\/(tcp|udp))?$/i),l=Number(c?.[1]);if(!c||!Number.isInteger(l)||l<1||l>65535)continue;let m=c[2]?.toLowerCase();o.set(l,{name:"http",port:l,protocol:m==="udp"?"udp":"http"});}return [...o.values()].sort((n,i)=>n.port-i.port)}catch{return []}}async function T(e){for(let t of e)if(await k.pathExists(t))return t;return null}async function Ie(e){for(let r of t$1(e,"workspace.json"))try{let o=await k.readJson(r);return {name:typeof o.workspace_name=="string"&&o.workspace_name.trim()||typeof o.name=="string"&&o.name.trim()||f__default.basename(e),profile:typeof o.profile=="string"?o.profile:void 0}}catch{}let t=await a$4(e);return t?.name?.trim()?{name:t.name.trim()}:{name:f__default.basename(e)}}async function De(e){let t=[],r=[e],o=new Set,n=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let i=r.shift();if(!i||o.has(i))continue;o.add(i);let c=await T(u(i,"project.json")),l=await T(u(i,"context.json"));if(c||l){t.push(c??l??"");continue}let m;try{m=await k.readdir(i,{withFileTypes:true});}catch{continue}for(let d of m)!d.isDirectory()||n.has(d.name)||a$1(d.name)||r.push(f__default.join(i,d.name));}return t.sort()}function Te(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function $e(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return Ce(e)?null:r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:r.startsWith("adopted.")?null:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function B(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function U(e,t,r){let o=e!==void 0&&e.source===void 0,n=$e(t.kit,t.runtime),i=e?.ports||[],c=t.ports||[],l=Ce(t.kit),m=t.source==="adopted-local"&&e?.source!==void 0,d=t.source!==void 0&&e?.source!==void 0,p=(l&&c.length===0?[]:m?c.length>0?c:n?[{name:"http",port:B(n,r),protocol:"http"}]:[]:i.length>0?i:c.length>0?c:n?[{name:"http",port:B(n,r),protocol:"http"}]:[]).map(P=>({...P,port:B(P.port,r)}));for(let P of p)r.add(P.port);let g={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&z(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:d?t.runtime:e?.runtime||t.runtime,framework:d?t.framework:e?.framework||t.framework,kit:d?t.kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:p,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:Ge([...e?.contracts?.env??[],...t.contracts.env??[]])}},h=JSON.stringify(e||null)!==JSON.stringify(g);return {project:g,changed:h}}async function Ee(e){let t=f__default.resolve(e.workspacePath),r=await Ie(t),o=await De(t),n=await I(t),i$1=new Map(n.map(s=>[f__default.resolve(s.path),s])),c=[];for(let s of n){let p=f__default.resolve(s.path),g=await T(u(p,"project.json"))??await T(u(p,"context.json"));!g||o.some(h=>f__default.resolve(h)===f__default.resolve(g))||c.push({projectJsonPath:g,registryEntry:s});}let l=[],m$1=[...o.map(s=>({projectJsonPath:s,registryEntry:i$1.get(f__default.resolve(f__default.dirname(f__default.dirname(s))))})),...c];for(let{projectJsonPath:s,registryEntry:p}of m$1){let g=f__default.dirname(f__default.dirname(s)),h=Pe(f__default.relative(t,g)),P=p!==void 0&&!z(h),C=fe(p?.name||f__default.basename(g),f__default.basename(g)),b=P?`external/${C}`:h||C,w=await k.readJson(s),a=typeof w.kit_name=="string"&&w.kit_name||typeof w.kit=="string"&&w.kit||void 0,E=j(w)?m(g,w):void 0,j$1=E!==void 0&&E.key!=="unknown",S=i({runtime:typeof w.runtime=="string"?w.runtime:void 0,framework:typeof w.framework=="string"?w.framework:void 0,kitName:a}),y=a$2(a),$=j$1?E.runtime:S.runtime!=="unknown"?S.runtime:y?.runtime,K=j$1?E.key:typeof w.framework=="string"&&w.framework||(S.key!=="unknown"?S.key:void 0)||y?.framework||Te(a),We=p?.relationship==="adopted"?"adopted":"imported",Se=j$1?`${We}.${E.key}`:a;l.push({slug:p?.name||b||f__default.basename(g),relativePath:b,source:p?.source??"workspace",relationship:p?.relationship,externalPath:P?g:void 0,runtime:$,framework:K,kit:Se,modules:ye(w.modules),ports:he(w).length>0?he(w):await Ne(g),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:Oe(w)}});}let d=new Map;for(let s of l){let p=fe(s.slug,s.relativePath),g=d.get(p);(!g||g.source!=="workspace"&&s.source==="workspace")&&d.set(p,s);}return {schemaVersion:G,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...d.values()]}}async function Et(e){let t=f__default.resolve(e.outputPath||a$3(e.workspacePath,v));if(await k.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await Ee({workspacePath:e.workspacePath,now:e.now}),o=new Set,n={...r,projects:r.projects.map(c=>U(void 0,c,o).project)},i=await be({workspacePath:e.workspacePath,contractPath:t,contract:n});if(e.strict&&i.status==="failed")throw new D(i);return await ve({workspacePath:e.workspacePath,contractPath:t,contract:n,now:e.now}),{contractPath:t,contract:n}}async function vt(e){let t=f__default.resolve(e.workspacePath),r=a$3(t,v),o=await g(t,v)??r,n=await Ee({workspacePath:t,now:e.now}),i=await k.pathExists(o)?await k.readJson(o):null,c=new Map((i?.projects||[]).map(h=>[h.slug,h])),l=new Set,m=[],d=[],s=[];for(let h of n.projects){let P=c.get(h.slug),C=U(P,h,l);P?C.changed&&d.push(h.slug):m.push(h.slug),s.push(C.project),c.delete(h.slug);}for(let h of c.values()){if(h.source)continue;let P=U(h,h,l);s.push(P.project);}let p={schemaVersion:G,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...i?.workspace||{},...n.workspace,name:n.workspace.name||i?.workspace?.name||f__default.basename(t)},projects:s.sort((h,P)=>h.slug.localeCompare(P.slug))},g$1=await be({workspacePath:t,contractPath:r,contract:p});if(e.strict&&g$1.status==="failed")throw new D(g$1);return await ve({workspacePath:t,contractPath:r,contract:p,now:e.now}),{contractPath:r,contract:p,addedProjects:m,updatedProjects:d,verification:g$1}}async function ke(e){return await k.pathExists(e)?{exists:true,contents:await k.readFile(e)}:{exists:false}}async function we(e,t){if(!t.exists){await k.remove(e);return}await k.outputFile(e,t.contents);}async function ve(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-ZC5CFZXP.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),n=a$3(e.workspacePath,r),i=c=>{if(!c||typeof c!="object"||Array.isArray(c))return JSON.stringify(c);let{generatedAt:l,...m}=c;return JSON.stringify(m)};if(await k.pathExists(e.contractPath)&&await k.pathExists(n)){let[c,l]=await Promise.all([k.readJson(e.contractPath),k.readJson(n)]);if(i(c)===i(e.contract)&&i(l)===i(o))return}b(v,e.contract),b(r,o),await f$1(e.workspacePath,v,async()=>{let[c,l]=await Promise.all([ke(e.contractPath),ke(n)]);try{if(e.contractPath===a$3(e.workspacePath,v)?await h(e.workspacePath,v,e.contract):(await k.ensureDir(f__default.dirname(e.contractPath)),await k.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await h(e.workspacePath,r,o);}catch(m){let s=(await Promise.allSettled([we(e.contractPath,c),we(n,l)])).filter(p=>p.status==="rejected");throw s.length>0?new AggregateError([m,...s.map(p=>p.reason)],"Workspace contract publication failed and rollback was incomplete."):m}});}async function je(e){let t=e.contractPath??(await g(e.workspacePath,v)||a$3(e.workspacePath,v)),r=await k.readJson(t);return {contractPath:t,contract:r}}var Ke={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function Ve(e,t){return d(e,t.relativePath,{...t.externalPath?{absolutePath:t.externalPath}:{}})}async function Me(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(Ke))for(let n of o)await k.pathExists(f__default.join(e,n))&&t[r].push(n);try{let r=await k.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,n)=>o.localeCompare(n));return t}function _(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function Fe(e){try{let t=await k.readJson(f__default.join(e,"package.json")),r={runtime:_(t.dependencies),development:_(t.devDependencies),peer:_(t.peerDependencies),optional:_(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:_(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function Le(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await k.readFile(f__default.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,n)=>o.localeCompare(n))}catch{}return []}function He(e,t){try{let r=D$1(e);if(r.engine!=="unknown")return r;let o=k.pathExistsSync(f__default.join(e,"package.json"))?"npm":k.pathExistsSync(f__default.join(e,"pyproject.toml"))?"python":k.pathExistsSync(f__default.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",runtimeCandidates:["unknown"],compositeRuntime:false,lifecycleCoverage:"complete",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function Je(e,t,r){let o=e.projects.map(n=>({id:n.slug,path:n.relativePath,runtime:n.runtime,framework:n.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function jt(e){let{contractPath:t,contract:r}=await je(e),o=e.now??new Date,n=o.toISOString(),{buildWorkspaceModel:i,workspaceModelProjectTopology:c}=await import('./workspace-model-J757KSDE.js'),{hashWorkspaceModel:l}=await import('./workspace-model-hash-ZXYPIGCW.js'),m=await i({workspacePath:e.workspacePath,includeEvidence:false,now:o}),d=c(m)??Je(r,n,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(d.nodes.map(a=>[a.id,a.operationalProfile])),{buildWorkspaceKnowledgeGraph:p$1}=await import('./workspace-knowledge-graph-5EECTGXQ.js'),g=await p$1({workspacePath:e.workspacePath,workspace:{name:m.workspace.name,...m.workspace.profile?{profile:m.workspace.profile}:{}},contract:r,projectTopology:d,now:o,projects:m.projects.map(a=>({id:a.name,path:a.path,...a.absolutePath?{absolutePath:a.absolutePath}:{},runtime:a.runtime,runtimeCandidates:a.runtimeCandidates,framework:a.framework,...a.kit?{kit:a.kit}:{}})),source:{kind:"workspace-model",artifact:p.model,hashAlgorithm:"sha256",hash:l(m)}}),h=await Promise.all(r.projects.map(async a=>{let u=Ve(e.workspacePath,a),[E,j,S]=await Promise.all([Me(u),Fe(u),Le(u)]),y=He(u,a);return {id:a.slug,label:a.slug,relativePath:a.relativePath,source:a.source,relationship:a.relationship,externalPath:a.externalPath,runtime:a.runtime??y.runtime,framework:a.framework??y.framework,kit:a.kit,modules:a.modules,ports:a.ports,apis:a.contracts.apis,owns:a.contracts.owns,env:[...new Set([...a.contracts.env,...S])].sort(($,K)=>$.localeCompare(K)),contracts:{owns:[...a.contracts.owns],apis:[...a.contracts.apis],publishes:[...a.contracts.publishes],consumes:[...a.contracts.consumes],dependsOn:[...a.contracts.dependsOn],env:[...a.contracts.env]},capabilities:{engine:y.engine,supportTier:y.frameworkSupportTier,runtimeSupportTier:y.runtimeSupportTier,doctorSupport:y.runtimeDoctorSupport,moduleSupport:y.moduleSupport,fleetStages:[...y.fleetStages],localOnlyCommands:[...y.localOnlyCommands],supportedCommands:[...y.supportedCommands]},files:E,...j?{package:j}:{},...s.get(a.slug)?{operationalProfile:s.get(a.slug)}:{}}})),P=new Set(h.map(a=>a.id)),C=new Map,b=[];for(let a of r.projects){for(let u of a.contracts.dependsOn||[])P.has(u)&&b.push({from:u,to:a.slug,type:"dependency",label:"dependsOn"});for(let u of a.contracts.publishes||[])C.has(u)||C.set(u,new Set),C.get(u)?.add(a.slug);}for(let a of r.projects)for(let u of a.contracts.consumes||[]){let E=C.get(u);if(E)for(let j of E)j!==a.slug&&b.push({from:j,to:a.slug,type:"event",label:u});}let w={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:n,nodes:h.sort((a,u)=>a.id.localeCompare(u.id)),edges:b.sort((a,u)=>`${a.from}:${a.to}:${a.type}:${a.label}`.localeCompare(`${u.from}:${u.to}:${u.type}:${u.label}`)),dependencyGraph:d,knowledgeGraph:g,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:h.length,dependencyEdges:b.filter(a=>a.type==="dependency").length,eventEdges:b.filter(a=>a.type==="event").length,portCount:h.reduce((a,u)=>a+u.ports.length,0),apiCount:h.reduce((a,u)=>a+u.apis.length,0),relationshipEdges:d.stats.edgeCount,inferredEdges:d.stats.inferredEdges,authoritativeEdges:d.stats.authoritativeEdges,orphanProjects:d.stats.orphanCount,hotspotProjects:d.stats.hotspotCount,evidenceCoverageRatio:d.stats.evidenceCoverageRatio,edgeCoverageRatio:d.stats.edgeCoverageRatio,connectedProjects:d.stats.connectedNodeCount,lowConfidenceEdges:d.stats.lowConfidenceEdges,hasCycle:d.stats.hasCycle,manifestCount:h.reduce((a,u)=>a+u.files.manifests.length,0),entrypointCount:h.reduce((a,u)=>a+u.files.entrypoints.length,0),diagnostics:d.diagnostics?.length??0,relationshipKinds:Object.fromEntries(me.map(a=>[a,d.edges.filter(u=>u.kind===a).length])),relationshipSources:Object.fromEntries(ge.map(a=>[a,d.edges.filter(u=>u.source===a).length])),entityCount:g.quality.entityCount,knowledgeRelations:g.quality.relationCount,proofCount:g.quality.proofCount,providerCount:g.providers.length,knowledgeUnknowns:g.quality.unknownCount}};return {contractPath:t,graph:w}}async function be(e){let t=e.contract?{contractPath:e.contractPath??a$3(e.workspacePath,v),contract:e.contract}:await je(e),{contractPath:r,contract:o}=t,n=[],i=[];o.kind!=="rapidkit.workspace.contract"&&n.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==G&&n.push(`Contract schemaVersion must be ${G}.`),o.workspace?.name||n.push("Contract workspace.name is required."),Array.isArray(o.projects)||n.push("Contract projects must be an array.");let c=new Set,l$1=new Map;for(let s of o.projects||[]){if(!s.slug){n.push("Every project must declare slug.");continue}c.has(s.slug)&&n.push(`Duplicate project slug: ${s.slug}.`),c.add(s.slug),s.relativePath?z(s.relativePath)||n.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):n.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||n.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),f__default.isAbsolute(s.externalPath)||n.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let p of s.ports||[]){(!Number.isInteger(p.port)||p.port<1||p.port>65535)&&n.push(`Project ${s.slug} declares invalid port: ${p.port}.`);let g=l$1.get(p.port);g&&n.push(`Port ${p.port} is claimed by both ${g} and ${s.slug}.`),l$1.set(p.port,s.slug);}for(let p of s.contracts?.apis||[])(!p.name?.trim()||!p.basePath?.startsWith("/"))&&n.push(`Project ${s.slug} declares invalid API contract.`);for(let p of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])p.trim()||n.push(`Project ${s.slug} declares an empty event contract.`);for(let p of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(p)||n.push(`Project ${s.slug} declares invalid env contract: ${p}.`);for(let p of s.contracts?.dependsOn||[])c.has(p);}for(let s of o.projects||[])for(let p of s.contracts?.dependsOn||[])c.has(p)||n.push(`Project ${s.slug} depends on unknown project: ${p}.`);i.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===G?"passed":"failed",message:"Contract schema and kind are valid."}),i.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),i.push({id:"ports",status:n.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),i.push({id:"dependencies",status:n.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),i.push({id:"contracts",status:n.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let m=await l(e.workspacePath);if(m.moduleCount>0){for(let s of m.issues)n.push(`${f__default.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);i.push({id:"module-paths",status:m.status,message:m.status==="passed"?`All ${m.moduleCount} registered module(s) resolve under canonical paths.`:`${m.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&i.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:n.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:i,violations:n}}async function bt(e){let t=f__default.resolve(e.workspacePath),r={schemaVersion:_e,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return h(t,xe,de(r))}
1
+ import {a as a$2,D as D$1}from'./chunk-7HV4U2OV.js';import {d}from'./chunk-ROOPODG6.js';import {j,m,i}from'./chunk-7EMG3C3H.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$3,g,f as f$1,h}from'./chunk-BLEIUQL6.js';import {b}from'./chunk-VN2MKTQO.js';import {a}from'./chunk-XWKGZRHN.js';import {a as a$4}from'./chunk-252EKOR6.js';import {l}from'./chunk-OCGZNSOE.js';import {c}from'./chunk-64XWHDZ3.js';import {t as t$1,u,q as q$1}from'./chunk-VQZ5PI5J.js';import {t,p,s,q}from'./chunk-ODK4LCEL.js';import*as f from'path';import f__default from'path';import k from'fs-extra';import Re from'crypto';var Ae="unknown-run";function de(e){let t=c();return !t||t===Ae?e:{...e,runId:t}}async function ue(e,t){await k.ensureDir(f.dirname(e));let r=`${e}.${process.pid}.${Date.now()}.${Re.randomUUID()}.tmp`;try{await k.writeJSON(r,t,{spaces:2}),await k.move(r,e,{overwrite:true});}finally{await k.remove(r).catch(()=>{});}}function le(e){return q$1(e,"imported-projects.json")}async function I(e){let t=(await Promise.all(t$1(e,"imported-projects.json").map(async r=>await k.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!t)return [];try{let r=await k.readJSON(t);if(!r||typeof r!="object"||r.version!==1||!Array.isArray(r.projects))throw new Error("expected a version 1 registry with a projects array");let o=r.projects,n=o.filter(i=>{if(!i||typeof i!="object")return false;let c=i;return typeof c.name=="string"&&typeof c.path=="string"&&typeof c.stack=="string"&&typeof c.confidence=="string"&&typeof c.importedAt=="string"});if(n.length!==o.length)throw new Error("one or more project entries are invalid");return n}catch(r){throw new Error(`Imported-project registry is invalid: ${t}`,{cause:r})}}async function Xe(e,t){if(t.length===0)return;let r=le(e);await a(`${r}.lock`,async()=>{let o=await I(e),n=new Map;for(let c of o)n.set(c.path,c);for(let c of t)n.set(c.path,c);let i=Array.from(n.values()).sort((c,l)=>c.name.localeCompare(l.name)).map(c=>({...c}));await ue(r,{version:1,updatedAt:new Date().toISOString(),projects:i});},{timeoutMs:3e4,staleMs:6e4,purpose:"imported-projects-registry-upsert"});}async function et(e,t){if(t.length===0)return;let r=le(e);await a(`${r}.lock`,async()=>{let o=await I(e),n=new Set(t.map(c=>f.resolve(c))),i=o.filter(c=>!n.has(f.resolve(c.path)));await ue(r,{version:1,updatedAt:new Date().toISOString(),projects:i});},{timeoutMs:3e4,staleMs:6e4,purpose:"imported-projects-registry-remove"});}var ot="workspace-dependency-graph.v1",me=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],ge=["inferred","contract","manual"];var v=t.workspaceContract,xe=p.contractVerify,G=s.workspaceContract.schemaVersion,_e=q.contractVerify,D=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function Pe(e){return e.replace(/\\/g,"/")}function z(e){let t=Pe(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function fe(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function ye(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Ge(e){return [...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function Oe(e){let t=e.contracts;return !t||typeof t!="object"||Array.isArray(t)?[]:ye(t.env)}function Ce(e){let t=(e||"").toLowerCase();return t.includes("vscode-extension")||t.includes("desktop.electron")||t.startsWith("extension.")||t.startsWith("desktop.")&&!t.includes("tauri")||t.startsWith("agent.")}function he(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(i=>{if(!i||typeof i!="object"||Array.isArray(i))return null;let c=i,l=Number(c.port);if(!Number.isInteger(l)||l<1||l>65535)return null;let m=c.protocol==="https"||c.protocol==="grpc"||c.protocol==="tcp"||c.protocol==="udp"?c.protocol:"http";return {name:typeof c.name=="string"&&c.name.trim()?c.name:"http",port:l,protocol:m}}).filter(i=>i!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,n=Number(e.port??o?.default_port);return Number.isInteger(n)&&n>=1&&n<=65535?[{name:"http",port:n,protocol:"http"}]:[]}async function Ne(e){let t=f__default.join(e,"Dockerfile");if(!await k.pathExists(t))return [];try{let r=await k.readFile(t,"utf8"),o=new Map;for(let n of r.matchAll(/^\s*EXPOSE\s+(.+)$/gim))for(let i of n[1].split(/\s+/)){let c=i.match(/^(\d{1,5})(?:\/(tcp|udp))?$/i),l=Number(c?.[1]);if(!c||!Number.isInteger(l)||l<1||l>65535)continue;let m=c[2]?.toLowerCase();o.set(l,{name:"http",port:l,protocol:m==="udp"?"udp":"http"});}return [...o.values()].sort((n,i)=>n.port-i.port)}catch{return []}}async function T(e){for(let t of e)if(await k.pathExists(t))return t;return null}async function Ie(e){for(let r of t$1(e,"workspace.json"))try{let o=await k.readJson(r);return {name:typeof o.workspace_name=="string"&&o.workspace_name.trim()||typeof o.name=="string"&&o.name.trim()||f__default.basename(e),profile:typeof o.profile=="string"?o.profile:void 0}}catch{}let t=await a$4(e);return t?.name?.trim()?{name:t.name.trim()}:{name:f__default.basename(e)}}async function De(e){let t=[],r=[e],o=new Set,n=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let i=r.shift();if(!i||o.has(i))continue;o.add(i);let c=await T(u(i,"project.json")),l=await T(u(i,"context.json"));if(c||l){t.push(c??l??"");continue}let m;try{m=await k.readdir(i,{withFileTypes:true});}catch{continue}for(let d of m)!d.isDirectory()||n.has(d.name)||a$1(d.name)||r.push(f__default.join(i,d.name));}return t.sort()}function Te(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function $e(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return Ce(e)?null:r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:r.startsWith("adopted.")?null:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function B(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function U(e,t,r){let o=e!==void 0&&e.source===void 0,n=$e(t.kit,t.runtime),i=e?.ports||[],c=t.ports||[],l=Ce(t.kit),m=t.source==="adopted-local"&&e?.source!==void 0,d=t.source!==void 0&&e?.source!==void 0,p=(l&&c.length===0?[]:m?c.length>0?c:n?[{name:"http",port:B(n,r),protocol:"http"}]:[]:i.length>0?i:c.length>0?c:n?[{name:"http",port:B(n,r),protocol:"http"}]:[]).map(P=>({...P,port:B(P.port,r)}));for(let P of p)r.add(P.port);let g={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&z(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:d?t.runtime:e?.runtime||t.runtime,framework:d?t.framework:e?.framework||t.framework,kit:d?t.kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:p,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:Ge([...e?.contracts?.env??[],...t.contracts.env??[]])}},h=JSON.stringify(e||null)!==JSON.stringify(g);return {project:g,changed:h}}async function Ee(e){let t=f__default.resolve(e.workspacePath),r=await Ie(t),o=await De(t),n=await I(t),i$1=new Map(n.map(s=>[f__default.resolve(s.path),s])),c=[];for(let s of n){let p=f__default.resolve(s.path),g=await T(u(p,"project.json"))??await T(u(p,"context.json"));!g||o.some(h=>f__default.resolve(h)===f__default.resolve(g))||c.push({projectJsonPath:g,registryEntry:s});}let l=[],m$1=[...o.map(s=>({projectJsonPath:s,registryEntry:i$1.get(f__default.resolve(f__default.dirname(f__default.dirname(s))))})),...c];for(let{projectJsonPath:s,registryEntry:p}of m$1){let g=f__default.dirname(f__default.dirname(s)),h=Pe(f__default.relative(t,g)),P=p!==void 0&&!z(h),C=fe(p?.name||f__default.basename(g),f__default.basename(g)),b=P?`external/${C}`:h||C,w=await k.readJson(s),a=typeof w.kit_name=="string"&&w.kit_name||typeof w.kit=="string"&&w.kit||void 0,E=j(w)?m(g,w):void 0,j$1=E!==void 0&&E.key!=="unknown",S=i({runtime:typeof w.runtime=="string"?w.runtime:void 0,framework:typeof w.framework=="string"?w.framework:void 0,kitName:a}),y=a$2(a),$=j$1?E.runtime:S.runtime!=="unknown"?S.runtime:y?.runtime,K=j$1?E.key:typeof w.framework=="string"&&w.framework||(S.key!=="unknown"?S.key:void 0)||y?.framework||Te(a),We=p?.relationship==="adopted"?"adopted":"imported",Se=j$1?`${We}.${E.key}`:a;l.push({slug:p?.name||b||f__default.basename(g),relativePath:b,source:p?.source??"workspace",relationship:p?.relationship,externalPath:P?g:void 0,runtime:$,framework:K,kit:Se,modules:ye(w.modules),ports:he(w).length>0?he(w):await Ne(g),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:Oe(w)}});}let d=new Map;for(let s of l){let p=fe(s.slug,s.relativePath),g=d.get(p);(!g||g.source!=="workspace"&&s.source==="workspace")&&d.set(p,s);}return {schemaVersion:G,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...d.values()]}}async function Et(e){let t=f__default.resolve(e.outputPath||a$3(e.workspacePath,v));if(await k.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await Ee({workspacePath:e.workspacePath,now:e.now}),o=new Set,n={...r,projects:r.projects.map(c=>U(void 0,c,o).project)},i=await be({workspacePath:e.workspacePath,contractPath:t,contract:n});if(e.strict&&i.status==="failed")throw new D(i);return await ve({workspacePath:e.workspacePath,contractPath:t,contract:n,now:e.now}),{contractPath:t,contract:n}}async function vt(e){let t=f__default.resolve(e.workspacePath),r=a$3(t,v),o=await g(t,v)??r,n=await Ee({workspacePath:t,now:e.now}),i=await k.pathExists(o)?await k.readJson(o):null,c=new Map((i?.projects||[]).map(h=>[h.slug,h])),l=new Set,m=[],d=[],s=[];for(let h of n.projects){let P=c.get(h.slug),C=U(P,h,l);P?C.changed&&d.push(h.slug):m.push(h.slug),s.push(C.project),c.delete(h.slug);}for(let h of c.values()){if(h.source)continue;let P=U(h,h,l);s.push(P.project);}let p={schemaVersion:G,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...i?.workspace||{},...n.workspace,name:n.workspace.name||i?.workspace?.name||f__default.basename(t)},projects:s.sort((h,P)=>h.slug.localeCompare(P.slug))},g$1=await be({workspacePath:t,contractPath:r,contract:p});if(e.strict&&g$1.status==="failed")throw new D(g$1);return await ve({workspacePath:t,contractPath:r,contract:p,now:e.now}),{contractPath:r,contract:p,addedProjects:m,updatedProjects:d,verification:g$1}}async function ke(e){return await k.pathExists(e)?{exists:true,contents:await k.readFile(e)}:{exists:false}}async function we(e,t){if(!t.exists){await k.remove(e);return}await k.outputFile(e,t.contents);}async function ve(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-3PXZENLC.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),n=a$3(e.workspacePath,r),i=c=>{if(!c||typeof c!="object"||Array.isArray(c))return JSON.stringify(c);let{generatedAt:l,...m}=c;return JSON.stringify(m)};if(await k.pathExists(e.contractPath)&&await k.pathExists(n)){let[c,l]=await Promise.all([k.readJson(e.contractPath),k.readJson(n)]);if(i(c)===i(e.contract)&&i(l)===i(o))return}b(v,e.contract),b(r,o),await f$1(e.workspacePath,v,async()=>{let[c,l]=await Promise.all([ke(e.contractPath),ke(n)]);try{if(e.contractPath===a$3(e.workspacePath,v)?await h(e.workspacePath,v,e.contract):(await k.ensureDir(f__default.dirname(e.contractPath)),await k.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await h(e.workspacePath,r,o);}catch(m){let s=(await Promise.allSettled([we(e.contractPath,c),we(n,l)])).filter(p=>p.status==="rejected");throw s.length>0?new AggregateError([m,...s.map(p=>p.reason)],"Workspace contract publication failed and rollback was incomplete."):m}});}async function je(e){let t=e.contractPath??(await g(e.workspacePath,v)||a$3(e.workspacePath,v)),r=await k.readJson(t);return {contractPath:t,contract:r}}var Ke={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function Ve(e,t){return d(e,t.relativePath,{...t.externalPath?{absolutePath:t.externalPath}:{}})}async function Me(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(Ke))for(let n of o)await k.pathExists(f__default.join(e,n))&&t[r].push(n);try{let r=await k.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,n)=>o.localeCompare(n));return t}function _(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function Fe(e){try{let t=await k.readJson(f__default.join(e,"package.json")),r={runtime:_(t.dependencies),development:_(t.devDependencies),peer:_(t.peerDependencies),optional:_(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:_(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function Le(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await k.readFile(f__default.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,n)=>o.localeCompare(n))}catch{}return []}function He(e,t){try{let r=D$1(e);if(r.engine!=="unknown")return r;let o=k.pathExistsSync(f__default.join(e,"package.json"))?"npm":k.pathExistsSync(f__default.join(e,"pyproject.toml"))?"python":k.pathExistsSync(f__default.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",runtimeCandidates:["unknown"],compositeRuntime:false,lifecycleCoverage:"complete",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function Je(e,t,r){let o=e.projects.map(n=>({id:n.slug,path:n.relativePath,runtime:n.runtime,framework:n.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function jt(e){let{contractPath:t,contract:r}=await je(e),o=e.now??new Date,n=o.toISOString(),{buildWorkspaceModel:i,workspaceModelProjectTopology:c}=await import('./workspace-model-LBICKRVI.js'),{hashWorkspaceModel:l}=await import('./workspace-model-hash-ZXYPIGCW.js'),m=await i({workspacePath:e.workspacePath,includeEvidence:false,now:o}),d=c(m)??Je(r,n,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(d.nodes.map(a=>[a.id,a.operationalProfile])),{buildWorkspaceKnowledgeGraph:p$1}=await import('./workspace-knowledge-graph-4RSZTEFJ.js'),g=await p$1({workspacePath:e.workspacePath,workspace:{name:m.workspace.name,...m.workspace.profile?{profile:m.workspace.profile}:{}},contract:r,projectTopology:d,now:o,projects:m.projects.map(a=>({id:a.name,path:a.path,...a.absolutePath?{absolutePath:a.absolutePath}:{},runtime:a.runtime,runtimeCandidates:a.runtimeCandidates,framework:a.framework,...a.kit?{kit:a.kit}:{}})),source:{kind:"workspace-model",artifact:p.model,hashAlgorithm:"sha256",hash:l(m)}}),h=await Promise.all(r.projects.map(async a=>{let u=Ve(e.workspacePath,a),[E,j,S]=await Promise.all([Me(u),Fe(u),Le(u)]),y=He(u,a);return {id:a.slug,label:a.slug,relativePath:a.relativePath,source:a.source,relationship:a.relationship,externalPath:a.externalPath,runtime:a.runtime??y.runtime,framework:a.framework??y.framework,kit:a.kit,modules:a.modules,ports:a.ports,apis:a.contracts.apis,owns:a.contracts.owns,env:[...new Set([...a.contracts.env,...S])].sort(($,K)=>$.localeCompare(K)),contracts:{owns:[...a.contracts.owns],apis:[...a.contracts.apis],publishes:[...a.contracts.publishes],consumes:[...a.contracts.consumes],dependsOn:[...a.contracts.dependsOn],env:[...a.contracts.env]},capabilities:{engine:y.engine,supportTier:y.frameworkSupportTier,runtimeSupportTier:y.runtimeSupportTier,doctorSupport:y.runtimeDoctorSupport,moduleSupport:y.moduleSupport,fleetStages:[...y.fleetStages],localOnlyCommands:[...y.localOnlyCommands],supportedCommands:[...y.supportedCommands]},files:E,...j?{package:j}:{},...s.get(a.slug)?{operationalProfile:s.get(a.slug)}:{}}})),P=new Set(h.map(a=>a.id)),C=new Map,b=[];for(let a of r.projects){for(let u of a.contracts.dependsOn||[])P.has(u)&&b.push({from:u,to:a.slug,type:"dependency",label:"dependsOn"});for(let u of a.contracts.publishes||[])C.has(u)||C.set(u,new Set),C.get(u)?.add(a.slug);}for(let a of r.projects)for(let u of a.contracts.consumes||[]){let E=C.get(u);if(E)for(let j of E)j!==a.slug&&b.push({from:j,to:a.slug,type:"event",label:u});}let w={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:n,nodes:h.sort((a,u)=>a.id.localeCompare(u.id)),edges:b.sort((a,u)=>`${a.from}:${a.to}:${a.type}:${a.label}`.localeCompare(`${u.from}:${u.to}:${u.type}:${u.label}`)),dependencyGraph:d,knowledgeGraph:g,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:h.length,dependencyEdges:b.filter(a=>a.type==="dependency").length,eventEdges:b.filter(a=>a.type==="event").length,portCount:h.reduce((a,u)=>a+u.ports.length,0),apiCount:h.reduce((a,u)=>a+u.apis.length,0),relationshipEdges:d.stats.edgeCount,inferredEdges:d.stats.inferredEdges,authoritativeEdges:d.stats.authoritativeEdges,orphanProjects:d.stats.orphanCount,hotspotProjects:d.stats.hotspotCount,evidenceCoverageRatio:d.stats.evidenceCoverageRatio,edgeCoverageRatio:d.stats.edgeCoverageRatio,connectedProjects:d.stats.connectedNodeCount,lowConfidenceEdges:d.stats.lowConfidenceEdges,hasCycle:d.stats.hasCycle,manifestCount:h.reduce((a,u)=>a+u.files.manifests.length,0),entrypointCount:h.reduce((a,u)=>a+u.files.entrypoints.length,0),diagnostics:d.diagnostics?.length??0,relationshipKinds:Object.fromEntries(me.map(a=>[a,d.edges.filter(u=>u.kind===a).length])),relationshipSources:Object.fromEntries(ge.map(a=>[a,d.edges.filter(u=>u.source===a).length])),entityCount:g.quality.entityCount,knowledgeRelations:g.quality.relationCount,proofCount:g.quality.proofCount,providerCount:g.providers.length,knowledgeUnknowns:g.quality.unknownCount}};return {contractPath:t,graph:w}}async function be(e){let t=e.contract?{contractPath:e.contractPath??a$3(e.workspacePath,v),contract:e.contract}:await je(e),{contractPath:r,contract:o}=t,n=[],i=[];o.kind!=="rapidkit.workspace.contract"&&n.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==G&&n.push(`Contract schemaVersion must be ${G}.`),o.workspace?.name||n.push("Contract workspace.name is required."),Array.isArray(o.projects)||n.push("Contract projects must be an array.");let c=new Set,l$1=new Map;for(let s of o.projects||[]){if(!s.slug){n.push("Every project must declare slug.");continue}c.has(s.slug)&&n.push(`Duplicate project slug: ${s.slug}.`),c.add(s.slug),s.relativePath?z(s.relativePath)||n.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):n.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||n.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),f__default.isAbsolute(s.externalPath)||n.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let p of s.ports||[]){(!Number.isInteger(p.port)||p.port<1||p.port>65535)&&n.push(`Project ${s.slug} declares invalid port: ${p.port}.`);let g=l$1.get(p.port);g&&n.push(`Port ${p.port} is claimed by both ${g} and ${s.slug}.`),l$1.set(p.port,s.slug);}for(let p of s.contracts?.apis||[])(!p.name?.trim()||!p.basePath?.startsWith("/"))&&n.push(`Project ${s.slug} declares invalid API contract.`);for(let p of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])p.trim()||n.push(`Project ${s.slug} declares an empty event contract.`);for(let p of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(p)||n.push(`Project ${s.slug} declares invalid env contract: ${p}.`);for(let p of s.contracts?.dependsOn||[])c.has(p);}for(let s of o.projects||[])for(let p of s.contracts?.dependsOn||[])c.has(p)||n.push(`Project ${s.slug} depends on unknown project: ${p}.`);i.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===G?"passed":"failed",message:"Contract schema and kind are valid."}),i.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),i.push({id:"ports",status:n.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),i.push({id:"dependencies",status:n.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),i.push({id:"contracts",status:n.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let m=await l(e.workspacePath);if(m.moduleCount>0){for(let s of m.issues)n.push(`${f__default.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);i.push({id:"module-paths",status:m.status,message:m.status==="passed"?`All ${m.moduleCount} registered module(s) resolve under canonical paths.`:`${m.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&i.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:n.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:i,violations:n}}async function bt(e){let t=f__default.resolve(e.workspacePath),r={schemaVersion:_e,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return h(t,xe,de(r))}
2
2
  export{I as a,Xe as b,et as c,de as d,ot as e,me as f,v as g,xe as h,G as i,_e as j,D as k,De as l,Ee as m,Et as n,vt as o,je as p,jt as q,be as r,bt as s};
@@ -1 +1 @@
1
- import {b as b$1,c,d as d$1}from'./chunk-5FVREPQC.js';import {a as a$3}from'./chunk-X7FYEKLI.js';import {c as c$2}from'./chunk-P5LI5DL3.js';import {c as c$1,d as d$4}from'./chunk-N4B2M44I.js';import {a as a$1,b as b$2}from'./chunk-PYCJWW4B.js';import {p as p$1,a,o,g as g$1,d as d$3,f}from'./chunk-VEMGICT4.js';import {r,n,d as d$5}from'./chunk-QDM6TWFK.js';import {d as d$2}from'./chunk-MD4CHXV3.js';import {g,h as h$1}from'./chunk-BLEIUQL6.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {d}from'./chunk-EWZZUQBR.js';import {q,p,t,r as r$1,s}from'./chunk-ODK4LCEL.js';import k from'path';import w from'fs-extra';var fe="rapidkit-blocker-resolution-v1";function pe(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return d$5({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function we(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function ge(e){let t=we(e.reason),r=pe({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",...e.sourceCommand?{}:{studioActionId:"run-analyze"}}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:fe,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?e.sourceCommand?`Run the source command once: ${e.sourceCommand}, then verify.`:"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function Re(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function Ce(e){return e.length===0||e.every(t=>Re(t))}function me(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&Ce(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function st(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var ye=q.verify,G=p.verify;function je(e,t){return k.isAbsolute(t)?t:k.join(e,t)}async function ke(e){let t=await w.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$2(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$2(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let a=s.transitiveImpact.reduce((l,d)=>Math.max(l,d.distance??0),0);s.summary.blastRadius.maxDistance!==a&&i.push("blastRadius.maxDistance does not match transitive impact distances");let g=n(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==g&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function Ae(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Se(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function Ee(e,t){if(e.id==="workspace.doctor")return k.join(t,p.doctor);if(e.id==="workspace.contract.verify")return k.join(t,p.contractVerify);if(e.id==="workspace.readiness")return k.join(t,p.readiness);if(e.id==="workspace.analyze")return k.join(t,".workspai","reports","analyze-last-run.json");if(e.id==="workspace.pipeline")return k.join(t,".workspai","reports","pipeline-last-run.json");if(e.id==="workspace.doctor-fix")return k.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e.id.startsWith("project.")&&e.id.includes("."))return k.join(t,".workspai","reports","workspace-run-last.json")}function h(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function We(e){if(!c$1(e,"workspace"))return {status:"fail",message:"Doctor evidence contract is missing or unsupported."};try{d$4(e);}catch(s){return {status:"fail",message:`Doctor evidence semantic validation failed: ${s instanceof Error?s.message:String(s)}`}}let t=a$3(e);return t.hasSystemErrors||t.blockingFindings>0?{status:"fail",message:`Doctor evidence reports ${t.blockingFindings} canonical blocking finding(s).`}:t.advisoryFindings+t.unknownFindings+t.contradictionCount+t.missingDiagnosisProjects>0||t.staleEvidence||t.unknownFreshness||t.minimumDiagnosisCompleteness<100?{status:"warn",message:`Doctor evidence needs attention (${t.advisoryFindings} advisory, ${t.unknownFindings} unknown, ${t.contradictionCount} contradictory; ${t.minimumDiagnosisCompleteness}% complete).`}:{status:"pass",message:"Canonical Doctor evidence is complete, fresh, and healthy."}}function Pe(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function xe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Ie(e){let t=h(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function Ve(e){let t=e.schemaVersion===s.doctorFixResult.schemaVersion?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s$1=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s$1.length>0)return {status:"fail",message:`Doctor fix result reports ${s$1.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function $e(e,t$1){let r=await g(e,t.doctorRemediationPlan);if(!r)return false;try{let s=h(await w.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let a=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!a||!t$1)return true;let g=Date.parse(a),l=Date.parse(t$1);return !Number.isFinite(g)||!Number.isFinite(l)?true:g>=l}catch{return false}}function Fe(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Oe(e){let t=h(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function De(e,t,r){let s=h(e.projectStages)??h(h(e.enterpriseControls)?.projectStages);if(!s)return null;let i=t.replace(/\\/g,"/").toLowerCase(),a=Object.entries(s).filter(([d,y])=>{let c=d.replace(/\\/g,"/").toLowerCase(),n=h(y),o=h(n?.[r]),p=typeof o?.projectName=="string"?o.projectName.toLowerCase():"",f=typeof o?.relativePath=="string"?o.relativePath.replace(/\\/g,"/").toLowerCase():"";return c===i||p===i||f===i});if(a.length>1)return "ambiguous";let g=h(a[0]?.[1]),l=h(g?.[r]);return l?{generatedAt:typeof l.generatedAt=="string"?l.generatedAt:void 0,status:typeof l.status=="string"?l.status:void 0}:null}function Be(e,t,r){let s=Fe(t),i=c$2(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let a=i.stage;if(s&&a!==s)return {status:"missing",message:`Workspace run evidence is for stage "${a}", expected "${s}".`};let g=Array.isArray(i.projects)?i.projects:[],l=t.project?.toLowerCase();if(!l)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=g.filter(c=>{let n=h(c);if(!n)return false;let o=typeof n.projectName=="string"?n.projectName.toLowerCase():"",p=["projectPath","relativePath","path"].map(f=>n[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return o===l||p.some(f=>f===l)});if(d.length>1)return {status:"fail",message:`Workspace run evidence is ambiguous for project ${t.project}.`};let y=d[0];if(y){let c=b(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(c)return {status:"fail",message:c};let n=h(y),o=typeof n?.status=="string"?n.status:"unknown";if(o==="failed"||o==="blocked")return {status:"fail",message:`Workspace run evidence ${o} for ${t.project}.`};if(o==="passed")return {status:"pass",message:`Workspace run evidence passed for ${t.project}.`};if(o==="skipped"){let p=De(e,l,s??i.stage);if(p==="ambiguous")return {status:"fail",message:`Workspace run history is ambiguous for project ${t.project}.`};if(p){let f=b(p.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(f)return {status:"fail",message:f};if(p.status==="passed")return {status:"pass",message:`Workspace run evidence passed for ${t.project} from keyed project/stage history.`};if(p.status==="failed"||p.status==="blocked")return {status:"fail",message:`Workspace run evidence ${p.status} for ${t.project}.`}}return {status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}}return {status:"warn",message:`Workspace run evidence status is ${o} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function b(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function _e(e){if(e.id==="workspace.doctor")return r$1.doctor;if(e.id==="workspace.readiness")return r$1.readiness;if(e.id==="workspace.contract.verify")return r$1.contractVerify;if(e.id==="workspace.analyze")return r$1.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function Ne(e,t,r,s$1){let i=Ee(e,t),a=i?k.relative(t,i).split(k.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let g$1=i?await g(t,a??""):null;if(!i||!g$1)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:a,message:a?`Missing evidence report: ${a}`:"No evidence mapping exists for this command."};let l;try{l=await w.readJson(g$1);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:a,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=h(l);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:a,message:"Evidence report is not a JSON object."};let y=_e(e);if(y)try{a$2(d,y,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:a,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=b(d.generatedAt,s$1,"Doctor evidence");n?c={status:"fail",message:n}:c=We(d);}else if(e.id==="workspace.readiness"){let n=b(d.generatedAt,s$1,"Release readiness evidence");n?c={status:"fail",message:n}:c=Pe(d);}else if(e.id==="workspace.contract.verify"){let n=b(d.generatedAt,s$1,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=xe(d);}else if(e.id==="workspace.analyze"){let n=b(d.generatedAt,s$1,"Analyze evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.pipeline"){let n=b(d.generatedAt,s$1,"Pipeline evidence");n?c={status:"fail",message:n}:c=Oe(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion===s.doctorFixResult.schemaVersion?d:d.fixResult,o=h(n),p=typeof o?.generatedAt=="string"?o.generatedAt:void 0,f=b(p,s$1,"Doctor fix result");f?c={status:"fail",message:f}:await $e(t,p)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=Ve(d);}else if(e.id.startsWith("project."))c=Be(d,e,s$1);else {let n=b(d.generatedAt,s$1,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:a,message:c.message}}function He(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,a=e.filter(n=>n.status==="missing").length,g=e.filter(n=>n.status==="skipped").length,l=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,y="ready",c=0;return l.length>0||t.blockingReasons.length>0?(y="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(y="needs-attention",c=1),{verdict:y,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:a,stepsSkipped:g}}function Me(e,t){let r=P(e.affectedProjects.map(o=>o.project?.name).filter(o=>typeof o=="string")),s=new Set(r.map(o=>o.toLowerCase())),i=P(e.transitiveImpact.map(o=>o.project?.name).filter(o=>typeof o=="string").filter(o=>!s.has(o.toLowerCase()))),a=new Map;for(let o of t){if(o.scope!=="project"||!o.project)continue;let p=o.project.toLowerCase(),f=a.get(p)??[];f.push(o),a.set(p,f);}let g=[],l=[],d=[],y=[],c=false,n=(o,p)=>{let f=a.get(o.toLowerCase())??[];if(f.length===0){d.push(o);return}let x=f.filter(m=>m.status==="fail"),R=x.filter(m=>m.required),I=f.filter(m=>m.status==="missing"),A=I.filter(m=>m.required),V=f.some(m=>m.status==="pass"||m.status==="warn");if(R.length>0){l.push(o),y.push(`graph.subgraph.${o}: ${p} has failed verification evidence (${R.map(m=>m.id).join(", ")}).`);return}if(x.length>0){l.push(o),c=true;return}if(A.length>0){l.push(o),y.push(`graph.subgraph.${o}: ${p} has missing required verification evidence (${A.map(m=>m.id).join(", ")}).`);return}if(I.length>0){l.push(o),c=true;return}if(V){g.push(o);return}d.push(o);};for(let o of r)n(o,"directly-changed");for(let o of i)n(o,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:P(g),uncovered:P(l),unverifiable:P(d)},blockingReasons:y,needsAttention:c}}function P(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function Te(e){let t=k.resolve(e.workspacePath);if(e.fromImpactPath){let a=je(t,e.fromImpactPath);return {impact:await ke(a),fromImpactRef:k.relative(t,a).split(k.sep).join("/"),impactFromDisk:true}}let r$1=k.join(t,g$1);if(await w.pathExists(r$1))return {impact:await ke(r$1),fromImpactRef:g$1,impactFromDisk:true};let s=k.join(t,d$3);if(await w.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$3,scope:e.scope,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),fromImpactRef:d$3,impactFromDisk:false};let i=await r({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {impact:{schemaVersion:f,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",diffRef:p.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:n(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:q.diff,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",toRef:p.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function Le(e,t){if(t)return e.generatedAt}async function wt(e){let t=k.resolve(e.workspacePath),{impact:r$1,fromImpactRef:s,impactFromDisk:i}=await Te(e),a$2=r$1.diff.currentModel,g=i?await r({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):a$2,l=[];if(i){let u=await p$1({workspacePath:t,fromPath:r$1.diff.fromRef,diff:r$1.diff,scope:e.scope,now:e.now}),E=[r$1.affectedProjects,r$1.transitiveImpact,r$1.verificationPlan],j=[u.affectedProjects,u.transitiveImpact,u.verificationPlan];JSON.stringify(E)!==JSON.stringify(j)&&l.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(g)!==r$1.diff.toHash&&l.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r$1.diff.git;if(i&&d$2?.available){let u=a(t,{ref:d$2.ref}),E=r$1.diff.changes.filter(v=>v.type.startsWith("git.")).map(v=>`${v.type}:${v.target.replace(/^git:/,"")}`).sort(),j=[...u.changedFiles.map(v=>`git.file.changed:${v}`),...u.untrackedFiles.map(v=>`git.untracked:${v}`),...u.deletedFiles.map(v=>`git.deleted:${v}`)].sort();(!u.available||u.commit!==d$2.commit||JSON.stringify(j)!==JSON.stringify(E))&&l.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let y=Le(r$1,i),c$1=Ae([...o(),...r$1.verificationPlan]).filter(u=>Se(e.scope,u)),n$1=[];for(let u of c$1)n$1.push(await Ne(u,t,a$2.contracts.exists===true,y));let o$1=Me(r$1,n$1),p=a$1(n(a$2)??{nodes:[],edges:[]}),f=b$1(a$2),x=await ze(t),R=c(f,x?.freshness?.projectHashes),I={verdict:R.verdict,baseline:R.baseline,changed:R.changed,added:R.added,removed:R.removed,projectHashes:d$1(f)},A=b$2(p),V=a$2.policies?.mode??"warn",m=await qe(a$2,t),B=Ke(V,m),S=He(n$1,{blockingReasons:[...o$1.blockingReasons,...A,...B.blockingReasons,...l],needsAttention:o$1.needsAttention||B.needsAttention}),he=n$1.filter(u=>u.status==="missing"&&u.evidencePath).map(u=>u.evidencePath),_=[...n$1.filter(u=>u.required&&(u.status==="fail"||u.status==="missing")).map(u=>`${u.id}: ${u.message}`),...o$1.blockingReasons,...A,...B.blockingReasons,...l],ve=m.filter(u=>u.severity==="error").length,be=a$2.summary?.projectCount??a$2.projects.length,U=me({projectCount:be,verdict:S.verdict,exitCode:S.exitCode,blockingReasons:_,policyErrorCount:ve});S.verdict=U.verdict,S.exitCode=U.exitCode;let Y=Array.from(new Set(_.map(u=>u.trim()).filter(Boolean))).slice(0,12).map((u,E)=>{let j=n$1.find(v=>u.startsWith(`${v.id}:`));return ge({reason:u,blockerId:`blocker-${E+1}`,sourceCommand:j?.command.display,sourceArtifact:j?.evidencePath,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:G})});return {schemaVersion:ye,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r$1.summary.changed,risk:r$1.summary.risk,affectedProjects:r$1.summary.affectedProjects,recommendedCommands:r$1.summary.recommendedCommands},summary:S,steps:n$1,missingEvidence:he,blockingReasons:_,...Y.length>0?{resolutionHints:Y}:{},verificationPlan:c$1,affectedSubgraph:o$1.subgraph,graphIntegrity:p,freshness:I,policyMode:V,policyViolations:m}}async function qe(e,t){let r=[];for(let i of e.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await g(t,p.contractVerify);try{if(s&&await w.pathExists(s)){let i=await w.readJson(s);if(Array.isArray(i.violations))for(let a of i.violations)typeof a=="string"&&a.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:a});}}catch{}return r.sort((i,a)=>i.source!==a.source?i.source.localeCompare(a.source):i.code!==a.code?i.code.localeCompare(a.code):i.message.localeCompare(a.message))}function Ke(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function ze(e){let t=k.join(e,G);try{if(!await w.pathExists(t))return null;let r=await w.readJson(t);return r&&r.schemaVersion===ye?r:null}catch{return null}}async function Rt(e,t){return h$1(t,G,d$2(e))}function Je(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function Ct(e,t){return Je(e,t).exitCode}export{fe as a,st as b,ye as c,G as d,Me as e,wt as f,Rt as g,Je as h,Ct as i};
1
+ import {b as b$1,c,d as d$1}from'./chunk-2ZVE7VE2.js';import {a as a$3}from'./chunk-X7FYEKLI.js';import {c as c$2}from'./chunk-P5LI5DL3.js';import {c as c$1,d as d$4}from'./chunk-N4B2M44I.js';import {a as a$1,b as b$2}from'./chunk-PYCJWW4B.js';import {p as p$1,a,o,g as g$1,d as d$3,f}from'./chunk-SKHRUHXO.js';import {r,n,d as d$5}from'./chunk-O4TZKLEC.js';import {d as d$2}from'./chunk-WU5M6UP7.js';import {g,h as h$1}from'./chunk-BLEIUQL6.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {d}from'./chunk-EWZZUQBR.js';import {q,p,t,r as r$1,s}from'./chunk-ODK4LCEL.js';import k from'path';import w from'fs-extra';var fe="rapidkit-blocker-resolution-v1";function pe(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return d$5({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function we(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function ge(e){let t=we(e.reason),r=pe({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",...e.sourceCommand?{}:{studioActionId:"run-analyze"}}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:fe,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?e.sourceCommand?`Run the source command once: ${e.sourceCommand}, then verify.`:"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function Re(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function Ce(e){return e.length===0||e.every(t=>Re(t))}function me(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&Ce(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function st(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var ye=q.verify,G=p.verify;function je(e,t){return k.isAbsolute(t)?t:k.join(e,t)}async function ke(e){let t=await w.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$2(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$2(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let a=s.transitiveImpact.reduce((l,d)=>Math.max(l,d.distance??0),0);s.summary.blastRadius.maxDistance!==a&&i.push("blastRadius.maxDistance does not match transitive impact distances");let g=n(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==g&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function Ae(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Se(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function Ee(e,t){if(e.id==="workspace.doctor")return k.join(t,p.doctor);if(e.id==="workspace.contract.verify")return k.join(t,p.contractVerify);if(e.id==="workspace.readiness")return k.join(t,p.readiness);if(e.id==="workspace.analyze")return k.join(t,".workspai","reports","analyze-last-run.json");if(e.id==="workspace.pipeline")return k.join(t,".workspai","reports","pipeline-last-run.json");if(e.id==="workspace.doctor-fix")return k.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e.id.startsWith("project.")&&e.id.includes("."))return k.join(t,".workspai","reports","workspace-run-last.json")}function h(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function We(e){if(!c$1(e,"workspace"))return {status:"fail",message:"Doctor evidence contract is missing or unsupported."};try{d$4(e);}catch(s){return {status:"fail",message:`Doctor evidence semantic validation failed: ${s instanceof Error?s.message:String(s)}`}}let t=a$3(e);return t.hasSystemErrors||t.blockingFindings>0?{status:"fail",message:`Doctor evidence reports ${t.blockingFindings} canonical blocking finding(s).`}:t.advisoryFindings+t.unknownFindings+t.contradictionCount+t.missingDiagnosisProjects>0||t.staleEvidence||t.unknownFreshness||t.minimumDiagnosisCompleteness<100?{status:"warn",message:`Doctor evidence needs attention (${t.advisoryFindings} advisory, ${t.unknownFindings} unknown, ${t.contradictionCount} contradictory; ${t.minimumDiagnosisCompleteness}% complete).`}:{status:"pass",message:"Canonical Doctor evidence is complete, fresh, and healthy."}}function Pe(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function xe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Ie(e){let t=h(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function Ve(e){let t=e.schemaVersion===s.doctorFixResult.schemaVersion?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s$1=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s$1.length>0)return {status:"fail",message:`Doctor fix result reports ${s$1.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function $e(e,t$1){let r=await g(e,t.doctorRemediationPlan);if(!r)return false;try{let s=h(await w.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let a=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!a||!t$1)return true;let g=Date.parse(a),l=Date.parse(t$1);return !Number.isFinite(g)||!Number.isFinite(l)?true:g>=l}catch{return false}}function Fe(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Oe(e){let t=h(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function De(e,t,r){let s=h(e.projectStages)??h(h(e.enterpriseControls)?.projectStages);if(!s)return null;let i=t.replace(/\\/g,"/").toLowerCase(),a=Object.entries(s).filter(([d,y])=>{let c=d.replace(/\\/g,"/").toLowerCase(),n=h(y),o=h(n?.[r]),p=typeof o?.projectName=="string"?o.projectName.toLowerCase():"",f=typeof o?.relativePath=="string"?o.relativePath.replace(/\\/g,"/").toLowerCase():"";return c===i||p===i||f===i});if(a.length>1)return "ambiguous";let g=h(a[0]?.[1]),l=h(g?.[r]);return l?{generatedAt:typeof l.generatedAt=="string"?l.generatedAt:void 0,status:typeof l.status=="string"?l.status:void 0}:null}function Be(e,t,r){let s=Fe(t),i=c$2(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let a=i.stage;if(s&&a!==s)return {status:"missing",message:`Workspace run evidence is for stage "${a}", expected "${s}".`};let g=Array.isArray(i.projects)?i.projects:[],l=t.project?.toLowerCase();if(!l)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=g.filter(c=>{let n=h(c);if(!n)return false;let o=typeof n.projectName=="string"?n.projectName.toLowerCase():"",p=["projectPath","relativePath","path"].map(f=>n[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return o===l||p.some(f=>f===l)});if(d.length>1)return {status:"fail",message:`Workspace run evidence is ambiguous for project ${t.project}.`};let y=d[0];if(y){let c=b(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(c)return {status:"fail",message:c};let n=h(y),o=typeof n?.status=="string"?n.status:"unknown";if(o==="failed"||o==="blocked")return {status:"fail",message:`Workspace run evidence ${o} for ${t.project}.`};if(o==="passed")return {status:"pass",message:`Workspace run evidence passed for ${t.project}.`};if(o==="skipped"){let p=De(e,l,s??i.stage);if(p==="ambiguous")return {status:"fail",message:`Workspace run history is ambiguous for project ${t.project}.`};if(p){let f=b(p.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(f)return {status:"fail",message:f};if(p.status==="passed")return {status:"pass",message:`Workspace run evidence passed for ${t.project} from keyed project/stage history.`};if(p.status==="failed"||p.status==="blocked")return {status:"fail",message:`Workspace run evidence ${p.status} for ${t.project}.`}}return {status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}}return {status:"warn",message:`Workspace run evidence status is ${o} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function b(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function _e(e){if(e.id==="workspace.doctor")return r$1.doctor;if(e.id==="workspace.readiness")return r$1.readiness;if(e.id==="workspace.contract.verify")return r$1.contractVerify;if(e.id==="workspace.analyze")return r$1.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function Ne(e,t,r,s$1){let i=Ee(e,t),a=i?k.relative(t,i).split(k.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let g$1=i?await g(t,a??""):null;if(!i||!g$1)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:a,message:a?`Missing evidence report: ${a}`:"No evidence mapping exists for this command."};let l;try{l=await w.readJson(g$1);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:a,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=h(l);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:a,message:"Evidence report is not a JSON object."};let y=_e(e);if(y)try{a$2(d,y,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:a,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=b(d.generatedAt,s$1,"Doctor evidence");n?c={status:"fail",message:n}:c=We(d);}else if(e.id==="workspace.readiness"){let n=b(d.generatedAt,s$1,"Release readiness evidence");n?c={status:"fail",message:n}:c=Pe(d);}else if(e.id==="workspace.contract.verify"){let n=b(d.generatedAt,s$1,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=xe(d);}else if(e.id==="workspace.analyze"){let n=b(d.generatedAt,s$1,"Analyze evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.pipeline"){let n=b(d.generatedAt,s$1,"Pipeline evidence");n?c={status:"fail",message:n}:c=Oe(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion===s.doctorFixResult.schemaVersion?d:d.fixResult,o=h(n),p=typeof o?.generatedAt=="string"?o.generatedAt:void 0,f=b(p,s$1,"Doctor fix result");f?c={status:"fail",message:f}:await $e(t,p)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=Ve(d);}else if(e.id.startsWith("project."))c=Be(d,e,s$1);else {let n=b(d.generatedAt,s$1,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:a,message:c.message}}function He(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,a=e.filter(n=>n.status==="missing").length,g=e.filter(n=>n.status==="skipped").length,l=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,y="ready",c=0;return l.length>0||t.blockingReasons.length>0?(y="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(y="needs-attention",c=1),{verdict:y,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:a,stepsSkipped:g}}function Me(e,t){let r=P(e.affectedProjects.map(o=>o.project?.name).filter(o=>typeof o=="string")),s=new Set(r.map(o=>o.toLowerCase())),i=P(e.transitiveImpact.map(o=>o.project?.name).filter(o=>typeof o=="string").filter(o=>!s.has(o.toLowerCase()))),a=new Map;for(let o of t){if(o.scope!=="project"||!o.project)continue;let p=o.project.toLowerCase(),f=a.get(p)??[];f.push(o),a.set(p,f);}let g=[],l=[],d=[],y=[],c=false,n=(o,p)=>{let f=a.get(o.toLowerCase())??[];if(f.length===0){d.push(o);return}let x=f.filter(m=>m.status==="fail"),R=x.filter(m=>m.required),I=f.filter(m=>m.status==="missing"),A=I.filter(m=>m.required),V=f.some(m=>m.status==="pass"||m.status==="warn");if(R.length>0){l.push(o),y.push(`graph.subgraph.${o}: ${p} has failed verification evidence (${R.map(m=>m.id).join(", ")}).`);return}if(x.length>0){l.push(o),c=true;return}if(A.length>0){l.push(o),y.push(`graph.subgraph.${o}: ${p} has missing required verification evidence (${A.map(m=>m.id).join(", ")}).`);return}if(I.length>0){l.push(o),c=true;return}if(V){g.push(o);return}d.push(o);};for(let o of r)n(o,"directly-changed");for(let o of i)n(o,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:P(g),uncovered:P(l),unverifiable:P(d)},blockingReasons:y,needsAttention:c}}function P(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function Te(e){let t=k.resolve(e.workspacePath);if(e.fromImpactPath){let a=je(t,e.fromImpactPath);return {impact:await ke(a),fromImpactRef:k.relative(t,a).split(k.sep).join("/"),impactFromDisk:true}}let r$1=k.join(t,g$1);if(await w.pathExists(r$1))return {impact:await ke(r$1),fromImpactRef:g$1,impactFromDisk:true};let s=k.join(t,d$3);if(await w.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$3,scope:e.scope,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),fromImpactRef:d$3,impactFromDisk:false};let i=await r({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {impact:{schemaVersion:f,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",diffRef:p.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:n(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:q.diff,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",toRef:p.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function Le(e,t){if(t)return e.generatedAt}async function wt(e){let t=k.resolve(e.workspacePath),{impact:r$1,fromImpactRef:s,impactFromDisk:i}=await Te(e),a$2=r$1.diff.currentModel,g=i?await r({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):a$2,l=[];if(i){let u=await p$1({workspacePath:t,fromPath:r$1.diff.fromRef,diff:r$1.diff,scope:e.scope,now:e.now}),E=[r$1.affectedProjects,r$1.transitiveImpact,r$1.verificationPlan],j=[u.affectedProjects,u.transitiveImpact,u.verificationPlan];JSON.stringify(E)!==JSON.stringify(j)&&l.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(g)!==r$1.diff.toHash&&l.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r$1.diff.git;if(i&&d$2?.available){let u=a(t,{ref:d$2.ref}),E=r$1.diff.changes.filter(v=>v.type.startsWith("git.")).map(v=>`${v.type}:${v.target.replace(/^git:/,"")}`).sort(),j=[...u.changedFiles.map(v=>`git.file.changed:${v}`),...u.untrackedFiles.map(v=>`git.untracked:${v}`),...u.deletedFiles.map(v=>`git.deleted:${v}`)].sort();(!u.available||u.commit!==d$2.commit||JSON.stringify(j)!==JSON.stringify(E))&&l.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let y=Le(r$1,i),c$1=Ae([...o(),...r$1.verificationPlan]).filter(u=>Se(e.scope,u)),n$1=[];for(let u of c$1)n$1.push(await Ne(u,t,a$2.contracts.exists===true,y));let o$1=Me(r$1,n$1),p=a$1(n(a$2)??{nodes:[],edges:[]}),f=b$1(a$2),x=await ze(t),R=c(f,x?.freshness?.projectHashes),I={verdict:R.verdict,baseline:R.baseline,changed:R.changed,added:R.added,removed:R.removed,projectHashes:d$1(f)},A=b$2(p),V=a$2.policies?.mode??"warn",m=await qe(a$2,t),B=Ke(V,m),S=He(n$1,{blockingReasons:[...o$1.blockingReasons,...A,...B.blockingReasons,...l],needsAttention:o$1.needsAttention||B.needsAttention}),he=n$1.filter(u=>u.status==="missing"&&u.evidencePath).map(u=>u.evidencePath),_=[...n$1.filter(u=>u.required&&(u.status==="fail"||u.status==="missing")).map(u=>`${u.id}: ${u.message}`),...o$1.blockingReasons,...A,...B.blockingReasons,...l],ve=m.filter(u=>u.severity==="error").length,be=a$2.summary?.projectCount??a$2.projects.length,U=me({projectCount:be,verdict:S.verdict,exitCode:S.exitCode,blockingReasons:_,policyErrorCount:ve});S.verdict=U.verdict,S.exitCode=U.exitCode;let Y=Array.from(new Set(_.map(u=>u.trim()).filter(Boolean))).slice(0,12).map((u,E)=>{let j=n$1.find(v=>u.startsWith(`${v.id}:`));return ge({reason:u,blockerId:`blocker-${E+1}`,sourceCommand:j?.command.display,sourceArtifact:j?.evidencePath,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:G})});return {schemaVersion:ye,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r$1.summary.changed,risk:r$1.summary.risk,affectedProjects:r$1.summary.affectedProjects,recommendedCommands:r$1.summary.recommendedCommands},summary:S,steps:n$1,missingEvidence:he,blockingReasons:_,...Y.length>0?{resolutionHints:Y}:{},verificationPlan:c$1,affectedSubgraph:o$1.subgraph,graphIntegrity:p,freshness:I,policyMode:V,policyViolations:m}}async function qe(e,t){let r=[];for(let i of e.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await g(t,p.contractVerify);try{if(s&&await w.pathExists(s)){let i=await w.readJson(s);if(Array.isArray(i.violations))for(let a of i.violations)typeof a=="string"&&a.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:a});}}catch{}return r.sort((i,a)=>i.source!==a.source?i.source.localeCompare(a.source):i.code!==a.code?i.code.localeCompare(a.code):i.message.localeCompare(a.message))}function Ke(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function ze(e){let t=k.join(e,G);try{if(!await w.pathExists(t))return null;let r=await w.readJson(t);return r&&r.schemaVersion===ye?r:null}catch{return null}}async function Rt(e,t){return h$1(t,G,d$2(e))}function Je(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function Ct(e,t){return Je(e,t).exitCode}export{fe as a,st as b,ye as c,G as d,Me as e,wt as f,Rt as g,Je as h,Ct as i};