workspai 0.73.0 → 0.74.0

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 (102) hide show
  1. package/contracts/runtime-command-surface.v1.json +7 -3
  2. package/dist/analyze-IA33T6MY.js +1 -0
  3. package/dist/{artifact-remediation-plan-WDK5ISRU.js → artifact-remediation-plan-OVTQM7HN.js} +1 -1
  4. package/dist/autopilot-release-T327V7QK.js +1 -0
  5. package/dist/chunk-252EKOR6.js +2 -0
  6. package/dist/{chunk-3GO7BJ5J.js → chunk-4JJDDL3X.js} +1 -1
  7. package/dist/chunk-5EVBOUYW.js +3 -0
  8. package/dist/chunk-5Y4YRYZI.js +12 -0
  9. package/dist/{chunk-J44PN2FX.js → chunk-773WUMFU.js} +15 -15
  10. package/dist/{chunk-FRH7AIGY.js → chunk-BTJPTJLT.js} +2 -2
  11. package/dist/{chunk-OIGI7MP6.js → chunk-C43NXRRE.js} +1 -1
  12. package/dist/chunk-D6BL7ARI.js +2 -0
  13. package/dist/chunk-DLLHUG2Q.js +9 -0
  14. package/dist/chunk-DPC5DKH6.js +2 -0
  15. package/dist/{chunk-R5OJD5K2.js → chunk-DTLLIA2C.js} +1 -1
  16. package/dist/{chunk-LDJAUIAG.js → chunk-FYR4FD7K.js} +1 -1
  17. package/dist/chunk-G6ADWA2B.js +2 -0
  18. package/dist/chunk-H333GKL4.js +3 -0
  19. package/dist/{chunk-EDDGQ6LM.js → chunk-H5DRKXXC.js} +1 -1
  20. package/dist/{chunk-DNKELRK6.js → chunk-IQFXLJIM.js} +1 -1
  21. package/dist/{chunk-UCNIXOTL.js → chunk-IUOMBLRR.js} +1 -1
  22. package/dist/chunk-K3FXRBER.js +4 -0
  23. package/dist/{chunk-TIZCESKY.js → chunk-KCIET26G.js} +1 -1
  24. package/dist/chunk-LEEOZRWR.js +7 -0
  25. package/dist/{chunk-T5NBSCVX.js → chunk-NCZJUPG5.js} +49 -49
  26. package/dist/{chunk-TSYDTKXO.js → chunk-RPM67N7A.js} +1 -1
  27. package/dist/{chunk-NSMRQOWP.js → chunk-SAZXL36B.js} +1 -1
  28. package/dist/chunk-SVGUAVMG.js +1 -0
  29. package/dist/chunk-TBOIXIQA.js +1 -0
  30. package/dist/chunk-TGDXD4CD.js +1 -0
  31. package/dist/{chunk-IPZT6WKM.js → chunk-TVSMNF5G.js} +1 -1
  32. package/dist/{chunk-D3N2WFDV.js → chunk-UHT2SW7O.js} +1 -1
  33. package/dist/chunk-VLKX5U4H.js +13 -0
  34. package/dist/chunk-XF65LQ6M.js +1 -0
  35. package/dist/chunk-ZKYH44ER.js +1 -0
  36. package/dist/{chunk-TZK2R6RD.js → chunk-ZNKZ2KXR.js} +1 -1
  37. package/dist/chunk-ZS7JHATN.js +1 -0
  38. package/dist/{create-XYKXS3JB.js → create-EKA2QG5R.js} +1 -1
  39. package/dist/doctor-BXSNADVR.js +1 -0
  40. package/dist/{goal-lifecycle-BIX2JVNO.js → goal-lifecycle-XXWNMIAD.js} +1 -1
  41. package/dist/{goal-pack-SUWH6K7U.js → goal-pack-NTHYLISY.js} +1 -1
  42. package/dist/index.js +158 -158
  43. package/dist/pipeline-JLOC2SUT.js +5 -0
  44. package/dist/{project-agent-entry-Y3NEHZED.js → project-agent-entry-ZNUHGCVC.js} +1 -1
  45. package/dist/{project-intelligence-lens-6Q6XSUDJ.js → project-intelligence-lens-W72OUEDW.js} +1 -1
  46. package/dist/{proof-carrying-change-456TYEDW.js → proof-carrying-change-WLUPMUO7.js} +1 -1
  47. package/dist/verified-goal-6O2JZOOR.js +1 -0
  48. package/dist/{workspace-ROUEA3RT.js → workspace-XTIGVLGH.js} +1 -1
  49. package/dist/{workspace-agent-sync-6UYG33EQ.js → workspace-agent-sync-TN6QDNBR.js} +1 -1
  50. package/dist/{workspace-context-H7ZXR6VI.js → workspace-context-Y3TNY2XZ.js} +1 -1
  51. package/dist/{workspace-contract-2V2BI6A3.js → workspace-contract-GRZY7WRD.js} +1 -1
  52. package/dist/{workspace-explain-IBMTRUSF.js → workspace-explain-KUYHJFLY.js} +1 -1
  53. package/dist/{workspace-foundation-H5B3TTZD.js → workspace-foundation-ZBUJTR56.js} +1 -1
  54. package/dist/{workspace-graph-stream-YDEET5LK.js → workspace-graph-stream-KC2XUAE4.js} +1 -1
  55. package/dist/workspace-graph-token-efficiency-YHXFGH3Z.js +1 -0
  56. package/dist/{workspace-intelligence-DXKQXTTM.js → workspace-intelligence-26YT6KMN.js} +1 -1
  57. package/dist/{workspace-intelligence-benchmark-L46EGZZM.js → workspace-intelligence-benchmark-QFVTUBDO.js} +1 -1
  58. package/dist/{workspace-intelligence-evaluation-QDSOOUHH.js → workspace-intelligence-evaluation-4AB4BBRP.js} +1 -1
  59. package/dist/{workspace-intelligence-runner-SCB44IXU.js → workspace-intelligence-runner-HVYKHCTX.js} +1 -1
  60. package/dist/{workspace-knowledge-graph-BNEVFEOW.js → workspace-knowledge-graph-RL3I2FHY.js} +1 -1
  61. package/dist/{workspace-knowledge-graph-query-GOC365ZR.js → workspace-knowledge-graph-query-TT2KK3SF.js} +1 -1
  62. package/dist/workspace-knowledge-graph-snapshot-JEJMRQZL.js +1 -0
  63. package/dist/workspace-marker-7U3NYRPJ.js +1 -0
  64. package/dist/{workspace-mcp-serve-JLZTTEVG.js → workspace-mcp-serve-2FGRXJG4.js} +1 -1
  65. package/dist/{workspace-model-XSNLDUI2.js → workspace-model-2ODVOWDQ.js} +1 -1
  66. package/dist/{workspace-onboarding-IRBVZTT4.js → workspace-onboarding-BY6RUBBH.js} +1 -1
  67. package/dist/{workspace-python-engine-state-BE4A3BL5.js → workspace-python-engine-state-VCOLSEWV.js} +2 -2
  68. package/dist/{workspace-registry-summary-CBZDSG6I.js → workspace-registry-summary-VKTJ7PHV.js} +1 -1
  69. package/dist/workspace-repair-engine-RBM7NCGI.js +3 -0
  70. package/dist/workspace-run-JCA5WPCR.js +1 -0
  71. package/dist/{workspace-verify-QTRY7WW3.js → workspace-verify-NFJ7RKKT.js} +1 -1
  72. package/dist/{workspace-watch-PDQKYBYQ.js → workspace-watch-3DBBB6IP.js} +1 -1
  73. package/docs/ci-workflows.md +1 -1
  74. package/package.json +1 -1
  75. package/dist/analyze-WC2TY5AT.js +0 -1
  76. package/dist/autopilot-release-LJDRECFW.js +0 -1
  77. package/dist/chunk-2BCECNIW.js +0 -1
  78. package/dist/chunk-2LIVMG5C.js +0 -2
  79. package/dist/chunk-3SNP6M4M.js +0 -2
  80. package/dist/chunk-4HQU2GQM.js +0 -1
  81. package/dist/chunk-4JAURS76.js +0 -13
  82. package/dist/chunk-7O7P4MRD.js +0 -1
  83. package/dist/chunk-AQNU5RXV.js +0 -2
  84. package/dist/chunk-CQBM6BBP.js +0 -2
  85. package/dist/chunk-CY4QZ3PE.js +0 -3
  86. package/dist/chunk-F6CTGVJA.js +0 -9
  87. package/dist/chunk-K3O3HENC.js +0 -5
  88. package/dist/chunk-LGC4CRUF.js +0 -3
  89. package/dist/chunk-NNQE4DS2.js +0 -2
  90. package/dist/chunk-NSH7TTSV.js +0 -1
  91. package/dist/chunk-SO4CGS35.js +0 -4
  92. package/dist/chunk-UNXG3ZFV.js +0 -1
  93. package/dist/chunk-VBMWFT7Q.js +0 -1
  94. package/dist/chunk-ZZWGD3X3.js +0 -12
  95. package/dist/doctor-LQ7FT6AZ.js +0 -1
  96. package/dist/pipeline-NSPPWD7U.js +0 -5
  97. package/dist/verified-goal-GRH5UOJR.js +0 -1
  98. package/dist/workspace-graph-token-efficiency-XM3LYFUC.js +0 -1
  99. package/dist/workspace-knowledge-graph-snapshot-2NMV7LEJ.js +0 -1
  100. package/dist/workspace-marker-XGAWZZDX.js +0 -1
  101. package/dist/workspace-repair-engine-TDUNQSFJ.js +0 -3
  102. package/dist/workspace-run-I2W5PIPK.js +0 -1
@@ -1 +1 @@
1
- import {a}from'./chunk-LDJAUIAG.js';import {d,s,m as m$1}from'./chunk-4HQU2GQM.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import y from'fs';var b="workspace-watch-event.v1";function R(e){return a$2(e,"contracts/workspace-watch-event.v1.json","Workspace watch event"),e}function g(e){return `${e.from}\0${e.to}\0${e.kind}`}function f(e){return (m$1(e)?.edges??[]).map(o=>({from:o.from,to:o.to,kind:o.kind}))}function m(e){let r=[...a(e).entries()].sort((a,n)=>a[0].localeCompare(n[0])).map(([a,n])=>({id:a,hash:n})),c=f(e).map(g).sort((a,n)=>a.localeCompare(n));return d({projects:r,edges:c})}function C(e,o){let r=a(o),c=e?a(e):new Map,a$1=[],n=[];for(let[t,s]of r.entries())c.has(t)?c.get(t)!==s&&a$1.push(t):n.push(t);let d=[];for(let t of c.keys())r.has(t)||d.push(t);let i=new Map(e?f(e).map(t=>[g(t),t]):[]),l=new Map(f(o).map(t=>[g(t),t])),p=[];for(let[t,s]of l.entries())i.has(t)||p.push(s);let h=[];for(let[t,s]of i.entries())l.has(t)||h.push(s);let u=(t,s)=>g(t).localeCompare(g(s));return a$1.sort((t,s)=>t.localeCompare(s)),n.sort((t,s)=>t.localeCompare(s)),d.sort((t,s)=>t.localeCompare(s)),p.sort(u),h.sort(u),{changedProjects:a$1,addedProjects:n,removedProjects:d,edgesAdded:p,edgesRemoved:h}}var k=class{model=null;sequence=0;rebuild;now;constructor(o,r){this.rebuild=r?.rebuild??(()=>s({...o})),this.now=r?.now??(()=>new Date);}get currentModel(){return this.model}async start(){let o=Date.now(),{model:r}=await this.rebuild();return this.model=r,this.buildEvent("ready","initial",null,r,Date.now()-o)}async pulse(){let o=Date.now(),r=this.model,{model:c,mode:a}=await this.rebuild(),n=this.buildEvent(this.hasStructuralChange(r,c)?"changed":"unchanged",a,r,c,Date.now()-o);return this.model=c,n}hasStructuralChange(o,r){return o?m(o)!==m(r):true}buildEvent(o,r,c,a,n){let d=C(c,a),i=m(a),l=c?m(c)!==i:true;return R({schemaVersion:b,kind:o,sequence:this.sequence++,timestamp:this.now().toISOString(),mode:r,modelHash:i,modelHashChanged:l,changedProjects:d.changedProjects,addedProjects:d.addedProjects,removedProjects:d.removedProjects,graph:{nodeCount:a.graph?.nodes.length??0,edgeCount:a.graph?.edges.length??0,edgesAdded:d.edgesAdded,edgesRemoved:d.edgesRemoved},durationMs:n})}},S=new Set([".git",".hg",".svn","node_modules",".venv","venv","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),j=new Set(["reports","cache","tmp",".cache"]);function O(e){if(!e)return false;let o=e.split(/[\\/]/).filter(Boolean);if(o.some(r=>S.has(r)||a$1(r)))return false;for(let r=0;r<o.length-1;r+=1)if((o[r]===".workspai"||o[r]===".rapidkit")&&j.has(o[r+1]))return false;return true}async function N(e){let o=new k(e.buildOptions,e.engineOptions),r=await o.start();if(e.emit(r),o.currentModel&&await e.onModel?.(o.currentModel,r),e.once)return;let c=e.debounceMs??250,a=e.selfWriteSuppressionMs??Math.max(400,c+150),n=null,d=false,i=false,l=0,p=async()=>{if(d){i=true;return}d=true;try{let t=await o.pulse();e.emit(t),o.currentModel&&await e.onModel?.(o.currentModel,t);}catch(t){e.emit(R({schemaVersion:b,kind:"error",sequence:-1,timestamp:new Date().toISOString(),mode:"full",modelHash:o.currentModel?m(o.currentModel):"",modelHashChanged:false,changedProjects:[],addedProjects:[],removedProjects:[],graph:{nodeCount:0,edgeCount:0,edgesAdded:[],edgesRemoved:[]},durationMs:0,error:t instanceof Error?t.message:String(t)}));}finally{d=false,l=Date.now()+a,i&&(i=false,p());}},h=t=>{O(t)&&(d||Date.now()<l||(n&&clearTimeout(n),n=setTimeout(()=>{n=null,p();},c)));};e.onProgress?.(`Watching ${e.workspacePath} for changes (Ctrl+C to stop).`);let u=y.watch(e.workspacePath,{recursive:true},(t,s)=>{typeof s=="string"?h(s):s&&h(Buffer.from(s).toString("utf8"));});await new Promise(t=>{let s=()=>{n&&clearTimeout(n),u.close(),t();};if(e.signal){if(e.signal.aborted){s();return}e.signal.addEventListener("abort",s,{once:true});}u.on("error",()=>s());});}export{b as WORKSPACE_WATCH_EVENT_SCHEMA_VERSION,k as WorkspaceWatchEngine,m as computeWatchModelHash,C as diffWatchModels,O as isWatchRelevantPath,N as runWorkspaceWatch};
1
+ import {a}from'./chunk-FYR4FD7K.js';import {d,s,m as m$1}from'./chunk-TGDXD4CD.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import y from'fs';var b="workspace-watch-event.v1";function R(e){return a$2(e,"contracts/workspace-watch-event.v1.json","Workspace watch event"),e}function g(e){return `${e.from}\0${e.to}\0${e.kind}`}function f(e){return (m$1(e)?.edges??[]).map(o=>({from:o.from,to:o.to,kind:o.kind}))}function m(e){let r=[...a(e).entries()].sort((a,n)=>a[0].localeCompare(n[0])).map(([a,n])=>({id:a,hash:n})),c=f(e).map(g).sort((a,n)=>a.localeCompare(n));return d({projects:r,edges:c})}function C(e,o){let r=a(o),c=e?a(e):new Map,a$1=[],n=[];for(let[t,s]of r.entries())c.has(t)?c.get(t)!==s&&a$1.push(t):n.push(t);let d=[];for(let t of c.keys())r.has(t)||d.push(t);let i=new Map(e?f(e).map(t=>[g(t),t]):[]),l=new Map(f(o).map(t=>[g(t),t])),p=[];for(let[t,s]of l.entries())i.has(t)||p.push(s);let h=[];for(let[t,s]of i.entries())l.has(t)||h.push(s);let u=(t,s)=>g(t).localeCompare(g(s));return a$1.sort((t,s)=>t.localeCompare(s)),n.sort((t,s)=>t.localeCompare(s)),d.sort((t,s)=>t.localeCompare(s)),p.sort(u),h.sort(u),{changedProjects:a$1,addedProjects:n,removedProjects:d,edgesAdded:p,edgesRemoved:h}}var k=class{model=null;sequence=0;rebuild;now;constructor(o,r){this.rebuild=r?.rebuild??(()=>s({...o})),this.now=r?.now??(()=>new Date);}get currentModel(){return this.model}async start(){let o=Date.now(),{model:r}=await this.rebuild();return this.model=r,this.buildEvent("ready","initial",null,r,Date.now()-o)}async pulse(){let o=Date.now(),r=this.model,{model:c,mode:a}=await this.rebuild(),n=this.buildEvent(this.hasStructuralChange(r,c)?"changed":"unchanged",a,r,c,Date.now()-o);return this.model=c,n}hasStructuralChange(o,r){return o?m(o)!==m(r):true}buildEvent(o,r,c,a,n){let d=C(c,a),i=m(a),l=c?m(c)!==i:true;return R({schemaVersion:b,kind:o,sequence:this.sequence++,timestamp:this.now().toISOString(),mode:r,modelHash:i,modelHashChanged:l,changedProjects:d.changedProjects,addedProjects:d.addedProjects,removedProjects:d.removedProjects,graph:{nodeCount:a.graph?.nodes.length??0,edgeCount:a.graph?.edges.length??0,edgesAdded:d.edgesAdded,edgesRemoved:d.edgesRemoved},durationMs:n})}},S=new Set([".git",".hg",".svn","node_modules",".venv","venv","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),j=new Set(["reports","cache","tmp",".cache"]);function O(e){if(!e)return false;let o=e.split(/[\\/]/).filter(Boolean);if(o.some(r=>S.has(r)||a$1(r)))return false;for(let r=0;r<o.length-1;r+=1)if((o[r]===".workspai"||o[r]===".rapidkit")&&j.has(o[r+1]))return false;return true}async function N(e){let o=new k(e.buildOptions,e.engineOptions),r=await o.start();if(e.emit(r),o.currentModel&&await e.onModel?.(o.currentModel,r),e.once)return;let c=e.debounceMs??250,a=e.selfWriteSuppressionMs??Math.max(400,c+150),n=null,d=false,i=false,l=0,p=async()=>{if(d){i=true;return}d=true;try{let t=await o.pulse();e.emit(t),o.currentModel&&await e.onModel?.(o.currentModel,t);}catch(t){e.emit(R({schemaVersion:b,kind:"error",sequence:-1,timestamp:new Date().toISOString(),mode:"full",modelHash:o.currentModel?m(o.currentModel):"",modelHashChanged:false,changedProjects:[],addedProjects:[],removedProjects:[],graph:{nodeCount:0,edgeCount:0,edgesAdded:[],edgesRemoved:[]},durationMs:0,error:t instanceof Error?t.message:String(t)}));}finally{d=false,l=Date.now()+a,i&&(i=false,p());}},h=t=>{O(t)&&(d||Date.now()<l||(n&&clearTimeout(n),n=setTimeout(()=>{n=null,p();},c)));};e.onProgress?.(`Watching ${e.workspacePath} for changes (Ctrl+C to stop).`);let u=y.watch(e.workspacePath,{recursive:true},(t,s)=>{typeof s=="string"?h(s):s&&h(Buffer.from(s).toString("utf8"));});await new Promise(t=>{let s=()=>{n&&clearTimeout(n),u.close(),t();};if(e.signal){if(e.signal.aborted){s();return}e.signal.addEventListener("abort",s,{once:true});}u.on("error",()=>s());});}export{b as WORKSPACE_WATCH_EVENT_SCHEMA_VERSION,k as WorkspaceWatchEngine,m as computeWatchModelHash,C as diffWatchModels,O as isWatchRelevantPath,N as runWorkspaceWatch};
@@ -95,7 +95,7 @@ Validate or preview the current CLI announcement locally:
95
95
  npm --workspace workspai run check:release-announcement
96
96
  npm --workspace workspai run release:announcement -- \
97
97
  --product workspai-cli \
98
- --tag v0.73.0 \
98
+ --tag v0.74.0 \
99
99
  --markdown-output /tmp/workspai-discord-announcement.md
100
100
  ```
101
101
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workspai",
3
- "version": "0.73.0",
3
+ "version": "0.74.0",
4
4
  "type": "module",
5
5
  "description": "Open-source workspace intelligence CLI for software systems: create, adopt, govern, verify, and align polyglot workspaces for humans, CI, IDEs, and AI agents.",
6
6
  "keywords": [
@@ -1 +0,0 @@
1
- export{b as printAnalyzeReport,a as runAnalyze}from'./chunk-F6CTGVJA.js';
@@ -1 +0,0 @@
1
- export{b as AUTOPILOT_RELEASE_ALIAS_FILENAME,a as AUTOPILOT_RELEASE_LAST_RUN_FILENAME,c as runAutopilotRelease}from'./chunk-3GO7BJ5J.js';
@@ -1 +0,0 @@
1
- import {a as a$2}from'./chunk-TZK2R6RD.js';import {j,l as l$1}from'./chunk-IPZT6WKM.js';import {g}from'./chunk-FRH7AIGY.js';import {u}from'./chunk-T5NBSCVX.js';import {j as j$1,e}from'./chunk-XVTN5DDV.js';import {b,c as c$1}from'./chunk-4JAURS76.js';import {c,d}from'./chunk-UCNIXOTL.js';import {a}from'./chunk-COICGD62.js';import {f as f$1,g as g$1,h as h$2}from'./chunk-R5OJD5K2.js';import {k,l,h as h$1,m,n as n$1,p as p$1,q as q$2}from'./chunk-3SNP6M4M.js';import {a as a$3}from'./chunk-D3N2WFDV.js';import {a as a$1}from'./chunk-F6CTGVJA.js';import {n,q as q$1,t}from'./chunk-4HQU2GQM.js';import {o,r as r$1,s}from'./chunk-NNQE4DS2.js';import {f,h}from'./chunk-FE5R6EUV.js';import {b as b$1}from'./chunk-K33JJVQZ.js';import {p,q,z,A,y,x}from'./chunk-ODK4LCEL.js';import {c as c$2}from'./chunk-PKKSRXUS.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(p.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===p.intelligenceRun,`artifactPath must be ${p.intelligenceRun}`),r(t.preflight.length===y.length,`preflight must contain exactly ${y.length} entries`);for(let[d,n]of y.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,z[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===x.length,`stages must contain exactly ${x.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of x.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,A[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y$1=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y$1?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=p.intelligenceRun,Ee=q.intelligenceRun,L=we;function I(t){c$2({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return f(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t$1){let s$1=t$1.workspacePath,m$1=[],u$1=[],h$3=false,y=async(e,o)=>{let c=[...z[e]];if(h$3){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$1.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$1.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$3=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$1.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$2=async(e,o)=>{let c=[...A[e].produces];if(h$3){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u$1.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u$1.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$3=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u$1.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o$1=await o({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o$1.contract.projects.length} projects`}});let p$2,d$1=()=>{if(!p$2)throw new Error("canonical workspace model is unavailable");return p$2};await l$2("model",async()=>(p$2={...await q$1({workspacePath:s$1,includeEvidence:true}),build:n({mode:"full",engineStatus:"disabled"})},await t(p$2,s$1),{message:`${p$2.summary.projectCount} projects modeled`}));let n$2=ge.join(s$1,p.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$2)){let c=await k({workspacePath:s$1,model:d$1()});return await l(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$2),o=h$1(e);return o?(await l(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$2("diff",async()=>{let e=await m({workspacePath:s$1,fromPath:p.snapshot,model:d$1()});return await n$1(e,s$1),{message:e.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$2("impact",async()=>{let e=await p$1({workspacePath:s$1,fromPath:p.diff});return await q$2(e,s$1),{message:`${e.summary.risk} risk; ${e.summary.affectedProjects} affected`}}),await l$2("doctor-evidence",async()=>{let e=await u({workspace:s$1,json:true,quiet:true,profile:t$1.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$2("contract-evidence",async()=>{let e=await r$1({workspacePath:s$1,strict:true});return await s({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$2("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t$1.strict===true});return {blocked:e.summary.verdict==="blocked"||t$1.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t$1.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$2("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t$1.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t$1.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$2("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:p.impact});await g$1(e$1,s$1);let o=h$2(e$1,{strict:t$1.strict===true});return await j$1(s$1,e(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$2("context",async()=>{let e=await c({workspacePath:s$1,model:d$1(),agent:t$1.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$2("agent-sync",async()=>{let e=await l$1({workspacePath:s$1,agent:t$1.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t$1.strict===true,preset:"enterprise"}),o=false,c$1=await a$3(s$1);if(c$1.status==="miss"){if(c$1.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c$1.reason}).`);p$2={...await q$1({workspacePath:s$1,includeEvidence:true}),build:n({mode:"full",engineStatus:"disabled"})},await t(p$2,s$1);let f=await c({workspacePath:s$1,model:p$2,agent:t$1.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$1({workspacePath:s$1,agent:t$1.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t$1.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t$1.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$2("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$1(e,s$1);let o=t$1.strict===true?u$1.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u$1.some(e=>e.status==="blocked"),G=h$3?"failed":me?"blocked":"passed",fe=h$3?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$1,status:G,exitCode:fe,stages:u$1,artifactPath:L};ue(b$1),await h(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await h(s$1,p.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
@@ -1,2 +0,0 @@
1
- import {r,s}from'./chunk-VQZ5PI5J.js';import o from'fs-extra';async function i(a){for(let t of [r(a),s(a)])try{if(await o.pathExists(t))return await o.readJson(t)}catch{}return null}async function c(a,t){let e=await i(a);e?.metadata&&(t.metadata={...e.metadata,...t.metadata});let r$1=JSON.stringify(t,null,2)+`
2
- `;await o.outputFile(r(a),r$1,"utf-8");}async function m(a,t){let e=await i(a);return e?(e.metadata={...e.metadata,...t,vscode:t.vscode?{...e.metadata?.vscode,...t.vscode}:e.metadata?.vscode,npm:t.npm?{...e.metadata?.npm,...t.npm}:e.metadata?.npm,python:t.python?{...e.metadata?.python,...t.python}:e.metadata?.python},await c(a,e),true):false}function u(a,t,e,r){return {signature:"RAPIDKIT_WORKSPACE",createdBy:"workspai-cli",version:t,createdAt:new Date().toISOString(),name:a,metadata:{npm:{packageVersion:t,installMethod:e,lastUsedAt:new Date().toISOString()},...r?{python:r}:{}}}}function f(a){if(!a||typeof a!="object")return false;let t=a;return t.signature==="RAPIDKIT_WORKSPACE"&&typeof t.createdBy=="string"&&typeof t.version=="string"&&typeof t.createdAt=="string"&&typeof t.name=="string"}export{i as a,c as b,m as c,u as d,f as e};
@@ -1,2 +0,0 @@
1
- import {q as q$1,l,m,k as k$1}from'./chunk-4HQU2GQM.js';import {a}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {d as d$1}from'./chunk-NNQE4DS2.js';import {h as h$1}from'./chunk-FE5R6EUV.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 $(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
- `)){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=$(e,["rev-parse","--is-inside-work-tree"]);if(!r.ok||r.stdout!=="true")return a;let i=$(e,["rev-parse","--abbrev-ref","HEAD"]),n=$(e,["rev-parse","HEAD"]),c=$(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,_=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!==k$1)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===k$1){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. ${_}. 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!==k$1||!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 q$1({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:l,model:t}}async function Qe(e,t){return h$1(t,_,d$1(e))}function x(e){return {name:e.name,path:e.path,kind:e.kind,category:e.category,runtime:e.runtime,framework:e.framework,generator:e.generator,supportTier:e.supportTier,commands:e.commands,importantFiles:e.importantFiles}}function h(e,t){e.push(t);}function Me(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 je(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:x(c)});continue}let m=x(p),l=x(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:x(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=a?We(e.fromPath):void 0,i=e.fromPath;if(a){let f=k.join(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=_;}let n=se(t,i),c=await be(n),p=e.model??await q$1({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),m=d(p),l$1=[...Me(c.model,p),...Ie(c.model,p),...je(c.model,p)],u;e.includeGitObservation!==false&&(u=e.gitObservation??Q(t,{ref:r}),u.available&&Ee(l$1,u,p));let v=l$1.filter(f=>f.type.startsWith("git.")).length,R=c.hash!==m,w=a?`git:${r??"HEAD"}`:k.relative(t,n).split(k.sep).join("/");return {schemaVersion:L,generatedAt:(e.now??new Date).toISOString(),fromRef:w,toRef:l,fromHash:c.hash,toHash:m,summary:{changed:R||v>0,addedProjects:l$1.filter(f=>f.type==="project.added").length,removedProjects:l$1.filter(f=>f.type==="project.removed").length,changedProjects:l$1.filter(f=>f.type==="project.changed").length,workspaceChanges:l$1.filter(f=>f.type==="workspace.changed").length,validationChanges:l$1.filter(f=>f.type==="validation.changed").length,gitChangedFiles:v},git:u?.available?Oe(u,r):{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:l$1,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 T(){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 Se(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 Ee(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=Se(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 Fe(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 $e(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 xe(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=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.get(o.before.name):void 0))?.path??o.target,y=p.get(d)??[];y.push(o),p.set(d,y);}let m$1=[];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$1.push({id:`project:${C}`,scope:"project",target:o,title:`Project impact: ${C}`,summary:s.map(M=>M.message).join(" "),risk:y,reasons:s.map(M=>`${M.type}: ${M.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):T()});}let l=m(r.currentModel),u=l?a(l):void 0,v=new Set(m$1.map(o=>o.project?.name).filter(o=>typeof o=="string")),R=new Map;for(let o of m$1)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,R.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.get(s.id);if(d&&!re(e.scope,d))continue;let y=s.path[0],C=s.path[s.path.length-2]??y,M=R.get(y)??"medium",de=Re(M),j=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):T(),origin:"transitive",distance:s.distance,path:s.path,via:s.via,...j?{centrality:{fanIn:j.fanIn,fanOut:j.fanOut,reach:j.reach,betweenness:j.betweenness,isHotspot:j.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,P=ce.map(o=>({id:`workspace:${o.target}`,scope:"workspace",target:o.target,title:`Workspace impact: ${o.target}`,summary:o.message,risk:Fe(o,{projectCount:K}),reasons:[`${o.type}: ${o.message}`],verification:T()})),B=Ae([...m$1.flatMap(o=>o.verification),...w.flatMap(o=>o.verification),...P.flatMap(o=>o.verification),...r.summary.changed?T():[]]).filter(o=>o.required),pe=Z([...m$1.map(o=>o.risk),...w.map(o=>o.risk),...P.map(o=>o.risk)]),z=$e({risk:pe,affectedProjects:m$1.length,projectCount:K,changes:r.changes}),q={changed:r.summary.changed,risk:z,affectedProjects:m$1.length,workspaceItems:P.length,recommendedCommands:B.length,blastRadius:{directlyAffected:m$1.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$1.sort((o,s)=>o.target.localeCompare(s.target)),transitiveImpact:w,criticalPathHotspots:ie,workspaceImpact:P.sort((o,s)=>o.target.localeCompare(s.target)),verificationPlan:B,agentBrief:xe({changed:q.changed,risk:z,affectedProjects:m$1,workspaceImpact:P}),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,_ 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,T as o,et as p,tt as q};
@@ -1 +0,0 @@
1
- import {k,q}from'./chunk-46QH3ZVI.js';import {a as a$6}from'./chunk-HTYMXMQM.js';import {b as b$2,c as c$2,a as a$3}from'./chunk-ND5YAC4T.js';import {a as a$2}from'./chunk-NMXGSVMD.js';import {d,a as a$1,p as p$1,g as g$1,f as f$1,e}from'./chunk-NNQE4DS2.js';import {c,b as b$1,j as j$2,z as z$1,f}from'./chunk-LGC4CRUF.js';import {m as m$1,j as j$3,l}from'./chunk-YYELANJO.js';import {a as a$5}from'./chunk-GR6442P7.js';import {j as j$1,g,a as a$4,h}from'./chunk-FE5R6EUV.js';import {a}from'./chunk-2LIVMG5C.js';import {d as d$1,c as c$1}from'./chunk-EWZZUQBR.js';import {q as q$1,p,t as t$1,s}from'./chunk-ODK4LCEL.js';import {t}from'./chunk-VQZ5PI5J.js';import m from'path';import P from'fs-extra';import Ot from'crypto';import {execFile}from'child_process';import {promisify}from'util';import {createRequire}from'module';var It=new Set(c().map(e=>e.id)),Ft=[...k().map(e=>({id:e.kitId,aliases:[...e.aliases],ecosystem:e.framework,plannerFramework:e.id,runtime:"node",runtimeCandidates:["node"],workspacePythonEngine:"none",status:"available",canExecuteCreate:true,versionPolicy:e.versionPolicy,officialCommands:[e.commandDisplay("<name>",{skipGit:false,skipInstall:false})],adoptAfterCreate:true,...e.minNodeVersion?{runtimeRequirements:{node:`>=${e.minNodeVersion}`}}:e.minNodeMajor?{runtimeRequirements:{node:`>=${e.minNodeMajor}`}}:{}})),...q().map(e=>({id:e.kitId,aliases:[...e.aliases],ecosystem:e.framework,plannerFramework:e.framework,runtime:e.runtime,runtimeCandidates:[...e.runtimeCandidates],workspacePythonEngine:"none",status:"available",canExecuteCreate:true,versionPolicy:e.versionPolicy,officialCommands:[e.commandDisplay("<name>",{skipGit:false,skipInstall:false})],adoptAfterCreate:true,...e.nodeSupport?{runtimeRequirements:{node:e.nodeSupport.requirement}}:{}})),{id:"wordpress-site",aliases:["wordpress","wordpress-site","wp","wp-site"],ecosystem:"wordpress",plannerFramework:"wordpress",runtime:"php",runtimeCandidates:["php"],workspacePythonEngine:"none",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["wp core download","wp config create","wp db create","wp core install"],adoptAfterCreate:true},{id:"wordpress-block",aliases:["wordpress-block","wp-block","gutenberg-block"],ecosystem:"wordpress",plannerFramework:"wordpress",runtime:"node",runtimeCandidates:["node","php"],workspacePythonEngine:"none",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["npx @wordpress/create-block@latest <slug>"],adoptAfterCreate:true},{id:"symfony",aliases:["symfony","php-symfony"],ecosystem:"php",plannerFramework:"symfony",runtime:"php",runtimeCandidates:["php"],workspacePythonEngine:"none",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["composer create-project symfony/skeleton <name>"],adoptAfterCreate:true},{id:"rails",aliases:["rails","ruby-on-rails","ruby-rails"],ecosystem:"ruby",plannerFramework:"rails",runtime:"ruby",runtimeCandidates:["ruby"],workspacePythonEngine:"none",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["rails new <name>"],adoptAfterCreate:true}],H=new Map;for(let e of Ft){H.set(e.id,e);for(let t of e.aliases)H.set(t,e);}var Dt=new Set(["php","ruby","rust","elixir","clojure","scala","kotlin","unknown"]);function K(e){return e?.trim().toLowerCase()||void 0}function tt(e){let t=K(e.kitId)??K(e.framework)??K(e.runtime)??"unknown";if(e.projectExists)return {lane:"existing",status:"available",canExecuteCreate:false,requested:t,reason:"Existing projects enter Workspace Intelligence through adopt/import."};let r=e.kitId?b$1(e.kitId):void 0;if(r&&It.has(r))return {lane:"native",status:"available",canExecuteCreate:true,requested:t,resolved:r,reason:"Workspai owns the create contract, project marker, registry, doctor, and workspace model path."};let o=H.get(t)??H.get(K(e.framework)??"")??H.get(K(e.runtime)??"");if(o)return {lane:"official",status:o.status,canExecuteCreate:o.canExecuteCreate,requested:t,resolved:o.id,officialCommands:o.officialCommands,fallbackLane:o.canExecuteCreate?void 0:"existing",reason:o.status==="available"?"Workspai runs the official ecosystem generator, then registers the project in Workspace Intelligence.":"Official generator support is planned but not enabled; use adopt/import until Workspai owns the post-create contract."};let s=K(e.runtime);return s&&Dt.has(s)?{lane:"existing",status:"available",canExecuteCreate:false,requested:t,resolved:s,reason:"Runtime can be governed through Workspace Intelligence, but native create is not supported."}:{lane:"existing",status:"available",canExecuteCreate:false,requested:t,reason:"No native create contract is available; use adopt/import to enter Workspace Intelligence."}}function Br(e){return !e.canExecuteCreate&&(e.lane==="official"||e.lane==="existing"&&e.resolved!==void 0)}var qr="rapidkit-freshness-metadata-v1";function fe(e){if(Array.isArray(e))return e.map(t=>fe(t));if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=fe(e[r]);return t}return e}function Gt(e){return JSON.stringify(fe(e))}function G(e){return Ot.createHash("sha256").update(Gt(e)).digest("hex")}var rt=".workspai/workspace-graph.overrides.json",_t=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),Tt=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","node_modules","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),ot=600,st=5,Nt=256*1024,nt={inferred:1,contract:2,manual:3};function Kt(e){return e.split(m.sep).join("/")}function Z(e,t){return Kt(m.relative(e,t)||".")}function at(e){let t=new Map;for(let r of e.projects)t.has(r.name)||t.set(r.name,{id:r.name,path:r.path,...r.runtime?{runtime:r.runtime}:{},...r.framework?{framework:r.framework}:{},...r.kind?{kind:r.kind}:{}});return [...t.values()].sort((r,o)=>r.id.localeCompare(o.id))}function it(e,t){let r=new Map,o=new Map;for(let n of t.projects){if(r.has(n.name))continue;let i=n.absolutePath?m.resolve(n.absolutePath):m.resolve(e,n.path);r.set(n.name,i),o.has(i)||o.set(i,n.name);}let s=[...o.entries()].map(([n,i])=>({dir:n,id:i})).sort((n,i)=>i.dir.length-n.dir.length||n.dir.localeCompare(i.dir));return {idToDir:r,dirToId:o,sortedDirs:s}}function ee(e,t){let r=m.resolve(t);for(let{dir:o,id:s}of e.sortedDirs)if(r===o||r.startsWith(`${o}${m.sep}`))return s;return null}function he(e,t){let r=m.relative(e,t);return r.length>0&&!r.startsWith("..")&&!m.isAbsolute(r)}function we(e,t,r){let o=e.idToDir.get(t),s=e.idToDir.get(r);return !o||!s?false:he(o,s)||he(s,o)}async function ke(e){try{if(!await P.pathExists(e))return null;let t=await P.readJSON(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async function ve(e){try{return await P.pathExists(e)?await P.readFile(e,"utf8"):null}catch{return null}}async function ct(e,t){let r=[],o=new Map;for(let[s,n]of t.idToDir.entries()){let i=await ke(m.join(n,"package.json")),a=typeof i?.name=="string"?i.name.trim():"";a&&!o.has(a)&&o.set(a,s);}for(let[s,n]of t.idToDir.entries()){let i=await ke(m.join(n,"package.json"));if(i){let a=["dependencies","devDependencies","peerDependencies","optionalDependencies"],c=new Set;for(let p of a){let u=i[p];if(!(!u||typeof u!="object"||Array.isArray(u)))for(let l of Object.keys(u)){let d=o.get(l);!d||d===s||c.has(d)||(c.add(d),r.push({from:s,to:d,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:Z(e,m.join(n,"package.json")),detail:`declares dependency ${l}`}]}));}}}r.push(...await $t(e,t,s,n)),r.push(...await Vt(e,t,s,n));}return r}async function $t(e,t,r,o){let s=await ve(m.join(o,"pyproject.toml"));if(!s)return [];let n=[],i=new Set,a=/path\s*=\s*["']([^"']+)["']/g,c;for(;(c=a.exec(s))!==null;){let p=ee(t,m.resolve(o,c[1]));!p||p===r||we(t,r,p)||i.has(p)||(i.add(p),n.push({from:r,to:p,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:Z(e,m.join(o,"pyproject.toml")),detail:`path dependency ${c[1]}`}]}));}return n}async function Vt(e,t,r,o){let s=await ve(m.join(o,"go.mod"));if(!s)return [];let n=[],i=new Set,a=/replace\s+\S+\s+=>\s+(\.[^\s]+)/g,c;for(;(c=a.exec(s))!==null;){let p=ee(t,m.resolve(o,c[1]));!p||p===r||we(t,r,p)||i.has(p)||(i.add(p),n.push({from:r,to:p,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:Z(e,m.join(o,"go.mod")),detail:`go.mod replace ${c[1]}`}]}));}return n}async function Ht(e,t,r=new Set){let o=[],s=[e];for(;s.length>0&&o.length<t;){let n=s.shift();if(!n)continue;let i=[];try{i=await P.readdir(n,{withFileTypes:true});}catch{continue}let a=[],c=[];for(let p of i)if(p.isDirectory()){let u=m.resolve(n,p.name);if(r.has(u)||Tt.has(p.name)||a$5(p.name)||p.name.startsWith("."))continue;a.push(m.join(n,p.name));}else p.isFile()&&_t.has(m.extname(p.name))&&c.push(m.join(n,p.name));c.sort((p,u)=>p.localeCompare(u)),a.sort((p,u)=>p.localeCompare(u));for(let p of c){if(o.length>=t)break;o.push(p);}s.push(...a);}return o}var Bt=[/\bfrom\s+["']([^"']+)["']/g,/\bimport\s+["']([^"']+)["']/g,/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g,/\brequire\s*\(\s*["']([^"']+)["']\s*\)/g];function Lt(e){let t=new Set;for(let r of Bt){r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){let s=o[1];s.startsWith(".")&&t.add(s);}}return [...t]}async function ye(e,t,r,o){let s=new Map;for(let[n,i]of t.idToDir.entries()){if(o&&!o.has(n))continue;let a=new Set([...t.idToDir.entries()].filter(([p,u])=>p!==n&&he(i,u)).map(([,p])=>m.resolve(p))),c=await Ht(i,r,a);for(let p of c){let u=await P.stat(p).catch(()=>null);if(!u||u.size>Nt)continue;let l=await ve(p);if(l)for(let d of Lt(l)){let f=m.resolve(m.dirname(p),d),k=ee(t,f);if(!k||k===n||we(t,n,k))continue;let g=`${n}\0${k}`,v=s.get(g);v||(v={from:n,to:k,evidence:[]},s.set(g,v)),v.evidence.length<st&&v.evidence.push({file:Z(e,p),detail:`imports ${d}`});}}}return [...s.values()].map(n=>({from:n.from,to:n.to,kind:"code-import",source:"inferred",confidence:"medium",evidence:n.evidence}))}function Ut(e,t,r){let o=new Map;for(let s of r.projects){let n=zt(e,t,s);n&&o.set(s.slug,n);}return o}function zt(e,t,r){let o=[r.relativePath,r.externalPath].filter(s=>typeof s=="string"&&s.length>0);for(let s of o){let n=m.resolve(e,s),i=t.dirToId.get(n)??ee(t,n);if(i)return i}return t.idToDir.has(r.slug)?r.slug:null}function dt(e,t,r){let o=[],s=Ut(e,t,r),n=g$1,i=new Map,a=new Map;for(let c of r.projects){let p=s.get(c.slug);if(!p)continue;let u=c.contracts??{publishes:[],consumes:[],dependsOn:[]};for(let l of u.dependsOn??[]){let d=s.get(l);!d||d===p||o.push({from:p,to:d,kind:"service-dependsOn",source:"contract",confidence:"high",evidence:[{file:n,detail:`dependsOn ${l}`}]});}for(let l of u.publishes??[])i.has(l)||i.set(l,new Set),i.get(l)?.add(p);for(let l of u.consumes??[])a.has(l)||a.set(l,new Set),a.get(l)?.add(p);}for(let[c,p]of i.entries()){let u=a.get(c);if(u)for(let l of u)for(let d of p)l!==d&&o.push({from:l,to:d,kind:"event-pub-sub",source:"contract",confidence:"high",evidence:[{file:n,detail:`consumes event ${c}`}]});}return o.push(...qt(r,s)),o}function ge(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function qt(e,t){let r=[],o=e.projects.map(s=>({project:s,id:t.get(s.slug)})).filter(s=>!!s.id).filter(s=>ge(s.project.slug).length>=3);for(let s of e.projects){let n=t.get(s.slug);if(!n)continue;let i=s.contracts?.env??[];if(i.length===0)continue;let a=new Set;for(let c of i){let p=ge(c);for(let u of o)u.id===n||a.has(u.id)||!(p.includes(ge(u.project.slug))&&(u.project.ports?.length??0)>0)||(a.add(u.id),r.push({from:n,to:u.id,kind:"shared-resource",source:"inferred",confidence:"low",evidence:[{file:g$1,detail:`env ${c} references ${u.project.slug}`}]}));}}return r}async function pt(e,t){let r=await ke(m.join(e,rt)),o=Array.isArray(r?.edges)?r?.edges:[],s=[],n=new Set(f$1);for(let i of o){if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i,c=typeof a.from=="string"?a.from:"",p=typeof a.to=="string"?a.to:"",u=typeof a.kind=="string"?a.kind:"";if(!t.has(c)||!t.has(p)||c===p||!n.has(u))continue;let l=Array.isArray(a.evidence)?a.evidence.map(d=>d&&typeof d=="object"&&typeof d.file=="string"?{file:d.file,...typeof d.detail=="string"?{detail:d.detail}:{}}:null).filter(d=>!!d):[];s.push({from:c,to:p,kind:u,source:"manual",confidence:"high",evidence:l.length>0?l:[{file:rt,detail:"manual edge"}]});}return s}function Jt(e){return `${e.from}\0${e.to}\0${e.kind}`}function Xt(e){let t=new Set,r=[];for(let o of e){let s=`${o.file}\0${o.detail??""}`;t.has(s)||(t.add(s),r.push(o));}return r.sort((o,s)=>o.file.localeCompare(s.file)||(o.detail??"").localeCompare(s.detail??"")).slice(0,st)}function Yt(e){let t=new Map;for(let r of e){let o=Jt(r),s=t.get(o);if(!s){t.set(o,{...r,evidence:[...r.evidence]});continue}let n=nt[s.source],i=nt[r.source];i>n?t.set(o,{...r,evidence:[...r.evidence,...s.evidence]}):i===n&&s.evidence.push(...r.evidence);}return [...t.values()].map(r=>({from:r.from,to:r.to,kind:r.kind,source:r.source,confidence:r.confidence,evidence:Xt(r.evidence)})).sort((r,o)=>r.from.localeCompare(o.from)||r.to.localeCompare(o.to)||r.kind.localeCompare(o.kind)||r.source.localeCompare(o.source))}function me(e){return Math.round(e*1e3)/1e3}function Qt(e){return Math.max(0,Math.min(100,Math.round(e)))}function Zt(e){return e>=75?"critical":e>=50?"high":e>=20?"medium":"low"}function er(e){return e==="critical"||e==="high"?"strict":e==="medium"?"elevated":"normal"}function tr(e,t){let r=a$6({nodes:e,edges:t}),o=new Map;for(let s of e){let n=r.byId.get(s.id)??{fanIn:0,fanOut:0,reach:0,betweenness:0,isHotspot:false},i=t.filter(f=>f.from===s.id||f.to===s.id),a=i.filter(f=>f.source==="contract"||f.source==="manual").length,c=i.filter(f=>f.confidence==="low").length,p=[],u=n.reach*20+n.fanIn*14+n.fanOut*8+Math.min(20,n.betweenness*4)+a*8;n.isHotspot&&(u+=24,p.push("Critical-path hotspot in dependency graph")),n.reach>0&&p.push(`Change reaches ${n.reach} dependent project(s)`),n.fanIn>0&&p.push(`${n.fanIn} direct dependent project(s)`),n.fanOut>0&&p.push(`${n.fanOut} direct dependency project(s)`),a>0&&p.push(`${a} contract/manual edge(s)`),c>0&&p.push(`${c} low-confidence inferred edge(s) need review`),i.length===0&&p.push(e.length===1?"Single-project workspace; inter-project dependency edges are not applicable":"No dependency evidence connected to this project yet");let l=Qt(u),d=Zt(l);o.set(s.id,{weight:d,score:l,verificationPriority:er(d),reasons:p.slice(0,5),centrality:{fanIn:n.fanIn,fanOut:n.fanOut,reach:n.reach,betweenness:n.betweenness,isHotspot:n.isHotspot}});}return o}function rr(e,t){let r=tr(e,t);return e.map(o=>({...o,operationalProfile:r.get(o.id)}))}function nr(e,t){let r=new Set;for(let c of t)r.add(c.from),r.add(c.to);let o=e.length,s=t.length,n=e.filter(c=>r.has(c.id)).length,i=Math.max(0,o-n),a=a$6({nodes:e,edges:t});return {nodeCount:o,edgeCount:s,inferredEdges:t.filter(c=>c.source==="inferred").length,contractEdges:t.filter(c=>c.source==="contract").length,manualEdges:t.filter(c=>c.source==="manual").length,authoritativeEdges:t.filter(c=>c.source==="contract"||c.source==="manual").length,lowConfidenceEdges:t.filter(c=>c.confidence==="low").length,orphanCount:i,connectedNodeCount:n,density:me(o>1?s/(o*(o-1)):0),edgeCoverageRatio:me(o>0?n/o:1),evidenceCoverageRatio:me(s>0?t.filter(c=>c.evidence.length>0).length/s:1),hotspotCount:a.hotspots.length,hasCycle:sr(e,t)}}function or(e,t,r){let o=[],s=e.filter(n=>!t.some(i=>i.from===n.id||i.to===n.id)).map(n=>n.id).sort((n,i)=>n.localeCompare(i));return r.nodeCount===0&&o.push({code:"graph.empty",severity:"info",message:"Workspace model has no projects, so dependency reasoning is unavailable.",recommendation:"Import, scaffold, or register projects before relying on graph-aware impact."}),r.nodeCount>1&&r.edgeCount===0?o.push({code:"graph.edges.missing",severity:"warning",message:"Projects were detected, but no inter-project dependency edges were found.",recommendation:"Run graph explain, add workspace contract relationships, or define manual graph overrides for operational dependencies that code imports cannot reveal.",nodeIds:s}):r.nodeCount>1&&r.orphanCount>0&&o.push({code:"graph.orphans.detected",severity:"warning",message:`${r.orphanCount} project(s) have no dependency evidence connected to the graph.`,recommendation:"Review isolated projects and add package, contract, or manual edges when they participate in release-critical flows.",nodeIds:s.slice(0,12)}),r.lowConfidenceEdges>0&&o.push({code:"graph.low_confidence_edges",severity:"info",message:`${r.lowConfidenceEdges} inferred edge(s) are low confidence.`,recommendation:"Promote important low-confidence relationships to workspace contract or manual overrides."}),r.edgeCount>0&&r.evidenceCoverageRatio<1&&o.push({code:"graph.evidence.partial",severity:"warning",message:"Some dependency edges do not include file-level evidence.",recommendation:"Attach evidence to manual overrides so agents can audit why a relationship exists."}),r.hasCycle&&o.push({code:"graph.cycle.detected",severity:"error",message:"The dependency graph contains at least one directed cycle.",recommendation:"Break the cycle or document the relationship explicitly before using graph-aware release gates."}),o.sort((n,i)=>{let a={error:0,warning:1,info:2};return a[n.severity]-a[i.severity]||n.code.localeCompare(i.code)})}function sr(e,t){let r=new Map;for(let c of e)r.set(c.id,[]);for(let c of t)r.has(c.from)||r.set(c.from,[]),r.get(c.from)?.push(c.to);let o=0,s=1,n=2,i=new Map;for(let c of r.keys())i.set(c,o);let a=c=>{let p=[{id:c,index:0}];for(i.set(c,s);p.length>0;){let u=p[p.length-1],l=r.get(u.id)??[];if(u.index>=l.length){i.set(u.id,n),p.pop();continue}let d=l[u.index];u.index+=1;let f=i.get(d)??o;if(f===s)return true;f===o&&(i.set(d,s),p.push({id:d,index:0}));}return false};for(let c of [...r.keys()].sort())if(i.get(c)===o&&a(c))return true;return false}function lt(e$1,t,r,o){let s=Yt(r.filter(c=>t.has(c.from)&&t.has(c.to))),n=rr(e$1,s),i=nr(e$1,s),a=or(e$1,s,i);return {schemaVersion:e,generatedAt:(o??new Date).toISOString(),nodes:n,edges:s,stats:i,...a.length>0?{diagnostics:a}:{}}}async function ut(e){let t=m.resolve(e.workspacePath),r=e.maxImportFilesPerProject??ot,o=at(e.model),s=new Set(o.map(a=>a.id)),n=it(t,e.model),i=[];return i.push(...await ct(t,n)),i.push(...await ye(t,n,r)),e.contract&&i.push(...dt(t,n,e.contract)),i.push(...await pt(t,s)),lt(o,s,i,e.now)}async function ft(e){let t=m.resolve(e.workspacePath),r=e.maxImportFilesPerProject??ot,o=at(e.model),s=new Set(o.map(a=>a.id)),n=it(t,e.model),i=[];if(i.push(...await ct(t,n)),e.structuralChange)i.push(...await ye(t,n,r));else {i.push(...await ye(t,n,r,e.changedProjectIds));for(let a of e.previousGraph.edges)a.kind==="code-import"&&a.source==="inferred"&&!e.changedProjectIds.has(a.from)&&s.has(a.from)&&s.has(a.to)&&i.push({from:a.from,to:a.to,kind:"code-import",source:"inferred",confidence:a.confidence,evidence:a.evidence});}return e.contract&&i.push(...dt(t,n,e.contract)),i.push(...await pt(t,s)),lt(o,s,i,e.now)}var te="workspace-model-producer.v3";var je=s.workspaceModelCache.schemaVersion,be=t$1.workspaceModelCache,pr=["package.json","pyproject.toml","setup.py","requirements.txt","requirements.in","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","Gemfile.lock","mix.exs","mix.lock","deno.json","deno.jsonc","deno.lock","bun.lock","bun.lockb","bunfig.toml",".bunfig.toml","deps.edn","project.clj","build.sbt","CMakeLists.txt","meson.build","workspai.project.json",".workspai/project.json",".workspai/context.json","rapidkit.project.json",".rapidkit/project.json",".rapidkit/context.json"],lr=[".csproj",".fsproj",".vbproj",".sln",".slnx",".gemspec"],gt=[t$1.workspaceContract,".workspai/workspace.json","workspai.workspace.json",".workspai/policies.yml",".workspai/policies.yaml",".rapidkit/workspace.contract.json",".rapidkit/workspace.json","rapidkit.workspace.json",".rapidkit/policies.yml",".rapidkit/policies.yaml"],mt=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".vue",".svelte",".rb",".go",".py",".java",".kt",".kts",".rs",".cs",".php",".ex",".exs",".clj",".cljs",".scala",".c",".cc",".cpp",".cxx",".h",".hh",".hpp",".hxx",".proto",".graphql",".gql",".sql",".sh"]),ur=new Set([".git",".workspai",".rapidkit","node_modules","dist","build","out","target","coverage",".next",".turbo",".cache",".venv"]),fr=1500,re=promisify(execFile);function gr(e){return mt.has(m.extname(e).toLowerCase())}async function mr(e){try{let{stdout:t}=await re("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",timeout:1e4,maxBuffer:1048576}),r=t.trim();if(!r)return null;let o=m.relative(r,e).split(m.sep).join("/");if(o===".."||o.startsWith("../"))return null;let s=o||".",n=o?`HEAD:${o}`:"HEAD^{tree}",{stdout:i}=await re("git",["-C",r,"rev-parse",n],{encoding:"utf8",timeout:1e4,maxBuffer:1024*1024}),[a,c]=await Promise.all([re("git",["-C",r,"diff","--name-only","-z","HEAD","--",s],{encoding:"buffer",timeout:2e4,maxBuffer:64*1024*1024}),re("git",["-C",r,"ls-files","--others","--exclude-standard","-z","--",s],{encoding:"buffer",timeout:2e4,maxBuffer:64*1024*1024})]),p=new Set([a.stdout,c.stdout].flatMap(l=>l.toString("utf8").split("\0")).filter(Boolean)),u=[`git-tree:${i.trim()}`];for(let l of [...p].sort((d,f)=>d.localeCompare(f))){let d=m.resolve(r,l),f=m.relative(e,d).split(m.sep).join("/");f===".."||f.startsWith("../")||!gr(f)||u.push(`${f}:${await L(d)??"<deleted>"}`);}return u}catch{return null}}var B=null;function Ce(){if(B)return B;try{B=createRequire(import.meta.url)("../package.json")?.version??"0.0.0";}catch{B="0.0.0";}return B}async function L(e){try{let t=await P.readFile(e);return Ot.createHash("sha256").update(t).digest("hex")}catch{return null}}async function ht(e){let t={};for(let o of pr){let s=await L(m.join(e,o));s&&(t[o]=s);}let r=await P.readdir(e).catch(()=>[]);for(let o of r.sort((s,n)=>s.localeCompare(n))){if(!lr.some(n=>o.toLowerCase().endsWith(n)))continue;let s=await L(m.join(e,o));s&&(t[o]=s);}return t}async function hr(e){let t=await ht(e),r=await mr(e),o=r??[];if(r)return G({manifests:t,source:o});let s=[e];for(;s.length>0&&o.length<fr;){let n=s.shift();if(!n)continue;let i=[];try{i=await P.readdir(n,{withFileTypes:true});}catch{continue}let a=[];for(let c of i)if(c.isDirectory()){if(ur.has(c.name)||a$5(c.name)||c.name.startsWith("."))continue;a.push(m.join(n,c.name));}else if(c.isFile()&&mt.has(m.extname(c.name))){let p=m.join(n,c.name),u=await P.stat(p).catch(()=>null);if(u){let l=m.relative(e,p).split(m.sep).join("/");o.push(`${l}:${u.size}:${Math.round(u.mtimeMs)}`);}}a.sort((c,p)=>c.localeCompare(p)),s.push(...a);}return o.sort((n,i)=>n.localeCompare(i)),G({manifests:t,source:o})}async function ne(e,t){let r=m.resolve(e),o={},s=[...new Set(t.map(n=>m.relative(r,m.resolve(n)).split(m.sep).join("/")))].sort((n,i)=>n.localeCompare(i));for(let n of s)o[n]=await hr(m.join(r,n));return o}async function oe(e){let t=m.resolve(e),r={};for(let o of gt){let s=await L(m.join(t,o));s&&(r[o]=s);}return r}async function se(e){let t=m.resolve(e.workspacePath),r=[...new Set(e.projectPaths.map(n=>m.relative(t,m.resolve(n)).split(m.sep).join("/")))].sort((n,i)=>n.localeCompare(i)),o=[];for(let n of r){let i=await ht(m.join(t,n));o.push({project:n,manifests:i});}let s={};for(let n of gt){let i=await L(m.join(t,n));i&&(s[n]=i);}return G({cacheSchema:je,cliVersion:e.cliVersion,flags:e.flags,workspaceJson:e.workspaceJson??null,marker:e.marker??null,projects:o,workspaceFiles:s})}async function Pe(e){let t=await g(e,be)??a$4(e,be);try{if(!await P.pathExists(t))return null;let r=await P.readJson(t);return !r||r.schemaVersion!==je||r.producerRevision!==te||typeof r.inputsHash!="string"||typeof r.cliVersion!="string"||!r.model?null:r}catch{return null}}async function ae(e,t){let r={schemaVersion:je,producerRevision:te,...t};return h(e,be,r)}var kt="rapidkit-fact-freshness-v1",U={durable:720*60*60,derived:10080*60,evidenceBacked:1440*60,live:300,verifyBeforeUse:1440*60};function kr(e){switch(e){case "durable":return U.durable;case "derived":return U.derived;case "evidence-backed":return U.evidenceBacked;case "live":return U.live;case "verify-before-use":return U.verifyBeforeUse}}function yr(e){if(e.status)return e.status;if(e.ttlSeconds===null)return "unknown";let t=Date.parse(e.generatedAt);if(!Number.isFinite(t))return "unknown";let r=t+e.ttlSeconds*1e3;return e.now.getTime()>r?"stale":"fresh"}function wr(e){let t=e.now??new Date,r=e.generatedAt??t.toISOString(),o=Date.parse(r),s=Number.isFinite(o),n=s?r:t.toISOString(),i=e.ttlSeconds===void 0?kr(e.kind):e.ttlSeconds,a=yr({generatedAt:n,ttlSeconds:i,status:e.status??(s?void 0:"unknown"),now:t}),c=Date.parse(n),p=i===null||!Number.isFinite(c)?void 0:new Date(c+i*1e3),u=e.verifyBeforeUse??(e.kind==="live"||e.kind==="verify-before-use"||e.category!=="structure"||a!=="fresh");return {schemaVersion:kt,kind:e.kind,category:e.category,generatedAt:n,ttlSeconds:i,...p?{expiresAt:p.toISOString()}:{},status:a,verifyBeforeUse:u,...e.sourceArtifact?{sourceArtifact:e.sourceArtifact}:{},...e.sourcePath?{sourcePath:e.sourcePath}:{},inputsHash:e.inputsHash??G(e.value??null),reason:e.reason}}function b(e){return {id:e.id,label:e.label,scope:e.scope,value:e.value,...e.project?{project:e.project}:{},freshness:wr({...e.freshness,value:e.value})}}function yt(e){let t=e.generatedAt??(e.now??new Date).toISOString(),r={durable:0,derived:0,"evidence-backed":0,live:0,"verify-before-use":0},o={structure:0,verification:0,state:0},s=0,n=0,i=0,a=0;for(let c of e.facts)r[c.freshness.kind]+=1,o[c.freshness.category]+=1,c.freshness.status==="stale"&&(s+=1),c.freshness.status==="unknown"&&(n+=1),c.freshness.kind==="live"&&(i+=1),c.freshness.verifyBeforeUse&&(a+=1);return {schemaVersion:kt,generatedAt:t,status:s>0?"stale":n>0?"unknown":"fresh",totalFacts:e.facts.length,staleFacts:s,unknownFacts:n,liveFacts:i,verifyBeforeUseFacts:a,byKind:r,byCategory:o}}function z(e,t){let r=[...new Set(e)],o=r.filter(s=>t.has(s)).length;return {eligibleCount:r.length,boundCount:o,unknownCount:r.length-o,coverageRatio:r.length===0?null:o/r.length}}function wt(e,t){let r=e.filter(d=>d.kind==="project").map(d=>d.id),o=e.filter(d=>d.kind==="endpoint").map(d=>d.id),s=new Set(o),n=e.filter(d=>d.kind==="api"&&!!d.projectId&&d.attributes.runtimeRegistrationRequired===true).map(d=>d.id),i=new Set(n),a=new Map(e.map(d=>[d.id,d.kind])),c=new Set(t.filter(d=>d.kind==="implements"||d.kind==="defines"&&a.get(d.from)==="file"&&a.get(d.to)==="endpoint").flatMap(d=>s.has(d.from)?[d.from]:s.has(d.to)?[d.to]:[])),p=new Set(t.filter(d=>d.kind==="implements"&&(a.get(d.from)==="runtime-unit"||a.get(d.to)==="runtime-unit")).flatMap(d=>i.has(d.from)?[d.from]:i.has(d.to)?[d.to]:[])),u=new Set(r),l=d=>new Set(t.filter(f=>f.kind===d).flatMap(f=>[f.from,f.to]).filter(f=>u.has(f)));return {apiImplementation:z(o,c),apiRuntimeRegistration:z(n,p),projectTests:z(r,l("tests")),projectDeployment:z(r,l("deploys")),projectOwnership:z(r,l("owns"))}}function vt(e,t){return e.filter(o=>o.code.includes("unknown")||o.code.includes("unresolved")||o.code.includes("limit_reached")||o.code.endsWith(".empty_result")).reduce((o,s)=>o+Math.max(s.entityIds?.length??0,s.relationIds?.length??0,1),0)+Object.values(t).reduce((o,s)=>o+s.unknownCount,0)}function Se(e,t){return t===0?1:e/t}function vr(e,t,r,o){return e.entityIds?.some(s=>t.has(s))||e.relationIds?.some(s=>r.has(s))?true:e.entityIds?.length||e.relationIds?.length?false:!/\bproject\b/i.test(e.message)||e.message.includes(o)}function br(e,t,r,o,s){let n=new Set(s.filter(a=>a.provider===e.id).map(a=>a.id)),i=e.inputCoverage?.filter(a=>a.scope==="workspace"||a.scope==="project"&&a.scopeId===t);return {...e,discoveredEntities:r.filter(a=>a.proofIds.some(c=>n.has(c))).length,discoveredRelations:o.filter(a=>a.proofIds.some(c=>n.has(c))).length,proofCount:n.size,...i?{inputCoverage:i}:{}}}function jr(e,t){let r=new Set(e.entities.filter(g=>g.projectId===t).map(g=>g.id)),o=e.relations.filter(g=>r.has(g.from)||r.has(g.to)),s=new Set(r);for(let g of o)s.add(g.from),s.add(g.to);let n=e.entities.filter(g=>s.has(g.id)),i=new Set([...n,...o].flatMap(g=>g.proofIds)),a=e.proofs.filter(g=>i.has(g.id)),c=new Set(o.map(g=>g.id)),p=e.diagnostics.filter(g=>vr(g,s,c,t)),u=e.providers.map(g=>br(g,t,n,o,a)),l=e.source.inputs?.scopes.filter(g=>g.kind==="workspace"||g.kind==="project"&&g.id===t)??[],d=l.filter(g=>!g.truncated).length,f=u.reduce((g,v)=>(v.status==="failed"?g.failed+=1:v.status==="skipped"||v.inputCoverage?.every(R=>R.status==="not-applicable")?g.notApplicable+=1:v.status==="partial"||v.inputCoverage?.some(R=>R.status==="bounded")?g.bounded+=1:g.complete+=1,g),{complete:0,bounded:0,notApplicable:0,failed:0}),k=wt(n,o);return {...e,entities:n,relations:o,proofs:a,providers:u,quality:{entityCount:n.length,relationCount:o.length,proofCount:a.length,entityProofCoverageRatio:Se(n.filter(g=>g.proofIds.length>0).length,n.length),relationProofCoverageRatio:Se(o.filter(g=>g.proofIds.length>0).length,o.length),providerSuccessRatio:Se(u.filter(g=>g.status!=="failed").length,u.length),conflictCount:p.filter(g=>g.code.includes("conflict")).length,unknownCount:vt(p,k),bindingCoverage:k,...e.quality.completeness?{completeness:{status:l.some(g=>g.truncated)||f.bounded>0||f.failed>0?"bounded":"complete",inventory:{scopeCount:l.length,completeScopes:d,boundedScopes:l.length-d,eligibleFiles:l.reduce((g,v)=>g+(v.eligibleFileCount??v.fileCount),0),indexedFiles:l.reduce((g,v)=>g+v.fileCount,0),eligibleFileCountExact:l.every(g=>g.eligibleFileCountExact!==false)},providers:f}}:{},portable:true,secretValuesEmitted:false},diagnostics:p}}var Cr=s.projectKnowledgeGraphReference.schemaVersion;function jt(e,t){let r=jr(e,t),o={schemaVersion:Cr,generatedAt:e.generatedAt,project:{name:t},canonical:{graph:"workspace:.workspai/reports/workspace-knowledge-graph.json",boundedQuery:`workspai workspace graph search <task-query> --scope project:${t} --limit 12 --json`,sourceHash:e.source.hash,projectionHash:c$1(r)},summary:{entityCount:r.entities.length,relationCount:r.relations.length,proofCount:r.proofs.length}};return {...o,integrity:{algorithm:"sha256",payloadHash:c$1(o),portable:true,absolutePathsEmitted:false}}}function Ct(e,t){return m.resolve(t.absolutePath??m.join(e,t.path))}var Pr=q$1.model,ie=p.model;function Ee(e){return e.projectTopology??e.graph}function St(e){return !!(e.projectTopology&&e.graph&&c$1(e.projectTopology)===c$1(e.graph))}function no(e){let t=e.engineStatus==="hit"||e.engineStatus==="unchanged"?"reused":e.engineStatus==="incremental"?"partially-reused":"rebuilt";return {schemaVersion:"workspace-model-build.v1",mode:e.mode,outcome:t,engineStatus:e.engineStatus}}var Sr=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","bun.lock","bun.lockb","bunfig.toml",".bunfig.toml","deps.edn","project.clj","build.sbt","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","terraform.tf"],Er=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next",".turbo"]);function Et(e,t){return (m.relative(e,t)||".").split(m.sep).join("/")}async function Wt(e){try{if(!await P.pathExists(e))return null;let t=await P.readJSON(e);return t&&typeof t=="object"?t:null}catch{return null}}async function Wr(e,t){for(let r of t)if(await P.pathExists(m.join(e,r)))return true;return false}function We(e){let t=Number.parseInt(process.env.RAPIDKIT_WORKSPACE_MODEL_SCAN_DEPTH??"",10),r=typeof e=="number"&&Number.isFinite(e)?e:Number.isFinite(t)?t:4;return Math.min(12,Math.max(1,Math.trunc(r)))}async function Rr(e,t){let r=m.resolve(e),o=[{dirPath:r,depth:0}],s=new Set,n=new Set;for(;o.length>0;){let i=o.shift();if(!i)continue;let a=m.resolve(i.dirPath);if(n.has(a))continue;if(n.add(a),a!==r&&await Wr(a,Sr)){s.add(a);continue}if(i.depth>=t)continue;let c=[];try{c=await P.readdir(a,{withFileTypes:true});}catch{continue}for(let p of c)!p.isDirectory()||Er.has(p.name)||a$5(p.name)||p.name.startsWith(".")&&p.name!==".config"||o.push({dirPath:m.join(a,p.name),depth:i.depth+1});}return Array.from(s).sort((i,a)=>i.localeCompare(a))}function xr(e){let t=new Set,r=[];for(let o of e){let s=m.resolve(o);t.has(s)||(t.add(s),r.push(s));}return r.sort((o,s)=>o.localeCompare(s))}function Pt(e,t){let r=e?.[t];return typeof r=="string"&&r.trim()?r.trim():void 0}function Ar(e,t){return e?.[t]===true}function Mr(e,t,r){let o=e?.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,s=Pt(o,"generator"),n=Pt(o,"command_display"),i=typeof t=="string"&&t.startsWith("frontend.");if(!(!s&&!i))return {...s?{id:s}:{},...t?{kit:t}:{},displayName:r,source:Ar(o,"official_generator")?"official-generator":"metadata",...n?{commandDisplay:n}:{}}}async function Ir(e){let t=[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json","package.json","product.json","tsconfig.json","pnpm-workspace.yaml","bunfig.toml",".bunfig.toml","nx.json","turbo.json","pyproject.toml","requirements.txt","go.mod","go.work","go.work.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","rust-toolchain.toml","rust-toolchain","CMakeLists.txt","meson.build","Makefile","WORKSPACE","WORKSPACE.bazel","MODULE.bazel","BUILD","BUILD.bazel",".bazelrc","composer.json","Gemfile","mix.exs","deno.json","setup.py","setup.cfg","Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","README.md"],r=[];for(let s of t)await P.pathExists(m.join(e,s))&&r.push(s);let o=new Set(["package.json","pyproject.toml","go.mod","go.work","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","CMakeLists.txt","meson.build","composer.json","Gemfile","mix.exs","deno.json"]);if(!r.some(s=>o.has(s))){let s=[],n=new Set([".git",".workspai",".rapidkit",".venv","build","dist","node_modules","target","third_party","vendor"]),i=(l,d)=>{let f=l.toLowerCase();return ["package.json","pyproject.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","cargo.toml","cmakelists.txt","meson.build","composer.json","gemfile","mix.exs","deno.json"].includes(f)||f.endsWith(".gemspec")||f==="description"&&d.toLowerCase()==="r"},a=async(l,d)=>{if(d>3||s.length>=512)return;let f=await P.readdir(l,{withFileTypes:true}).catch(()=>[]);for(let k of f.sort((g,v)=>g.name.localeCompare(v.name))){if(s.length>=512)return;k.isFile()&&i(k.name,m.basename(l))?s.push(m.relative(e,m.join(l,k.name)).split(m.sep).join("/")):k.isDirectory()&&!n.has(k.name)&&await a(m.join(l,k.name),d+1);}};await a(e,0);let c=new Map;for(let l of s){let d=l.split("/")[0],f=c.get(d)??[];f.push(l),c.set(d,f);}for(let l of c.values())l.sort((d,f)=>d.split("/").length-f.split("/").length||d.localeCompare(f));let p=[],u=[...c.keys()].sort();for(let l=0;p.length<16&&u.some(d=>l<(c.get(d)?.length??0));l+=1)for(let d of u){let f=c.get(d)?.[l];f&&p.length<16&&p.push(f);}r.push(...p.filter(l=>!r.includes(l)));}return r}async function x(e,t,r,o=t){let s=await g(e,t),n=s!==null,i={path:o.split(m.sep).join("/"),exists:n};if(s&&r){let a=await Wt(s);typeof a?.generatedAt=="string"&&(i.generatedAt=a.generatedAt);let c=a?.status??a?.result??a?.verdict;typeof c=="string"&&(i.status=c);}return i}async function Fr(e,t,r){let o=Et(e,t),s=".workspai/reports",n=c=>x(t,`${s}/${c}`,r,`${o}/${s}/${c}`),i=await n("doctor-project-last-run.json");return {doctor:i?.exists===true?i:await n("doctor-last-run.json"),remediationPlan:await n("doctor-remediation-plan-last-run.json"),fixResult:await n("doctor-fix-result-last-run.json"),analyze:await n("analyze-last-run.json"),readiness:await n("release-readiness-last-run.json")}}async function Dr(e,t,r){let o=j$2(t),s=m$1(t,o),n=z$1(t),i=f(s.runtime),a=await b$2(t,o,{runtime:s.runtime,framework:s.key}),c=r.contractProject?.slug?r.contractProject.slug:typeof o?.name=="string"&&o.name.trim()?o.name.trim():m.basename(t),p=j$3(o)?`adopted.${s.key}`:typeof o?.kit_name=="string"?o.kit_name:typeof o?.kit=="string"?o.kit:r.contractProject?.kit,u=typeof o?.engine=="string"?o.engine:n.engine!=="unknown"?n.engine:void 0,l$1=Mr(o,p,s.displayName),d=tt({kitId:p,framework:s.key,runtime:s.runtime}),f$1=l(t),k=[s.runtime,...f$1.filter(v=>v!==s.runtime)],g=await c$2({projectPath:t,declaration:r.contractProject?.governance});return {name:c,path:Et(e,t),...r.includeAbsolutePaths?{absolutePath:t}:{},kind:a,category:a$3(a),runtime:s.runtime,runtimeCandidates:k,framework:s.key,frameworkDisplayName:s.displayName,confidence:s.confidence,detectionSource:s.source,supportTier:s.supportTier,runtimeSupportTier:i.tier,runtimeDoctorSupport:i.doctorSupport,moduleSupport:n.moduleSupport,...p?{kit:p}:{},...u?{engine:u}:{},...l$1?{generator:l$1}:{},createCapability:d,commands:{supported:n.supportedCommands,unsupported:n.unsupportedCommands,global:n.globalCommands,fleetStages:n.fleetStages,localOnly:n.localOnlyCommands,map:n.commandMap},importantFiles:await Ir(t),governance:g,evidence:await Fr(e,t,r.includeEvidence),provenance:{path:r.contractProject?"workspace contract declaration reconciled with filesystem discovery":"filesystem discovery",runtime:s.source,framework:s.source,commands:"project command capability matrix",createCapability:"create planner capability contract",governance:r.contractProject?.governance!==void 0?"workspace contract declaration reconciled with repository evidence":"repository and documented external governance discovery",evidence:"project .workspai/reports"}}}async function Or(e){for(let t$1 of t(e,"workspace.json")){let r=await Wt(t$1);if(r)return r}return null}function Gr(e){if(e.length===0)return "empty-workspace";let t=new Set(e.map(r=>r.category));return t.size>1?"polyglot-product-workspace":t.has("frontend")&&e.length>1?"full-stack-workspace":t.has("frontend")?"frontend-workspace":t.has("desktop")?"desktop-application-workspace":t.has("extension")?"extension-workspace":t.has("platform")?"platform-workspace":t.has("library")?"library-workspace":e.length>1?"backend-platform":"backend-workspace"}function _r(e){let t=new Set;for(let r of e){let o=`${r.name} ${r.path}`.toLowerCase();for(let s of ["auth","billing","payment","notification","order","admin","report","search","analytics"])o.includes(s)&&t.add(s);}return Array.from(t).sort()}function C(e,t,r,o){return {severity:e,code:t,message:r,target:o}}function Rt(e){let t=[];e.workspace.name.trim()||t.push(C("error","workspace.name.missing","Workspace name could not be resolved.","workspace")),e.workspace.type==="observed-workspace"&&t.push(C("warning","workspace.marker.missing","Workspace marker is missing; model is based on filesystem observation.","workspace.marker")),e.summary.projectCount===0&&t.push(C("warning","workspace.projects.empty","No project roots were detected in this workspace.","projects")),e.contracts.exists||t.push(C("warning","workspace.contract.missing","Workspace contract is missing; dependency and API edges may be incomplete.",e.contracts.workspaceContractPath));let r=new Map;for(let n of e.projects){let i=n.name.toLowerCase(),a=r.get(i)??[];a.push(n),r.set(i,a),n.importantFiles.length||t.push(C("warning","project.markers.missing",`Project ${n.name} has no important manifest files recorded.`,n.path));let c=m.isAbsolute(n.path)?n.path:m.resolve(e.workspace.root,n.path);P.existsSync(c)||t.push(C("warning","project.path.missing",`Registered project ${n.name} is not available at its declared path.`,n.path)),n.runtime==="unknown"&&t.push(C("warning","project.runtime.unknown",`Project ${n.name} runtime could not be confidently detected.`,n.path));let p=["test","build"];for(let d of p)n.commands.supported.includes(d)&&n.commands.unsupported.includes(d)&&t.push(C("error","project.commands.conflict",`Project ${n.name} marks ${d} as both supported and unsupported.`,n.path));let u=new Set(n.commands.fleetStages),l=new Set(n.commands.localOnly);for(let d of n.commands.fleetStages){l.has(d)&&t.push(C("error","project.commands.scope-conflict",`Project ${n.name} marks ${d} as both fleet and local-only.`,n.path));let f=n.commands.map[d];(!f||f.status!=="supported"||f.fleetEligible!==true||f.executionScope!=="fleet")&&t.push(C("error","project.commands.fleet-stage-invalid",`Project ${n.name} advertises ${d} as a fleet stage without a supported fleet capability.`,n.path));}for(let d of n.commands.localOnly){let f=n.commands.map[d];(!f||f.status!=="supported"||f.executionScope!=="local-only"||f.fleetEligible===true)&&t.push(C("error","project.commands.local-only-invalid",`Project ${n.name} advertises ${d} as local-only without a matching local-only capability.`,n.path));}for(let d of Object.values(n.commands.map))d.status==="supported"&&(d.fleetEligible===true&&!u.has(d.command)&&t.push(C("error","project.commands.fleet-stage-missing",`Project ${n.name} capability ${d.command} is fleet-eligible but missing from fleetStages.`,n.path)),d.executionScope==="local-only"&&d.fleetEligible!==true&&!l.has(d.command)&&t.push(C("error","project.commands.local-only-missing",`Project ${n.name} capability ${d.command} is local-only but missing from localOnly commands.`,n.path)));}for(let[n,i]of r.entries())i.length>1&&t.push(C("error","project.name.duplicate",`Project name "${n}" is ambiguous across ${i.length} project roots.`,i.map(a=>a.path).join(", ")));e.projectTopology&&e.graph&&c$1({...e.projectTopology,generatedAt:"<ignored>"})!==c$1({...e.graph,generatedAt:"<ignored>"})&&t.push(C("error","workspace.project-topology.alias-mismatch","Deprecated model.graph must remain structurally identical to canonical model.projectTopology during the v1 migration window.","projectTopology"));let o=t.filter(n=>n.severity==="error").length,s=t.filter(n=>n.severity==="warning").length;return {status:o>0?"failed":s>0?"warning":"passed",errors:o,warnings:s,issues:t}}function oo(e){return Rt(e)}function j(e){return e.join(".")}function Tr(e,t){let r=ie,o=e.generatedAt,s=[b({id:"workspace.name",label:"Workspace name",scope:"workspace",value:e.workspace.name,freshness:{kind:"durable",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["workspace","name"]),reason:"Workspace identity is structural metadata and changes through workspace setup."}}),b({id:"workspace.type",label:"Workspace type",scope:"workspace",value:e.identity.workspaceType,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["identity","workspaceType"]),reason:"Workspace type is derived from the current project inventory."}}),b({id:"workspace.projectCount",label:"Project count",scope:"workspace",value:e.summary.projectCount,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["summary","projectCount"]),reason:"Project count is derived from workspace discovery and should be refreshed after structural changes."}}),b({id:"workspace.runtimeFamilies",label:"Runtime families",scope:"workspace",value:e.identity.runtimeFamilies,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["identity","runtimeFamilies"]),reason:"Runtime coverage is inferred from project surfaces."}}),b({id:"workspace.policyMode",label:"Workspace policy mode",scope:"policy",value:e.policies.mode,freshness:{kind:"durable",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["policies","mode"]),reason:"Policy mode is configuration, not runtime state."}}),b({id:"workspace.contract.exists",label:"Workspace contract presence",scope:"contract",value:e.contracts.exists,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["contracts","exists"]),reason:"Contract presence is derived from workspace files and should be refreshed before release gating."}})],n=Ee(e);n&&s.push(b({id:"graph.edgeCount",label:"Dependency graph edge count",scope:"graph",value:n.stats.edgeCount,freshness:{kind:"derived",category:"structure",generatedAt:n.generatedAt??o,now:t,sourceArtifact:r,sourcePath:j(["projectTopology","stats","edgeCount"]),reason:"Graph topology is derived from manifests, imports, and workspace contracts."}}),b({id:"graph.evidenceCoverageRatio",label:"Dependency graph evidence coverage",scope:"graph",value:n.stats.evidenceCoverageRatio,freshness:{kind:"derived",category:"structure",generatedAt:n.generatedAt??o,now:t,sourceArtifact:r,sourcePath:j(["projectTopology","stats","evidenceCoverageRatio"]),reason:"Graph evidence coverage changes when dependency evidence or contract edges change."}}));for(let[i,a]of e.projects.entries()){let c=`projects[${i}]`,p={kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,reason:"Project facts are derived from workspace discovery, project metadata, and framework probes."};s.push(b({id:`project.${a.name}.kind`,label:`${a.name} kind`,scope:"project",project:a.name,value:a.kind,freshness:{...p,sourcePath:j([c,"kind"])}}),b({id:`project.${a.name}.category`,label:`${a.name} category`,scope:"project",project:a.name,value:a.category,freshness:{...p,sourcePath:j([c,"category"])}}),b({id:`project.${a.name}.runtime`,label:`${a.name} runtime`,scope:"project",project:a.name,value:a.runtime,freshness:{...p,sourcePath:j([c,"runtime"])}}),b({id:`project.${a.name}.framework`,label:`${a.name} framework`,scope:"project",project:a.name,value:a.frameworkDisplayName,freshness:{...p,sourcePath:j([c,"frameworkDisplayName"])}}),b({id:`project.${a.name}.supportTier`,label:`${a.name} support tier`,scope:"project",project:a.name,value:a.supportTier,freshness:{...p,sourcePath:j([c,"supportTier"])}}),b({id:`project.${a.name}.safeFleetStages`,label:`${a.name} safe fleet stages`,scope:"command",project:a.name,value:a.commands.fleetStages,freshness:{...p,sourcePath:j([c,"commands","fleetStages"]),reason:"Safe command availability is derived from package and project command surfaces."}}),...["ci","release","ownership"].map(u=>b({id:`project.${a.name}.governance.${u}`,label:`${a.name} ${u} governance`,scope:"policy",project:a.name,value:a.governance?.[u]??{status:"unknown",provider:null,evidence:[],reference:null},freshness:{...p,sourcePath:j([c,"governance",u]),reason:"Governance truth is reconciled from repository surfaces and explicit workspace contract declarations."}})));for(let[u,l]of Object.entries(a.evidence))s.push(b({id:`project.${a.name}.evidence.${u}`,label:`${a.name} ${u} evidence`,scope:"evidence",project:a.name,value:l?{path:l.path,exists:l.exists,status:l.status??null}:{exists:false},freshness:{kind:l?.exists?"evidence-backed":"verify-before-use",category:"verification",generatedAt:l?.generatedAt??o,now:t,status:l?.exists?void 0:"unknown",sourceArtifact:l?.path??r,sourcePath:j([c,"evidence",u]),verifyBeforeUse:true,reason:l?.exists?"Evidence reports can expire or become stale after source changes.":"Missing evidence must be generated before this fact is used for verification."}}));}for(let[i,a]of Object.entries(e.evidence))s.push(b({id:`workspace.evidence.${i}`,label:`Workspace ${i} evidence`,scope:"evidence",value:a?{path:a.path,exists:a.exists,status:a.status??null}:null,freshness:{kind:a?.exists?"evidence-backed":"verify-before-use",category:"verification",generatedAt:a?.generatedAt??o,now:t,status:a?.exists?void 0:"unknown",sourceArtifact:a?.path??r,sourcePath:j(["evidence",i]),verifyBeforeUse:true,reason:a?.exists?"Workspace evidence can expire or become stale after project, dependency, or policy changes.":"Missing workspace evidence must be generated before release or repair decisions."}}));return s}async function Re(e,t){let[r,o,s,n,i,a$3]=await Promise.all([a(e),Or(e),xe(e),a$1(e),a$2(e,{descendIntoMatchedProjects:false}),Rr(e,t)]),c=new Map;for(let u of s?.projects??[]){let l=u.externalPath?m.resolve(e,u.externalPath):m.resolve(e,u.relativePath);c.set(l,u);}let p=xr([...i,...a$3,...c.keys(),...n.map(u=>m.isAbsolute(u.path)?u.path:m.join(e,u.path))]);return {marker:r,workspaceJson:o,workspaceContract:s,contractProjectPaths:c,projectPaths:p}}async function ce(e){let t$2=m.resolve(e.workspacePath),r=e.includeAbsolutePaths===true,o=e.includeEvidence===true,s=We(e.observableScanDepth),n=e.now??new Date,{marker:i,workspaceJson:a,workspaceContract:c,contractProjectPaths:p$1,projectPaths:u}=await Re(t$2,s),l=e.reuseProjectModels,d=await Promise.all(u.map(w=>{if(l){let Mt=m.relative(t$2,m.resolve(w)).split(m.sep).join("/"),Ae=l.get(Mt);if(Ae)return Promise.resolve(Ae)}return Dr(t$2,w,{includeAbsolutePaths:r,includeEvidence:o,contractProject:p$1.get(m.resolve(w))})})),f=typeof a?.workspace_name=="string"?a.workspace_name:typeof a?.name=="string"?a.name:i?.name||c?.workspace.name||m.basename(t$2),k=typeof a?.profile=="string"?a.profile:typeof a?.mode=="string"?a.mode:c?.workspace.profile,g=Array.from(new Set(d.map(w=>w.kind))).sort(),v=Array.from(new Set(d.map(w=>w.category))).sort(),R=Array.from(new Set(d.flatMap(w=>w.runtimeCandidates.length>0?w.runtimeCandidates:[w.runtime]))).sort(),q=Array.from(new Set(d.map(w=>w.framework))).sort(),_=[".workspai/policies.yml",".workspai/policies.yaml",".rapidkit/policies.yml",".rapidkit/policies.yaml"].find(w=>P.existsSync(m.join(t$2,w))),J=t(t$2,"workspace.contract.json").map(w=>m.relative(t$2,w).split(m.sep).join("/")).find(w=>P.existsSync(m.join(t$2,w)))??t$1.workspaceContract,D=await P.pathExists(m.join(t$2,J)),X={schemaVersion:Pr,generatedAt:n.toISOString(),workspace:{name:f,root:t$2,...k?{profile:k}:{},type:i?"rapidkit-workspace":"observed-workspace",...i?{marker:{createdBy:i.createdBy,version:i.version,createdAt:i.createdAt}}:{}},identity:{workspaceType:Gr(d),surfaces:g,categories:v,runtimeFamilies:R,businessCapabilities:_r(d)},discovery:{observableScanDepth:s},projects:d,policies:{mode:typeof a?.policy_mode=="string"?a.policy_mode:typeof a?.policyMode=="string"?a.policyMode:"warn",source:_??null,exists:!!_},contracts:{workspaceContractPath:J,exists:D,status:D?"known":"missing"},evidence:{doctor:await x(t$2,p.doctor,o),projectDoctor:await x(t$2,t$1.doctorProject,o),doctorRemediationPlan:await x(t$2,t$1.doctorRemediationPlan,o),artifactRemediationPlan:await x(t$2,t$1.artifactRemediationPlan,o),doctorFixResult:await x(t$2,t$1.doctorFixResult,o),analyze:await x(t$2,p.analyze,o),readiness:await x(t$2,p.readiness,o),pipeline:await x(t$2,t$1.pipelineLastRun,o)},summary:{projectCount:d.length,runtimes:R,frameworks:q,firstClassProjects:d.filter(w=>w.supportTier==="first-class").length,extendedProjects:d.filter(w=>w.supportTier==="extended").length,observedProjects:d.filter(w=>w.supportTier==="observed").length}},S=await xt(t$2,X,{contractExists:D,now:n,incrementalGraph:e.incrementalGraph}),E={...X,projectTopology:S,graph:S},O=Rt(E),T=Tr({...E},n),At=yt({facts:T,generatedAt:n.toISOString(),now:n});return {...E,facts:T,factFreshness:At,validation:O}}async function so(e){if(e.cache!==true)return {model:await ce(e),cache:"disabled"};let t=m.resolve(e.workspacePath),r=We(e.observableScanDepth),o=Ce(),{marker:s,workspaceJson:n,projectPaths:i}=await Re(t,r),a=await se({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:i,workspaceJson:n,marker:s}),c=await Pe(t);if(c&&c.cliVersion===o&&c.inputsHash===a&&St(c.model))return {model:c.model,cache:"hit"};let p=await ce({...e}),[u,l]=await Promise.all([ne(t,i),oe(t)]);return await ae(t,{cliVersion:o,inputsHash:a,generatedAt:(e.now??new Date).toISOString(),model:p,projectSignatures:u,workspaceFileSignatures:l}),{model:p,cache:"miss"}}function Nr(e,t){let r=new Set,o=new Set,s=new Set;for(let[n,i]of Object.entries(t))n in e?e[n]!==i&&r.add(n):o.add(n);for(let n of Object.keys(e))n in t||s.add(n);return {changed:r,added:o,removed:s}}function Kr(e={},t={}){let r=new Set([...Object.keys(e),...Object.keys(t)]);for(let o of r)if(e[o]!==t[o])return false;return true}async function ao(e){let t=m.resolve(e.workspacePath),r=We(e.observableScanDepth),o=Ce(),s=e.now??new Date,{marker:n,workspaceJson:i,projectPaths:a}=await Re(t,r),c=await Pe(t),p=async()=>{let S=await ce({...e}),E=await se({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:a,workspaceJson:i,marker:n}),[O,T]=await Promise.all([ne(t,a),oe(t)]);return await ae(t,{cliVersion:o,inputsHash:E,generatedAt:s.toISOString(),model:S,projectSignatures:O,workspaceFileSignatures:T}),{model:S,mode:"full"}},u=c?Ee(c.model):void 0;if(!c||c.cliVersion!==o||!c.projectSignatures||!u||!St(c.model))return p();let l=await oe(t);if(!Kr(c.workspaceFileSignatures,l))return p();let d=await ne(t,a),{changed:f,added:k,removed:g}=Nr(c.projectSignatures,d);if(f.size===0&&k.size===0&&g.size===0)return {model:c.model,mode:"unchanged"};let v=new Set([...f,...k]),R=new Map;for(let S of c.model.projects){let E=S.path.split(m.sep).join("/");!v.has(E)&&!g.has(E)&&R.set(E,S);}let q=new Set,_=false;for(let S of c.model.projects){let E=S.path.split(m.sep).join("/");f.has(E)&&q.add(S.name);}let J=k.size>0||g.size>0,D=await ce({...e,reuseProjectModels:R,incrementalGraph:{previousGraph:u,changedProjectIds:q,structuralChange:J||_}});for(let S of c.model.projects){let E=S.path.split(m.sep).join("/");if(!f.has(E))continue;let O=D.projects.find(T=>T.path.split(m.sep).join("/")===E);if(O&&O.name!==S.name){_=true;break}}if(_)return p();let X=await se({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:a,workspaceJson:i,marker:n});return await ae(t,{cliVersion:o,inputsHash:X,generatedAt:s.toISOString(),model:D,projectSignatures:d,workspaceFileSignatures:l}),{model:D,mode:"incremental"}}async function xe(e){try{let{contract:t}=await p$1({workspacePath:e});return t&&typeof t=="object"?t:null}catch{return null}}async function xt(e,t,r){let o=r.contractExists?await xe(e):null;try{return r.incrementalGraph?await ft({workspacePath:e,model:t,contract:o,now:r.now,previousGraph:r.incrementalGraph.previousGraph,changedProjectIds:r.incrementalGraph.changedProjectIds,structuralChange:r.incrementalGraph.structuralChange}):await ut({workspacePath:e,model:t,contract:o,now:r.now})}catch{let s=t.projects.map(n=>({id:n.name,path:n.path}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:r.now.toISOString(),nodes:s,edges:[],stats:{nodeCount:s.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:s.length,connectedNodeCount:0,density:0,edgeCoverageRatio:s.length>0?0:1,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:s.length>1?[{code:"graph.inference.failed",severity:"warning",message:"Dependency graph inference failed; model contains projects but no dependency edges.",recommendation:"Run workspace model again after fixing graph inputs, or add workspace contract/manual graph overrides.",nodeIds:s.map(n=>n.id).sort((n,i)=>n.localeCompare(i))}]:void 0}}}async function io(e,t,r={}){let o=e.contracts.exists?await xe(t):null,{buildWorkspaceKnowledgeGraph:s}=await import('./workspace-knowledge-graph-BNEVFEOW.js'),n=d(e),i=r.refreshKnowledgeGraph?null:await P.readJson(m.join(t,p.knowledgeGraph)).then(l=>l).catch(()=>null),a=await s({workspacePath:t,workspace:{name:e.workspace.name,...e.workspace.profile?{profile:e.workspace.profile}:{}},projects:e.projects.map(l=>({id:l.name,path:l.path,...l.absolutePath?{absolutePath:l.absolutePath}:{},runtime:l.runtime,runtimeCandidates:l.runtimeCandidates,framework:l.framework,kind:l.kind,category:l.category,...l.governance?{governance:l.governance}:{},...l.kit?{kit:l.kit}:{}})),projectTopology:Ee(e)??await xt(t,e,{contractExists:e.contracts.exists,now:new Date(e.generatedAt)}),contract:o,now:new Date(e.generatedAt),source:{kind:"workspace-model",artifact:ie,hashAlgorithm:"sha256",hash:d$1(n)},previousGraph:i}),c=[],p$1=new Map;for(let l of e.projects){let d=Ct(t,l);if(!(await P.stat(d).catch(()=>null))?.isDirectory())continue;let k=await P.realpath(d),g=p$1.get(k);if(g)throw new Error(`Projects ${g} and ${l.name} resolve to the same graph artifact root: ${d}`);p$1.set(k,l.name),c.push({rootPath:d,relativePath:t$1.projectKnowledgeGraphReference,payload:jt(a,l.name)});}let u=await j$1(t,ie,[{rootPath:t,relativePath:p.knowledgeGraph,payload:a},{rootPath:t,relativePath:ie,payload:n},...c]);for(let l of c){let d=m.join(l.rootPath,p.knowledgeGraph);(await P.readJson(d).catch(()=>null))?.schemaVersion===q$1.knowledgeGraph&&await P.remove(d).catch(()=>{});}return u[1]}export{tt as a,Br as b,qr as c,G as d,kt as e,b as f,yt as g,wt as h,vt as i,jr as j,Pr as k,ie as l,Ee as m,no as n,oo as o,Tr as p,ce as q,so as r,ao as s,io as t};
@@ -1,13 +0,0 @@
1
- import {a as a$1}from'./chunk-JEI6BTZI.js';import {a}from'./chunk-IVYPC36J.js';import {c,e,d}from'./chunk-QYEQVNBF.js';import {d as d$1,b}from'./chunk-R5OJD5K2.js';import {g}from'./chunk-3SNP6M4M.js';import {q as q$1,m}from'./chunk-4HQU2GQM.js';import {p,d as d$2}from'./chunk-NNQE4DS2.js';import {h}from'./chunk-FE5R6EUV.js';import {b as b$1}from'./chunk-K33JJVQZ.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import j from'path';import W from'fs-extra';function X(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function q(e$1){switch(e$1){case "why":return d;case "trace":return e;default:return c}}async function P(e,n,o){try{if(!await W.pathExists(e))return null;let r=await W.readJson(e);return n?b$1(n,r,e):o&&a$2(r,o,e),r}catch(r){if((n||o)&&await W.pathExists(e))throw r;return null}}function Y(e,n){if(!e)return null;let o=n.trim().toLowerCase();return e.projects.find(r=>r.slug.toLowerCase()===o||r.relativePath.toLowerCase()===o)??null}function Q(e,n,o){let r=o.trim().toLowerCase(),t=(m(e)?.nodes.map(i=>i.id)??e.projects.map(i=>i.name)).find(i=>i.toLowerCase()===r);if(t)return t;let m$1=e.projects.find(i=>[i.name,i.path,j.basename(i.path)].filter(u=>u.trim().length>0).some(u=>u.toLowerCase()===r));if(m$1)return m$1.name;let p=Y(n,o);if(p){let i=e.projects.find(u=>u.path===p.relativePath||u.path.endsWith(`/${p.relativePath}`));if(i)return i.name}return o}function U(e,n){if(!e)return [];let o=n.trim().toLowerCase(),r=new Set;for(let d of e.projects){d.contracts.dependsOn?.some(t=>t.toLowerCase()===o)&&r.add(d.slug);for(let t of d.contracts.consumes??[])for(let m of e.projects)m.contracts.publishes?.includes(t)&&m.slug===o&&r.add(d.slug);}return [...r].sort()}function Z(e,n){if(!e)return [];let o=n.trim().toLowerCase();return e.steps.filter(r=>r.scope==="project"&&r.project?.toLowerCase()===o&&r.command?.display).map(r=>r.command.display).slice(0,8)}function l(e,n,o){return {id:e,title:n,body:o.trim()}}async function ke(e){let n=j.resolve(e.workspacePath),o=(e.now??new Date).toISOString(),r=e.model??await q$1({workspacePath:n,includeEvidence:true}),d=e.contract;if(d===void 0)try{d=(await p({workspacePath:n})).contract;}catch{d=null;}let t=e.verify;t===void 0&&(t=await P(j.join(n,d$1),d$1));let m$1=e.impact;if(m$1===void 0&&(m$1=await P(j.join(n,g),g)),e.target.kind==="release-blocked"){let s=t?.blockingReasons??[],c=(r.summary?.projectCount??r.projects.length)===0,g=[l("verdict",c?"Workspace scaffold posture":"Release verdict",t?c?`Scaffold posture: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Freshness: **${t.freshness.verdict}**. No registered projects yet \u2014 release gates apply after the first project is added.`:`Verdict: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Risk: **${t.impact.risk}**. Freshness: **${t.freshness.verdict}**.`:"No workspace verify report found. Run `npx workspai workspace verify --json --write` first."),l("blockers",c?"Pre-project signals":"Blocking reasons",s.length?s.map(h=>`- ${h}`).join(`
2
- `):c?"No pre-project signals in the latest verify report.":"No blocking reasons in the latest verify report.")];return t?.resolutionHints?.length&&g.push(l("resolution","Resolution hints",t.resolutionHints.map(h=>`- **${h.blockerId}** (${h.resolutionClass}): ${h.commandRetryHint??h.fixHints[0]?.detail??"See fix hints"}`).join(`
3
- `))),{schemaVersion:a,generatedAt:o,workspacePath:n,target:e.target,summary:t?c?b(s.length,t.summary.verdict):s.length>0||t.summary.verdict==="blocked"?`Release blocked: ${t.summary.verdict} with ${s.length} blocking reason(s).`:t.summary.verdict==="needs-attention"?"Release needs attention: advisory or incomplete verification evidence remains; no blocking reason was reported.":`Release posture: ${t.summary.verdict}; no blocking reason was reported.`:"Release posture unknown \u2014 verify report missing.",sections:g,releaseVerdict:t?.summary.verdict,evidenceFreshness:t?.freshness.verdict,blocking:!!(t&&(t.summary.verdict==="blocked"||s.length>0)),releaseRisk:t?.impact.risk,blockingReasons:s,resolutionHints:t?.resolutionHints}}if(e.target.kind==="blocker"){let s=e.target,f=t?.resolutionHints?.find(g=>g.blockerId===s.blockerId),c=t?.blockingReasons.find(g=>g.includes(s.blockerId))??t?.blockingReasons[0];return {schemaVersion:a,generatedAt:o,workspacePath:n,target:s,summary:f?`Blocker ${s.blockerId}: ${f.resolutionClass}`:`Blocker ${s.blockerId} (no structured hint)`,sections:[l("reason","Blocking signal",c??"No matching blocking reason in verify."),l("hint","Resolution class",f?`${f.resolutionClass}
4
-
5
- ${f.commandRetryHint??""}
6
-
7
- ${f.fixHints.map(g=>`- ${g.detail}`).join(`
8
- `)}`:"Run workspace verify to emit resolutionHints for this blocker.")],blockingReasons:c?[c]:[],resolutionHints:f?[f]:[]}}if(e.target.kind==="trace"){let s=j.isAbsolute(e.target.diffRef)?e.target.diffRef:j.join(n,e.target.diffRef),f=await P(s,void 0,"contracts/workspace-intelligence/workspace-model-diff.v1.json"),c=[...new Set((f?.changes??[]).filter(a=>a.type?.startsWith("project.")).map(a=>{let O=X(a.after),H=X(a.before);return typeof O.name=="string"&&O.name.trim()||typeof H.name=="string"&&H.name.trim()||a.project?.trim()||a.target?.trim()||""}).filter(Boolean))],h=(r.summary?.projectCount??r.projects.length)===0,_=m$1?.transitiveImpact?.map(a=>`${a.project?.name??a.target} (d${a.distance??0}, via ${a.via??"\u2014"})`)??[],y=t?.affectedSubgraph;return {schemaVersion:a,generatedAt:o,workspacePath:n,target:e.target,summary:c?.length?`Trace from ${c.length} changed project(s) through blast radius to gate coverage.`:h?"Trace: workspace scaffold baseline \u2014 no project changes in the latest diff.":"Trace: diff baseline present with no project changes.",sections:[l("origin","Change origin",c?.length?c.map(a=>`- ${a}`).join(`
9
- `):"No changed projects in diff."),l("blast-radius","Transitive impact",_.length?_.map(a=>`- ${a}`).join(`
10
- `):"No transitive impact report."),l("gate","Subgraph gate",y?`Directly changed: ${y.directlyChanged}; transitive dependents: ${y.transitiveDependents}; covered: ${y.covered}; uncovered: ${y.uncovered}; unverifiable: ${y.unverifiable}.`:"No verify subgraph coverage available.")],releaseRisk:m$1?.summary?.risk??t?.impact.risk,blockingReasons:t?.blockingReasons}}let p$1=e.target.project,i=Q(r,d,p$1),u=m(r),k=u?a$1(u,i):{found:false,centrality:null,directDependents:[],transitiveDependents:[]},w=Y(d,p$1),E=U(d,p$1),x=Z(t,p$1),v=r.projects.find(s=>s.name.toLowerCase()===p$1.toLowerCase()),A=[l("overview","Project overview",v?`${v.name} (${v.frameworkDisplayName}, ${v.runtime}) at \`${v.path}\`.`:`Project **${p$1}** ${k.found?"exists in graph":"not found in workspace model"}.`),l("consumers","Consumers / dependents",[`Direct dependents: ${k.directDependents.join(", ")||"none"}`,`Contract consumers: ${E.join(", ")||"none"}`,`Transitive dependents (blast radius): ${k.transitiveDependents.length}`].join(`
11
- `)),l("contracts","Critical contracts",w?[`Owns: ${w.contracts?.owns?.join(", ")||"none"}`,`Publishes: ${w.contracts.publishes.join(", ")||"none"}`,`Consumes: ${w.contracts.consumes.join(", ")||"none"}`,`APIs: ${w.contracts.apis.map(s=>s.name).join(", ")||"none"}`].join(`
12
- `):"No workspace.contract.json entry for this project."),l("verification","Required verification",x.length?x.map(s=>`- ${s}`).join(`
13
- `):"- `npx workspai workspace verify --json`\n- Project test/build via `workspace run` when configured")];k.centrality&&A.push(l("centrality","Graph centrality",`fanIn ${k.centrality.fanIn}, fanOut ${k.centrality.fanOut}, reach ${k.centrality.reach}, hotspot ${k.centrality.isHotspot?"yes":"no"}.`));let I=p$1.trim().toLowerCase(),T=s=>s.project?.name?.toLowerCase()===I||s.target.toLowerCase()===I,S=m$1?.affectedProjects?.find(T)?.risk??m$1?.transitiveImpact?.find(T)?.risk??t?.impact.risk??"unknown";return {schemaVersion:a,generatedAt:o,workspacePath:n,target:e.target,summary:`${p$1}: ${E.length} consumer(s), release risk **${S}**.`,sections:A,releaseRisk:String(S)}}async function he(e,n,o="explain"){let r=q(o);return await h(n,r,d$2(e)),r}export{q as a,ke as b,he as c};
@@ -1 +0,0 @@
1
- var ie="workspace-knowledge-search.v1";function k(e){return e.trim().toLowerCase()}var $=new WeakMap;function O(e){let t=$.get(e);if(t)return t;let s=new Map(e.relations.map(i=>[i.id,i])),o=new Map(e.entities.map(i=>[i.id,i])),a=new Map(e.proofs.map(i=>[i.id,i])),r=new Map,l=new Map,p=(i,h)=>{let g=l.get(i)??[];g.push(h),l.set(i,g);};for(let i of e.entities){let h=[i.id,i.label,i.identity.key,...i.kind==="project"&&i.projectId?[i.projectId]:[],...i.identity.aliases];for(let g of new Set(h.map(k))){let y=r.get(g)??[];y.push(i),r.set(g,y);}}for(let i of e.relations)p(i.from,{from:i.from,to:i.to,relationId:i.id,kind:i.kind,direction:"forward",proofIds:i.proofIds}),p(i.to,{from:i.to,to:i.from,relationId:i.id,kind:i.kind,direction:"reverse",proofIds:i.proofIds});for(let i of r.values())i.sort((h,g)=>h.id.localeCompare(g.id));for(let i of l.values())i.sort((h,g)=>h.to.localeCompare(g.to)||h.relationId.localeCompare(g.relationId));let d={entitiesById:o,relationsById:s,entitiesByAlias:r,proofsById:a,adjacency:l};return $.set(e,d),d}function D(e,t,s){let o=O(e),a=o.relationsById.get(t);if(a)return {found:true,targetType:"relation",relation:a};let r=k(t),l=(o.entitiesByAlias.get(r)??[]).filter(p=>!s||p.projectId===s);return l.length===1?{found:true,targetType:"entity",entity:l[0]}:{found:false,query:t,candidates:l.map(p=>p.id).sort()}}function ve(e,t,s){let o=D(e,t,s);if(!o.found)return {query:t,found:false,target:null,proofs:[],candidates:o.candidates};let a=o.targetType==="entity"?o.entity:o.relation,r=new Set(a.proofIds);return {query:t,found:true,target:a,candidates:[],proofs:[...r].map(l=>O(e).proofsById.get(l)).filter(l=>!!l).sort((l,p)=>l.id.localeCompare(p.id))}}function Me(e,t,s,o){let a=D(e,t,o),r=D(e,s,o);if(!a.found||a.targetType!=="entity"||!r.found||r.targetType!=="entity")return {from:t,to:s,found:false,resolvedFrom:a.found&&a.targetType==="entity"?a.entity.id:null,resolvedTo:r.found&&r.targetType==="entity"?r.entity.id:null,entityPath:[],hops:[],proofs:[]};let l=O(e),p=[a.entity.id],d=new Map,i=new Set(p),h=0;for(;h<p.length&&!i.has(r.entity.id);){let f=p[h++];for(let u of l.adjacency.get(f)??[])i.has(u.to)||(i.add(u.to),d.set(u.to,u),p.push(u.to));}if(!i.has(r.entity.id))return {from:t,to:s,found:false,resolvedFrom:a.entity.id,resolvedTo:r.entity.id,entityPath:[],hops:[],proofs:[]};let g=[],y=r.entity.id;for(;y!==a.entity.id;){let f=d.get(y);if(!f)break;g.push(f),y=f.from;}g.reverse();let I=new Set(g.flatMap(f=>f.proofIds));return {from:t,to:s,found:true,resolvedFrom:a.entity.id,resolvedTo:r.entity.id,entityPath:[a.entity.id,...g.map(f=>f.to)],hops:g,proofs:[...I].map(f=>l.proofsById.get(f)).filter(f=>!!f).sort((f,u)=>f.id.localeCompare(u.id))}}function je(e,t,s){return e.entities.filter(o=>(!t||o.kind===t)&&(!s||o.projectId===s)).sort((o,a)=>o.kind.localeCompare(a.kind)||o.label.localeCompare(a.label))}var w={relations:12,relatedEntities:12,proofs:8,proofIdsPerItem:4,aliasesPerEntity:8,attributeArrayItems:8,attributeStringCharacters:256};function ae(e){let t=[],s=new Set;for(let o=0;o<w.proofIdsPerItem&&t.length<w.proofs;o+=1)for(let a of e){let r=a.proofIds[o];if(!(!r||s.has(r))&&(s.add(r),t.push(r),t.length>=w.proofs))break}return t}function re(e,t,s){let o=e.identity.aliases.slice(0,w.aliasesPerEntity);s.aliases+=e.identity.aliases.length-o.length;let a=Object.fromEntries(Object.entries(e.attributes).map(([l,p])=>{if(Array.isArray(p)){let d=p.slice(0,w.attributeArrayItems);return s.attributeValues+=p.length-d.length,[l,d]}return typeof p=="string"&&p.length>w.attributeStringCharacters?(s.attributeValues+=1,[l,p.slice(0,w.attributeStringCharacters)]):[l,p]})),r=e.proofIds.filter(l=>t.has(l)).slice(0,w.proofIdsPerItem);return s.proofReferences+=e.proofIds.length-r.length,{...e,identity:{...e.identity,aliases:o},attributes:a,proofIds:r}}function ce(e){let t=Object.values(e.attributes).flatMap(s=>Array.isArray(s)?s:[s]);return [e.id,e.kind,e.label,e.projectId??"",e.identity.key,...e.identity.aliases,...t.map(s=>String(s??""))].join(" ").toLowerCase()}var le=new Set(["a","an","and","are","as","at","be","been","being","by","can","check","could","did","do","does","find","for","from","give","had","has","have","how","i","in","into","is","it","its","may","might","of","on","or","our","show","should","that","the","their","them","then","there","these","they","this","those","tell","to","was","we","were","what","when","where","which","who","why","will","with","would","you","your"]),de=new Map([["authenticate","auth"],["authenticated","auth"],["authentication","auth"],["authorization","auth"],["authorizing","auth"],["config","configuration"],["configs","configuration"],["dependencies","dependency"],["connected","connect"],["connecting","connect"],["connection","connect"],["connections","connect"],["diagnostics","diagnostic"],["defined","define"],["definition","define"],["definitions","define"],["events","event"],["handled","handle"],["handling","handle"],["implemented","implement"],["implementing","implement"],["implementations","implementation"],["implements","implement"],["reliable","reliability"],["tested","test"],["testing","test"],["tests","test"],["tools","tool"],["verification","verify"],["verified","verify"],["verifies","verify"],["verifying","verify"]]);function v(e){let t=s=>k(s).replace(/\bc\+\+/gu," cplusplus ").replace(/\bc#/gu," csharp ").split(/[^a-z0-9]+/u).filter(o=>o.length>1||o==="c"||o==="r").map(o=>de.get(o)??o);return [...new Set([...t(e),...t(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2"))])]}function pe(e){let t=k(e.label),s=k(e.identity.key),o=e.identity.aliases.map(k),a=ce(e);return {entity:e,label:t,identity:s,aliases:o,haystack:a,labelTokens:new Set(v(e.label)),identityTokens:new Set(v(e.identity.key)),aliasTokens:new Set(e.identity.aliases.flatMap(v)),allTokens:new Set(v(a))}}function E(e,t){return e.has(t)||t.length>=3&&[...e].some(s=>s.startsWith(t))}function B(e,t){return E(e.labelTokens,t)||E(e.identityTokens,t)||E(e.aliasTokens,t)||E(e.allTokens,t)}function ge(e,t,s,o){let{label:a,identity:r,aliases:l,haystack:p}=e,d=0;(a===t||r===t||l.includes(t))&&(d+=1e4),(a.startsWith(t)||r.startsWith(t))&&(d+=250),p.includes(t)&&(d+=100);let i=0;for(let h of s){let g=o.get(h)??1,y=E(e.labelTokens,h),I=E(e.identityTokens,h),f=E(e.aliasTokens,h),u=B(e,h);u&&(i+=1),a===h?d+=80*g:y&&(d+=36*g),I&&(d+=24*g),f&&(d+=20*g),u&&(d+=10*g);}return s.length>0&&(d+=i/s.length*120),d}function ue(e,t){if(["build","compiled","dist","generated","fixture","fixtures","testdata","target","third","vendor","vendored"].some(r=>t.has(r)))return 0;if(e.attributes.generated===true)return 5e3;let o=typeof e.attributes.artifact=="string"?e.attributes.artifact:"",a=`${e.label}/${e.identity.key}/${o}`.toLowerCase();return /(?:^|\/)(?:__fixtures__|__testfixtures__|build|compiled|dist|fixture|fixtures|generated|node_modules|target|testdata|third_party|vendor)(?:\/|$)/u.test(a)?5e3:0}function L(e,t){let s=new Set;for(let o of t){let a=e.allTokens.has(o)?o:void 0,r=a===void 0&&o.length>=3?[...e.allTokens].find(p=>p.startsWith(o)&&!s.has(p)):void 0,l=a??r;l&&!s.has(l)&&s.add(l);}return s.size}function he(e,t){let s=new Set([...e.labelTokens,...e.identityTokens,...e.aliasTokens]);return L({allTokens:s},t)}var X=new Map([["c","c"],["clojure","clojure"],["cplusplus","cpp"],["cpp","cpp"],["typescript","typescript"],["ts","typescript"],["javascript","javascript"],["js","javascript"],["nodejs","javascript"],["python","python"],["py","python"],["go","go"],["golang","go"],["csharp","csharp"],["ada","ada"],["assembly","assembly"],["asm","assembly"],["cuda","cuda"],["dotnet","csharp"],["dart","dart"],["elixir","elixir"],["fsharp","fsharp"],["fortran","fortran"],["java","java"],["kotlin","kotlin"],["hlsl","hlsl"],["llvmir","llvm-ir"],["mlir","mlir"],["lua","lua"],["php","php"],["r","r"],["ruby","ruby"],["rust","rust"],["tablegen","tablegen"],["scala","scala"],["svelte","svelte"],["swift","swift"],["vue","vue"]]);function fe(e){let t=new Set(e.map(o=>X.get(o)).filter(o=>!!o));return (e.includes("nodejs")||e.includes("node")&&e.includes("js"))&&(t.add("javascript"),t.add("typescript")),t}function ye(e){let t=new Set(e.filter(o=>X.has(o)));return (e.includes("nodejs")||e.includes("node")&&e.includes("js"))&&(t.add("node"),t.add("js"),t.add("nodejs")),t}function Y(e){let t=e.attributes.language;return typeof t=="string"?k(t):null}function me(e){return {project:1e3,service:900,api:900,package:850,endpoint:800,container:700,deployment:700,environment:650,pipeline:600,"test-suite":550,owner:500,decision:450,document:400}[e.kind]??0}var we=new Set(["language","languages","binding","bindings","bridge","bridges","dependency","dependencies","depends","core","runtime","owner","owners","ownership","maintainer","ci","pipeline","pipelines","workflow","deploy","deployment","infrastructure","container","doc","docs","document","documentation","service","services","api","rpc","schema","schemas","message","protobuf","proto","contract"]),ke=new Set(["app","application","applications","call","calls","code","communicate","communication","connect","define","defined","expose","exposed","handle","handled","implement","implementation","integrate","integration","interact","interaction","project","provide","provided","sdk","system","use","used","uses","using"]);function be(e){return we.has(e)||ke.has(e)}function Ie(e,t){let s=t.has("language")||t.has("languages"),o=t.has("binding")||t.has("bindings")||t.has("bridge")||t.has("bridges"),a=t.has("dependency")||t.has("dependencies")||t.has("depends"),r=t.has("core")||t.has("runtime"),l=t.has("owner")||t.has("owners")||t.has("ownership")||t.has("maintainer"),p=t.has("ci")||t.has("pipeline")||t.has("pipelines")||t.has("workflow"),d=t.has("deploy")||t.has("deployment")||t.has("infrastructure")||t.has("container"),i=t.has("doc")||t.has("docs")||t.has("document")||t.has("documentation"),h=t.has("service")||t.has("services")||t.has("api")||t.has("rpc"),g=t.has("schema")||t.has("schemas")||t.has("message")||t.has("protobuf")||t.has("proto")||t.has("contract"),y=typeof e.attributes.mechanism=="string"?k(e.attributes.mechanism):"",I=typeof e.attributes.specification=="string"?k(e.attributes.specification):"",f=k(e.label),u=0;if(s&&e.kind==="language"){let j=typeof e.attributes.fileCount=="number"?e.attributes.fileCount:0;u+=900+Math.min(j,1e4)/10;}return o&&e.kind==="protocol"&&(u+=800),a&&e.kind==="package"&&(u+=650),r&&e.kind==="package"&&/(?:^|[_-])core(?:$|[_-])/u.test(f)&&(u+=700),r&&e.kind==="protocol"&&y.includes("core")&&(u+=300),l&&e.kind==="owner"&&(u+=850),p&&e.kind==="pipeline"&&(u+=800),d&&["deployment","container","environment"].includes(e.kind)&&(u+=775),i&&["document","decision"].includes(e.kind)&&(u+=725),h&&["api","endpoint","service"].includes(e.kind)&&(u+=700),g&&(e.kind==="schema"||(e.kind==="api"||e.kind==="protocol")&&(I.includes("protobuf")||y.includes("protobuf")))&&(u+=750),u}function Se(e){return [e.has("language")||e.has("languages"),e.has("binding")||e.has("bindings")||e.has("bridge")||e.has("bridges"),e.has("dependency")||e.has("dependencies")||e.has("depends"),e.has("core")||e.has("runtime"),e.has("owner")||e.has("ownership")||e.has("maintainer"),e.has("ci")||e.has("pipeline")||e.has("workflow"),e.has("deploy")||e.has("deployment")||e.has("infrastructure"),e.has("doc")||e.has("docs")||e.has("documentation"),e.has("service")||e.has("api")||e.has("rpc"),e.has("schema")||e.has("protobuf")||e.has("proto")||e.has("contract")].filter(Boolean).length>=3}function Re(e,t){let s=k(t.query),o=[...new Set(v(t.query))],a=new Set(v(t.projectId??"")),r=t.projectId?o.filter(n=>!a.has(n)):o,l=!!(t.projectId&&o.length>0&&r.length===0),p=r.filter(n=>!le.has(n)),d=p.length>0?p:r,i=fe(d),h=ye(d),g=new Set(d),y=d.filter(n=>!h.has(n)&&!be(n)),I=Se(g),f=d.length<=1?d.length:Math.min(2,Math.ceil(d.length/3)),u=t.minimumTermMatches===void 0?f:Math.min(f,Math.max(1,Math.trunc(t.minimumTermMatches))),j=Math.max(1,Math.min(Math.trunc(t.limit??12),100)),Z=Math.max(0,Math.min(Math.trunc(t.relationsPerEntity??4),20)),G=new Set;if(t.projectId){let n=new Set(e.entities.filter(c=>c.kind==="project"&&(c.projectId===t.projectId||c.label===t.projectId)).map(c=>c.id));for(let c of e.relations)n.has(c.from)&&G.add(c.to),n.has(c.to)&&G.add(c.from);}let R=e.entities.filter(n=>(!t.kind||n.kind===t.kind)&&(!t.projectId||n.projectId===t.projectId||n.projectId===void 0&&G.has(n.id))).map(pe),J=new Map(d.map(n=>{let c=R.filter(m=>B(m,n)).length;return [n,Math.log((R.length+1)/(c+1))+1]})),ee=y.some(n=>R.some(c=>B(c,n))),M=R.map(n=>{let c=L(n,d),m=L(n,y),b=he(n,y),S=Y(n.entity),C=S&&i.has(S)?400:0,A=Ie(n.entity,g),F=y.length===0||y.some(se=>B(n,se))?A:0;return {entity:n.entity,matchedTerms:c,matchedQualifiers:m,intentScore:F,score:l?me(n.entity):ge(n,s,d,J)+m*300+b*400+C+F-ue(n.entity,g)}}).filter(n=>{let c=Y(n.entity);return (i.size===0||c===null||i.has(c))&&(s.length===0||n.score>0&&(!ee||y.length===0||n.matchedQualifiers>0)&&(l||n.matchedTerms>=u||n.intentScore>0&&(I||d.length<=2)))}).sort((n,c)=>c.score-n.score||n.entity.kind.localeCompare(c.entity.kind)||n.entity.label.localeCompare(c.entity.label)),W=(I?(()=>{let n=[],c=[],m=new Map,b=new Set;for(let S of M){let C=m.get(S.entity.kind)??0,A=k(S.entity.label);C<2&&!b.has(A)?(n.push(S),m.set(S.entity.kind,C+1),b.add(A)):c.push(S);}return [...n,...c]})():M).slice(0,j).map(n=>n.entity),P=new Set(W.map(n=>n.id)),Q=new Map,N=e.relations.filter(n=>{if(!(P.has(n.from)||P.has(n.to)))return false;let m=P.has(n.from)?n.from:n.to,b=Q.get(m)??0;return b>=Z?false:(Q.set(m,b+1),true)}),K=t.projection==="agent",T=K?N.slice(0,w.relations):N,q=O(e),H=[...new Set(T.flatMap(n=>[n.from,n.to]).filter(n=>!P.has(n)))].map(n=>q.entitiesById.get(n)).filter(n=>!!n).map(({id:n,kind:c,label:m,projectId:b})=>({id:n,kind:c,label:m,...b?{projectId:b}:{}})).sort((n,c)=>n.kind.localeCompare(c.kind)||n.label.localeCompare(c.label)),z=K?H.slice(0,w.relatedEntities):H,V=new Set([...W.flatMap(n=>n.proofIds),...T.flatMap(n=>n.proofIds)]),te=K?ae([...W,...T]):[...V],x=new Set(te),_={entities:M.length-W.length,relations:N.length-T.length,relatedEntities:H.length-z.length,proofs:V.size-x.size,proofReferences:0,aliases:0,attributeValues:0},U=K?W.map(n=>re(n,x,_)):W,ne=K?T.map(n=>{let c=n.proofIds.filter(m=>x.has(m)).slice(0,w.proofIdsPerItem);return _.proofReferences+=n.proofIds.length-c.length,{...n,proofIds:c}}):T,oe=[...x].map(n=>q.proofsById.get(n)).filter(n=>!!n).sort((n,c)=>n.id.localeCompare(c.id));return {schemaVersion:ie,graphSourceHash:e.source.hash,query:t.query,kind:t.kind??null,...t.projectId?{projectId:t.projectId}:{},limit:j,totalMatches:M.length,truncated:M.length>U.length||K&&Object.values(_).some(n=>n>0),entities:U,relatedEntities:z,relations:ne,proofs:oe,...K?{budget:{mode:"agent",limits:{...w},omitted:_}}:{}}}export{ie as a,D as b,ve as c,Me as d,je as e,Re as f};
@@ -1,2 +0,0 @@
1
- import {l}from'./chunk-VBMWFT7Q.js';import {a as a$1}from'./chunk-D3N2WFDV.js';import {b}from'./chunk-EBQS5T7Q.js';import {j}from'./chunk-4HQU2GQM.js';import {b as b$1}from'./chunk-K33JJVQZ.js';import {a}from'./chunk-AFIFZTOY.js';import {c}from'./chunk-EWZZUQBR.js';import {s,t,p}from'./chunk-ODK4LCEL.js';import Pe from'crypto';import O from'fs';import M from'fs/promises';import f from'path';var le=s.projectAgentEntry.schemaVersion,L=t.projectAgentEntry,Ce="workspai.agent-bootstrap-receipt.v1",Ve="<!-- WORKSPAI:AGENT-ENTRY:START -->",Be="<!-- WORKSPAI:AGENT-ENTRY:END -->",B=["generic","codex","claude","gemini","qwen","kimi","grok","copilot","cursor","windsurf","amazon-q"],Ue=["CLAUDE.md","GEMINI.md","QWEN.md",".amazonq/rules/workspai-agent-entry.md"];function Te(t){let s=t?.trim().toLowerCase()||"generic";if(s==="orca")return "grok";if(B.includes(s))return s;throw new Error(`Unsupported agent host "${s}". Expected one of: ${B.join(", ")}.`)}function de(t){let s=t.map(c=>c.id).sort(),n=[...B].sort();if(s.length!==n.length||s.some((c,p)=>c!==n[p]))throw new Error("Project agent entry must define each supported host exactly once.")}function U(t){let{integrity:s,...n}=t;return n}function S(t){return c(t)}function Je(t$1){de(t$1.hosts);let s={schemaVersion:le,generatedAt:t$1.context.generatedAt,project:{name:t$1.context.project.name,relativePath:t$1.context.project.relativePath,...t$1.context.project.runtime?{runtime:t$1.context.project.runtime}:{},...t$1.context.project.framework?{framework:t$1.context.project.framework}:{}},workspace:{name:t$1.context.workspace.name,relationship:t$1.context.workspace.relationship,localBinding:t.projectWorkspaceLink,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},canonical:{projectContext:t.projectContextAgent,projectGrounding:".workspai/PROJECT-GROUNDING.md",projectKnowledgeGraph:t.projectKnowledgeGraphReference,goalIndex:`workspace:${t.goalIndex}`,workspaceIndex:`workspace:${p.agentIndex}`,workspaceContext:`workspace:${p.agentContext}`,workspaceModel:`workspace:${p.model}`,knowledgeGraph:`workspace:${p.knowledgeGraph}`,workspaceSkillsIndex:`workspace:${p.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json"},protocol:{mode:"canonical-first",bootstrapCommand:"workspai agent bootstrap --for-agent generic --strict --json",verifyCommand:"workspai project agent-entry verify --for-agent all --strict --json",requiredReadOrder:[L,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",t.projectContextAgent,`workspace:${t.goalIndex}`,`workspace:${p.skillsIndex}`,"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json","source:targeted-live-files"],sourcePolicy:{liveSourceAuthority:"exact-implementation",workspaceEvidenceAuthority:"identity-topology-readiness-goals",broadScanBeforeBootstrap:false,sourceMutation:"governed-only",verificationClaims:"cli-evidence-only"},degradedMode:{discloseMissingEvidence:true,allowCompleteArchitectureClaims:false,allowReadOnlySourceInspection:true}},hosts:[...t$1.hosts].sort((c,p)=>c.id.localeCompare(p.id))},n={...s,integrity:{algorithm:"sha256",projectContextHash:t$1.context.integrity.payloadHash,payloadHash:S(s),portable:true,absolutePathsEmitted:false}};if(!A(n))throw new Error("Project agent entry rejected a non-portable local path.");return a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n}function A(t){return typeof t=="string"?!(/^[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])file:\/\//i.test(t)||/(?:^|[\s("'`])\\\\[^\\\s]+[\\]/.test(t)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(t)):Array.isArray(t)?t.every(A):t&&typeof t=="object"?Object.values(t).every(A):true}async function Se(t){let s=f.join(t,L),n=JSON.parse(await M.readFile(s,"utf8"));if(a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n.integrity.payloadHash!==S(U(n)))throw new Error("Project agent entry integrity validation failed.");if(de(n.hosts),!A(n)||n.integrity.absolutePathsEmitted)throw new Error("Project agent entry contains a non-portable local path.");return n}async function Re(t$1){let s=f.join(t$1,t.projectContextAgent),n=JSON.parse(await M.readFile(s,"utf8"));a(n,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent");let c=U(n),p=Pe.createHash("sha256").update(JSON.stringify(c)).digest("hex");if(n.integrity.payloadHash!==p)throw new Error("Project context agent integrity validation failed.");if(!A(n)||n.integrity.absolutePathsEmitted)throw new Error("Project context agent contains a non-portable local path.");return n}function xe(t){return t.includes("blocked")?"blocked":t.includes("degraded")?"degraded":"ready"}async function Ye(t$1){let s=b({startPath:f.resolve(t$1.startPath??process.cwd()),strict:true,requireProjectMembership:true});if(!s?.projectPath)throw new Error("No canonically bound Workspai project was resolved.");let n=s.projectPath,c$1=s.workspacePath,p$1=await Se(n),o=await Re(n);if(p$1.integrity.projectContextHash!==o.integrity.payloadHash||p$1.project.name!==o.project.name||p$1.workspace.name!==o.workspace.name)throw new Error("Project agent entry is not bound to the current project context.");let J=t$1.forAgent?.trim().toLowerCase()||"generic",Y=J==="all",g=Y?"all":Te(J),D=g,u=Y?p$1.hosts:p$1.hosts.filter(e=>e.id===g),z=p$1.hosts.find(e=>e.id==="generic");if(u.length===0&&z&&u.push(z),u.length===0)throw new Error("Project agent entry does not define generic host coverage.");let y=[],d=(e,r,P,h)=>y.push({id:e,status:r,message:P,...h?{artifact:h}:{}});d("workspace-binding","passed","Canonical workspace membership is resolved."),d("entry-integrity","passed","Project entry manifest integrity is valid.",L),d("project-context-integrity","passed","Project context integrity and manifest binding are valid.",t.projectContextAgent);let K=[...new Set(u.flatMap(e=>e.entryFiles))].sort(),ge=K.filter(e=>!O.existsSync(f.join(n,e))),k=u.some(e=>e.status==="blocked")||ge.length>0?"blocked":u.some(e=>e.status==="degraded")?"degraded":"ready";d("host-discovery",k==="ready"?"passed":k==="degraded"?"warning":"failed",k==="ready"?`${g} has discoverable Workspai entry coverage.`:k==="degraded"?u.find(e=>e.reason)?.reason??`${g} entry coverage is degraded.`:`${g} entry coverage is missing required files.`,K[0]);let Z=[p.agentIndex,p.agentContext,p.skillsIndex,p.model,p.knowledgeGraph],R=Z.filter(e=>!O.existsSync(f.join(c$1,e)));d("canonical-evidence",R.length===0?"passed":"failed",R.length===0?"Required canonical workspace evidence is present.":`Required canonical evidence is missing: ${R.join(", ")}.`);let E=[],x=null,m=null;for(let e of Z)if(!R.includes(e))try{let r=JSON.parse(await M.readFile(f.join(c$1,e),"utf8"));b$1(e,r,e),e===p.model&&(x=r),e===p.knowledgeGraph&&(m=r);}catch{E.push(e);}d("canonical-contracts",E.length===0?"passed":"failed",E.length===0?"Canonical workspace evidence satisfies its published schemas.":`Canonical evidence failed contract validation: ${E.join(", ")}.`);let b$2=t.projectKnowledgeGraphReference,Q=f.join(n,b$2),X="failed",I="The project Knowledge Graph reference is missing.";if(O.existsSync(Q)&&m)try{let e=JSON.parse(await M.readFile(Q,"utf8"));b$1(b$2,e,b$2);let r=j(m,o.project.name),{integrity:P,...h}=e,C=m.source;e.project.name===o.project.name&&e.canonical.sourceHash===C?.hash&&e.canonical.projectionHash===c(r)&&e.integrity.payloadHash===c(h)?(X="passed",I="The project reference integrity-binds the exact current projection of canonical workspace evidence."):I="The project Knowledge Graph reference is stale or does not match the canonical project projection.";}catch{I="The project Knowledge Graph reference failed schema or integrity validation.";}d("project-knowledge-graph",X,I,b$2);let he=x?.workspace,fe=m?.workspace,ue=Array.isArray(m?.entities)?m.entities:[],me=Array.isArray(x?.projects)?x.projects:[],ee=E.length===0&&he?.name===o.workspace.name&&fe?.name===o.workspace.name&&me.some(e=>e.name===o.project.name)&&ue.some(e=>e.projectId===o.project.name);d("canonical-project-membership",ee?"passed":"failed",ee?"The project and workspace identities agree across the entry, Model, and Graph.":"The project or workspace identity is missing or inconsistent in canonical evidence.");let te=!o.intelligence.freshness.graphMatchesModel||["missing","stale"].includes(o.intelligence.freshness.model)||["missing","stale"].includes(o.intelligence.freshness.graph)?"failed":o.intelligence.freshness.model==="unknown"||o.intelligence.freshness.graph==="unknown"?"warning":"passed",j$1=false,G;if(t$1.validateLiveInputs!==false)try{let e=await a$1(c$1);j$1=e.status==="hit";let r=e.status==="hit"?"Live project inputs match the persisted Model and Knowledge Graph snapshot.":`Live project inputs require an intelligence refresh (${e.reason}).`;G={id:"live-inputs",status:j$1?"passed":"failed",message:r};}catch{G={id:"live-inputs",status:"failed",message:"Live project inputs could not be validated against canonical graph evidence."};}else G={id:"live-inputs",status:"warning",message:"Live input validation was skipped; persisted compatibility was checked only."};let $=te==="warning"&&o.intelligence.freshness.model==="unknown"&&o.intelligence.freshness.graph==="fresh"&&o.intelligence.freshness.graphMatchesModel&&j$1?"passed":te;d("persisted-freshness",$,$==="passed"?o.intelligence.freshness.model==="unknown"?"Model and Graph bindings are current; live input validation closes structural freshness while verify-before-use facts remain individually governed.":"Persisted Model and Knowledge Graph bindings are current.":$==="warning"?"Persisted evidence is compatible, but at least one freshness state is unknown.":"Persisted Model or Knowledge Graph evidence is missing, stale, or mismatched."),y.push(G);let i={present:false,appliesToProject:false,status:"none"},_=[],we=f.join(c$1,t.goalIndex);if(O.existsSync(we)){let e=null;try{e=await l({workspacePath:c$1,validateBindings:false});}catch{_.push("workspai goal --list --json"),d("active-goal","failed","The Goal index is present but invalid.");}if(e?.active&&(i={present:true,appliesToProject:e.active.scope.projects.includes(o.project.name),status:"invalid",id:e.active.id,objective:e.active.objective,lifecycle:e.active.lifecycle,goalPack:`workspace:${e.active.goalPack}`,agentHandoff:`workspace:${e.active.agentHandoff}`}),e)try{let r=await l({workspacePath:c$1,validateBindings:true});r.active&&(i={present:true,appliesToProject:r.active.scope.projects.includes(o.project.name),status:"ready",id:r.active.id,objective:r.active.objective,lifecycle:r.active.lifecycle,goalPack:`workspace:${r.active.goalPack}`,agentHandoff:`workspace:${r.active.agentHandoff}`}),d("active-goal","passed",r.active?"The active Goal Pack and agent handoff have valid canonical bindings.":"No active Goal Pack is selected.");}catch(r){let P=r instanceof Error?r.message:String(r),h=i.present&&/\bstale\b|--refresh/i.test(P);if(i.present&&(i.status=h?"stale":"invalid"),h&&i.objective){let w=e.active,ve=w?.scope.kind==="project"&&w.scope.projects.length===1?`project:${w.scope.projects[0]}`:w?.scope.kind==="project-set"&&w.scope.projects.length>1?`projects:${w.scope.projects.join(",")}`:"workspace";_.push(`workspai goal ${JSON.stringify(i.objective)} --scope ${ve} --for-agent generic --refresh --json`);}else _.push("workspai goal --status --json");let C=!i.present||i.appliesToProject;d("active-goal",C?"failed":"warning",h?C?"The selected Goal Pack is present but stale; regenerate it against current canonical evidence before acting.":"The selected Goal Pack is stale, but it does not apply to this project; current project evidence remains usable while the Goal is refreshed for its own scope.":i.present?C?"The selected Goal Pack is present but its canonical binding or handoff is invalid.":"The selected Goal Pack has an invalid canonical binding, but it does not apply to this project; current project evidence remains usable while the Goal is repaired for its own scope.":"The Goal index could not be validated.");}}else d("active-goal","passed","No Goal index is present for this workspace.");let oe=y.filter(e=>e.id!=="active-goal"),W=oe.some(e=>e.status==="failed")?"blocked":oe.some(e=>e.status==="warning")?"degraded":"ready",ye=y.some(e=>e.id==="active-goal"&&e.status==="failed")?"blocked":y.some(e=>e.id==="active-goal"&&e.status==="warning")?"degraded":"ready",N=xe([k,W,ye]),v=o.blockers.some(e=>e.severity==="error")?"blocked":o.blockers.length>0?"degraded":"ready",ke=v==="blocked"?"blocked":v==="degraded"?"degraded":"not-verified",je=`command:workspai agent bootstrap --for-agent ${g} --strict --json`,Ae=p$1.protocol.requiredReadOrder.map(e=>e==="command:workspai agent bootstrap --for-agent generic --strict --json"?je:e),ne={schemaVersion:Ce,generatedAt:(t$1.now??new Date).toISOString(),status:N,statusScope:"agent-grounding",readiness:{agentGrounding:N,architectureEvidence:W,projectEnvironment:v,release:ke},requestedAgent:D,resolvedHost:g,project:{name:o.project.name,relativePath:o.project.relativePath,...o.project.runtime?{runtime:o.project.runtime}:{},...o.project.framework?{framework:o.project.framework}:{}},workspace:{name:o.workspace.name,relationship:o.workspace.relationship,resolved:true,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},entry:{artifact:L,schemaVersion:le,hostStatus:k,entryFiles:K},canonicalEvidence:{projectContext:t.projectContextAgent,projectKnowledgeGraph:t.projectKnowledgeGraphReference,workspaceIndex:`workspace:${p.agentIndex}`,workspaceContext:`workspace:${p.agentContext}`,workspaceModel:`workspace:${p.model}`,knowledgeGraph:`workspace:${p.knowledgeGraph}`,workspaceSkillsIndex:`workspace:${p.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json",modelFreshness:j$1?"fresh":o.intelligence.freshness.model,graphFreshness:j$1?"fresh":o.intelligence.freshness.graph,graphMatchesModel:o.intelligence.freshness.graphMatchesModel,liveInputsValidated:j$1,blockerCount:o.blockers.length},activeGoal:i,requiredReadOrder:Ae,claims:{architecture:W==="ready"?"allowed-with-citations":"prohibited",sourceInspection:"bounded-and-targeted",sourceMutation:"governed-cli-transaction-only",verification:"cli-evidence-only"},checks:y,nextActions:N==="ready"?[...i.present&&i.appliesToProject&&i.agentHandoff?[`read:${i.agentHandoff}`]:[],...v==="blocked"?["workspai doctor project --json","workspai workspace explain release-blocked --json"]:v==="degraded"?["workspai doctor project --json"]:[],`workspai workspace graph search <task-query> --scope project:${o.project.name} --limit 12 --json`,"inspect only the returned proof paths and target source files"]:[..._,"workspai workspace intelligence run --for-agent generic --strict --json",`workspai agent bootstrap --for-agent ${g} --strict --json`]},re=S(U(p$1)),Ee=S({manifestHash:re,projectContextHash:o.integrity.payloadHash,requestedAgent:D,status:N,generatedAt:ne.generatedAt}),se={...ne,receiptId:Ee},F={...se,integrity:{algorithm:"sha256",manifestHash:re,projectContextHash:o.integrity.payloadHash,payloadHash:S(se),portable:true,absolutePathsEmitted:false}};if(!A(F))throw new Error("Agent bootstrap receipt rejected a non-portable local path.");return a(F,"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json","Agent bootstrap receipt"),F}
2
- export{le as a,L as b,Ce as c,Ve as d,Be as e,B as f,Ue as g,Te as h,Je as i,Ye as j};
@@ -1,2 +0,0 @@
1
- import u from'fs';import a from'path';function N(n){try{let t=JSON.parse(u.readFileSync(a.join(n,"package.json"),"utf8"));return typeof t.packageManager!="string"?null:t.packageManager.trim().match(/^(npm|pnpm|yarn|bun)(?:@|$)/)?.[1]??null}catch{return null}}function x(n){let t=N(n);return t||(u.existsSync(a.join(n,"bun.lock"))||u.existsSync(a.join(n,"bunfig.toml"))?"bun":u.existsSync(a.join(n,"pnpm-lock.yaml"))?"pnpm":u.existsSync(a.join(n,"yarn.lock"))?"yarn":u.existsSync(a.join(n,"package-lock.json"))?"npm":u.existsSync(a.join(n,"pnpm-workspace.yaml"))?"pnpm":"npm")}function G(n,t,e=x(n)){return e==="npm"?`npm run ${t}`:`${e} run ${t}`}function V(n,t=x(n)){return `${t} install`}var C="polyglot-lifecycle-plan.v1",M=new Set([".git",".workspai",".rapidkit",".venv","bin","build","dist","node_modules","obj","target","third_party","vendor","fixture","fixtures","__fixtures__","testdata"]);function h(n,t){return a.relative(n,t).split(a.sep).join("/")||"."}function A(n,t){let e=[],r=(o,l)=>{if(l>t)return;let g=[];try{g=u.readdirSync(o,{withFileTypes:true});}catch{return}for(let f of g.sort((i,p)=>i.name.localeCompare(p.name))){let i=a.join(o,f.name);if(f.isDirectory()){M.has(f.name)||r(i,l+1);continue}f.isFile()&&(["package.json","deno.json","deno.jsonc","pyproject.toml","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts","build.sbt","deps.edn","composer.json","Gemfile","mix.exs","CMakeLists.txt","meson.build"].includes(f.name)||/\.(?:cs|fs|vb)proj$/i.test(f.name))&&e.push(i);}};return r(n,0),e}function O(n,t){let e=h(n,t).toLowerCase().split("/"),r=e.findIndex(o=>["test","tests","spec","specs","e2e","integration","integration-tests","eval","evals","bench","benchmark","benchmarks","benchmark-app","benchmark-apps"].includes(o));return r<0?false:e.length-r>2}function E(n){if(a.basename(n)!=="package.json")return true;try{let t=a.dirname(n),e=JSON.parse(u.readFileSync(n,"utf8")),r=l=>{let g=e[l];return !!(g&&typeof g=="object"&&Object.keys(g).length>0)},o=e.scripts&&typeof e.scripts=="object"?e.scripts:{};return ["dependencies","devDependencies","optionalDependencies","peerDependencies"].some(r)||["preinstall","install","postinstall","prepare","init","test","build","start"].some(l=>typeof o[l]=="string")||["package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"].some(l=>u.existsSync(a.join(t,l)))||P(n).length>0||u.existsSync(a.join(t,"pnpm-workspace.yaml"))}catch{return true}}function B(n,t){let e=a.basename(t);return e!=="build.gradle"&&e!=="build.gradle.kts"||a.dirname(t)===n?false:u.existsSync(a.join(n,"settings.gradle"))||u.existsSync(a.join(n,"settings.gradle.kts"))}function j(n,t){let e=n.match(new RegExp(`^\\s*${t}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"m"));return e?.[1]?[...e[1].matchAll(/["']([^"']+)["']/g)].map(r=>r[1]??""):[]}function P(n){try{let t=JSON.parse(u.readFileSync(n,"utf8"));if(Array.isArray(t.workspaces))return t.workspaces.filter(e=>typeof e=="string");if(t.workspaces&&typeof t.workspaces=="object"&&!Array.isArray(t.workspaces)){let e=t.workspaces.packages;return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}}catch{}return []}function _(n){if(!u.existsSync(n))return [];try{let t=u.readFileSync(n,"utf8"),e=t.match(/^packages\s*:\s*\[([^\]]*)\]/m)?.[1];return e!==void 0?[...e.matchAll(/["']([^"']+)["']/g)].map(o=>o[1]??""):[...(t.match(/^packages\s*:\s*\n((?:^[ \t]+-.*\n?)*)/m)?.[1]??"").matchAll(/^[ \t]+-[ \t]+["']?([^"'#\n]+?)["']?[ \t]*$/gm)].map(o=>(o[1]??"").trim())}catch{return []}}function S(n,t){let e=t.replace(/^\.\//,"").replace(/\/$/,""),r="^";for(let o=0;o<e.length;o+=1){let l=e[o]??"";l==="*"&&e[o+1]==="*"?(r+=".*",o+=1):l==="*"?r+="[^/]*":l==="?"?r+="[^/]":r+=l.replace(/[|\\{}()[\]^$+?.]/g,"\\$&");}return new RegExp(`${r}$`).test(n)}function F(n,t){let e=h(n.root,t);return e==="."||e.startsWith("../")||!n.patterns.some(o=>!o.startsWith("!")&&S(e,o))?false:!n.exclusions.some(o=>S(e,o))}function I(n){return n.filter(t=>a.basename(t)==="package.json").map(t=>{let e=a.dirname(t),r=[...P(t),..._(a.join(e,"pnpm-workspace.yaml"))];return {root:e,patterns:r.filter(o=>!o.startsWith("!")),exclusions:r.filter(o=>o.startsWith("!")).map(o=>o.slice(1))}}).filter(t=>t.patterns.length>0)}function W(n){return n.filter(t=>a.basename(t)==="Cargo.toml").map(t=>{try{let e=u.readFileSync(t,"utf8");return /^\s*\[workspace\]\s*$/m.test(e)?{root:a.dirname(t),patterns:j(e,"members"),exclusions:j(e,"exclude")}:null}catch{return null}}).filter(t=>!!t?.patterns.length)}function w(n,t,e){if(a.basename(n)!==e)return false;let r=a.dirname(n);return t.some(o=>o.root!==r&&F(o,r))}function s(n,t,e="high"){return {stage:n,command:t,confidence:e,preflight:"executable-and-inputs"}}function T(n,t){let e={};try{let l=JSON.parse(t);l.scripts&&typeof l.scripts=="object"&&!Array.isArray(l.scripts)&&(e=l.scripts);}catch{}let r=x(n),o=l=>`${r} run ${l}`;return [s("init",r==="yarn"?"yarn install":`${r} install`),...typeof e.test=="string"?[s("test",o("test"))]:[],...typeof e.build=="string"?[s("build",o("build"))]:[],...typeof e.start=="string"?[s("start",o("start"))]:[]]}function D(n,t){let e=a.basename(t),r=a.dirname(t),o=h(n,r),l=h(n,t),g=l.toLowerCase().split("/"),f=g.some(c=>["example","examples","sample","samples","worked","eval","evals","bench","benchmark","benchmarks","benchmark-app","benchmark-apps"].includes(c))?"example":g.some(c=>["test","tests","e2e","integration","integration-tests"].includes(c))?"test":g.some(c=>["script","scripts","tool","tools","tooling"].includes(c))?"tooling":"production",i="";try{i=u.readFileSync(t,"utf8");}catch{return null}let p,d,m;if(e==="package.json"){let c=u.existsSync(a.join(r,"bun.lock"))||u.existsSync(a.join(r,"bun.lockb"))||u.existsSync(a.join(r,"bunfig.toml"))||u.existsSync(a.join(r,".bunfig.toml"));p=c?"bun":"node",d=c?"bun":"npm",m=T(r,i);}else if(e==="deno.json"||e==="deno.jsonc"){p="deno",d="deno";let c={};try{let y=JSON.parse(i);y.tasks&&typeof y.tasks=="object"&&!Array.isArray(y.tasks)&&(c=y.tasks);}catch{}m=[...typeof c.test=="string"?[s("test","deno task test")]:[s("test","deno test","medium")],...typeof c.build=="string"?[s("build","deno task build")]:[],...typeof c.start=="string"?[s("start","deno task start")]:typeof c.dev=="string"?[s("start","deno task dev","medium")]:[]];}else if(e==="pyproject.toml")p="python",d="python",m=[s("init","python -m pip install -e ."),...u.existsSync(a.join(r,"tests"))||/\[tool\.pytest/i.test(i)?[s("test","python -m pytest")]:[],.../\[build-system\]/.test(i)?[s("build","python -m build","medium")]:[]];else if(e==="go.mod")p="go",d="go",m=[s("init","go mod download"),s("test","go test ./..."),s("build","go build ./...")];else if(e==="Cargo.toml")p="rust",d="cargo",m=[s("init","cargo fetch"),s("test","cargo test"),s("build","cargo build"),...u.existsSync(a.join(r,"src","main.rs"))?[s("start","cargo run")]:[]];else if(e==="pom.xml"){p="java",d="maven";let c=u.existsSync(a.join(r,"mvnw"))?"./mvnw":"mvn";m=[s("init",`${c} dependency:go-offline`),s("test",`${c} test`),s("build",`${c} package`)];}else if(e==="build.gradle"||e==="build.gradle.kts"){p=/(?:kotlin|org\.jetbrains\.kotlin)/i.test(i)?"kotlin":"java",d="gradle";let c=u.existsSync(a.join(r,"gradlew"))?"./gradlew":"gradle";m=[s("init",`${c} dependencies`),s("test",`${c} test`),s("build",`${c} build`)];}else if(e==="build.sbt")p="scala",d="sbt",m=[s("init","sbt update"),s("test","sbt test"),s("build","sbt compile")];else if(e==="deps.edn")p="clojure",d="clojure-cli",m=[s("init","clojure -P"),.../:test\b/.test(i)?[s("test","clojure -X:test","medium")]:[]];else if(/\.(?:cs|fs|vb)proj$/i.test(e)){p="dotnet",d="nuget";let c=f==="test"||/<IsTestProject>\s*true\s*<\/IsTestProject>/i.test(i)||/PackageReference\s+Include=["']Microsoft\.NET\.Test\.Sdk["']/i.test(i);m=[s("init",`dotnet restore ${e}`),...c?[s("test",`dotnet test ${e}`)]:[],s("build",`dotnet build ${e}`)];}else if(e==="composer.json"){p="php",d="composer";let c={};try{let y=JSON.parse(i);y.scripts&&typeof y.scripts=="object"&&!Array.isArray(y.scripts)&&(c=y.scripts);}catch{}m=[s("init","composer install"),...typeof c.test<"u"?[s("test","composer test")]:u.existsSync(a.join(r,"vendor","bin","phpunit"))||u.existsSync(a.join(r,"phpunit.xml"))||u.existsSync(a.join(r,"phpunit.xml.dist"))?[s("test","vendor/bin/phpunit","medium")]:[],...typeof c.build<"u"?[s("build","composer build")]:[],...typeof c.start<"u"?[s("start","composer start")]:[]];}else if(e==="Gemfile"){p="ruby",d="bundler";let c=u.existsSync(a.join(r,"bin","rails")),y=c||/\bgem\s+['\"]rails['\"]/.test(i),v=u.existsSync(a.join(r,"spec"))||/\bgem\s+['\"]rspec(?:-rails)?['\"]/.test(i),$=u.existsSync(a.join(r,"test"));m=[s("init","bundle install"),...$&&y?[s("test","bundle exec rails test")]:v?[s("test","bundle exec rspec")]:u.existsSync(a.join(r,"Rakefile"))?[s("test","bundle exec rake test","medium")]:[],...c?[s("start","bundle exec rails server")]:[]];}else if(e==="mix.exs")p="elixir",d="mix",m=[s("init","mix deps.get"),s("test","mix test"),s("build","mix compile"),.../(?:phoenix|phx\.server)/i.test(i)?[s("start","mix phx.server")]:[]];else if(e==="CMakeLists.txt")p=/(?:\bcxx\b|\bcplusplus\b|\bc\+\+\b)/iu.test(i)?"cpp":"c",d="cmake",m=[s("init","cmake -S . -B build"),s("test","ctest --test-dir build --output-on-failure","medium"),s("build","cmake --build build")];else if(e==="meson.build")p=/(?:cpp|c\+\+)/iu.test(i)?"cpp":"c",d="meson",m=[s("init","meson setup build"),s("test","meson test -C build","medium"),s("build","meson compile -C build")];else return null;return {id:`${p}:${o}:${a.basename(l)}`,runtime:p,ecosystem:d,role:f,root:o,manifest:l,stages:m}}function X(n,t={}){let e=a.resolve(n),r=A(e,Math.max(0,Math.min(t.maxDepth??4,12))),o=I(r),l=W(r),g=r.filter(i=>!O(e,i)).filter(i=>!B(e,i)).filter(i=>E(i)).filter(i=>!w(i,o,"package.json")).filter(i=>!w(i,l,"Cargo.toml")).map(i=>D(e,i)).filter(i=>!!i).filter(i=>t.includeExamples===true||i.role!=="example").sort((i,p)=>i.runtime.localeCompare(p.runtime)||i.root.localeCompare(p.root)||i.manifest.localeCompare(p.manifest)),f=[...new Set(g.map(i=>i.runtime))].sort();return {schemaVersion:C,projectRoot:".",polyglot:f.length>1,runtimes:f,units:g}}
2
- export{x as a,G as b,V as c,X as d};
@@ -1,3 +0,0 @@
1
- import {a as a$1,b}from'./chunk-O5XQP5E7.js';import {a as a$2}from'./chunk-7Q7X4X5I.js';import {b as b$1}from'./chunk-AO2ZI42U.js';import {a,h,e}from'./chunk-FE5R6EUV.js';import {t,s}from'./chunk-ODK4LCEL.js';import y from'path';import {existsSync}from'fs';import re from'fs-extra';var ie=[{artifactKind:"bootstrap-compliance",cardId:"bootstrap",fileNames:["bootstrap-compliance.latest.json"]},{artifactKind:"doctor-workspace",cardId:"doctor",fileNames:["doctor-remediation-plan-last-run.json","doctor-last-run.json"]},{artifactKind:"analyze",cardId:"analyze",fileNames:["analyze-last-run.json"]},{artifactKind:"readiness",cardId:"readiness",fileNames:["release-readiness-last-run.json"]},{artifactKind:"pipeline",cardId:"pipeline",fileNames:["pipeline-last-run.json"]},{artifactKind:"workspace-run",cardId:"workspaceRun",fileNames:["workspace-run-last.json"]},{artifactKind:"workspace-verify",cardId:"workspaceVerify",fileNames:["workspace-verify-last-run.json"]}];function f(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function w(e){return Array.isArray(e)?e.filter(i=>typeof i=="string"&&i.trim().length>0):[]}function P(e){return [...new Set(e.map(i=>i.trim()).filter(Boolean))]}function G(e){return (e.notes.includes("Doctor finding status: blocking")?16:0)+(e.transaction?8:0)+(e.operation?4:0)+(e.invocation?2:0)+(e.strategy?.length?1:0)}function oe(e){let i=G(e.incoming)>G(e.existing),r=structuredClone(i?e.incoming:e.existing),o=i?e.existing:e.incoming,t=o.sourceStepId;return r.order=e.existing.order,r.files=P([...r.files,...o.files]),r.notes=P([...r.notes,...o.notes.filter(n=>!n.startsWith("Source Doctor capability:")&&!n.startsWith("Doctor finding status:")),...t?[`Also satisfies Doctor capability: ${t}`]:[]]),r}function ne(e,i,r){return r?i:y.relative(e,i).split(y.sep).join("/")}function D(e){return e.includeAbsolutePaths?e.projectPath:b({workspacePath:e.workspacePath,projectPath:e.projectPath,projectName:e.projectName}).contractRelativePath}function U(e){let i=y.isAbsolute(e.filePath)?y.resolve(e.filePath):y.resolve(e.projectPath,e.filePath);if(e.includeAbsolutePaths)return i;let r=y.relative(e.projectPath,i);return !r||r===".."||r.startsWith(`..${y.sep}`)||y.isAbsolute(r)?void 0:`${D(e)}/${r.split(y.sep).join("/")}`}function ae(e){let i=e?.trim()||"npx workspai bootstrap";if(!/(?:^|\s)--ci(?:\s|$)/.test(i)&&/(?:^|\s)--json(?:\s|$)/.test(i))return i.replace(/(?:^|\s)--json(?:\s|$)/,o=>{let t=o.startsWith(" ")?" ":"",n=o.endsWith(" ")?" ":"";return `${t}--ci --json${n}`}).trim();let r=/(?:^|\s)--ci(?:\s|$)/.test(i)?i:`${i} --ci`;return /(?:^|\s)--json(?:\s|$)/.test(r)?r:`${r} --json`}function M(e,i){return y.basename(e).toLowerCase().replace(/\.cmd$/,"")==="npx"&&i[0]==="workspai"&&!i.includes("--no-install")?["--no-install",...i]:i}function J(e){return {cwd:".",executable:"npx",args:M("npx",["workspai",...e])}}function se(e){return `${JSON.stringify({schemaVersion:s.compatibilityMatrix.schemaVersion,generatedAt:e,source:"workspai workspace remediation-plan",runtimes:{},notes:["Minimal enterprise baseline. Add runtime and toolchain entries as governance matures."]},null,2)}
2
- `}function ce(e){return `${JSON.stringify({schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:e,note:"Minimal enterprise baseline. Set enabled: true and add artifact entries to activate mirroring."},null,2)}
3
- `}function de(e){let i=e.payload,r=w(i.blockers),o=w(i.blockingReasons),t=w(i.failures),n=w(i.reasons),d=w(i.policyViolations),c=f(i.summary),l=w(c?.blockers);if(e.artifactKind==="analyze"){let k=(Array.isArray(i.findings)?i.findings:[]).map(b=>f(b)).filter(b=>!!b).map(b=>String(b.message??b.title??b.id??"").trim()).filter(Boolean);return P([...r,...k,...o])}if(e.artifactKind==="workspace-run"){let p=f(i.stages),k=Object.entries(p??{}).flatMap(([b,s])=>{let a=f(s);return (Array.isArray(a?.projects)?a.projects:[]).map(u=>f(u)).filter(u=>!!u).filter(u=>u.status==="failed"||u.ok===false).map(u=>`${b}: ${String(u.project??u.name??"project")} failed`)});return P([...r,...k,...o])}return P([...r,...o,...t,...n,...d,...l])}function v(e){let i=e.findingId?.trim()||e.sourceStepId?.trim()||e.id,r=e.findingStatus??"blocking",o=e.causalKey?.trim()||[e.cardId,e.projectName??e.scope??"workspace",i].map(t=>String(t).trim().toLowerCase()).join(":");return {id:e.id,artifactKind:e.artifactKind,cardId:e.cardId,title:e.title,order:e.order,phase:e.phase,scope:e.scope??"workspace",...e.projectName?{projectName:e.projectName}:{},...e.projectPath?{projectPath:e.projectPath}:{},...e.sourceStepId?{sourceStepId:e.sourceStepId}:{},findingId:i,findingStatus:r,causalKey:o,...e.dependsOn?{dependsOn:e.dependsOn}:{},...e.strategy?{strategy:structuredClone(e.strategy)}:{},...e.transaction?{transaction:structuredClone(e.transaction)}:{},...e.requirements?{requirements:structuredClone(e.requirements)}:{},...e.retryPolicy?{retryPolicy:structuredClone(e.retryPolicy)}:{},status:e.status??"ready",mode:e.mode,risk:e.risk,requiresApproval:true,blocker:e.blocker,summary:e.summary,...e.command?{command:e.command}:{},...e.invocation?{invocation:structuredClone(e.invocation)}:{},verifyCommand:e.verifyCommand,cwd:e.cwd??"workspace",files:e.files??[],...e.operation?{operation:e.operation}:{},rollback:e.rollback??(e.operation?{available:true,strategy:"idempotent"}:{available:false,strategy:"none"}),notes:e.notes??[]}}function le(e){return (Array.isArray(e.report.payload.steps)?e.report.payload.steps:[]).flatMap((r,o)=>{let t=f(r),n=typeof t?.id=="string"?t.id.trim():"",d=typeof t?.projectName=="string"?t.projectName.trim():"",c=typeof t?.projectPath=="string"?t.projectPath.trim():"",l=typeof t?.originalCommand=="string"?t.originalCommand.trim():"";if(!t||!n||!d||!c)return [];let p=f(t.studioStatus),k=p?.state==="ready"||p?.state==="review-required"||p?.state==="blocked"||p?.state==="guidance-only"?p.state:"guidance-only",b=t.risk==="safe"||t.risk==="guarded"||t.risk==="invasive"?t.risk:"guarded",s=f(t.preview),a=D({workspacePath:e.workspacePath,projectPath:c,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}),g=Z({capability:{...t,command:l},absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),u=H({capability:t,absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),R=E({operation:t.operation,absoluteProjectPath:c}),h=t.findingStatus==="blocking"||t.findingStatus==="advisory"||t.findingStatus==="informational"?t.findingStatus:"unknown",j=typeof t.diagnosisFindingId=="string"&&t.diagnosisFindingId.trim()?t.diagnosisFindingId.trim():typeof t.issueId=="string"&&t.issueId.trim()?t.issueId.trim():n,x=typeof t.causalKey=="string"&&t.causalKey.trim()?t.causalKey.trim():void 0,m=!!g&&(t.executable===true||t.executableInCurrentEnvironment===true),A=X({strategy:t.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),I=f(t.transaction),C=I?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(I):void 0;return C&&(C.projectPath=a),[v({id:`doctor.${n}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof s?.title=="string"&&s.title.trim()?s.title.trim():`Repair ${d}`,order:e.startOrder+o,phase:typeof t.phase=="string"?t.phase:"doctor-remediation",blocker:typeof s?.summary=="string"&&s.summary.trim()?s.summary.trim():`Doctor remediation is pending for ${d}.`,summary:typeof s?.summary=="string"&&s.summary.trim()?s.summary.trim():`Execute the CLI-authored Doctor step for ${d}.`,mode:m?"run-command":"manual-guidance",risk:b,status:k,...m&&g?{command:g}:{},...m&&u?{invocation:u}:{},...R?{operation:R}:{},verifyCommand:typeof t.verifyCommand=="string"&&t.verifyCommand.trim()?t.verifyCommand.trim():"npx workspai doctor project --json",files:w(t.files).map($=>U({workspacePath:e.workspacePath,projectPath:c,projectName:d,filePath:$,includeAbsolutePaths:e.includeAbsolutePaths})).filter($=>!!$),notes:[`Source Doctor step: ${n}`,`Doctor finding id: ${j}`,`Doctor finding status: ${h}`,...typeof p?.reason=="string"?[p.reason]:[]],scope:"project",projectName:d,projectPath:a,sourceStepId:n,findingId:j,findingStatus:h,causalKey:x,dependsOn:w(t.dependsOn).map($=>`doctor.${$}`),strategy:A,transaction:C,cwd:"project",...f(t.rollback)?.available===true?{rollback:{available:true,strategy:"manual"}}:{}})]})}function Z(e){let i=typeof e.capability.command=="string"?e.capability.command.trim():"";if(e.includeAbsolutePaths&&i)return i;let r=E({operation:e.capability.operation,absoluteProjectPath:e.absoluteProjectPath});if(r)return b$1(r);let o=f(e.capability.invocation),t=typeof o?.executable=="string"?o.executable.trim():"",n=M(t,w(o?.args));if(t)return [t,...n].map(c=>/^[a-zA-Z0-9_./:@=+-]+$/.test(c)?c:JSON.stringify(c)).join(" ");if(!i)return;let d=e.absoluteProjectPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return i.replace(new RegExp(`^cd\\s+["']?${d}["']?\\s*&&\\s*`,"i"),"").replaceAll(e.absoluteProjectPath,".")}function H(e){let i=f(e.capability.invocation),r=typeof i?.executable=="string"?i.executable.trim():"",o=w(i?.args);if(!(!r||o.length!==(Array.isArray(i?.args)?i.args.length:0)))return {cwd:e.includeAbsolutePaths?e.absoluteProjectPath:".",executable:r,args:M(r,o)}}function E(e){let i=f(e.operation);if(!i||typeof i.type!="string")return;let r=structuredClone(i);for(let o of ["path","sourcePath"]){let t=r[o];if(typeof t!="string")continue;let n=y.isAbsolute(t)?y.relative(e.absoluteProjectPath,t):t;if(!n||n===".."||n.startsWith(`..${y.sep}`)||y.isAbsolute(n))return;r[o]=n.split(y.sep).join("/");}return r}function X(e){if(!Array.isArray(e.strategy))return;let i=structuredClone(e.strategy);if(!e.includeAbsolutePaths)for(let r of i)r.invocation&&(r.invocation.cwd=".");return i}function pe(e){let i=Array.isArray(e.report.payload.projects)?e.report.payload.projects:e.report.payload.project?[e.report.payload.project]:[],r=new Set,o=[];for(let t of i){let n=f(t);if(!n)continue;let d=typeof n.name=="string"?n.name.trim():"",c=typeof n.path=="string"?n.path.trim():"";if(!d||!c)continue;let l=Array.isArray(n.repairCapabilities)?n.repairCapabilities:Array.isArray(n.probes)?n.probes.map(s=>f(s)?.repairCapability).filter(s=>s!==void 0):[],p=new Map,k=new Map,b=f(n.diagnosis);for(let s of Array.isArray(b?.findings)?b.findings:[]){let a=f(s),g=f(a?.repair),u=typeof g?.capabilityId=="string"?g.capabilityId.trim():"",R=typeof a?.id=="string"?a.id.trim():"",h=typeof a?.causalKey=="string"?a.causalKey.trim():"",j=a?.status==="blocking"||a?.status==="advisory"||a?.status==="informational"||a?.status==="unknown"?a.status:"unknown";u&&R&&h&&k.set(u,{findingId:R,causalKey:h,findingStatus:j});}for(let s of Array.isArray(n.probes)?n.probes:[]){let a=f(s),g=f(a?.repairCapability),u=typeof g?.id=="string"?g.id.trim():"";u&&p.set(u,a?.status==="fail"?"blocking":"advisory");}for(let s of l){let a=f(s),g=typeof a?.id=="string"?a.id.trim():"";if(!a||!g)continue;let u=`${d}:${g}`;if(r.has(u))continue;r.add(u);let R=a.risk==="safe"||a.risk==="guarded"||a.risk==="invasive"?a.risk:"guarded",h=Z({capability:a,absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),j=H({capability:a,absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),x=E({operation:a.operation,absoluteProjectPath:c}),m=a.status==="available"&&!!h,A=f(a.transaction),I=A?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(A):void 0,C=k.get(g),$=C?.findingStatus??p.get(g)??(I?"blocking":"advisory");I&&(I.projectPath=D({workspacePath:e.workspacePath,projectPath:c,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}));let Y=X({strategy:a.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),ee=w(a.files).map(S=>U({workspacePath:e.workspacePath,projectPath:c,projectName:d,filePath:S,includeAbsolutePaths:e.includeAbsolutePaths})).filter(S=>!!S),W=v({id:`doctor.${d}.${g}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof a.title=="string"&&a.title.trim()?a.title.trim():`Repair ${d}`,order:e.startOrder+o.length,phase:I?"dependency-remediation":"doctor-remediation",blocker:typeof a.reason=="string"&&a.reason.trim()?a.reason.trim():`Doctor remediation is pending for ${d}.`,summary:typeof a.reason=="string"&&a.reason.trim()?a.reason.trim():`Execute the Doctor-authored repair capability for ${d}.`,mode:m?a.canEditFiles===true?"edit-file":"run-command":"manual-guidance",risk:R,status:m?"ready":a.status==="manual"?"guidance-only":"blocked",...h?{command:h}:{},...j?{invocation:j}:{},verifyCommand:typeof a.verifyCommand=="string"&&a.verifyCommand.trim()?a.verifyCommand.trim():"npx workspai doctor project --json",files:ee,notes:[`Source Doctor capability: ${g}`,`Doctor finding status: ${$}`,...w(a.limitations)],scope:"project",projectName:d,projectPath:D({workspacePath:e.workspacePath,projectPath:c,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}),sourceStepId:g,findingId:C?.findingId??(typeof a.issueId=="string"&&a.issueId.trim()?a.issueId.trim():g),findingStatus:$,causalKey:C?.causalKey,strategy:Y,transaction:I,cwd:"project",...x?{operation:x,rollback:{available:true,strategy:"manual"}}:{}}),O=h?o.findIndex(S=>S.projectName===d&&S.command===h&&S.cwd==="project"):-1;if(O>=0){o[O]=oe({existing:o[O],incoming:W});continue}o.push(W);}}return o}function me(e){let i=[],r=ae("npx workspai bootstrap --json");for(let o of e.blockers)o.includes("profile.enterprise.ci")&&i.push(v({id:"bootstrap.enterprise-ci",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Run bootstrap in deterministic CI mode",order:10,phase:"bootstrap-preflight",blocker:o,summary:"Enterprise bootstrap compliance requires --ci for deterministic execution.",mode:"run-command",risk:"safe",command:r,verifyCommand:r})),o.includes("profile.enterprise.compatibility-matrix")&&i.push(v({id:"bootstrap.compatibility-matrix",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise compatibility matrix baseline",order:20,phase:"bootstrap-config",blocker:o,summary:"Create the missing compatibility matrix baseline without overwriting user data.",mode:"edit-file",risk:"safe",verifyCommand:r,files:[t.compatibilityMatrix],operation:{type:"file-create",path:t.compatibilityMatrix,content:se(e.generatedAt),overwrite:false}})),o.includes("profile.enterprise.mirror-config")&&i.push(v({id:"bootstrap.mirror-config",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise mirror config baseline",order:30,phase:"bootstrap-config",blocker:o,summary:"Create the missing mirror configuration baseline without enabling mirroring.",mode:"edit-file",risk:"safe",verifyCommand:r,files:[".workspai/mirror-config.json"],operation:{type:"file-create",path:".workspai/mirror-config.json",content:ce(e.generatedAt),overwrite:false}}));return i}function ue(e){let i=Array.isArray(e.report.payload.steps)?e.report.payload.steps:[],r=[],o=new Map;for(let t of i){let n=f(t),d=f(n?.command),c=typeof n?.id=="string"?n.id.trim():"",l=typeof n?.project=="string"?n.project.trim():"",p=typeof n?.status=="string"?n.status:"",k=typeof d?.display=="string"?d.display.trim():"",b=n?.required===true;if(!c.startsWith("project.")||!l||!b||p!=="fail"&&p!=="missing"||!/^npx\s+workspai\s+workspace\s+run\s+/i.test(k))continue;let s=c.split(".").at(-1)??"stage",a=`workspaceVerify.${c}`,g=o.get(l),u=/(?:^|\s)--no-gates(?:\s|$)/.test(k)?k:`${k} --no-gates`;r.push(v({id:a,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof n.label=="string"&&n.label.trim()?n.label.trim():`Run ${s} for ${l}`,order:e.startOrder+r.length,phase:"fleet-run",blocker:typeof n.message=="string"&&n.message.trim()?n.message.trim():`${s} evidence is not current for ${l}.`,summary:`Produce fresh ${s} evidence for ${l} without re-entering the blocked aggregate gates.`,mode:"run-command",risk:s==="start"?"guarded":"safe",status:"ready",command:u,verifyCommand:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",scope:"project",projectName:l,projectPath:l,sourceStepId:c,...g?{dependsOn:[g]}:{},cwd:"workspace",notes:[`Source Workspace Verify step: ${c}`,"Aggregate verification must run only after this project evidence producer completes."]})),o.set(l,a);}return r}var T={python:["python3","python","py"],node:["node"],go:["go"],java:["java"],dotnet:["dotnet"],rust:["cargo"],php:["php"]};async function fe(e,i,r){for(let o of T[e]??[e])if(r?await r(o,i):await a$2({executable:o,cwd:i}))return o}async function ge(e){let i=P(e.blockers.flatMap(o=>{let t=o.match(/(?:project runtimes?|workspace)\s*\(([^)]+)\)\s+(?:is|are) not pinned/i);return t?.[1]?t[1].split(",").map(n=>n.trim().toLowerCase()).filter(n=>/^(python|node|go|java|dotnet|rust|php)$/.test(n)):[]})),r=[];for(let o of i){let t=T[o]??[o],n=await fe(o,e.workspacePath,e.toolAvailable),d=`environment.runtime.${o}`,c=`readiness.toolchain.${o}.setup`,l=e.blockers.find(p=>p.toLowerCase().includes(`(${o})`))??`The ${o} runtime is not pinned in the canonical workspace toolchain.`;n||r.push(v({id:d,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Provide the ${o} host runtime`,order:e.startOrder+r.length,phase:"host-prerequisite",blocker:`No launchable ${o} runtime is available in the current environment.`,summary:`Install or configure ${t.join(" or ")} outside Workspai, then refresh the remediation plan.`,mode:"manual-guidance",risk:"safe",status:"guidance-only",verifyCommand:`npx workspai setup ${o} --json`,requirements:[{kind:"executable",id:`executable:${o}`,status:"missing",executable:t.join("|"),message:`A launchable ${t.join(" or ")} executable must be visible to Workspai.`}],retryPolicy:{sameGeneration:"forbidden",resumeWhen:"environment-changed"},notes:["`workspai setup` detects and pins an existing runtime; it does not install host software."]})),r.push(v({id:c,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Pin ${o} in the workspace toolchain`,order:e.startOrder+r.length,phase:"toolchain-reconciliation",blocker:l,summary:`Detect and persist the current ${o} runtime in the canonical workspace toolchain lock.`,mode:"run-command",risk:"safe",status:n?"ready":"blocked",command:`npx workspai setup ${o} --json`,invocation:J(["setup",o,"--json"]),verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:n?void 0:[d],requirements:[{kind:"executable",id:`executable:${o}`,status:n?"satisfied":"missing",executable:n??t.join("|"),message:n?`Runtime prerequisite is launchable: ${n}.`:`Runtime prerequisite is unavailable: ${t.join(" or ")}.`},...n?[]:[{kind:"action",id:`action:${d}`,status:"pending",actionId:d,message:"The host runtime prerequisite must be resolved first."}]],retryPolicy:n?{sameGeneration:"allowed",resumeWhen:"immediate"}:{sameGeneration:"forbidden",resumeWhen:"environment-changed"},notes:["Run from the workspace root so the canonical toolchain.lock is updated."]})),r.push(v({id:`readiness.toolchain.${o}.bootstrap`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Reconcile the ${o} workspace foundation`,order:e.startOrder+r.length,phase:"toolchain-reconciliation",blocker:`The ${o} runtime pin must be reconciled with the workspace foundation.`,summary:"Refresh the workspace foundation after the runtime pin is written.",mode:"run-command",risk:"guarded",status:n?"ready":"blocked",command:"npx workspai bootstrap --ci --json",invocation:J(["bootstrap","--ci","--json"]),verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:[c],requirements:[{kind:"action",id:`action:${c}`,status:"pending",actionId:c,message:`The ${o} toolchain pin must complete first.`}],retryPolicy:{sameGeneration:n?"allowed":"forbidden",resumeWhen:n?"dependencies-complete":"environment-changed"}}));}return r}function ye(e){if(e.report.artifactKind==="readiness"&&/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(e.blocker))return v({id:`${e.report.cardId}.doctor-owner.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:"Resolve dependency vulnerability through Doctor",order:e.order,phase:"dependency-remediation",blocker:e.blocker,summary:"Release Readiness is the aggregate gate; use the project-scoped Doctor remediation capability that owns this dependency failure.",mode:"verify-before-fix",risk:"guarded",status:"review-required",command:"npx workspai doctor workspace --plan --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Read doctor-remediation-plan-last-run.json and execute the matching surface-security-hygiene capability before rerunning Readiness.","Do not treat a Readiness refresh as remediation for a source dependency vulnerability."]});let r={analyze:{title:"Refresh analyze evidence",phase:"analysis",command:"npx workspai analyze --strict --json",verify:"npx workspai analyze --strict --json"},readiness:{title:"Refresh release readiness",phase:"release-readiness",command:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",verify:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json"},pipeline:{title:"Rerun governance pipeline",phase:"governance-pipeline",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"},"workspace-run":{title:"Rerun failed workspace stage",phase:"fleet-run",command:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json",verify:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json"},"workspace-verify":{title:"Refresh workspace verify gate",phase:"verification",command:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",verify:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json"},"doctor-workspace":{title:"Use Doctor remediation plan",phase:"doctor-remediation",command:"npx workspai doctor workspace --plan --json",verify:"npx workspai doctor workspace --json"}}[e.report.artifactKind]??{title:"Refresh artifact evidence",phase:"evidence-refresh",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"};return v({id:`${e.report.cardId}.refresh.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:r.title,order:e.order,phase:r.phase,blocker:e.blocker,summary:"No deterministic file operation is available for this artifact yet; refresh the evidence and continue with the card-specific plan.",mode:e.report.artifactKind==="doctor-workspace"?"verify-before-fix":"run-command",risk:"guarded",status:e.report.artifactKind==="doctor-workspace"?"review-required":"ready",command:r.command,verifyCommand:r.verify,notes:e.report.artifactKind==="doctor-workspace"?["Read doctor-remediation-plan-last-run.json for ordered file-level steps."]:[]})}function Q(e){let i=e.transaction?.ecosystem.toLowerCase(),r=y.basename(e.invocation?.executable??"").toLowerCase(),o=`${i??""}:${r}`;if(/(^|:)(python|pip|pip3|poetry|uv)(:|$)/.test(o))return "python";if(/(^|:)(node|npm|pnpm|yarn|bun)(:|$)/.test(o))return "node";if(/(^|:)(go)(:|$)/.test(o))return "go";if(/(^|:)(java|maven|mvn|mvnw|gradle|gradlew)(:|$)/.test(o))return "java";if(/(^|:)(dotnet|nuget)(:|$)/.test(o))return "dotnet";if(/(^|:)(rust|cargo|rustc)(:|$)/.test(o))return "rust";if(/(^|:)(php|composer)(:|$)/.test(o))return "php"}function be(e,i){let r=i.invocation?.cwd??e;return y.isAbsolute(r)?r:y.resolve(e,r)}function he(e,i){let r=Q(e);if(r&&T[r]?.includes(y.basename(i)))return `environment.runtime.${r}`;let o=(e.projectName??"workspace").replace(/[^a-zA-Z0-9.-]+/g,"-"),t=y.basename(i).replace(/[^a-zA-Z0-9.-]+/g,"-");return `environment.executable.${o}.${t}`}async function ke(e){let i=new Map,r=new Map(e.actions.map(t=>[t.id,t]));for(let t of e.actions){if(!t.invocation||t.status==="guidance-only")continue;let n=be(e.workspacePath,t),d=e.toolAvailable?await e.toolAvailable(t.invocation.executable,n):await a$2({executable:t.invocation.executable,cwd:n}),c={kind:"executable",id:`executable:${t.invocation.executable}`,status:d?"satisfied":"missing",executable:t.invocation.executable,message:d?`Required executable is launchable: ${t.invocation.executable}.`:`Required executable is unavailable: ${t.invocation.executable}.`};if(t.requirements=[...(t.requirements??[]).filter(p=>p.id!==c.id),c],d)continue;let l=he(t,t.invocation.executable);!r.has(l)&&!i.has(l)&&i.set(l,v({id:l,artifactKind:t.artifactKind,cardId:"environment",title:`Provide ${y.basename(t.invocation.executable)}`,order:0,phase:"host-prerequisite",blocker:`The required executable ${t.invocation.executable} is unavailable.`,summary:"Install or configure the required executable outside Workspai, then refresh the plan.",mode:"manual-guidance",risk:"safe",status:"guidance-only",verifyCommand:t.verifyCommand,scope:t.scope,projectName:t.projectName,projectPath:t.projectPath,requirements:[c],retryPolicy:{sameGeneration:"forbidden",resumeWhen:"environment-changed"},notes:["The CLI does not install host runtimes or system package managers implicitly."]})),t.status="blocked",t.dependsOn=P([...t.dependsOn??[],l]),t.requirements.push({kind:"action",id:`action:${l}`,status:"pending",actionId:l,message:"Resolve the executable prerequisite and generate fresh evidence first."}),t.retryPolicy={sameGeneration:"forbidden",resumeWhen:"environment-changed"},t.notes.push("This action is not eligible in the current plan generation because its executable precondition failed.");}let o=[...i.values(),...e.actions];return o.forEach((t,n)=>{t.order=n+1;}),o}function Ae(e){let i=new Set(e.map(r=>r.id));for(let r of e){if(!r.transaction)continue;let o=Q(r);if(!o)continue;let t=`readiness.toolchain.${o}.bootstrap`;i.has(t)&&(r.dependsOn=P([...r.dependsOn??[],t]),r.requirements=[...r.requirements??[],{kind:"action",id:`action:${t}`,status:"pending",actionId:t,message:`The canonical ${o} workspace foundation must be reconciled first.`}],r.status==="ready"&&(r.retryPolicy={sameGeneration:"allowed",resumeWhen:"dependencies-complete"}));}}function we(e){let i=e.filter(t=>t.status==="ready"&&(t.dependsOn?.length??0)===0).map(t=>t.id),r=e.filter(t=>t.status==="blocked").map(t=>t.id),o=e.find(t=>t.status==="guidance-only")?.id??null;return {nextActionId:i[0]??o,eligibleActionIds:i,blockedActionIds:r}}async function ve(e$1){let i=[a(e$1,".workspai/reports"),e(e$1,".workspai/reports")],r=[],o=new Set;for(let t of ie)for(let n of t.fileNames){let d=(await Promise.all(i.map(c=>y.join(c,n)))).find(c=>existsSync(c));if(!(!d||o.has(`${t.artifactKind}:${n}`))){o.add(`${t.artifactKind}:${n}`);try{let c=await re.readJSON(d),l=f(c);if(!l)continue;r.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:n,absolutePath:d,payload:l});break}catch{r.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:n,absolutePath:d,payload:{blockers:[`${t.artifactKind}: report exists but could not be parsed.`]}});break}}}return r}async function Ne(e){let i=y.resolve(e.workspacePath),r=e.includeAbsolutePaths===true,o=e.ciMode===true,t=new Date().toISOString(),n=a(i,".workspai/reports"),d=await ve(i),c=[],l=1;for(let s of d){if(s.artifactKind==="doctor-workspace"){let m=Array.isArray(s.payload.steps)?le({report:s,workspacePath:i,includeAbsolutePaths:r,startOrder:l}):pe({report:s,workspacePath:i,includeAbsolutePaths:r,startOrder:l});c.push(...m),l+=m.length;continue}let a=de(s);if(a.length===0)continue;if(s.artifactKind==="bootstrap-compliance"){c.push(...me({blockers:a,generatedAt:t})),l=c.length+1;continue}if(s.artifactKind==="workspace-verify"){let m=ue({report:s,startOrder:l,ciMode:o});if(m.length>0){c.push(...m),l+=m.length;continue}}if(s.artifactKind==="readiness"){let m=await ge({report:s,blockers:a,startOrder:l,ciMode:o,workspacePath:i,toolAvailable:e.toolAvailable});if(m.length>0){c.push(...m),l+=m.length;continue}}let g=c.some(m=>m.transaction?.kind==="dependency-security"),u=s.artifactKind==="readiness"&&a.some(m=>/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(m));if(g&&u)continue;let R=a[0],h=ye({report:s,blocker:R,order:l,ciMode:o}),x={readiness:new Set(["bootstrap","doctor"]),pipeline:new Set(["bootstrap","doctor","analyze","readiness"]),workspaceVerify:new Set(["bootstrap","doctor","readiness","workspaceRun"])}[s.cardId];if(s.cardId==="pipeline"){let m=["doctor","analyze","readiness"].find(A=>R.toLowerCase().includes(A));m&&(x=new Set([m]));}if(x){let m=c.filter(A=>x.has(A.cardId)&&A.risk!=="invasive"&&A.status!=="blocked"&&A.status!=="guidance-only").map(A=>A.id);m.length>0&&(h.dependsOn=P([...h.dependsOn??[],...m]),h.notes.push("This aggregate gate must run after its contract-owned upstream remediation actions."));}a.length>1&&h.notes.push(...a.slice(1,8).map(m=>`Related blocker: ${m}`)),c.push(h),l+=1;}Ae(c);let p=await ke({actions:c,workspacePath:i,toolAvailable:e.toolAvailable}),k=we(p),b={safe:p.filter(s=>s.risk==="safe").length,guarded:p.filter(s=>s.risk==="guarded").length,invasive:p.filter(s=>s.risk==="invasive").length};return {schemaVersion:a$1,generatedAt:t,workspace:{name:y.basename(i),...r?{path:i}:{}},source:{command:"workspace remediation-plan",reportsDir:ne(i,n,r),includeAbsolutePaths:r,ciMode:o},summary:{artifactsScanned:d.length,cardsCovered:P(p.map(s=>s.cardId)).length,totalActions:p.length,executableActions:p.filter(s=>s.status==="ready").length,blockedActions:p.filter(s=>s.status==="blocked").length,guidanceActions:p.filter(s=>s.status==="guidance-only").length,risk:b},execution:k,actions:p}}async function qe(e,i){return h(i,t.artifactRemediationPlan,e)}export{Ne as a,qe as b};
@@ -1,9 +0,0 @@
1
- import {f,e,g}from'./chunk-NSH7TTSV.js';import {a,b}from'./chunk-MGL6DBOR.js';import {b as b$1,c}from'./chunk-ND5YAC4T.js';import {a as a$1}from'./chunk-NMXGSVMD.js';import {p,a as a$2}from'./chunk-NNQE4DS2.js';import {k as k$1,m,l}from'./chunk-YYELANJO.js';import {h as h$1}from'./chunk-FE5R6EUV.js';import {p as p$1,q}from'./chunk-ODK4LCEL.js';import {k,t,u}from'./chunk-VQZ5PI5J.js';import j from'fs';import i 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 j.promises.access(e,j.constants.F_OK),true}catch{return false}}async function F(e){try{let n=JSON.parse(await j.promises.readFile(e,"utf-8"));return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async function v(e){try{return await j.promises.readFile(e,"utf-8")}catch{return ""}}function ne(e){return a(e)}async function te(e,n){return await Y([...u(e,"project.json"),...u(e,"context.json")])?true:b(e)?false:i.resolve(e)===i.resolve(n)?k$1(e).length>0:k$1(e).length>0}async function re(e){let n=await a$1(e,{skipDirs:ee,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:te}),o=(await a$2(e)).filter(a=>a.relationship==="adopted"||a.source==="adopted-local").map(a=>i.resolve(a.path)).filter(a=>j.existsSync(a)),r=[...new Set([...n.map(a=>i.resolve(a)),...o])];return r.length>0?r:b(e)?[]:k$1(e).length>0?[e]:[]}function oe(e,n){return i.relative(e,n).replace(/\\/g,"/")||"."}async function S(e,n){for(let t of n)if(await E(i.join(e,t)))return true;return false}async function Y(e){for(let n of e)if(await E(n))return true;return false}async function Z(e){for(let n of e){let t=await F(n);if(t)return t}return null}async function ae(e){if(await S(e,["health","health.ts","health.js","health.py","health.go","health.kt","health.rb","health.php","healthcheck","health-check","src/health.ts","src/health.js","src/health.py","src/health.go","src/health.kt","src/health.rb","src/health.php","src/healthcheck.ts","src/healthcheck.js","src/liveness.ts","src/readiness.ts","src/ping.ts","app/controllers/health_controller.rb","app/controllers/health_check_controller.rb","config/initializers/health_check.rb"]))return true;let t=await v(i.join(e,"config","routes.rb"));return /(?:health|readiness|liveness|readiness_check|health_check)/iu.test(t)}async function se(e,n){if(await S(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(i.join(e,"package.json")),r={...o?.dependencies??{},...o?.devDependencies??{}};if(Object.keys(r).some(d=>/^(?:dotenv|dotenv-flow|env-cmd)$/iu.test(d)))return true;let a=await v(i.join(e,"pyproject.toml"));if(/\b(?:python-dotenv|pydantic-settings)\b/iu.test(a))return true;let l=[await v(i.join(e,"compose.yaml")),await v(i.join(e,"compose.yml")),await v(i.join(e,"docker-compose.yml")),await v(i.join(e,"docker-compose.yaml"))].join(`
2
- `);return /^\s*(?:env_file|environment)\s*:/imu.test(l)}async function ie(e){return (await g(e)).detected}async function ce(e){let n=await F(i.join(e,"package.json")),t=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return Object.keys(t).sort()}function h(e,n,t,o,r,a,l){return {id:e,severity:n,target:t,title:o,detail:r,remediation:a,...l&&l.length>0?{files:[...l]}:{}}}function de(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 le(e,n,t){let o=await Z(u(n,"project.json")),r=m(n,o),a=l(n),l$1=r.runtime==="unknown"?a[0]||"unknown":r.runtime,d=[l$1,...a.filter(G=>G!==l$1)],p=r.key==="unknown"&&new Set(d.filter(G=>G!=="unknown")).size>1,A=await b$1(n,o,{runtime:l$1,framework:r.key}),f=["backend","service","worker"].includes(A),w=f&&/^(?:fastapi|django|flask|nestjs|express|fastify|springboot|gofiber|gogin|dotnet-webapi|laravel|rails|phoenix|axum|actix|rocket)$/u.test(r.key),k=oe(e,n),m$1=k,$=await ce(n),P=await Y([...u(n,"project.json"),...u(n,"context.json")]),x=await ie(n),R=await S(n,["Dockerfile","dockerfile"]),z=await S(n,[".env.example","env.example","config/env.example"]),y=await se(n,o),c$1=await c({projectPath:n,declaration:t?.governance}),u$1=c$1.ci.status==="repository",C=await ae(n),g=[];return r.key==="unknown"&&g.push(h(p?"project.stack.aggregate":"project.stack.unknown",p?"info":"fail",m$1,p?"Multi-runtime aggregate boundary detected":"Project stack is unknown",p?`Workspai detected multiple runtimes (${d.join(", ")}) and intentionally did not promote one nested framework as the aggregate project identity.`:"Workspai cannot confidently classify this backend project.",p?"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||g.push(h("project.marker.missing","warn",m$1,"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||g.push(h("project.tests.missing","warn",m$1,"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.")),f&&y&&!z&&g.push(h("project.env.example.missing","info",m$1,"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"])),c$1.ci.status==="unknown"?g.push(h("project.ci.missing","warn",m$1,"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"])):c$1.ci.status==="external-observed"&&g.push(h("project.ci.external-observed","info",m$1,"Continuous integration appears externally managed",`Repository documentation references an external CI control plane (${c$1.ci.evidence.join(", ")}).`,"Declare the external CI provider in the canonical workspace contract when authoritative release gating depends on it.")),w&&!C&&g.push(h("project.health.missing","info",m$1,"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.")),f&&!R&&g.push(h("project.container.missing","info",m$1,"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():i.basename(n),path:n,relativePath:k,runtime:l$1,runtimeCandidates:d,framework:r.key,confidence:r.confidence,supportTier:r.supportTier,hasRapidKitMarker:P,hasTests:x,hasDockerfile:R,hasEnvExample:z,hasCiConfig:u$1,governance:c$1,hasHealthEndpoint:C,scripts:$,findings:g,score:de(g)}}function pe(e){return e.name.toLowerCase()}async function ue(e){let n=new Map(e.map(r=>[pe(r),r])),t=[];for(let r of e){let a=await F(i.join(r.path,"package.json")),l={...a?.dependencies??{},...a?.devDependencies??{},...a?.peerDependencies??{}};for(let p of Object.keys(l)){let A=p.replace(/^@[^/]+\//,"").toLowerCase(),f=n.get(A);f&&f.relativePath!==r.relativePath&&t.push({from:r.relativePath,to:f.relativePath,kind:"package"});}let d=await v(i.join(r.path,"pyproject.toml"));for(let p of e)p.relativePath!==r.relativePath&&d.includes(p.name)&&t.push({from:r.relativePath,to:p.relativePath,kind:"workspace-reference"});}let o=new Set;return t.filter(r=>{let a=`${r.from}\0${r.to}\0${r.kind}`;return o.has(a)?false:(o.add(a),true)})}function me(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),a=t.get(o.to);r&&(r.directDependencies+=1),a&&(a.directDependents+=1);}return Array.from(t.values()).sort((o,r)=>r.directDependents-o.directDependents||r.directDependencies-o.directDependencies)}async function fe(e){let n=await Z(t(e,"workspace.json"));return typeof n?.profile=="string"?n.profile:null}function ge(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 he(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 $e(e$1={}){let n=i.resolve(e$1.workspacePath||process.cwd());if(!await E(n))throw new Error(`Workspace path does not exist: ${n}`);let t=ne(n)??n,o=k(t),r=await fe(t),a=await re(t),l;try{l=(await p({workspacePath:t})).contract;}catch{}let d=await Promise.all(a.map(c=>{let u=l?.projects.find(C=>{let g=C.externalPath??C.relativePath;return i.resolve(t,g)===i.resolve(c)});return le(t,c,u)})),p$2=await ue(d),A=me(d,p$2),f$1=[];o||f$1.push(h("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.")),d.length===0&&f$1.push(h("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 w=[...f$1,...d.flatMap(c=>c.findings)],k$1=ge(w),m={};for(let c of d)for(let u of c.runtimeCandidates)m[u]=(m[u]||0)+1;let $=d.length>0?Math.round(d.reduce((c,u)=>c+u.score,0)/d.length):0,P=f$1.reduce((c,u)=>c+(u.severity==="fail"?20:u.severity==="warn"?8:2),0),x=Math.max(0,$-P),R=d.length===0&&k$1.fail===0&&w.length>0&&w.every(c=>c.id==="workspace.projects.missing"&&c.severity==="warn"),z=k$1.fail>0||e$1.strict&&k$1.warn>0&&!R?"blocked":k$1.warn>0?"needs-attention":"ready",y={schemaVersion:q.analyze,generatedAt:new Date().toISOString(),workspacePath:t,workspaceDetected:o,profile:r,summary:{statusScope:"source-structure",releaseReadiness:"not-evaluated",score:x,verdict:z,projectCount:d.length,runtimeCount:Object.keys(m).length,findings:k$1},runtimes:m,projects:d,dependencyGraph:{status:p$2.length>0?"generated":"empty",edges:p$2,topImpactedProjects:A.slice(0,5)},findings:w,nextActions:he({findings:w,projectCount:d.length,hasCanonicalGraph:await E(i.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 j.promises.mkdir(i.dirname(i.resolve(e$1.output)),{recursive:true}),await j.promises.writeFile(i.resolve(e$1.output),`${JSON.stringify(y,null,2)}
3
- `)),!e$1.output&&o){let c=f(y,{commandId:"workspaceAnalyze",exitCode:y.summary.verdict==="blocked"?2:y.summary.verdict==="needs-attention"?1:0,generatedAt:y.generatedAt,blockers:y.findings.filter(u=>u.severity==="fail").map(u=>u.title).slice(0,12),runId:e()});await h$1(t,p$1.analyze,c);}return y}function Ge(e){let n=e.summary.verdict==="ready"?s.green:e.summary.verdict==="needs-attention"?s.yellow:s.red;if(console.log(s.bold(`
4
- Workspai Workspace Analysis
5
- `)),console.log(s.cyan("Workspace:"),e.workspacePath),console.log(s.cyan("Profile:"),e.profile||"not configured"),console.log(s.cyan("Source score:"),`${e.summary.score}/100`),console.log(s.cyan("Source verdict:"),n(e.summary.verdict)),console.log(s.cyan("Release readiness:"),e.summary.releaseReadiness),console.log(s.gray(`Projects: ${e.summary.projectCount}, runtimes: ${e.summary.runtimeCount}, findings: ${e.summary.findings.fail} fail / ${e.summary.findings.warn} warn / ${e.summary.findings.info} info`)),e.projects.length>0){console.log(s.bold(`
6
- Projects`));for(let t of e.projects){let o=t.score>=85?s.green("pass"):t.score>=65?s.yellow("watch"):s.red("risk");console.log(` ${t.relativePath} ${s.gray(`${t.runtime}/${t.framework}`)} ${o} ${t.score}/100`);}}if(e.dependencyGraph.status==="generated"&&(console.log(s.bold(`
7
- Dependency Graph`)),console.log(s.gray(` edges: ${e.dependencyGraph.edges.length}`)),e.dependencyGraph.topImpactedProjects.length>0)){console.log(s.gray(" Top impacted projects:"));for(let t of e.dependencyGraph.topImpactedProjects.slice(0,3))console.log(` ${t.project} (${t.directDependents} dependents, ${t.directDependencies} dependencies)`);}if(e.findings.length>0){console.log(s.bold(`
8
- Top Findings`));for(let t of e.findings.slice(0,8)){let o=t.severity==="fail"?s.red:t.severity==="warn"?s.yellow:s.gray;console.log(` ${o(t.severity.toUpperCase())} ${t.target}: ${t.title}`),console.log(s.gray(` ${t.remediation}`));}}console.log(s.bold(`
9
- Next Actions`));for(let t of e.nextActions.slice(0,5))console.log(s.gray(` - ${t}`));console.log();}export{$e as a,Ge as b};