workspai 0.62.0 → 0.64.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 (98) hide show
  1. package/contracts/create-planner-capabilities.v1.json +251 -8
  2. package/contracts/studio-card-repair-capabilities.v1.json +65 -1
  3. package/contracts/workspace-intelligence/studio-blocker-handoff.v1.json +28 -0
  4. package/dist/analyze-NUGNB256.js +1 -0
  5. package/dist/{artifact-remediation-plan-HPNQTNJ2.js → artifact-remediation-plan-XIQNI35L.js} +1 -1
  6. package/dist/autopilot-release-TWJWSVVF.js +1 -0
  7. package/dist/capabilities-command-LHM3XIS6.js +1 -0
  8. package/dist/chunk-2VJUAKMS.js +2 -0
  9. package/dist/{chunk-O6R7SE6Y.js → chunk-3A23KJAQ.js} +1 -1
  10. package/dist/{chunk-GGOQHTZV.js → chunk-5B2GAZAC.js} +1 -1
  11. package/dist/{chunk-PPQL5UTI.js → chunk-6DAQ7PYT.js} +1 -1
  12. package/dist/{chunk-HS3DJMU5.js → chunk-6TBTMWNA.js} +1 -1
  13. package/dist/{chunk-46USUSIK.js → chunk-CCAXADKP.js} +26 -26
  14. package/dist/chunk-CJHWKXDN.js +1 -0
  15. package/dist/{chunk-NBJ6AP7K.js → chunk-CT4IODPG.js} +1 -1
  16. package/dist/{chunk-UZNACYV7.js → chunk-DK6JNE6K.js} +1 -1
  17. package/dist/{chunk-3VU7ROHY.js → chunk-DOXNVBX6.js} +1 -1
  18. package/dist/{chunk-A4BK7C7M.js → chunk-DWB2RRF4.js} +1 -1
  19. package/dist/{chunk-VDEFHP6I.js → chunk-FQSBOLM7.js} +1 -1
  20. package/dist/chunk-GQSRNUCU.js +105 -0
  21. package/dist/chunk-ISOOENLW.js +8 -0
  22. package/dist/chunk-J7RU5WR5.js +2 -0
  23. package/dist/{chunk-DIJGQUEV.js → chunk-JQLJBK5N.js} +1 -1
  24. package/dist/chunk-KANAJH65.js +681 -0
  25. package/dist/{chunk-JNPXLZA6.js → chunk-KJXMLBSY.js} +1 -1
  26. package/dist/{chunk-VRQLHCE2.js → chunk-KV6PS54A.js} +1 -1
  27. package/dist/{chunk-GPOZILMY.js → chunk-L22EABIC.js} +1 -1
  28. package/dist/{chunk-GPGEJVVO.js → chunk-NHTDPXTW.js} +1 -1
  29. package/dist/{chunk-KG3TUTXU.js → chunk-Q2WF7D5U.js} +1 -1
  30. package/dist/chunk-RGNCL5OB.js +1 -0
  31. package/dist/{chunk-TVCJKE2U.js → chunk-RSG2GJXT.js} +1 -1
  32. package/dist/{chunk-KCJ3VS6R.js → chunk-SFO5GVRT.js} +1 -1
  33. package/dist/{chunk-MWCKJOOU.js → chunk-TOYN76K4.js} +1 -1
  34. package/dist/chunk-U5WVR74V.js +1 -0
  35. package/dist/{chunk-W3HXTCSY.js → chunk-UXEO5QCF.js} +1 -1
  36. package/dist/{chunk-PKKP5H3T.js → chunk-VB6I52ZT.js} +3 -3
  37. package/dist/{chunk-QJCCZLOF.js → chunk-VRGEPPUB.js} +1 -1
  38. package/dist/chunk-VYDURWN7.js +1 -0
  39. package/dist/chunk-WRQWVSBJ.js +3 -0
  40. package/dist/{chunk-SS7NJMFL.js → chunk-WY4DOMEA.js} +1 -1
  41. package/dist/{chunk-ZCPT6KC3.js → chunk-XKDR5BGS.js} +6 -6
  42. package/dist/{chunk-E4LJ3PQD.js → chunk-ZGS5NKEO.js} +1 -1
  43. package/dist/chunk-ZH7CXQH3.js +94 -0
  44. package/dist/create-PWJDTKDN.js +1 -0
  45. package/dist/{doctor-MAPZ2ZCD.js → doctor-CGXY4IDE.js} +1 -1
  46. package/dist/{goal-lifecycle-7L5JFYOI.js → goal-lifecycle-BRFFTIU2.js} +1 -1
  47. package/dist/{goal-pack-SGHXUPMU.js → goal-pack-FG3QDNQH.js} +1 -1
  48. package/dist/index.d.ts +2 -1
  49. package/dist/index.js +161 -157
  50. package/dist/{pipeline-W2CKUZBS.js → pipeline-DF4UIHAD.js} +1 -1
  51. package/dist/{platform-capabilities-PR6YL4KC.js → platform-capabilities-DB4BZPTD.js} +1 -1
  52. package/dist/{project-agent-entry-66GTQQPX.js → project-agent-entry-IWUCV72J.js} +1 -1
  53. package/dist/{project-intelligence-lens-NWNWLJMB.js → project-intelligence-lens-PZPPSCUW.js} +1 -1
  54. package/dist/{project-test-coverage-E2Q4QL44.js → project-test-coverage-4S7MEQ6T.js} +1 -1
  55. package/dist/{pythonRapidkitExec-4YTAMLBD.js → pythonRapidkitExec-VAW5XE4Z.js} +1 -1
  56. package/dist/{verified-goal-AY5VU6LG.js → verified-goal-BBHZRYYH.js} +1 -1
  57. package/dist/{workspace-FSOLFNAJ.js → workspace-35Q2IXAR.js} +1 -1
  58. package/dist/{workspace-agent-sync-ZURWHL3H.js → workspace-agent-sync-FFNSW2PD.js} +1 -1
  59. package/dist/{workspace-context-DPDGFTWJ.js → workspace-context-IJ36ZP6G.js} +1 -1
  60. package/dist/{workspace-contract-3BWIRSVQ.js → workspace-contract-JS4LZZQZ.js} +1 -1
  61. package/dist/{workspace-explain-OU2PEVYO.js → workspace-explain-TITIT5XN.js} +1 -1
  62. package/dist/workspace-foundation-GMGDUMPR.js +1 -0
  63. package/dist/{workspace-graph-stream-XTSDKRLM.js → workspace-graph-stream-7UU2YVHC.js} +1 -1
  64. package/dist/{workspace-intelligence-625UN27X.js → workspace-intelligence-5NO4K5SC.js} +1 -1
  65. package/dist/{workspace-intelligence-runner-7RIOUCCM.js → workspace-intelligence-runner-FGEBFVVM.js} +1 -1
  66. package/dist/{workspace-knowledge-graph-3ZBPSAS7.js → workspace-knowledge-graph-RSDP2E36.js} +1 -1
  67. package/dist/workspace-knowledge-graph-snapshot-3FJHH5IK.js +1 -0
  68. package/dist/{workspace-mcp-serve-PYKYJIE6.js → workspace-mcp-serve-WUIQ2AE6.js} +1 -1
  69. package/dist/{workspace-model-ETCLINRB.js → workspace-model-OKY4CQ3X.js} +1 -1
  70. package/dist/{workspace-onboarding-RP3RZ3CC.js → workspace-onboarding-VS3YYNGK.js} +1 -1
  71. package/dist/{workspace-registry-summary-VSOBKAJG.js → workspace-registry-summary-MIDFG6EC.js} +1 -1
  72. package/dist/workspace-repair-engine-VUBT77Y7.js +3 -0
  73. package/dist/workspace-run-SSF6Z26G.js +1 -0
  74. package/dist/{workspace-verify-7ENGIY4S.js → workspace-verify-4R7QHUPO.js} +1 -1
  75. package/dist/{workspace-watch-2YFSB2WL.js → workspace-watch-IOPSHQS5.js} +1 -1
  76. package/docs/ci-workflows.md +1 -1
  77. package/docs/creating-workspaces-and-projects.md +49 -8
  78. package/docs/real-world-qualification.md +7 -0
  79. package/package.json +1 -1
  80. package/dist/analyze-K6JDMF5C.js +0 -1
  81. package/dist/autopilot-release-GNTOXKIL.js +0 -1
  82. package/dist/capabilities-command-VBLZXP2T.js +0 -1
  83. package/dist/chunk-7DSYI7YN.js +0 -3
  84. package/dist/chunk-BQCGULHR.js +0 -1
  85. package/dist/chunk-NA2NXX5P.js +0 -1
  86. package/dist/chunk-NVQUBUTY.js +0 -2
  87. package/dist/chunk-PTNLVI62.js +0 -16
  88. package/dist/chunk-PVXSIYLP.js +0 -1
  89. package/dist/chunk-RJIYCDVC.js +0 -1
  90. package/dist/chunk-SCP5LJNO.js +0 -2
  91. package/dist/chunk-TFOOSYGO.js +0 -8
  92. package/dist/chunk-TR6OFSJM.js +0 -691
  93. package/dist/chunk-VDFHUYAQ.js +0 -91
  94. package/dist/create-CKUQRSJF.js +0 -1
  95. package/dist/workspace-foundation-PPZKC36U.js +0 -1
  96. package/dist/workspace-knowledge-graph-snapshot-ZI4W735H.js +0 -1
  97. package/dist/workspace-repair-engine-L47XZXYZ.js +0 -3
  98. package/dist/workspace-run-QV5ER2VW.js +0 -1
@@ -1,22 +1,22 @@
1
- import {b as b$3,a}from'./chunk-THIOE2PB.js';import {h,g as g$2}from'./chunk-MWCKJOOU.js';import {b as b$4,g as g$1}from'./chunk-UZNACYV7.js';import {b as b$1,f as f$2,s,t,u,P,v,q,r,R as R$1,Q,n,o,p as p$2,h as h$2,i as i$2,m as m$1,j,k as k$1,l,O,w,x,y,z,A as A$1,B,C,E,G,I,D,F as F$1,H,J,K,L as L$1,M,N as N$1,S,T,U as U$1,V as V$1,Y,X,W,a as a$2}from'./chunk-YUGKQ44M.js';import {b,c,d as d$1}from'./chunk-TVCJKE2U.js';import {b as b$2}from'./chunk-LNXIMF3O.js';import {d as d$2}from'./chunk-O6R7SE6Y.js';import {p as p$1,k as k$2,f as f$3}from'./chunk-NA2NXX5P.js';import {m}from'./chunk-KG3TUTXU.js';import {d}from'./chunk-CCDGHPEJ.js';import {a as a$1,b as b$5}from'./chunk-D65FCQIO.js';import {f,e,i,h as h$3}from'./chunk-NZ3WZYD5.js';import {f as f$1,g,h as h$1}from'./chunk-MOSXTVPU.js';import i$1 from'path';import k from'fs-extra';var oe=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var qt="workspace-operational-skill.v1";function Ht(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function bt(e){let t=Ht(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:qt,skillId:t,canonicalPath:W(t),title:e.title,triggers:[...e.triggers].sort((r,a)=>r.localeCompare(a)),requiredReports:[...e.requiredReports].sort((r,a)=>r.localeCompare(a)),scopedProjects:[...e.scopedProjects??[]].sort((r,a)=>r.localeCompare(a)),verificationCommands:[...e.verificationCommands],answerContractSections:[...oe],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var Mt=f.skillsIndex;function It(e){let t=[...e.skills].sort((a,s)=>a.skillId.localeCompare(s.skillId)),r=e.inputsHash??f$3({skillIds:t.map(a=>a.skillId),paths:t.map(a=>a.canonicalPath)});return {schemaVersion:Mt,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(a=>({skillId:a.skillId,path:a.canonicalPath,schemaVersion:a.schemaVersion,title:a.title}))}}var Et=[e.agentIndex,b,d$2],se="<!-- WORKSPAI:GENERATED-OPERATIONAL-SKILL -->",Ut=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${e.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${e.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."]},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${e.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${e.verify}\` for verdict and blocking reasons.`,`Read \`${i.artifactRemediationPlan}\` when a Studio or agent repair path is needed.`,"List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."]},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Require project-scoped test/build commands before promoting the migration.","Document rollback and verification signals."]},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Prefer workspace run test/build for affected projects.","Re-run `workspace verify` after evidence refresh."]},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:[`Read \`${i.workspaceContract}\` for publishes/consumes/owns edges.`,"List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."]}];function ie(e){return `npx workspai ${e}`.trim()}function Vt(e){let t=["---",`name: ${e.template.skillId}`,`description: ${e.template.objective}`,"---","",se,"",`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",...Et.map(r=>`- \`${r}\``),"","## Procedure","",...e.template.steps.map((r,a)=>`${a+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",ie("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
2
- `)}function Ft(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function zt(e){let t=new Map;for(let d of e.projects){let u=Ft(d.runtime);if(!u||u==="unknown")continue;let o=t.get(u)??[];o.push(d.name),t.set(u,o);}let r=[];for(let[d,u]of [...t.entries()].sort(([o],[w])=>o.localeCompare(w)))r.push({skillId:`workspai-${d}-runtime-validation`,title:`${d.toUpperCase()} runtime validation`,triggers:[`${d} build`,`${d} test`,`${d} runtime failure`],objective:`Validate ${d} changes against the detected project commands and canonical Workspai evidence.`,steps:["Read the scoped project lens and current fail/warn evidence before changing source.","Use the registered project commands; do not substitute a different runtime toolchain.","Run only the affected project validation first, then verify the workspace when the change crosses a contract boundary."],scopedProjects:[...u].sort()});t.size>1&&r.push({skillId:"workspai-polyglot-change-validation",title:"Polyglot change validation",triggers:["cross-language change","polyglot change","binding change","multi-runtime validation"],objective:"Plan and verify a cross-runtime change without assuming that one runtime command proves the whole system.",steps:["Use the project topology and bounded Graph query to identify runtime and contract boundaries.","Validate each affected runtime with its registered project command.","Run workspace impact and canonical verification before declaring the change complete."]});let a=e.projects.filter(d=>d.commands.supported.includes("test")).map(d=>d.name).sort();a.length>0&&r.push({skillId:"workspai-test-evidence-recovery",title:"Test evidence recovery",triggers:["test failure","coverage","regression","test evidence"],objective:"Repair a test or coverage blocker by proving changed behavior, not merely improving a metric.",steps:["Read the exact Analyze, Doctor, or Goal evidence that owns the test finding.","Inspect the behavior and relevant test boundary before proposing a source change.","Run the scoped test command, then the exact producer and canonical verification."],scopedProjects:a});let s=e.projects.filter(d=>d.importantFiles.some(u=>/(?:^|\/)(?:Dockerfile|docker-compose|compose\.|Chart\.yaml|\.github\/workflows)/i.test(u))).map(d=>d.name).sort();return s.length>0&&r.push({skillId:"workspai-delivery-evidence",title:"Delivery evidence and CI recovery",triggers:["ci failure","workflow failure","container build","deployment evidence"],objective:"Diagnose delivery evidence with the owning project and CI/container artifacts before changing application source.",steps:["Identify whether the failing evidence is project-owned or workspace-owned.","Inspect the referenced workflow or delivery artifact and its bounded proof paths.","Validate the affected project first, then refresh the exact evidence producer and verify the workspace."],scopedProjects:s}),r}function Jt(e){return e?.safeCommands?.length?e.safeCommands.slice(0,8).map(t=>t.display):[ie("workspace verify --json"),ie("doctor workspace --json")]}function Bt(e){return e?.projects?.length?e.projects.slice(0,12).map(r=>{let a=r.contracts?.owns?.join(", ")||"none",s=r.contracts?.publishes?.join(", ")||"none",d=r.contracts?.consumes?.join(", ")||"none";return `- **${r.slug}**: owns \`${a}\`; publishes \`${s}\`; consumes \`${d}\``}).join(`
3
- `):void 0}function xt(e){let t=e.model.workspace.name,r=Jt(e.context??null),a=Bt(e.contract??null);return [...Ut,...zt(e.model)].map(s=>{let d=s.scopedProjects??e.model.projects.map(o=>o.name),u=Vt({template:s,workspaceName:t,scopedProjects:d,verificationCommands:r,contractSummary:a});return bt({skillId:s.skillId,title:s.title,triggers:s.triggers,requiredReports:[...Et],scopedProjects:d,verificationCommands:r,...X(s.skillId)?{promptStem:Y[s.skillId]}:{},markdown:u})})}async function Ct(e){let t=i$1.resolve(e.workspacePath),r=[],a=f$3({skills:e.skills.map(o=>({id:o.skillId,path:o.canonicalPath,hash:f$3({markdown:o.markdown})}))}),s=It({generatedAt:e.generatedAt,skills:e.skills,inputsHash:a}),d=new Set(e.skills.map(o=>o.skillId)),u=[];if(e.write){let o=i$1.join(t,".workspai","skills");if(await k.pathExists(o))for(let m of await k.readdir(o,{withFileTypes:true})){if(!m.isFile()||!m.name.endsWith(".md"))continue;let g=m.name.slice(0,-3);if(d.has(g))continue;let I=i$1.join(o,m.name);(await k.readFile(I,"utf8")).includes(se)&&(await k.remove(I),u.push(g));}for(let m of e.skills){let g=i$1.join(t,m.canonicalPath);await k.ensureDir(i$1.dirname(g)),await k.writeFile(g,m.markdown,"utf8"),r.push(m.canonicalPath);}let w=i$1.join(t,b$1);await k.ensureDir(i$1.dirname(w)),await k.writeJson(w,s,{spaces:2}),r.push(b$1);}return {skills:e.skills,index:s,writtenPaths:r,removedSkillIds:u.sort()}}function _t(e){return ["## Operational skills (canonical)","","Read workspace-native playbooks from `.workspai/skills/` before generic repo scans. Legacy `.rapidkit/skills/` playbooks are read only when already present from older workspaces:","",...e.skills.map(r=>`- \`${r.path}\` \u2014 ${r.title} (\`${r.skillId}\`)`),"","Regenerate:","","```bash",ie("workspace agent-sync --write --refresh-context"),"```",""].join(`
4
- `)}var Yt={"workspai-diagnose-api-failure":A$1,"workspai-release-readiness":E},Fe="## Workspace verification (hydrated)";function Xt(e){let t=[Fe,"","Verification commands for this workspace:","",...e.verificationCommands.length?e.verificationCommands.map(r=>`- \`${r}\``):["- `npx workspai workspace verify --json`"]];return e.scopedProjects.length>0&&t.push("","Scoped projects:","",...e.scopedProjects.map(r=>`- ${r}`)),t.push(""),t.join(`
5
- `)}async function Ot(e){let t=i$1.resolve(e.workspacePath),r=[];for(let a of e.skills){let s=Yt[a.skillId];if(!s)continue;let d=i$1.join(t,s);if(!await k.pathExists(d))continue;let u=await k.readFile(d,"utf8"),o=Xt(a),w=u.includes(Fe)?u.replace(new RegExp(`${Fe}[\\s\\S]*$`),o.trimEnd()):`${u.trimEnd()}
1
+ import {b as b$3,a}from'./chunk-THIOE2PB.js';import {h,g as g$2}from'./chunk-TOYN76K4.js';import {b as b$4,g as g$1}from'./chunk-DK6JNE6K.js';import {b as b$1,f as f$2,s,t,u,P,v,q,r,R as R$1,Q,n,o,p as p$2,h as h$2,i as i$2,m as m$1,j,k as k$1,l,O,w,x,y,z as z$1,A as A$1,B,C,E,G as G$1,I,D,F as F$1,H,J,K,L as L$1,M,N,S,T,U,V as V$1,Y,X,W,a as a$2}from'./chunk-YUGKQ44M.js';import {b,c,d as d$1}from'./chunk-RSG2GJXT.js';import {b as b$2}from'./chunk-LNXIMF3O.js';import {d as d$2}from'./chunk-3A23KJAQ.js';import {p as p$1,k as k$2,f as f$3}from'./chunk-CJHWKXDN.js';import {m}from'./chunk-Q2WF7D5U.js';import {d}from'./chunk-CCDGHPEJ.js';import {a as a$1,b as b$5}from'./chunk-D65FCQIO.js';import {f,e,i,h as h$3}from'./chunk-NZ3WZYD5.js';import {f as f$1,g,h as h$1}from'./chunk-MOSXTVPU.js';import i$1 from'path';import k from'fs-extra';var ie=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var qt="workspace-operational-skill.v1";function Ht(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function bt(e){let t=Ht(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:qt,skillId:t,canonicalPath:W(t),title:e.title,triggers:[...e.triggers].sort((r,a)=>r.localeCompare(a)),requiredReports:[...e.requiredReports].sort((r,a)=>r.localeCompare(a)),scopedProjects:[...e.scopedProjects??[]].sort((r,a)=>r.localeCompare(a)),verificationCommands:[...e.verificationCommands],answerContractSections:[...ie],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var Mt=f.skillsIndex;function It(e){let t=[...e.skills].sort((a,s)=>a.skillId.localeCompare(s.skillId)),r=e.inputsHash??f$3({skillIds:t.map(a=>a.skillId),paths:t.map(a=>a.canonicalPath)});return {schemaVersion:Mt,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(a=>({skillId:a.skillId,path:a.canonicalPath,schemaVersion:a.schemaVersion,title:a.title}))}}var Et=[e.agentIndex,b,d$2],ce="<!-- WORKSPAI:GENERATED-OPERATIONAL-SKILL -->",Ut=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${e.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${e.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."]},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${e.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${e.verify}\` for verdict and blocking reasons.`,`Read \`${i.artifactRemediationPlan}\` when a Studio or agent repair path is needed.`,"List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."]},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Require project-scoped test/build commands before promoting the migration.","Document rollback and verification signals."]},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Prefer workspace run test/build for affected projects.","Re-run `workspace verify` after evidence refresh."]},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:[`Read \`${i.workspaceContract}\` for publishes/consumes/owns edges.`,"List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."]}];function se(e){return `npx workspai ${e}`.trim()}function Vt(e){let t=["---",`name: ${e.template.skillId}`,`description: ${e.template.objective}`,"---","",ce,"",`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",...Et.map(r=>`- \`${r}\``),"","## Procedure","",...e.template.steps.map((r,a)=>`${a+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",se("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
2
+ `)}function Ft(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function zt(e){let t=new Map;for(let d of e.projects){let u=Ft(d.runtime);if(!u||u==="unknown")continue;let o=t.get(u)??[];o.push(d.name),t.set(u,o);}let r=[];for(let[d,u]of [...t.entries()].sort(([o],[w])=>o.localeCompare(w)))r.push({skillId:`workspai-${d}-runtime-validation`,title:`${d.toUpperCase()} runtime validation`,triggers:[`${d} build`,`${d} test`,`${d} runtime failure`],objective:`Validate ${d} changes against the detected project commands and canonical Workspai evidence.`,steps:["Read the scoped project lens and current fail/warn evidence before changing source.","Use the registered project commands; do not substitute a different runtime toolchain.","Run only the affected project validation first, then verify the workspace when the change crosses a contract boundary."],scopedProjects:[...u].sort()});t.size>1&&r.push({skillId:"workspai-polyglot-change-validation",title:"Polyglot change validation",triggers:["cross-language change","polyglot change","binding change","multi-runtime validation"],objective:"Plan and verify a cross-runtime change without assuming that one runtime command proves the whole system.",steps:["Use the project topology and bounded Graph query to identify runtime and contract boundaries.","Validate each affected runtime with its registered project command.","Run workspace impact and canonical verification before declaring the change complete."]});let a=e.projects.filter(d=>d.commands.supported.includes("test")).map(d=>d.name).sort();a.length>0&&r.push({skillId:"workspai-test-evidence-recovery",title:"Test evidence recovery",triggers:["test failure","coverage","regression","test evidence"],objective:"Repair a test or coverage blocker by proving changed behavior, not merely improving a metric.",steps:["Read the exact Analyze, Doctor, or Goal evidence that owns the test finding.","Inspect the behavior and relevant test boundary before proposing a source change.","Run the scoped test command, then the exact producer and canonical verification."],scopedProjects:a});let s=e.projects.filter(d=>d.importantFiles.some(u=>/(?:^|\/)(?:Dockerfile|docker-compose|compose\.|Chart\.yaml|\.github\/workflows)/i.test(u))).map(d=>d.name).sort();return s.length>0&&r.push({skillId:"workspai-delivery-evidence",title:"Delivery evidence and CI recovery",triggers:["ci failure","workflow failure","container build","deployment evidence"],objective:"Diagnose delivery evidence with the owning project and CI/container artifacts before changing application source.",steps:["Identify whether the failing evidence is project-owned or workspace-owned.","Inspect the referenced workflow or delivery artifact and its bounded proof paths.","Validate the affected project first, then refresh the exact evidence producer and verify the workspace."],scopedProjects:s}),r}function Jt(e){return e?.safeCommands?.length?e.safeCommands.slice(0,8).map(t=>t.display):[se("workspace verify --json"),se("doctor workspace --json")]}function Bt(e){return e?.projects?.length?e.projects.slice(0,12).map(r=>{let a=r.contracts?.owns?.join(", ")||"none",s=r.contracts?.publishes?.join(", ")||"none",d=r.contracts?.consumes?.join(", ")||"none";return `- **${r.slug}**: owns \`${a}\`; publishes \`${s}\`; consumes \`${d}\``}).join(`
3
+ `):void 0}function xt(e){let t=e.model.workspace.name,r=Jt(e.context??null),a=Bt(e.contract??null);return [...Ut,...zt(e.model)].map(s=>{let d=s.scopedProjects??e.model.projects.map(o=>o.name),u=Vt({template:s,workspaceName:t,scopedProjects:d,verificationCommands:r,contractSummary:a});return bt({skillId:s.skillId,title:s.title,triggers:s.triggers,requiredReports:[...Et],scopedProjects:d,verificationCommands:r,...X(s.skillId)?{promptStem:Y[s.skillId]}:{},markdown:u})})}async function Ct(e){let t=i$1.resolve(e.workspacePath),r=[],a=f$3({skills:e.skills.map(o=>({id:o.skillId,path:o.canonicalPath,hash:f$3({markdown:o.markdown})}))}),s=It({generatedAt:e.generatedAt,skills:e.skills,inputsHash:a}),d=new Set(e.skills.map(o=>o.skillId)),u=[];if(e.write){let o=i$1.join(t,".workspai","skills");if(await k.pathExists(o))for(let m of await k.readdir(o,{withFileTypes:true})){if(!m.isFile()||!m.name.endsWith(".md"))continue;let g=m.name.slice(0,-3);if(d.has(g))continue;let I=i$1.join(o,m.name);(await k.readFile(I,"utf8")).includes(ce)&&(await k.remove(I),u.push(g));}for(let m of e.skills){let g=i$1.join(t,m.canonicalPath);await k.ensureDir(i$1.dirname(g)),await k.writeFile(g,m.markdown,"utf8"),r.push(m.canonicalPath);}let w=i$1.join(t,b$1);await k.ensureDir(i$1.dirname(w)),await k.writeJson(w,s,{spaces:2}),r.push(b$1);}return {skills:e.skills,index:s,writtenPaths:r,removedSkillIds:u.sort()}}function Ot(e){return ["## Operational skills (canonical)","","Read workspace-native playbooks from `.workspai/skills/` before generic repo scans. Legacy `.rapidkit/skills/` playbooks are read only when already present from older workspaces:","",...e.skills.map(r=>`- \`${r.path}\` \u2014 ${r.title} (\`${r.skillId}\`)`),"","Regenerate:","","```bash",se("workspace agent-sync --write --refresh-context"),"```",""].join(`
4
+ `)}var Yt={"workspai-diagnose-api-failure":A$1,"workspai-release-readiness":E},ze="## Workspace verification (hydrated)";function Xt(e){let t=[ze,"","Verification commands for this workspace:","",...e.verificationCommands.length?e.verificationCommands.map(r=>`- \`${r}\``):["- `npx workspai workspace verify --json`"]];return e.scopedProjects.length>0&&t.push("","Scoped projects:","",...e.scopedProjects.map(r=>`- ${r}`)),t.push(""),t.join(`
5
+ `)}async function _t(e){let t=i$1.resolve(e.workspacePath),r=[];for(let a of e.skills){let s=Yt[a.skillId];if(!s)continue;let d=i$1.join(t,s);if(!await k.pathExists(d))continue;let u=await k.readFile(d,"utf8"),o=Xt(a),w=u.includes(ze)?u.replace(new RegExp(`${ze}[\\s\\S]*$`),o.trimEnd()):`${u.trimEnd()}
6
6
 
7
7
  ${o}`;e.write&&await k.writeFile(d,`${w.trimEnd()}
8
- `,"utf8"),r.push(s);}return r}var Qt="workspai-agent-customization-pack-capabilities.v1";function Tt(){return {schemaVersion:Qt,presets:{minimal:{meaning:"Generate the portable grounding index, AGENTS.md, and provider-specific lightweight instructions.",requiredOutputs:[e.agentIndex,e.agentCustomizationPack,e.agents]},enterprise:{meaning:"Generate the full VS Code-native pack: instructions, prompts, skills, custom agents, and validation metadata.",requiredOutputs:[e.agentIndex,e.agentCustomizationPack,e.agents,w,A$1,M,".github/agents/workspai-advisor.agent.md",S,b$1]}},targets:{all:{meaning:"Generate every supported customization surface.",outputFamilies:["portable","vscode","copilot","cursor","claude","gemini","qwen","kimi","grok","windsurf","amazon-q"]},vscode:{meaning:"Generate VS Code-native customizations for Copilot Chat and agent workflows.",outputFamilies:["instructions","prompts","skills","agents","hooks"]},agents:{meaning:"Generate portable AGENTS.md grounding for any agent.",outputFamilies:["portable"]},copilot:{meaning:"Generate GitHub Copilot instructions, prompts, and skills.",outputFamilies:["instructions","prompts","skills"]},cursor:{meaning:"Generate Cursor rules.",outputFamilies:["rules"]},claude:{meaning:"Generate Claude Code grounding files.",outputFamilies:["rules","portable"]},codex:{meaning:"Use AGENTS.md and the report index as the Codex grounding layer.",outputFamilies:["portable"]},gemini:{meaning:"Generate Gemini CLI grounding through GEMINI.md and canonical AGENTS.md.",outputFamilies:["adapter","portable"]},qwen:{meaning:"Generate Qwen Code grounding through QWEN.md and canonical AGENTS.md.",outputFamilies:["adapter","portable"]},kimi:{meaning:"Use AGENTS.md and the report index as the Kimi Code grounding layer.",outputFamilies:["portable"]},grok:{meaning:"Use AGENTS.md and the report index as the xAI Grok grounding layer.",outputFamilies:["portable"]},windsurf:{meaning:"Use AGENTS.md and the report index as the Windsurf grounding layer.",outputFamilies:["portable"]},"amazon-q":{meaning:"Generate an Amazon Q project rule that routes agents to canonical evidence.",outputFamilies:["rules","portable"]},orca:{meaning:"Legacy compatibility alias for AGENTS.md consumers; prefer the grok target.",outputFamilies:["portable"]}},standardAnswerContract:[...oe],requiredReports:U.map(e=>({path:e.relativePath,label:e.label,required:e.required})),strictRules:["Required reports must exist.","Generated report paths must stay inside the workspace root.","Generated customization text must be English-only.","Agent answers must not claim pass, ready, or healthy without cited evidence.","Commands must distinguish display guidance from execution requests.","Agent hook files must be advisory and disabled by default unless the user explicitly enables them.","MCP design artifacts must stay read-mostly until write tools have explicit approval boundaries."],outputKinds:["report","grounding","instruction","prompt","skill","skill-resource","operational-skill","skills-index","explain-report","agent","rule","hook","mcp-design"],pathLayers:{l1CanonicalRoots:[".workspai/reports/",`${a$2}/`],l2PrefixedMirrorRoots:[".github/",".cursor/",".claude/",".amazonq/"],l3SharedIndustryFiles:["AGENTS.md",".github/copilot-instructions.md","CLAUDE.md","GEMINI.md","QWEN.md"]}}}var Zt=f.agentIndex,er=f.agentCustomizationPack,F=e.agentIndex,V=e.agentCustomizationPack;var U=[{relativePath:i.goalIndex,label:"Active Goal Pack index",required:false},{relativePath:i.goalPackLastRun,label:"Latest governed Goal Pack",required:false},{relativePath:b,label:"Agent context pack",required:true},{relativePath:b$1,label:"Operational skills index",required:true},{relativePath:e.model,label:"Workspace model",required:false},{relativePath:e.knowledgeGraph,label:"Workspace knowledge graph",required:false},{relativePath:e.evaluationLastRun,label:"Workspace Intelligence evaluation",required:false},{relativePath:e.doctor,label:"Workspace doctor",required:false},{relativePath:i.doctorProject,label:"Project doctor",required:false},{relativePath:i.doctorRemediationPlan,label:"Doctor remediation plan",required:false},{relativePath:i.artifactRemediationPlan,label:"Artifact remediation plan",required:false},{relativePath:i.doctorFixResult,label:"Doctor fix result",required:false},{relativePath:e.analyze,label:"Workspace analyze",required:false},{relativePath:i.pipelineLastRun,label:"Governance pipeline",required:false},{relativePath:e.readiness,label:"Release readiness",required:false},{relativePath:e.impact,label:"Workspace impact",required:false},{relativePath:e.verify,label:"Workspace verify",required:false},{relativePath:e.snapshot,label:"Workspace model snapshot",required:false},{relativePath:e.diff,label:"Workspace model diff",required:false},{relativePath:e.explain,label:"Workspace explain",required:false},{relativePath:e.contractVerify,label:"Workspace contract verify",required:false},{relativePath:e.history,label:"Workspace intelligence history",required:false}];function tr(){let e=U.map(r=>r.relativePath),t=b$2().consumers.agents.canonicalReadOrder;return [...new Set(t.filter(r=>r!==F&&e.includes(r)))]}async function rr(e){try{let{contract:t}=await m({workspacePath:e});if(t?.workspace?.name)return `workspace:${t.workspace.name}`}catch{}for(let t of [".workspai/workspace.json",".rapidkit/workspace.json"])try{let r=await k.readJson(i$1.join(e,t)),a=typeof r.workspace_name=="string"?r.workspace_name:typeof r.name=="string"?r.name:null;if(a?.trim())return `workspace:${a.trim()}`}catch{}return `workspace:${i$1.basename(i$1.resolve(e))}`}function A(e){return `npx workspai ${e}`.trim()}function Qe(e){return e&&typeof e=="object"?e:null}function ze(e,t=12){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0).slice(0,t):[]}function nr(e){let t=ze(e.blockers,12);if(t.length>0)return t;let r=ze(e.blockingReasons,12);if(r.length>0)return r;let a=Qe(e.summary);return a&&Array.isArray(a.blockingReasons)?ze(a.blockingReasons,12):[]}function ar(e){let t=[...new Set(e.map(r=>r.trim()).filter(Boolean))];return t.filter(r=>{let a=r.toLowerCase();return !t.some(s=>{if(s===r||!s.includes(":"))return false;let d=s.toLowerCase();return d.length>a.length&&d.endsWith(a)})})}function or(e){for(let t of ["generatedAt","updatedAt","timestamp"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}if(Array.isArray(e.entries)){let t=e.entries.map(r=>Qe(r)?.generatedAt).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim()).filter(r=>Number.isFinite(Date.parse(r)));if(t.length>0)return t.reduce((r,a)=>Date.parse(a)>Date.parse(r)?a:r)}}function ir(e,t,r){if(!e)return true;let a=Date.parse(e);return Number.isFinite(a)?r.getTime()-a>t*60*60*1e3:true}function sr(e$1,t,r){return e$1.path===e.snapshot?false:ir(e$1.generatedAt,t,r)}function cr(e){let t=e&&e.length>0?e:["all"];return t.includes("all")?new Set(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"]):new Set(t)}function R(e,t){return e.has("all")||e.has(t)}function $t(e){return R(e,"copilot")||R(e,"vscode")}function lr(e,t){return t==="generic"?R(e,"agents"):t==="copilot"?$t(e):t==="grok"?R(e,"grok")||R(e,"orca"):R(e,t)}function dr(e){return e??"enterprise"}function pr(e){return e===b$1?"skills-index":e.includes("workspace-explain-last-run.json")?"explain-report":(e.startsWith(`${a$2}/`)||e.startsWith(".rapidkit/skills/"))&&e.endsWith(".md")?"operational-skill":e.includes("hooks")||e===U$1||e===V$1?"hook":e.includes("mcp")||e===S||e===T?"mcp-design":e.endsWith(".json")?"report":e.includes("/instructions/")||e.endsWith("copilot-instructions.md")?"instruction":e.includes("/prompts/")?"prompt":e.includes("/skills/")&&e.endsWith("/SKILL.md")?"skill":e.includes("/skills/")?"skill-resource":e.includes("/agents/")?"agent":e.includes("/rules/")||e.endsWith(".mdc")?"rule":"grounding"}function ur(e){return e.startsWith(".github/")?["vscode","copilot"]:e.startsWith(".cursor/")?["cursor"]:e.startsWith(".claude/")||e==="CLAUDE.md"?["claude"]:e==="GEMINI.md"?["gemini"]:e==="QWEN.md"?["qwen"]:e.startsWith(".amazonq/")?["amazon-q"]:e===".windsurfrules"||e.startsWith(".windsurf/")?["windsurf"]:e.startsWith(".grok/")?["grok"]:e.startsWith(".agents/")?["codex","kimi","grok","orca"]:e==="AGENTS.md"||e.startsWith(".rapidkit/")?["agents","codex","kimi","grok","copilot","cursor","claude","gemini","qwen","amazon-q","windsurf","orca","vscode"]:e.startsWith(".vscode/")?["vscode"]:["agents"]}function Wt(e){return [{target:"agents",path:`.agents/skills/${e}/SKILL.md`},{target:"copilot",path:`.github/skills/${e}/SKILL.md`},{target:"claude",path:`.claude/skills/${e}/SKILL.md`},{target:"cursor",path:`.cursor/skills/${e}/SKILL.md`},{target:"grok",path:`.grok/skills/${e}/SKILL.md`}]}async function gr(e,t){let r=i$1.join(e,t);!await k.pathExists(r)||!(await k.readFile(r,"utf8")).includes(se)||await k.remove(r);}function mr(e,t){return Tt().presets[t].requiredOutputs.includes(e)}async function fr(e,t){if(t)return t;let r=await d(e,k$2)??i$1.join(e,k$2);if(await k.pathExists(r))try{let a=await k.readJson(r);return b$5(k$2,a,r),a}catch{}return p$1({workspacePath:e,includeEvidence:true})}function kr(e){return e.length>0&&!i$1.isAbsolute(e)&&!e.split(/[\\/]+/).includes("..")}function hr(e){return Object.fromEntries(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"].map(r=>[r,{enabled:e.targets.includes("all")||e.targets.includes(r),outputs:e.outputs.filter(a=>a.targets.includes(r)).map(a=>a.path).sort()}]))}async function wr(e,t){try{if(!await k.pathExists(e))return {payload:null,exists:false,validity:"missing"};let r=await k.readJson(e),a=Qe(r);return a?a$1(t)?(b$5(t,a,e),{payload:a,exists:true,validity:"valid"}):{payload:a,exists:true,validity:"uncontracted"}:{payload:null,exists:true,validity:"invalid",validationError:"Artifact root must be a JSON object"}}catch(r){return {payload:null,exists:true,validity:"invalid",validationError:r instanceof Error?r.message:String(r)}}}async function jt(e){let t=e.now??new Date,r=e.staleAfterHours??24,a=[],s=[];for(let o of U){let w=await d(e.workspacePath,o.relativePath)??i$1.join(e.workspacePath,o.relativePath),m=await wr(w,o.relativePath),g=m.payload;m.validity==="invalid"?s.push(`Invalid evidence contract: ${o.relativePath}`):g&&s.push(...nr(g)),a.push({path:o.relativePath,label:o.label,required:o.required,exists:m.exists,validity:m.validity,validationError:m.validationError,generatedAt:g?or(g):void 0,commandId:typeof g?.commandId=="string"?g.commandId:void 0,exitCode:typeof g?.exitCode=="number"?g.exitCode:void 0});}let d$1=ar(s).slice(0,16),u=b$2();return {schemaVersion:Zt,generatedAt:t.toISOString(),workspaceRoot:await rr(e.workspacePath),intelligenceChain:{schemaVersion:u.schemaVersion,contractPath:u.contractPath,currentStep:"agent-sync"},readOrder:tr(),blockers:d$1,staleAfterHours:r,reports:a,refreshCommand:A("workspace agent-sync --write --refresh-context")}}function Ar(e$1){let t=["# Workspai agent grounding","","Cross-tool instructions for Copilot, Cursor, Claude Code, Codex, Grok, and other agents.","","## Read order (mandatory before workspace diagnosis)","",`1. \`${e.agentIndex}\` \u2014 latest blockers, timestamps, and report paths`,`2. \`${i.goalIndex}\` \u2014 when present, read the active Goal Pack and its handoff before choosing work.`,`3. \`${e.agentContext}\` \u2014 read only task-relevant context`,`4. \`${e.skillsIndex}\` \u2014 select only the Skill that matches the task.`,"5. Read only the task-relevant evidence artifacts listed in the index.","6. Use the Goal Pack retrieval queries, `workspace graph search <query> --limit 12 --json`, or MCP `searchWorkspaceGraph` before loading the full graph.","","Do **not** full-repo scan or inject the complete graph when a bounded query can answer the task.","","## Regenerate intelligence","","```bash",A("workspace agent-sync --write --refresh-context"),A("workspace context --for-agent --json --write"),A("pipeline --json --write"),"```",""];if(e$1.index.blockers.length>0){t.push("## Current blockers","");for(let r of e$1.index.blockers.slice(0,12))t.push(`- ${r}`);t.push("");}if(e$1.context?.safeCommands?.length){t.push("## Safe commands (prefer these)","");for(let r of e$1.context.safeCommands.slice(0,10))t.push(`- \`${r.display}\` \u2014 ${r.description}`);t.push("");}return t.push("## Rules","","- Treat `.workspai/reports/*` as the source of truth for health, gates, and release posture.","- Prefer deterministic Workspai CLI commands over heuristic framework guesses.","- If evidence is missing or stale, run the refresh commands above before proposing fixes.","- Keep project-scoped advice aligned with the active project named in the context pack.","- Never claim that an active goal is satisfied until its CLI-owned verification lifecycle is `verified`.",""),t.join(`
8
+ `,"utf8"),r.push(s);}return r}var Qt="workspai-agent-customization-pack-capabilities.v1";function Tt(){return {schemaVersion:Qt,presets:{minimal:{meaning:"Generate the portable grounding index, AGENTS.md, and provider-specific lightweight instructions.",requiredOutputs:[e.agentIndex,e.agentCustomizationPack,e.agents]},enterprise:{meaning:"Generate the full VS Code-native pack: instructions, prompts, skills, custom agents, and validation metadata.",requiredOutputs:[e.agentIndex,e.agentCustomizationPack,e.agents,w,A$1,M,".github/agents/workspai-advisor.agent.md",S,b$1]}},targets:{all:{meaning:"Generate every supported customization surface.",outputFamilies:["portable","vscode","copilot","cursor","claude","gemini","qwen","kimi","grok","windsurf","amazon-q"]},vscode:{meaning:"Generate VS Code-native customizations for Copilot Chat and agent workflows.",outputFamilies:["instructions","prompts","skills","agents","hooks"]},agents:{meaning:"Generate portable AGENTS.md grounding for any agent.",outputFamilies:["portable"]},copilot:{meaning:"Generate GitHub Copilot instructions, prompts, and skills.",outputFamilies:["instructions","prompts","skills"]},cursor:{meaning:"Generate Cursor rules.",outputFamilies:["rules"]},claude:{meaning:"Generate Claude Code grounding files.",outputFamilies:["rules","portable"]},codex:{meaning:"Use AGENTS.md and the report index as the Codex grounding layer.",outputFamilies:["portable"]},gemini:{meaning:"Generate Gemini CLI grounding through GEMINI.md and canonical AGENTS.md.",outputFamilies:["adapter","portable"]},qwen:{meaning:"Generate Qwen Code grounding through QWEN.md and canonical AGENTS.md.",outputFamilies:["adapter","portable"]},kimi:{meaning:"Use AGENTS.md and the report index as the Kimi Code grounding layer.",outputFamilies:["portable"]},grok:{meaning:"Use AGENTS.md and the report index as the xAI Grok grounding layer.",outputFamilies:["portable"]},windsurf:{meaning:"Use AGENTS.md and the report index as the Windsurf grounding layer.",outputFamilies:["portable"]},"amazon-q":{meaning:"Generate an Amazon Q project rule that routes agents to canonical evidence.",outputFamilies:["rules","portable"]},orca:{meaning:"Legacy compatibility alias for AGENTS.md consumers; prefer the grok target.",outputFamilies:["portable"]}},standardAnswerContract:[...ie],requiredReports:V.map(e=>({path:e.relativePath,label:e.label,required:e.required})),strictRules:["Required reports must exist.","Generated report paths must stay inside the workspace root.","Generated customization text must be English-only.","Agent answers must not claim pass, ready, or healthy without cited evidence.","Commands must distinguish display guidance from execution requests.","Agent hook files must be advisory and disabled by default unless the user explicitly enables them.","MCP design artifacts must stay read-mostly until write tools have explicit approval boundaries."],outputKinds:["report","grounding","instruction","prompt","skill","skill-resource","operational-skill","skills-index","explain-report","agent","rule","hook","mcp-design"],pathLayers:{l1CanonicalRoots:[".workspai/reports/",`${a$2}/`],l2PrefixedMirrorRoots:[".github/",".cursor/",".claude/",".amazonq/"],l3SharedIndustryFiles:["AGENTS.md",".github/copilot-instructions.md","CLAUDE.md","GEMINI.md","QWEN.md"]}}}var Zt=f.agentIndex,er=f.agentCustomizationPack,z=e.agentIndex,F=e.agentCustomizationPack;var V=[{relativePath:i.goalIndex,label:"Active Goal Pack index",required:false},{relativePath:i.goalPackLastRun,label:"Latest governed Goal Pack",required:false},{relativePath:b,label:"Agent context pack",required:true},{relativePath:b$1,label:"Operational skills index",required:true},{relativePath:e.model,label:"Workspace model",required:false},{relativePath:e.knowledgeGraph,label:"Workspace knowledge graph",required:false},{relativePath:e.evaluationLastRun,label:"Workspace Intelligence evaluation",required:false},{relativePath:e.doctor,label:"Workspace doctor",required:false},{relativePath:i.doctorProject,label:"Project doctor",required:false},{relativePath:i.doctorRemediationPlan,label:"Doctor remediation plan",required:false},{relativePath:i.artifactRemediationPlan,label:"Artifact remediation plan",required:false},{relativePath:i.doctorFixResult,label:"Doctor fix result",required:false},{relativePath:e.analyze,label:"Workspace analyze",required:false},{relativePath:i.pipelineLastRun,label:"Governance pipeline",required:false},{relativePath:e.readiness,label:"Release readiness",required:false},{relativePath:e.impact,label:"Workspace impact",required:false},{relativePath:e.verify,label:"Workspace verify",required:false},{relativePath:e.snapshot,label:"Workspace model snapshot",required:false},{relativePath:e.diff,label:"Workspace model diff",required:false},{relativePath:e.explain,label:"Workspace explain",required:false},{relativePath:e.contractVerify,label:"Workspace contract verify",required:false},{relativePath:e.history,label:"Workspace intelligence history",required:false}];function tr(){let e=V.map(r=>r.relativePath),t=b$2().consumers.agents.canonicalReadOrder;return [...new Set(t.filter(r=>r!==z&&e.includes(r)))]}async function rr(e){try{let{contract:t}=await m({workspacePath:e});if(t?.workspace?.name)return `workspace:${t.workspace.name}`}catch{}for(let t of [".workspai/workspace.json",".rapidkit/workspace.json"])try{let r=await k.readJson(i$1.join(e,t)),a=typeof r.workspace_name=="string"?r.workspace_name:typeof r.name=="string"?r.name:null;if(a?.trim())return `workspace:${a.trim()}`}catch{}return `workspace:${i$1.basename(i$1.resolve(e))}`}function A(e){return `npx workspai ${e}`.trim()}function Ze(e){return e&&typeof e=="object"?e:null}function Je(e,t=12){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0).slice(0,t):[]}function nr(e){let t=Je(e.blockers,12);if(t.length>0)return t;let r=Je(e.blockingReasons,12);if(r.length>0)return r;let a=Ze(e.summary);return a&&Array.isArray(a.blockingReasons)?Je(a.blockingReasons,12):[]}function ar(e){let t=[...new Set(e.map(r=>r.trim()).filter(Boolean))];return t.filter(r=>{let a=r.toLowerCase();return !t.some(s=>{if(s===r||!s.includes(":"))return false;let d=s.toLowerCase();return d.length>a.length&&d.endsWith(a)})})}function or(e){for(let t of ["generatedAt","updatedAt","timestamp"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}if(Array.isArray(e.entries)){let t=e.entries.map(r=>Ze(r)?.generatedAt).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim()).filter(r=>Number.isFinite(Date.parse(r)));if(t.length>0)return t.reduce((r,a)=>Date.parse(a)>Date.parse(r)?a:r)}}function ir(e,t,r){if(!e)return true;let a=Date.parse(e);return Number.isFinite(a)?r.getTime()-a>t*60*60*1e3:true}function sr(e$1,t,r){return e$1.path===e.snapshot?false:ir(e$1.generatedAt,t,r)}function cr(e){let t=e&&e.length>0?e:["all"];return t.includes("all")?new Set(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"]):new Set(t)}function R(e,t){return e.has("all")||e.has(t)}function $t(e){return R(e,"copilot")||R(e,"vscode")}function lr(e,t){return t==="generic"?R(e,"agents"):t==="copilot"?$t(e):t==="grok"?R(e,"grok")||R(e,"orca"):R(e,t)}function dr(e){return e??"enterprise"}function pr(e){return e===b$1?"skills-index":e.includes("workspace-explain-last-run.json")?"explain-report":(e.startsWith(`${a$2}/`)||e.startsWith(".rapidkit/skills/"))&&e.endsWith(".md")?"operational-skill":e.includes("hooks")||e===U||e===V$1?"hook":e.includes("mcp")||e===S||e===T?"mcp-design":e.endsWith(".json")?"report":e.includes("/instructions/")||e.endsWith("copilot-instructions.md")?"instruction":e.includes("/prompts/")?"prompt":e.includes("/skills/")&&e.endsWith("/SKILL.md")?"skill":e.includes("/skills/")?"skill-resource":e.includes("/agents/")?"agent":e.includes("/rules/")||e.endsWith(".mdc")?"rule":"grounding"}function ur(e){return e.startsWith(".github/")?["vscode","copilot"]:e.startsWith(".cursor/")?["cursor"]:e.startsWith(".claude/")||e==="CLAUDE.md"?["claude"]:e==="GEMINI.md"?["gemini"]:e==="QWEN.md"?["qwen"]:e.startsWith(".amazonq/")?["amazon-q"]:e===".windsurfrules"||e.startsWith(".windsurf/")?["windsurf"]:e.startsWith(".grok/")?["grok"]:e.startsWith(".agents/")?["codex","kimi","grok","orca"]:e==="AGENTS.md"||e.startsWith(".rapidkit/")?["agents","codex","kimi","grok","copilot","cursor","claude","gemini","qwen","amazon-q","windsurf","orca","vscode"]:e.startsWith(".vscode/")?["vscode"]:["agents"]}function Wt(e){return [{target:"agents",path:`.agents/skills/${e}/SKILL.md`},{target:"copilot",path:`.github/skills/${e}/SKILL.md`},{target:"claude",path:`.claude/skills/${e}/SKILL.md`},{target:"cursor",path:`.cursor/skills/${e}/SKILL.md`},{target:"grok",path:`.grok/skills/${e}/SKILL.md`}]}async function gr(e,t){let r=i$1.join(e,t);!await k.pathExists(r)||!(await k.readFile(r,"utf8")).includes(ce)||await k.remove(r);}function mr(e,t){return Tt().presets[t].requiredOutputs.includes(e)}async function fr(e,t){if(t)return t;let r=await d(e,k$2)??i$1.join(e,k$2);if(await k.pathExists(r))try{let a=await k.readJson(r);return b$5(k$2,a,r),a}catch{}return p$1({workspacePath:e,includeEvidence:true})}function kr(e){return e.length>0&&!i$1.isAbsolute(e)&&!e.split(/[\\/]+/).includes("..")}function hr(e){return Object.fromEntries(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"].map(r=>[r,{enabled:e.targets.includes("all")||e.targets.includes(r),outputs:e.outputs.filter(a=>a.targets.includes(r)).map(a=>a.path).sort()}]))}async function wr(e,t){try{if(!await k.pathExists(e))return {payload:null,exists:false,validity:"missing"};let r=await k.readJson(e),a=Ze(r);return a?a$1(t)?(b$5(t,a,e),{payload:a,exists:true,validity:"valid"}):{payload:a,exists:true,validity:"uncontracted"}:{payload:null,exists:true,validity:"invalid",validationError:"Artifact root must be a JSON object"}}catch(r){return {payload:null,exists:true,validity:"invalid",validationError:r instanceof Error?r.message:String(r)}}}async function jt(e){let t=e.now??new Date,r=e.staleAfterHours??24,a=[],s=[];for(let o of V){let w=await d(e.workspacePath,o.relativePath)??i$1.join(e.workspacePath,o.relativePath),m=await wr(w,o.relativePath),g=m.payload;m.validity==="invalid"?s.push(`Invalid evidence contract: ${o.relativePath}`):g&&s.push(...nr(g)),a.push({path:o.relativePath,label:o.label,required:o.required,exists:m.exists,validity:m.validity,validationError:m.validationError,generatedAt:g?or(g):void 0,commandId:typeof g?.commandId=="string"?g.commandId:void 0,exitCode:typeof g?.exitCode=="number"?g.exitCode:void 0});}let d$1=ar(s).slice(0,16),u=b$2();return {schemaVersion:Zt,generatedAt:t.toISOString(),workspaceRoot:await rr(e.workspacePath),intelligenceChain:{schemaVersion:u.schemaVersion,contractPath:u.contractPath,currentStep:"agent-sync"},readOrder:tr(),blockers:d$1,staleAfterHours:r,reports:a,refreshCommand:A("workspace agent-sync --write --refresh-context")}}function Ar(e$1){let t=["# Workspai agent grounding","","Cross-tool instructions for Copilot, Cursor, Claude Code, Codex, Grok, and other agents.","","## Read order (mandatory before workspace diagnosis)","",`1. \`${e.agentIndex}\` \u2014 latest blockers, timestamps, and report paths`,`2. \`${i.goalIndex}\` \u2014 when present, read the active Goal Pack and its handoff before choosing work.`,`3. \`${e.agentContext}\` \u2014 read only task-relevant context`,`4. \`${e.skillsIndex}\` \u2014 select only the Skill that matches the task.`,"5. Read only the task-relevant evidence artifacts listed in the index.","6. Use the Goal Pack retrieval queries, `workspace graph search <query> --limit 12 --json`, or MCP `searchWorkspaceGraph` before loading the full graph.","","Do **not** full-repo scan or inject the complete graph when a bounded query can answer the task.","","## Regenerate intelligence","","```bash",A("workspace agent-sync --write --refresh-context"),A("workspace context --for-agent --json --write"),A("pipeline --json --write"),"```",""];if(e$1.index.blockers.length>0){t.push("## Current blockers","");for(let r of e$1.index.blockers.slice(0,12))t.push(`- ${r}`);t.push("");}if(e$1.context?.safeCommands?.length){t.push("## Safe commands (prefer these)","");for(let r of e$1.context.safeCommands.slice(0,10))t.push(`- \`${r.display}\` \u2014 ${r.description}`);t.push("");}return t.push("## Rules","","- Treat `.workspai/reports/*` as the source of truth for health, gates, and release posture.","- Prefer deterministic Workspai CLI commands over heuristic framework guesses.","- If evidence is missing or stale, run the refresh commands above before proposing fixes.","- Keep project-scoped advice aligned with the active project named in the context pack.","- Never claim that an active goal is satisfied until its CLI-owned verification lifecycle is `verified`.",""),t.join(`
9
9
  `)}function Rr(e$1){return ["# Workspai agent grounding","",`Generated: ${e$1.generatedAt}`,"",`This file is tool-agnostic. Synced agents should read it together with \`${e.agentIndex}\`.`,"","## Mandatory read order","",...e$1.readOrder.map((t,r)=>`${r+1}. \`${t}\``),"",e$1.blockers.length>0?"## Blockers":"",...e$1.blockers.length>0?e$1.blockers.map(t=>`- ${t}`):[],"","## Refresh","","```bash",e$1.refreshCommand,"```",""].filter(t=>t!=="").join(`
10
10
  `)}function Pr(){return ["# Workspai workspace grounding","","Before answering workspace, release, or architecture questions:","","1. Read `AGENTS.md` (managed Workspai section).",`2. Read \`${e.agentIndex}\` and only task-relevant context from \`${e.agentContext}\`.`,"3. Use bounded `workspace graph search` or MCP `searchWorkspaceGraph` before scanning the full repository.","","Regenerate stale intelligence:","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""].join(`
11
- `)}function vr(){return ["## Claude Code","",`- Load \`${e.agentIndex}\` before diagnosing blockers.`,"- Use `.claude/rules/workspai-evidence.md` for scoped Workspai evidence rules.","- Treat `.claude/rules/rapidkit-evidence.md` as a legacy compatibility mirror.","- Refresh grounding with `npx workspai workspace agent-sync --write`.",""].join(`
12
- `)}function Je(e$1){return [`## ${e$1}`,"","- Treat `AGENTS.md` as the portable workspace instruction authority.",`- Load \`${e.agentIndex}\` before diagnosing blockers or architecture.`,`- Read only task-relevant context from \`${e.agentContext}\`.`,"- Use bounded Workspace Knowledge Graph search before broad source discovery.","- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.","- Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","- Refresh grounding with `workspai workspace agent-sync --write --refresh-context`.",""].join(`
13
- `)}function Sr(){return ["---","description: Workspai workspace evidence and intelligence grounding","globs: []","alwaysApply: true","---","","# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Read order","",`1. Read \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Read only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context and evidence.`,"- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","- Do not translate unsupported stack requests into unrelated native kits.","","## Intelligent loop","","When applying changes, follow the full repair loop:","","1. Discover \u2014 read bounded workspace context, select a matching Skill, and query the graph for the task.","2. Inspect \u2014 read relevant evidence and source files.","3. Patch \u2014 apply changes through the CLI-owned repair transaction.","4. Verify \u2014 run verification to confirm workspace health.","5. Complete \u2014 only after verified evidence confirms success.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh when stale","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""].join(`
11
+ `)}function Sr(){return ["## Claude Code","",`- Load \`${e.agentIndex}\` before diagnosing blockers.`,"- Use `.claude/rules/workspai-evidence.md` for scoped Workspai evidence rules.","- Treat `.claude/rules/rapidkit-evidence.md` as a legacy compatibility mirror.","- Refresh grounding with `npx workspai workspace agent-sync --write`.",""].join(`
12
+ `)}function Be(e$1){return [`## ${e$1}`,"","- Treat `AGENTS.md` as the portable workspace instruction authority.",`- Load \`${e.agentIndex}\` before diagnosing blockers or architecture.`,`- Read only task-relevant context from \`${e.agentContext}\`.`,"- Use bounded Workspace Knowledge Graph search before broad source discovery.","- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.","- Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","- Refresh grounding with `workspai workspace agent-sync --write --refresh-context`.",""].join(`
13
+ `)}function vr(){return ["---","description: Workspai workspace evidence and intelligence grounding","globs: []","alwaysApply: true","---","","# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Read order","",`1. Read \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Read only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context and evidence.`,"- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","- Do not translate unsupported stack requests into unrelated native kits.","","## Intelligent loop","","When applying changes, follow the full repair loop:","","1. Discover \u2014 read bounded workspace context, select a matching Skill, and query the graph for the task.","2. Inspect \u2014 read relevant evidence and source files.","3. Patch \u2014 apply changes through the CLI-owned repair transaction.","4. Verify \u2014 run verification to confirm workspace health.","5. Complete \u2014 only after verified evidence confirms success.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh when stale","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""].join(`
14
14
  `)}function yr(){return ["---","description: Workspai evidence artifact discipline",'globs: [".workspai/**", "**/.workspai/**", ".rapidkit/**", "**/.rapidkit/**"]',"alwaysApply: false","---","","When reading or editing `.workspai/` or legacy `.rapidkit/` artifacts:","",`- Start from \`${e.agentIndex}\` for read order and active blockers.`,"- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.","- JSON files (.json) require strictly valid JSON. Never include comments, trailing commas, or non-standard syntax.","","Regenerate evidence:","","```bash",A("workspace intelligence run"),"```",""].join(`
15
- `)}function Ze(e$1){return ["---",`description: ${e$1.description}`,`globs: ${e$1.globs}`,"alwaysApply: false","---","",e$1.objective,"","Read first:","",`- \`${e.agentIndex}\``,`- \`${e.agentContext}\``,"- Any report referenced by the current blocker or task","","Steps:","",...e$1.steps.map((t,r)=>`${r+1}. ${t}`),"","Use the standard Workspai answer contract: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
16
- `)}function br(){return Ze({description:"Diagnose Workspai workspace blockers from evidence reports",globs:"[]",objective:"Diagnose this workspace using Workspai evidence only.",steps:["Root cause grounded in report blockers","Smallest safe fix path (commands + file edits)","One verification command to prove recovery"]})}function Ir(){return Ze({description:"Repair Workspai blockers with evidence and verification",globs:"[]",objective:"Plan the smallest safe repair for the current Workspai blocker.",steps:["Blocker and affected workspace/project scope","Evidence paths and exact failing signals","Minimal fix plan","Human-run commands","Verification command and expected success signal"]})}function Er(){return Ze({description:"Assess Workspai release readiness from evidence",globs:"[]",objective:"Assess whether this workspace is release-ready using Workspai gates.",steps:["Readiness verdict with cited reports","Blocking gates","Safe next command","Verification checklist"]})}function xr(){return ["---","trigger: always_on","description: Workspai workspace evidence and intelligence grounding","---","","# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Read order","",`1. \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context.`,"- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh when stale","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""].join(`
15
+ `)}function et(e$1){return ["---",`description: ${e$1.description}`,`globs: ${e$1.globs}`,"alwaysApply: false","---","",e$1.objective,"","Read first:","",`- \`${e.agentIndex}\``,`- \`${e.agentContext}\``,"- Any report referenced by the current blocker or task","","Steps:","",...e$1.steps.map((t,r)=>`${r+1}. ${t}`),"","Use the standard Workspai answer contract: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
16
+ `)}function br(){return et({description:"Diagnose Workspai workspace blockers from evidence reports",globs:"[]",objective:"Diagnose this workspace using Workspai evidence only.",steps:["Root cause grounded in report blockers","Smallest safe fix path (commands + file edits)","One verification command to prove recovery"]})}function Ir(){return et({description:"Repair Workspai blockers with evidence and verification",globs:"[]",objective:"Plan the smallest safe repair for the current Workspai blocker.",steps:["Blocker and affected workspace/project scope","Evidence paths and exact failing signals","Minimal fix plan","Human-run commands","Verification command and expected success signal"]})}function Er(){return et({description:"Assess Workspai release readiness from evidence",globs:"[]",objective:"Assess whether this workspace is release-ready using Workspai gates.",steps:["Readiness verdict with cited reports","Blocking gates","Safe next command","Verification checklist"]})}function xr(){return ["---","trigger: always_on","description: Workspai workspace evidence and intelligence grounding","---","","# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Read order","",`1. \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context.`,"- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh when stale","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""].join(`
17
17
  `)}function Cr(){return ["---","trigger: glob","description: Workspai evidence artifact discipline",'globs: [".workspai/**", ".rapidkit/**"]',"---","","When reading or editing `.workspai/` or legacy `.rapidkit/` artifacts:","",`- Start from \`${e.agentIndex}\` for read order and active blockers.`,"- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.","- JSON files (.json) require strictly valid JSON. No comments, no trailing commas.",""].join(`
18
- `)}function _r(){return ["# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Read order","",`1. \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context.`,"- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh when stale","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""].join(`
19
- `)}function Or(){return ["# Workspai evidence artifact discipline","","Applies when reading or editing `.workspai/` or legacy `.rapidkit/` artifacts.","",`- Start from \`${e.agentIndex}\` for read order and active blockers.`,"- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.","- JSON files (.json) require strictly valid JSON. No comments, no trailing commas.","","Regenerate evidence:","","```bash",A("workspace intelligence run"),"```",""].join(`
18
+ `)}function Or(){return ["# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Read order","",`1. \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context.`,"- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh when stale","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""].join(`
19
+ `)}function _r(){return ["# Workspai evidence artifact discipline","","Applies when reading or editing `.workspai/` or legacy `.rapidkit/` artifacts.","",`- Start from \`${e.agentIndex}\` for read order and active blockers.`,"- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.","- JSON files (.json) require strictly valid JSON. No comments, no trailing commas.","","Regenerate evidence:","","```bash",A("workspace intelligence run"),"```",""].join(`
20
20
  `)}function Tr(){return ["# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Read order","",`1. \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context.`,"- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
21
21
  `)}function Wr(){return ["# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Read order","",`1. \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context.`,"- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","- Do not translate unsupported stack requests into unrelated native kits.","","## Evidence discipline","","- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.","- JSON files (.json) require strictly valid JSON. No comments, no trailing commas.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh when stale","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""].join(`
22
22
  `)}function jr(){return ["# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Read order","",`1. \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context and evidence.`,"- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","","## Intelligent loop","","When applying changes, follow the full repair loop:","","1. Discover \u2014 read bounded workspace context, select a matching Skill, and query the graph for the task.","2. Inspect \u2014 read relevant evidence and source files.","3. Patch \u2014 apply changes through the CLI-owned repair transaction.","4. Verify \u2014 run verification to confirm workspace health.","5. Complete \u2014 only after verified evidence confirms success.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh when stale","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""].join(`
@@ -27,23 +27,23 @@ ${o}`;e.write&&await k.writeFile(d,`${w.trimEnd()}
27
27
  `)}function Dr(){return ["---","description: Legacy RapidKit metadata compatibility alias",'globs: [".rapidkit/**", "**/.rapidkit/**"]',"alwaysApply: false","---","","Use `.cursor/rules/workspai-grounding.mdc` for canonical Workspai grounding.",""].join(`
28
28
  `)}function Nt(e){return ["---",'applyTo: ".rapidkit/**,**/.rapidkit/**"',"description: Legacy RapidKit metadata compatibility alias","---","",`Use \`.github/instructions/workspai-${e}.instructions.md\` as the canonical Workspai instruction.`,""].join(`
29
29
  `)}function Lt(){return ["---","description: Diagnose Workspai workspace blockers from evidence reports","---","","Diagnose this workspace using Workspai evidence only.","","Read:","",`- \`${e.agentIndex}\``,`- \`${e.agentContext}\``,"- Any fail/warn reports referenced in the index","","Return:","","1. Root cause grounded in report blockers","2. Smallest safe fix path (commands + file edits)","3. One verification command to prove recovery",""].join(`
30
- `)}function ce(e$1){return ["---",`description: ${e$1.description}`,"---","",e$1.objective,"","Read first:","",`- \`${e.agentIndex}\``,`- \`${e.agentContext}\``,"- Any report referenced by the current blocker or task","","Return:","",...e$1.expectedOutput.map((t,r)=>`${r+1}. ${t}`),"","Use the standard Workspai answer contract: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
31
- `)}function L(e){return ["# "+e.title,"",...e.lines,""].join(`
32
- `)}function Kr(){return L({title:"MCP Tool Design",lines:["Workspai MCP is a read-mostly bridge over contract-validated workspace artifacts.","","Candidate read tools:",`- \`getWorkspaceModel\` \u2014 read \`${e.model}\`.`,`- \`getWorkspaceKnowledgeGraph\` \u2014 read \`${e.knowledgeGraph}\`.`,`- \`getWorkspaceEvaluation\` \u2014 read \`${e.evaluationLastRun}\` (or the live evaluation when requested).`,"- `queryWorkspaceEntities` \u2014 filter proof-backed graph entities by kind.","- `searchWorkspaceGraph` \u2014 retrieve bounded proof-backed context by text query.","- `getWorkspaceGraphEvidence` \u2014 resolve evidence for an entity or relation.","- `findWorkspaceGraphPath` \u2014 find a shortest proof-carrying relationship path.",`- \`getEvidenceIndex\` \u2014 read \`${e.agentIndex}\`.`,"- `getBlockers` \u2014 derive current blockers from INDEX and gate reports.","- `getSafeCommands` \u2014 read safe commands from `workspace-context-agent.json`.","- `getProjectContext` \u2014 return one project-scoped slice of the workspace model.","- `getArtifact` \u2014 read one explicit artifact path inside the workspace root.",`- \`listOperationalSkills\` \u2014 read \`${e.skillsIndex}\`.`,"- `getWorkspaceExplain` \u2014 read/build workspace explain for release-blocked or project scope.","- `refreshWorkspaceIntelligence` \u2014 explicit user-approved refresh command only.","","Write or repair tools require explicit approval boundaries and are intentionally not part of the first read-mostly design."]})}function qr(e$1){return `${JSON.stringify({schemaVersion:h$3.workspaiMcpDesign.schemaVersion,generatedAt:e$1.generatedAt,workspaceRoot:e$1.workspaceRef,status:"design-only",mode:"read-mostly",safety:{writeToolsEnabled:false,approvalRequiredForRefresh:true,artifactReadsMustStayInsideWorkspace:true},candidateTools:[{name:"getWorkspaceModel",reads:[e.model],mutates:false},{name:"getWorkspaceKnowledgeGraph",reads:[e.knowledgeGraph],mutates:false},{name:"getWorkspaceEvaluation",reads:[e.evaluationLive,e.evaluationLastRun],mutates:false},{name:"queryWorkspaceEntities",reads:[e.knowledgeGraph],mutates:false},{name:"searchWorkspaceGraph",reads:[e.knowledgeGraph],mutates:false},{name:"getWorkspaceGraphEvidence",reads:[e.knowledgeGraph],mutates:false},{name:"findWorkspaceGraphPath",reads:[e.knowledgeGraph],mutates:false},{name:"getEvidenceIndex",reads:[e.agentIndex],mutates:false},{name:"getBlockers",reads:[e.agentIndex,e.verify,i.pipelineLastRun],mutates:false},{name:"getSafeCommands",reads:[e.agentContext],mutates:false},{name:"getProjectContext",reads:[e.model,e.agentContext],mutates:false},{name:"getArtifact",reads:["requested workspace-relative artifact path"],mutates:false},{name:"listOperationalSkills",reads:[e.skillsIndex],mutates:false},{name:"getWorkspaceExplain",reads:[e.explain,e.verify,e.impact],mutates:false},{name:"refreshWorkspaceIntelligence",command:A("workspace agent-sync --write --refresh-context"),mutates:true,approvalRequired:true}]},null,2)}
30
+ `)}function le(e$1){return ["---",`description: ${e$1.description}`,"---","",e$1.objective,"","Read first:","",`- \`${e.agentIndex}\``,`- \`${e.agentContext}\``,"- Any report referenced by the current blocker or task","","Return:","",...e$1.expectedOutput.map((t,r)=>`${r+1}. ${t}`),"","Use the standard Workspai answer contract: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
31
+ `)}function G(e){return ["# "+e.title,"",...e.lines,""].join(`
32
+ `)}function Kr(){return G({title:"MCP Tool Design",lines:["Workspai MCP is a read-mostly bridge over contract-validated workspace artifacts.","","Candidate read tools:",`- \`getWorkspaceModel\` \u2014 read \`${e.model}\`.`,`- \`getWorkspaceKnowledgeGraph\` \u2014 read \`${e.knowledgeGraph}\`.`,`- \`getWorkspaceEvaluation\` \u2014 read \`${e.evaluationLastRun}\` (or the live evaluation when requested).`,"- `queryWorkspaceEntities` \u2014 filter proof-backed graph entities by kind.","- `searchWorkspaceGraph` \u2014 retrieve bounded proof-backed context by text query.","- `getWorkspaceGraphEvidence` \u2014 resolve evidence for an entity or relation.","- `findWorkspaceGraphPath` \u2014 find a shortest proof-carrying relationship path.",`- \`getEvidenceIndex\` \u2014 read \`${e.agentIndex}\`.`,"- `getBlockers` \u2014 derive current blockers from INDEX and gate reports.","- `getSafeCommands` \u2014 read safe commands from `workspace-context-agent.json`.","- `getProjectContext` \u2014 return one project-scoped slice of the workspace model.","- `getArtifact` \u2014 read one explicit artifact path inside the workspace root.",`- \`listOperationalSkills\` \u2014 read \`${e.skillsIndex}\`.`,"- `getWorkspaceExplain` \u2014 read/build workspace explain for release-blocked or project scope.","- `refreshWorkspaceIntelligence` \u2014 explicit user-approved refresh command only.","","Write or repair tools require explicit approval boundaries and are intentionally not part of the first read-mostly design."]})}function qr(e$1){return `${JSON.stringify({schemaVersion:h$3.workspaiMcpDesign.schemaVersion,generatedAt:e$1.generatedAt,workspaceRoot:e$1.workspaceRef,status:"design-only",mode:"read-mostly",safety:{writeToolsEnabled:false,approvalRequiredForRefresh:true,artifactReadsMustStayInsideWorkspace:true},candidateTools:[{name:"getWorkspaceModel",reads:[e.model],mutates:false},{name:"getWorkspaceKnowledgeGraph",reads:[e.knowledgeGraph],mutates:false},{name:"getWorkspaceEvaluation",reads:[e.evaluationLive,e.evaluationLastRun],mutates:false},{name:"queryWorkspaceEntities",reads:[e.knowledgeGraph],mutates:false},{name:"searchWorkspaceGraph",reads:[e.knowledgeGraph],mutates:false},{name:"getWorkspaceGraphEvidence",reads:[e.knowledgeGraph],mutates:false},{name:"findWorkspaceGraphPath",reads:[e.knowledgeGraph],mutates:false},{name:"getEvidenceIndex",reads:[e.agentIndex],mutates:false},{name:"getBlockers",reads:[e.agentIndex,e.verify,i.pipelineLastRun],mutates:false},{name:"getSafeCommands",reads:[e.agentContext],mutates:false},{name:"getProjectContext",reads:[e.model,e.agentContext],mutates:false},{name:"getArtifact",reads:["requested workspace-relative artifact path"],mutates:false},{name:"listOperationalSkills",reads:[e.skillsIndex],mutates:false},{name:"getWorkspaceExplain",reads:[e.explain,e.verify,e.impact],mutates:false},{name:"refreshWorkspaceIntelligence",command:A("workspace agent-sync --write --refresh-context"),mutates:true,approvalRequired:true}]},null,2)}
33
33
  `}function Hr(e$1){return `${JSON.stringify({schemaVersion:h$3.agentHooks.schemaVersion,generatedAt:e$1.generatedAt,workspaceRoot:e$1.workspaceRef,enabledByDefault:false,mode:"advisory",hooks:[{name:"workspai-pre-tool-use-workspace-boundary",event:"PreToolUse",purpose:"Block or warn on state-changing commands outside the active workspace root.",defaultAction:"warn",rules:["Allow read-only commands.","Warn before write/delete commands outside workspaceRoot.","Never run destructive commands without explicit user approval."]},{name:"workspai-post-tool-use-verify-suggestion",event:"PostToolUse",purpose:"Suggest non-destructive verification commands after edits.",defaultAction:"suggest",commands:[A("doctor workspace"),A("workspace verify --strict --json")]},{name:"workspai-user-prompt-submit-scope-hint",event:"UserPromptSubmit",purpose:"Inject lightweight workspace scope and evidence index hints.",defaultAction:"inject-context-hint",reads:[e.agentIndex,e.agentContext]}]},null,2)}
34
34
  `}function Gt(e$1){let t=["---","name: workspai-workspace-intelligence","description: Use Workspai workspace intelligence reports to answer, repair, verify, and release with evidence","---","","# Workspai Workspace Intelligence","","Use this skill for workspace architecture, project lifecycle, blocker repair, release readiness, agent grounding, and CI evidence questions.","","## Decision flow","","1. Load `resources/scope-model.md`.",`2. Load \`${e.agentIndex}\`.`,`3. Load \`${e.agentContext}\`.`,`4. Load \`${e.skillsIndex}\` when operational playbooks are needed.`,"5. Load the smallest evidence report required for the task.","6. Answer with Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Rules","","- Prefer Workspai reports over full-repo scans.","- Never claim a gate passed without a cited report.","- Separate display commands from execution requests.","- Keep project-scoped fixes inside the active project unless workspace evidence says otherwise.",""];return e$1?.trim()&&t.push(e$1.trim(),""),t.join(`
35
- `)}function le(e$1){return ["---",`name: ${e$1.name}`,`description: ${e$1.description}`,`tools: [${e$1.tools.map(t=>`'${t}'`).join(", ")}]`,"---","",`You are the ${e$1.name} agent for Workspai Workspace Intelligence.`,"",`Mode: ${e$1.mode}.`,"",`Start every task by reading \`${e.agentIndex}\` and \`${e.agentContext}\`.`,"","Use this answer contract:","","- Scope","- Evidence","- Diagnosis","- Fix Plan","- Run","- Verify","- Assumptions","","Do not invent health, readiness, or policy status. Cite report paths and command outputs.",""].join(`
36
- `)}function N(e$1){let t=["---","name: workspai-grounding","description: Load Workspai workspace intelligence reports before diagnosing or changing code","---","","# Workspai grounding","","Use when the user asks about workspace health, release gates, doctor/pipeline failures, or project structure.","","## Workflow","",`1. Read \`${e.agentIndex}\``,`2. Read \`${e.agentContext}\``,"3. Read fail/warn evidence artifacts listed in the index","4. Propose the smallest safe fix with explicit verification commands",""],r=e$1.model?.projects?.map(a=>a.name||a.slug).filter(Boolean).slice(0,10);if(r&&r.length>0){t.push("## Projects in this workspace","");for(let a of r)t.push(`- ${a}`);t.push("");}if(e$1.index.blockers.length>0){t.push("## Current blockers","");for(let a of e$1.index.blockers.slice(0,8))t.push(`- ${a}`);t.push("");}if(e$1.context?.safeCommands?.length){t.push("## Safe commands (prefer these)","");for(let a of e$1.context.safeCommands.slice(0,6))t.push(`- \`${a.display}\` \u2014 ${a.description}`);t.push("");}return t.push("## Rules","","- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.","- Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
37
- `)}async function p(e,t,r){return r?(await k.ensureDir(i$1.dirname(e)),await k.writeFile(e,t,"utf8"),"written"):"skipped"}async function Be(e){if(!e.write)return "skipped";await et(e.workspacePath,e.absolutePath);let t=await k.pathExists(e.absolutePath)?await k.readFile(e.absolutePath,"utf8"):null,{upsertManagedAgentSection:r}=await import('./managed-agent-markers-COE5DJ3W.js'),a=r(t,e.generatedBody),s=e.preamble?`${e.preamble.trimEnd()}
35
+ `)}function de(e$1){return ["---",`name: ${e$1.name}`,`description: ${e$1.description}`,`tools: [${e$1.tools.map(t=>`'${t}'`).join(", ")}]`,"---","",`You are the ${e$1.name} agent for Workspai Workspace Intelligence.`,"",`Mode: ${e$1.mode}.`,"",`Start every task by reading \`${e.agentIndex}\` and \`${e.agentContext}\`.`,"","Use this answer contract:","","- Scope","- Evidence","- Diagnosis","- Fix Plan","- Run","- Verify","- Assumptions","","Do not invent health, readiness, or policy status. Cite report paths and command outputs.",""].join(`
36
+ `)}function L(e$1){let t=["---","name: workspai-grounding","description: Load Workspai workspace intelligence reports before diagnosing or changing code","---","","# Workspai grounding","","Use when the user asks about workspace health, release gates, doctor/pipeline failures, or project structure.","","## Workflow","",`1. Read \`${e.agentIndex}\``,`2. Read \`${e.agentContext}\``,"3. Read fail/warn evidence artifacts listed in the index","4. Propose the smallest safe fix with explicit verification commands",""],r=e$1.model?.projects?.map(a=>a.name||a.slug).filter(Boolean).slice(0,10);if(r&&r.length>0){t.push("## Projects in this workspace","");for(let a of r)t.push(`- ${a}`);t.push("");}if(e$1.index.blockers.length>0){t.push("## Current blockers","");for(let a of e$1.index.blockers.slice(0,8))t.push(`- ${a}`);t.push("");}if(e$1.context?.safeCommands?.length){t.push("## Safe commands (prefer these)","");for(let a of e$1.context.safeCommands.slice(0,6))t.push(`- \`${a.display}\` \u2014 ${a.description}`);t.push("");}return t.push("## Rules","","- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.","- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.","- Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",A("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
37
+ `)}async function p(e,t,r){return r?(await k.ensureDir(i$1.dirname(e)),await k.writeFile(e,t,"utf8"),"written"):"skipped"}async function Ye(e){if(!e.write)return "skipped";await tt(e.workspacePath,e.absolutePath);let t=await k.pathExists(e.absolutePath)?await k.readFile(e.absolutePath,"utf8"):null,{upsertManagedAgentSection:r}=await import('./managed-agent-markers-COE5DJ3W.js'),a=r(t,e.generatedBody),s=e.preamble?`${e.preamble.trimEnd()}
38
38
 
39
- ${a}`:a;return await k.ensureDir(i$1.dirname(e.absolutePath)),await k.writeFile(e.absolutePath,s,"utf8"),"written"}async function Ye(e){if(!e.write)return "skipped";await et(e.workspacePath,e.absolutePath);let t=await k.pathExists(e.absolutePath)?await k.readFile(e.absolutePath,"utf8"):"",{upsertManagedAgentSection:r}=await import('./managed-agent-markers-COE5DJ3W.js'),a=r(t,e.generatedBody),s=a.includes(e.importLine)?a:`${e.importLine}
39
+ ${a}`:a;return await k.ensureDir(i$1.dirname(e.absolutePath)),await k.writeFile(e.absolutePath,s,"utf8"),"written"}async function Xe(e){if(!e.write)return "skipped";await tt(e.workspacePath,e.absolutePath);let t=await k.pathExists(e.absolutePath)?await k.readFile(e.absolutePath,"utf8"):"",{upsertManagedAgentSection:r}=await import('./managed-agent-markers-COE5DJ3W.js'),a=r(t,e.generatedBody),s=a.includes(e.importLine)?a:`${e.importLine}
40
40
 
41
- ${a}`;return await k.ensureDir(i$1.dirname(e.absolutePath)),await k.writeFile(e.absolutePath,s,"utf8"),"written"}async function et(e,t){let r=i$1.resolve(e),a=i$1.resolve(t),s=i$1.relative(r,a);if(!s||s===".."||s.startsWith(`..${i$1.sep}`)||i$1.isAbsolute(s))throw new Error("Agent output path must remain inside the canonical workspace.");let d=s.split(i$1.sep),u=r;for(let[o,w]of d.entries()){u=i$1.join(u,w);let m=await k.lstat(u).catch(I=>{if(I.code==="ENOENT")return null;throw I});if(!m)return;let g=o===d.length-1;if(m.isSymbolicLink()||(g?!m.isFile():!m.isDirectory()))throw new Error(`Agent output path is blocked by authored repository state: ${s}`)}}function $n(e){if(!e?.trim())return;let t=new Set(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"]),r=e.split(",").map(a=>a.trim().toLowerCase()).filter(a=>t.has(a));return r.length>0?r:void 0}function Mr(e){let t=[...e.outputs].sort((a,s)=>a.path.localeCompare(s.path)),r=b$2();return {schemaVersion:er,generatedAt:e.generatedAt,workspaceRoot:e.workspaceRef,preset:e.preset,targets:[...e.targets].sort(),sourceReports:e.index.reports.filter(a=>a.exists).map(a=>a.path).sort(),intelligenceChain:{schemaVersion:r.schemaVersion,contractPath:r.contractPath,currentStep:"agent-sync"},outputInventory:t,capabilityMatrix:hr({targets:e.targets,outputs:t}),drift:{missingRequired:e.missingRequired,staleReports:e.staleReports,strictViolations:e.strictViolations},answerContract:["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"],refreshCommand:A(`workspace agent-sync --write --refresh-context --preset ${e.preset}`),experimental:{hooksEnabled:e.experimentalHooks,mcpReady:t.some(a=>a.kind==="mcp-design")}}}async function Xe(e){let t$1=i$1.resolve(e.workspacePath),r$1=e.now??new Date,a=e.staleAfterHours??24,s$1=cr(e.targets),d=[...s$1].sort(),u$1=dr(e.preset),o$1=e.write===true,w$1=e.strict===true,m$2,g=null,I$1=e.model;e.refreshContext&&(I$1??=await p$1({workspacePath:t$1,includeEvidence:true}),g=await c({workspacePath:t$1,model:I$1,agent:e.agent??"generic",scope:e.scope,includeEvidence:true}),o$1&&(m$2=await d$1(g,t$1)));let x$1=[],de=[],pe=[],ue=[],l$1=(c,f)=>{c==="written"?de.push(f):pe.push(f),ue.push({path:f,kind:pr(f),targets:ur(f),required:mr(f,u$1),status:c==="written"?"written":e.dryRun?"planned":"skipped"});},ge="",C$1=await fr(t$1,I$1),me=null;try{me=(await m({workspacePath:t$1})).contract;}catch{me=null;}let Dt=xt({model:C$1,context:g,contract:me}),z$1=await Ct({workspacePath:t$1,skills:Dt,generatedAt:r$1.toISOString(),write:o$1});for(let c of z$1.skills){l$1(o$1?"written":"skipped",c.canonicalPath);for(let f of Wt(c.skillId))R(s$1,f.target)&&l$1(await p(i$1.join(t$1,f.path),c.markdown,o$1),f.path);}for(let c of z$1.removedSkillIds)for(let f of Wt(c))!R(s$1,f.target)||!o$1||await gr(t$1,f.path);l$1(o$1?"written":"skipped",b$1),ge=_t(z$1.index);let P$1=await jt({workspacePath:t$1,staleAfterHours:a,now:r$1});if(l$1(await p(i$1.join(t$1,F),`${JSON.stringify(P$1,null,2)}
42
- `,o$1),F),l$1(await p(i$1.join(t$1,f$2),`${Rr(P$1)}
43
- `,o$1),f$2),["agents","vscode","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"].some(c=>R(s$1,c))&&l$1(await Be({workspacePath:t$1,absolutePath:i$1.join(t$1,"AGENTS.md"),generatedBody:Ar({index:P$1,context:g}),write:o$1}),"AGENTS.md"),R(s$1,"claude")){let c=i$1.join(t$1,"CLAUDE.md");if(o$1){await et(t$1,c);let{upsertManagedAgentSection:f}=await import('./managed-agent-markers-COE5DJ3W.js'),h=await k.pathExists(c)?await k.readFile(c,"utf8"):"",S=f(h,vr()),_=S.includes("@AGENTS.md")?S:`@AGENTS.md
41
+ ${a}`;return await k.ensureDir(i$1.dirname(e.absolutePath)),await k.writeFile(e.absolutePath,s,"utf8"),"written"}async function tt(e,t){let r=i$1.resolve(e),a=i$1.resolve(t),s=i$1.relative(r,a);if(!s||s===".."||s.startsWith(`..${i$1.sep}`)||i$1.isAbsolute(s))throw new Error("Agent output path must remain inside the canonical workspace.");let d=s.split(i$1.sep),u=r;for(let[o,w]of d.entries()){u=i$1.join(u,w);let m=await k.lstat(u).catch(I=>{if(I.code==="ENOENT")return null;throw I});if(!m)return;let g=o===d.length-1;if(m.isSymbolicLink()||(g?!m.isFile():!m.isDirectory()))throw new Error(`Agent output path is blocked by authored repository state: ${s}`)}}function $n(e){if(!e?.trim())return;let t=new Set(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"]),r=e.split(",").map(a=>a.trim().toLowerCase()).filter(a=>t.has(a));return r.length>0?r:void 0}function Mr(e){let t=[...e.outputs].sort((a,s)=>a.path.localeCompare(s.path)),r=b$2();return {schemaVersion:er,generatedAt:e.generatedAt,workspaceRoot:e.workspaceRef,preset:e.preset,targets:[...e.targets].sort(),sourceReports:e.index.reports.filter(a=>a.exists).map(a=>a.path).sort(),intelligenceChain:{schemaVersion:r.schemaVersion,contractPath:r.contractPath,currentStep:"agent-sync"},outputInventory:t,capabilityMatrix:hr({targets:e.targets,outputs:t}),drift:{missingRequired:e.missingRequired,staleReports:e.staleReports,strictViolations:e.strictViolations},answerContract:["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"],refreshCommand:A(`workspace agent-sync --write --refresh-context --preset ${e.preset}`),experimental:{hooksEnabled:e.experimentalHooks,mcpReady:t.some(a=>a.kind==="mcp-design")}}}async function Qe(e){let t$1=i$1.resolve(e.workspacePath),r$1=e.now??new Date,a=e.staleAfterHours??24,s$1=cr(e.targets),d=[...s$1].sort(),u$1=dr(e.preset),o$1=e.write===true,w$1=e.strict===true,m$2,g=null,I$1=e.model;e.refreshContext&&(I$1??=await p$1({workspacePath:t$1,includeEvidence:true}),g=await c({workspacePath:t$1,model:I$1,agent:e.agent??"generic",scope:e.scope,includeEvidence:true}),o$1&&(m$2=await d$1(g,t$1)));let y$1=[],W=[],pe=[],ue=[],l$1=(c,f)=>{c==="written"?W.push(f):pe.push(f),ue.push({path:f,kind:pr(f),targets:ur(f),required:mr(f,u$1),status:c==="written"?"written":e.dryRun?"planned":"skipped"});},ge="",C$1=await fr(t$1,I$1),me=null;try{me=(await m({workspacePath:t$1})).contract;}catch{me=null;}let Dt=xt({model:C$1,context:g,contract:me}),J$1=await Ct({workspacePath:t$1,skills:Dt,generatedAt:r$1.toISOString(),write:o$1});for(let c of J$1.skills){l$1(o$1?"written":"skipped",c.canonicalPath);for(let f of Wt(c.skillId))R(s$1,f.target)&&l$1(await p(i$1.join(t$1,f.path),c.markdown,o$1),f.path);}for(let c of J$1.removedSkillIds)for(let f of Wt(c))!R(s$1,f.target)||!o$1||await gr(t$1,f.path);l$1(o$1?"written":"skipped",b$1),ge=Ot(J$1.index);let P$1=await jt({workspacePath:t$1,staleAfterHours:a,now:r$1});if(l$1(await p(i$1.join(t$1,z),`${JSON.stringify(P$1,null,2)}
42
+ `,o$1),z),l$1(await p(i$1.join(t$1,f$2),`${Rr(P$1)}
43
+ `,o$1),f$2),["agents","vscode","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"].some(c=>R(s$1,c))&&l$1(await Ye({workspacePath:t$1,absolutePath:i$1.join(t$1,"AGENTS.md"),generatedBody:Ar({index:P$1,context:g}),write:o$1}),"AGENTS.md"),R(s$1,"claude")){let c=i$1.join(t$1,"CLAUDE.md");if(o$1){await tt(t$1,c);let{upsertManagedAgentSection:f}=await import('./managed-agent-markers-COE5DJ3W.js'),h=await k.pathExists(c)?await k.readFile(c,"utf8"):"",v=f(h,Sr()),O=v.includes("@AGENTS.md")?v:`@AGENTS.md
44
44
 
45
- ${S}`;await k.ensureDir(i$1.dirname(c)),await k.writeFile(c,_,"utf8"),de.push("CLAUDE.md");}else pe.push("CLAUDE.md");l$1(await p(i$1.join(t$1,s),`${Gr()}
45
+ ${v}`;await k.ensureDir(i$1.dirname(c)),await k.writeFile(c,O,"utf8"),W.push("CLAUDE.md");}else pe.push("CLAUDE.md");l$1(await p(i$1.join(t$1,s),`${Gr()}
46
46
  `,o$1),s),l$1(await p(i$1.join(t$1,t),`${jr()}
47
47
  `,o$1),t),l$1(await p(i$1.join(t$1,u),`${$r()}
48
- `,o$1),u),l$1(await p(i$1.join(t$1,P),N({index:P$1,context:g,model:C$1}),o$1),P);}if(R(s$1,"gemini")&&l$1(await Ye({workspacePath:t$1,absolutePath:i$1.join(t$1,"GEMINI.md"),importLine:"@./AGENTS.md",generatedBody:Je("Gemini CLI"),write:o$1}),"GEMINI.md"),R(s$1,"qwen")&&l$1(await Ye({workspacePath:t$1,absolutePath:i$1.join(t$1,"QWEN.md"),importLine:"@AGENTS.md",generatedBody:Je("Qwen Code"),write:o$1}),"QWEN.md"),R(s$1,"amazon-q")&&(l$1(await Ye({workspacePath:t$1,absolutePath:i$1.join(t$1,".amazonq/rules/workspai-agent-entry.md"),importLine:"@../../AGENTS.md",generatedBody:Je("Amazon Q Developer"),write:o$1}),".amazonq/rules/workspai-agent-entry.md"),l$1(await p(i$1.join(t$1,v),Tr(),o$1),v)),R(s$1,"grok")&&(l$1(await p(i$1.join(t$1,q),_r(),o$1),q),l$1(await p(i$1.join(t$1,r),Or(),o$1),r),l$1(await p(i$1.join(t$1,R$1),N({index:P$1,context:g,model:C$1}),o$1),R$1)),R(s$1,"codex")&&l$1(await p(i$1.join(t$1,Q),N({index:P$1,context:g,model:C$1}),o$1),Q),R(s$1,"windsurf")&&(l$1(await Be({workspacePath:t$1,absolutePath:i$1.join(t$1,n),generatedBody:Wr(),write:o$1}),n),l$1(await p(i$1.join(t$1,o),xr(),o$1),o),l$1(await p(i$1.join(t$1,p$2),Cr(),o$1),p$2)),R(s$1,"cursor")&&(l$1(await p(i$1.join(t$1,h$2),Sr(),o$1),h$2),l$1(await p(i$1.join(t$1,i$2),yr(),o$1),i$2),l$1(await p(i$1.join(t$1,m$1),Dr(),o$1),m$1),u$1==="enterprise"&&(l$1(await p(i$1.join(t$1,j),br(),o$1),j),l$1(await p(i$1.join(t$1,k$1),Ir(),o$1),k$1),l$1(await p(i$1.join(t$1,l),Er(),o$1),l)),l$1(await p(i$1.join(t$1,O),N({index:P$1,context:g,model:C$1}),o$1),O)),$t(s$1)){if(l$1(await Be({workspacePath:t$1,absolutePath:i$1.join(t$1,".github/copilot-instructions.md"),generatedBody:Pr(),write:o$1}),".github/copilot-instructions.md"),l$1(await p(i$1.join(t$1,w),Lr(),o$1),w),l$1(await p(i$1.join(t$1,x),Nt("workspace"),o$1),x),l$1(await p(i$1.join(t$1,y),Nr(),o$1),y),l$1(await p(i$1.join(t$1,z),Nt("evidence"),o$1),z),l$1(await p(i$1.join(t$1,A$1),Lt(),o$1),A$1),l$1(await p(i$1.join(t$1,B),Lt(),o$1),B),u$1==="enterprise"){let c=[[C,ce({description:"Repair Workspai blockers with evidence and verification",objective:"Plan the smallest safe repair for the current Workspai blocker.",expectedOutput:["Blocker and affected workspace/project scope","Evidence paths and exact failing signals","Minimal fix plan","Human-run commands","Verification command and expected success signal"]})],[E,ce({description:"Assess Workspai release readiness from evidence",objective:"Assess whether this workspace is release-ready using Workspai gates.",expectedOutput:["Readiness verdict with cited reports","Blocking gates","Safe next command","Verification checklist"]})],[G,ce({description:"Onboard a project into Workspai Workspace Intelligence",objective:"Guide project onboarding using workspace model and create planner capabilities.",expectedOutput:["Target project scope","Native create, official generator, or existing lane","Safe commands","Post-onboarding verification"]})],[I,ce({description:"Adopt an existing project into Workspai governance",objective:"Adopt an existing project without changing its runtime behavior.",expectedOutput:["Detected stack and confidence","Adoption plan","Generated metadata expectations","Doctor and workspace model verification"]})]];for(let[h,S]of c)l$1(await p(i$1.join(t$1,h),S,o$1),h);let f=[[D,c[0][1]],[F$1,c[1][1]],[H,c[2][1]],[J,c[3][1]]];for(let[h,S]of f)l$1(await p(i$1.join(t$1,h),S,o$1),h);if(e.hydratePrompts===true)for(let h of await Ot({workspacePath:t$1,skills:z$1.skills,write:o$1}))l$1(o$1?"written":"skipped",h);}if(l$1(await p(i$1.join(t$1,K),N({index:P$1,context:g,model:C$1}),o$1),K),l$1(await p(i$1.join(t$1,L$1),N({index:P$1,context:g,model:C$1}),o$1),L$1),u$1==="enterprise"){l$1(await p(i$1.join(t$1,M),Gt(ge),o$1),M),l$1(await p(i$1.join(t$1,N$1),Gt(ge),o$1),N$1);let c=[["artifact-map.md",L({title:"Artifact Map",lines:U.map(h=>`- \`${h.relativePath}\` \u2014 ${h.label}`)})],["command-map.md",L({title:"Command Map",lines:["- `npx workspai workspace agent-sync --write --refresh-context` \u2014 refresh agent grounding.","- `npx workspai workspace model --json --write` \u2014 refresh workspace model.","- `npx workspai doctor workspace` \u2014 refresh health evidence.","- `npx workspai workspace verify --strict --json` \u2014 verify release gates."]})],["scope-model.md",L({title:"Scope Model",lines:["- Workspace scope is the default source of truth.","- Project scope is selected only when the active task targets a specific project.","- Always name the workspace and project when giving repair or lifecycle advice."]})],["runtime-support.md",L({title:"Runtime Support",lines:["- Native create is available only for Workspai-owned scaffold contracts.","- Unsupported stacks should use the official lane when a stable ecosystem generator exists.","- Existing projects should use the existing lane when native create is unavailable."]})],["create-planner-capabilities.md",L({title:"Create Planner Capabilities",lines:["- Use `contracts/create-planner-capabilities.v1.json` to decide native, official, or existing.","- Do not map PHP, WordPress, Laravel, Rails, or Symfony requests to unrelated native kits.","- Explain unsupported native create requests and guide users to adopt/import."]})],["mcp-tools.md",Kr()]];for(let[h,S]of c){let _=`${i$1.dirname(M)}/resources/${h}`;l$1(await p(i$1.join(t$1,_),S,o$1),_);let rt=`${i$1.dirname(N$1)}/resources/${h}`;l$1(await p(i$1.join(t$1,rt),S,o$1),rt);}let f=[["workspai-advisor.agent.md",le({name:"Workspai Advisor",description:"Read-only workspace and project guidance using Workspai evidence",mode:"read-only",tools:["search","read"]})],["workspai-repair.agent.md",le({name:"Workspai Repair",description:"Turn Workspai blockers into minimal fixes and verification steps",mode:"repair",tools:["search","read","edit"]})],["workspai-release.agent.md",le({name:"Workspai Release",description:"Assess readiness, governance gates, and release safety from evidence",mode:"release",tools:["search","read"]})],["workspai-project-onboarder.agent.md",le({name:"Workspai Project Onboarder",description:"Guide create, import, and adopt flows with Workspai contracts",mode:"onboard",tools:["search","read","edit"]})]];for(let[h,S]of f){let _=`.github/agents/${h}`;l$1(await p(i$1.join(t$1,_),S,o$1),_);}}}if(u$1==="enterprise"){let c=qr({workspaceRef:P$1.workspaceRoot,generatedAt:P$1.generatedAt});b$5(S,JSON.parse(c)),l$1(await p(i$1.join(t$1,S),c,o$1),S),l$1(await p(i$1.join(t$1,T),c,o$1),T);}if(u$1==="enterprise"&&e.experimentalHooks===true){let c=Hr({workspaceRef:P$1.workspaceRoot,generatedAt:P$1.generatedAt});b$5(U$1,JSON.parse(c)),l$1(await p(i$1.join(t$1,U$1),c,o$1),U$1),l$1(await p(i$1.join(t$1,V$1),c,o$1),V$1);}let J$1=o$1?await jt({workspacePath:t$1,staleAfterHours:a,now:r$1}):P$1,B$1=J$1.reports.filter(c=>c.required&&!c.exists).map(c=>c.path),Y=J$1.reports.filter(c=>c.exists&&sr(c,a,r$1)).map(c=>c.path);if(w$1){B$1.length>0&&x$1.push(`Missing required reports: ${B$1.join(", ")}`),Y.length>0&&x$1.push(`Stale reports (>${a}h): ${Y.join(", ")}`);let c=ue.map(f=>f.path).filter(f=>!kr(f));c.length>0&&x$1.push(`Unsafe generated output paths: ${c.join(", ")}`);}let W=o$1?await g$2({workspacePath:t$1,mode:e.projectGrounding??"managed",now:r$1}):void 0;if(w$1&&W&&W.skipped.length>0&&x$1.push(`Project grounding incomplete: ${W.skipped.map(c=>`${c.name} (${c.reason})`).join(", ")}`),w$1&&W){let c=W.projects.flatMap(f=>(f.hostCoverage??[]).filter(h=>h.status==="blocked"&&lr(s$1,h.id)).map(h=>`${i$1.basename(f.projectPath)}:${h.id}`));c.length>0&&x$1.push(`Project agent entry coverage blocked: ${c.join(", ")}`);}let tt=Mr({workspaceRef:J$1.workspaceRoot,generatedAt:r$1.toISOString(),preset:u$1,targets:d,index:J$1,outputs:[...ue,{path:V,kind:"report",targets:["agents","vscode","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"],required:true,status:o$1?"written":e.dryRun?"planned":"skipped"}],missingRequired:B$1,staleReports:Y,strictViolations:x$1,experimentalHooks:e.experimentalHooks===true});if(o$1&&process.env.WORKSPAI_TEST_FAIL_AGENT_SYNC_BEFORE_PACK==="1")throw new Error("Injected agent-sync failure before generation commit.");return l$1(await p(i$1.join(t$1,V),`${JSON.stringify(tt,null,2)}
49
- `,o$1),V),{workspacePath:t$1,indexPath:i$1.join(t$1,F),packPath:i$1.join(t$1,V),pack:tt,contextPath:m$2,writtenFiles:de,skippedFiles:pe,blockers:P$1.blockers,missingRequired:B$1,staleReports:Y,strictViolations:x$1,projectLenses:W}}async function Dn(e){if(e.write!==true)return Xe(e);let t=i$1.resolve(e.workspacePath),r=i$1.join(t,".workspai","transactions","agent-sync");await b$3(r);let a$1=await Xe({...e,write:false,dryRun:true});if(!a$1.pack)throw new Error("Agent-sync dry run did not produce an output inventory.");let s=[...a$1.pack.outputInventory.map(u=>u.path),F,V],d=await a({journalDirectory:r});try{for(let w of [...new Set(s)].sort()){let m=i$1.resolve(t,w),g=i$1.relative(t,m);if(g===".."||g.startsWith(`..${i$1.sep}`)||i$1.isAbsolute(g))throw new Error(`Agent-sync output escapes workspace root: ${w}`);await d.captureFile(m);}let u=await h(t);for(let w of u.resolved)for(let m of [f$1,g,h$1,b$4,...g$1,"AGENTS.md",".gitignore"])await d.captureFile(i$1.join(w.projectPath,m));let o=await Xe(e);return await d.commit(),o}catch(u){try{await d.rollback();}catch(o){throw new AggregateError([u,o],"Agent-sync generation failed and rollback was incomplete.")}throw u}}export{qt as a,Mt as b,Qt as c,Zt as d,er as e,F as f,V as g,U as h,tr as i,jt as j,$n as k,Dn as l};
48
+ `,o$1),u),l$1(await p(i$1.join(t$1,P),L({index:P$1,context:g,model:C$1}),o$1),P);}if(R(s$1,"gemini")&&l$1(await Xe({workspacePath:t$1,absolutePath:i$1.join(t$1,"GEMINI.md"),importLine:"@./AGENTS.md",generatedBody:Be("Gemini CLI"),write:o$1}),"GEMINI.md"),R(s$1,"qwen")&&l$1(await Xe({workspacePath:t$1,absolutePath:i$1.join(t$1,"QWEN.md"),importLine:"@AGENTS.md",generatedBody:Be("Qwen Code"),write:o$1}),"QWEN.md"),R(s$1,"amazon-q")&&(l$1(await Xe({workspacePath:t$1,absolutePath:i$1.join(t$1,".amazonq/rules/workspai-agent-entry.md"),importLine:"@../../AGENTS.md",generatedBody:Be("Amazon Q Developer"),write:o$1}),".amazonq/rules/workspai-agent-entry.md"),l$1(await p(i$1.join(t$1,v),Tr(),o$1),v)),R(s$1,"grok")&&(l$1(await p(i$1.join(t$1,q),Or(),o$1),q),l$1(await p(i$1.join(t$1,r),_r(),o$1),r),l$1(await p(i$1.join(t$1,R$1),L({index:P$1,context:g,model:C$1}),o$1),R$1)),R(s$1,"codex")&&l$1(await p(i$1.join(t$1,Q),L({index:P$1,context:g,model:C$1}),o$1),Q),R(s$1,"windsurf")&&(l$1(await Ye({workspacePath:t$1,absolutePath:i$1.join(t$1,n),generatedBody:Wr(),write:o$1}),n),l$1(await p(i$1.join(t$1,o),xr(),o$1),o),l$1(await p(i$1.join(t$1,p$2),Cr(),o$1),p$2)),R(s$1,"cursor")&&(l$1(await p(i$1.join(t$1,h$2),vr(),o$1),h$2),l$1(await p(i$1.join(t$1,i$2),yr(),o$1),i$2),l$1(await p(i$1.join(t$1,m$1),Dr(),o$1),m$1),u$1==="enterprise"&&(l$1(await p(i$1.join(t$1,j),br(),o$1),j),l$1(await p(i$1.join(t$1,k$1),Ir(),o$1),k$1),l$1(await p(i$1.join(t$1,l),Er(),o$1),l)),l$1(await p(i$1.join(t$1,O),L({index:P$1,context:g,model:C$1}),o$1),O)),$t(s$1)){if(l$1(await Ye({workspacePath:t$1,absolutePath:i$1.join(t$1,".github/copilot-instructions.md"),generatedBody:Pr(),write:o$1}),".github/copilot-instructions.md"),l$1(await p(i$1.join(t$1,w),Lr(),o$1),w),l$1(await p(i$1.join(t$1,x),Nt("workspace"),o$1),x),l$1(await p(i$1.join(t$1,y),Nr(),o$1),y),l$1(await p(i$1.join(t$1,z$1),Nt("evidence"),o$1),z$1),l$1(await p(i$1.join(t$1,A$1),Lt(),o$1),A$1),l$1(await p(i$1.join(t$1,B),Lt(),o$1),B),u$1==="enterprise"){let c=[[C,le({description:"Repair Workspai blockers with evidence and verification",objective:"Plan the smallest safe repair for the current Workspai blocker.",expectedOutput:["Blocker and affected workspace/project scope","Evidence paths and exact failing signals","Minimal fix plan","Human-run commands","Verification command and expected success signal"]})],[E,le({description:"Assess Workspai release readiness from evidence",objective:"Assess whether this workspace is release-ready using Workspai gates.",expectedOutput:["Readiness verdict with cited reports","Blocking gates","Safe next command","Verification checklist"]})],[G$1,le({description:"Onboard a project into Workspai Workspace Intelligence",objective:"Guide project onboarding using workspace model and create planner capabilities.",expectedOutput:["Target project scope","Native create, official generator, or existing lane","Safe commands","Post-onboarding verification"]})],[I,le({description:"Adopt an existing project into Workspai governance",objective:"Adopt an existing project without changing its runtime behavior.",expectedOutput:["Detected stack and confidence","Adoption plan","Generated metadata expectations","Doctor and workspace model verification"]})]];for(let[h,v]of c)l$1(await p(i$1.join(t$1,h),v,o$1),h);let f=[[D,c[0][1]],[F$1,c[1][1]],[H,c[2][1]],[J,c[3][1]]];for(let[h,v]of f)l$1(await p(i$1.join(t$1,h),v,o$1),h);if(e.hydratePrompts===true)for(let h of await _t({workspacePath:t$1,skills:J$1.skills,write:o$1}))l$1(o$1?"written":"skipped",h);}if(l$1(await p(i$1.join(t$1,K),L({index:P$1,context:g,model:C$1}),o$1),K),l$1(await p(i$1.join(t$1,L$1),L({index:P$1,context:g,model:C$1}),o$1),L$1),u$1==="enterprise"){l$1(await p(i$1.join(t$1,M),Gt(ge),o$1),M),l$1(await p(i$1.join(t$1,N),Gt(ge),o$1),N);let c=[["artifact-map.md",G({title:"Artifact Map",lines:V.map(h=>`- \`${h.relativePath}\` \u2014 ${h.label}`)})],["command-map.md",G({title:"Command Map",lines:["- `npx workspai workspace agent-sync --write --refresh-context` \u2014 refresh agent grounding.","- `npx workspai workspace model --json --write` \u2014 refresh workspace model.","- `npx workspai doctor workspace` \u2014 refresh health evidence.","- `npx workspai workspace verify --strict --json` \u2014 verify release gates."]})],["scope-model.md",G({title:"Scope Model",lines:["- Workspace scope is the default source of truth.","- Project scope is selected only when the active task targets a specific project.","- Always name the workspace and project when giving repair or lifecycle advice."]})],["runtime-support.md",G({title:"Runtime Support",lines:["- Native create is available only for Workspai-owned scaffold contracts.","- Unsupported stacks should use the official lane when a stable ecosystem generator exists.","- Existing projects should use the existing lane when native create is unavailable."]})],["create-planner-capabilities.md",G({title:"Create Planner Capabilities",lines:["- Use `contracts/create-planner-capabilities.v1.json` to decide native, official, or existing.","- Do not map PHP, WordPress, Laravel, Rails, or Symfony requests to unrelated native kits.","- Explain unsupported native create requests and guide users to adopt/import."]})],["mcp-tools.md",Kr()]];for(let[h,v]of c){let O=`${i$1.dirname(M)}/resources/${h}`;l$1(await p(i$1.join(t$1,O),v,o$1),O);let nt=`${i$1.dirname(N)}/resources/${h}`;l$1(await p(i$1.join(t$1,nt),v,o$1),nt);}let f=[["workspai-advisor.agent.md",de({name:"Workspai Advisor",description:"Read-only workspace and project guidance using Workspai evidence",mode:"read-only",tools:["search","read"]})],["workspai-repair.agent.md",de({name:"Workspai Repair",description:"Turn Workspai blockers into minimal fixes and verification steps",mode:"repair",tools:["search","read","edit"]})],["workspai-release.agent.md",de({name:"Workspai Release",description:"Assess readiness, governance gates, and release safety from evidence",mode:"release",tools:["search","read"]})],["workspai-project-onboarder.agent.md",de({name:"Workspai Project Onboarder",description:"Guide create, import, and adopt flows with Workspai contracts",mode:"onboard",tools:["search","read","edit"]})]];for(let[h,v]of f){let O=`.github/agents/${h}`;l$1(await p(i$1.join(t$1,O),v,o$1),O);}}}if(u$1==="enterprise"){let c=qr({workspaceRef:P$1.workspaceRoot,generatedAt:P$1.generatedAt});b$5(S,JSON.parse(c)),l$1(await p(i$1.join(t$1,S),c,o$1),S),l$1(await p(i$1.join(t$1,T),c,o$1),T);}if(u$1==="enterprise"&&e.experimentalHooks===true){let c=Hr({workspaceRef:P$1.workspaceRoot,generatedAt:P$1.generatedAt});b$5(U,JSON.parse(c)),l$1(await p(i$1.join(t$1,U),c,o$1),U),l$1(await p(i$1.join(t$1,V$1),c,o$1),V$1);}let B$1=o$1?await jt({workspacePath:t$1,staleAfterHours:a,now:r$1}):P$1,Y=B$1.reports.filter(c=>c.required&&!c.exists).map(c=>c.path),X=B$1.reports.filter(c=>c.exists&&sr(c,a,r$1)).map(c=>c.path);if(w$1){Y.length>0&&y$1.push(`Missing required reports: ${Y.join(", ")}`),X.length>0&&y$1.push(`Stale reports (>${a}h): ${X.join(", ")}`);let c=ue.map(f=>f.path).filter(f=>!kr(f));c.length>0&&y$1.push(`Unsafe generated output paths: ${c.join(", ")}`);}let j$1=o$1?await g$2({workspacePath:t$1,mode:e.projectGrounding??"managed",now:r$1}):void 0;if(w$1&&j$1&&j$1.skipped.length>0&&y$1.push(`Project grounding incomplete: ${j$1.skipped.map(c=>`${c.name} (${c.reason})`).join(", ")}`),w$1&&j$1){let c=j$1.projects.flatMap(f=>(f.hostCoverage??[]).filter(h=>h.status==="blocked"&&lr(s$1,h.id)).map(h=>`${i$1.basename(f.projectPath)}:${h.id}`));c.length>0&&y$1.push(`Project agent entry coverage blocked: ${c.join(", ")}`);}let rt=Mr({workspaceRef:B$1.workspaceRoot,generatedAt:r$1.toISOString(),preset:u$1,targets:d,index:B$1,outputs:[...ue,{path:F,kind:"report",targets:["agents","vscode","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"],required:true,status:o$1?"written":e.dryRun?"planned":"skipped"}],missingRequired:Y,staleReports:X,strictViolations:y$1,experimentalHooks:e.experimentalHooks===true});if(o$1&&process.env.WORKSPAI_TEST_FAIL_AGENT_SYNC_BEFORE_PACK==="1")throw new Error("Injected agent-sync failure before generation commit.");return l$1(await p(i$1.join(t$1,F),`${JSON.stringify(rt,null,2)}
49
+ `,o$1),F),{workspacePath:t$1,indexPath:i$1.join(t$1,z),packPath:i$1.join(t$1,F),pack:rt,contextPath:m$2,writtenFiles:W,skippedFiles:pe,blockers:P$1.blockers,missingRequired:Y,staleReports:X,strictViolations:y$1,projectLenses:j$1}}async function Dn(e){if(e.write!==true)return Qe(e);let t=i$1.resolve(e.workspacePath),r=i$1.join(t,".workspai","transactions","agent-sync");await b$3(r);let a$1=await Qe({...e,write:false,dryRun:true});if(!a$1.pack)throw new Error("Agent-sync dry run did not produce an output inventory.");let s=[...a$1.pack.outputInventory.map(u=>u.path),z,F],d=await a({journalDirectory:r});try{for(let w of [...new Set(s)].sort()){let m=i$1.resolve(t,w),g=i$1.relative(t,m);if(g===".."||g.startsWith(`..${i$1.sep}`)||i$1.isAbsolute(g))throw new Error(`Agent-sync output escapes workspace root: ${w}`);await d.captureFile(m);}let u=await h(t);for(let w of u.resolved)for(let m of [f$1,g,h$1,b$4,...g$1,"AGENTS.md",".gitignore"]){let g=i$1.join(w.projectPath,m);(m==="AGENTS.md"||g$1.some(y=>y===m))&&(await k.lstat(g).catch(W=>{if(W.code==="ENOENT")return null;throw W}))?.isSymbolicLink()||await d.captureFile(g);}let o=await Qe(e);return await d.commit(),o}catch(u){try{await d.rollback();}catch(o){throw new AggregateError([u,o],"Agent-sync generation failed and rollback was incomplete.")}throw u}}export{qt as a,Mt as b,Qt as c,Zt as d,er as e,z as f,F as g,V as h,tr as i,jt as j,$n as k,Dn as l};
@@ -0,0 +1 @@
1
+ import {k,q}from'./chunk-GQSRNUCU.js';import {a as a$2}from'./chunk-27UR373Z.js';import {a as a$6}from'./chunk-HTYMXMQM.js';import {a}from'./chunk-Y5YAP4F3.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {m,a as a$3,d as d$2,c as c$2,b as b$2}from'./chunk-Q2WF7D5U.js';import {c,b as b$1,i as i$1,w,f as f$3}from'./chunk-J7RU5WR5.js';import {a as a$1}from'./chunk-T5YRFRJV.js';import {j as j$1,i as i$2,h}from'./chunk-XKDR5BGS.js';import {a as a$4}from'./chunk-GR6442P7.js';import {f as f$2,d as d$1,a as a$5,e as e$1}from'./chunk-CCDGHPEJ.js';import {f,e,i,h as h$1}from'./chunk-NZ3WZYD5.js';import {t,s}from'./chunk-MOSXTVPU.js';import f$1 from'path';import W from'fs-extra';import Dt from'crypto';import {createRequire}from'module';var At=new Set(["backend","desktop","extension","service","frontend","worker","library","infra","docs","test-suite","unknown"]);async function rt(e){try{if(!await W.pathExists(e))return null;let t=await W.readJSON(e);return t&&typeof t=="object"?t:null}catch{return null}}async function Rt(e){for(let t of e){let r=await rt(t);if(r)return r}return null}function tt(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return At.has(t)?t==="service"?"backend":t:null}function nt(e){switch(e){case "backend":case "service":case "worker":return "backend";case "frontend":case "desktop":case "extension":case "library":return e;case "infra":return "infrastructure";case "docs":return "documentation";case "test-suite":return "quality";default:return "unknown"}}async function ot(e,t$1){let r=t$1??await Rt(t(e,"project.json")),o=tt(r?.kind)??tt(r?.type);if(o)return o;let s=typeof r?.kit_name=="string"?r.kit_name:r?.kit,n=typeof r?.framework=="string"?r.framework:null,i=typeof r?.runtime=="string"?r.runtime:null,a=`${typeof s=="string"?s:""} ${n??""} ${i??""}`.trim().toLowerCase();if(/\b(tauri|electron|wails|desktop)\b/.test(a))return "desktop";if(/\b(vscode-extension|visual studio code extension|jetbrains-plugin|browser-extension)\b/.test(a))return "extension";if(/\b(frontend|nextjs|next\.js|react|vue|svelte|vite|angular|astro|remix|nuxt)\b/.test(a))return "frontend";if(/\b(fastapi|nestjs|springboot|spring boot|gofiber|gogin|dotnet|webapi|django|flask|express|fastify|python|node|java|go|rust|php|ruby|elixir)\b/.test(a))return "backend";let c=await rt(f$1.join(e,"package.json"));if(c){let d={...c.dependencies??{},...c.devDependencies??{}},u=c.scripts??{},p=Object.values(u).filter(v=>typeof v=="string").join(" ").toLowerCase(),l=c.engines??{},m=Array.isArray(c.categories)?c.categories.filter(v=>typeof v=="string"):[];if(d["@tauri-apps/api"]||d["@tauri-apps/cli"]||await W.pathExists(f$1.join(e,"src-tauri","tauri.conf.json"))||await W.pathExists(f$1.join(e,"src-tauri","tauri.conf.json5"))||d.electron||d["@electron-forge/cli"]||p.includes("electron-forge")||p.includes("electron "))return "desktop";if(typeof l.vscode=="string"||m.some(v=>v.toLowerCase()==="extension packs")||c.publisher&&(c.activationEvents||c.contributes))return "extension";if(d.next||d.react||d.vue||d.svelte||d.vite||d["@angular/core"]||p.includes("next ")||p.includes("vite "))return "frontend";if(c.private===true&&!d.express&&!d["@nestjs/core"])return "library"}return await W.pathExists(f$1.join(e,"Dockerfile"))||await W.pathExists(f$1.join(e,"docker-compose.yml"))||await W.pathExists(f$1.join(e,"terraform.tf"))?"infra":"backend"}var Mt=new Set(c().map(e=>e.id)),It=[...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}],z=new Map;for(let e of It){z.set(e.id,e);for(let t of e.aliases)z.set(t,e);}var Ft=new Set(["php","ruby","rust","elixir","clojure","scala","kotlin","unknown"]);function $(e){return e?.trim().toLowerCase()||void 0}function st(e){let t=$(e.kitId)??$(e.framework)??$(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&&Mt.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=z.get(t)??z.get($(e.framework)??"")??z.get($(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=$(e.runtime);return s&&Ft.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 Gr(e){return !e.canExecuteCreate&&(e.lane==="official"||e.lane==="existing"&&e.resolved!==void 0)}var $r="rapidkit-freshness-metadata-v1";function ke(e){if(Array.isArray(e))return e.map(t=>ke(t));if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=ke(e[r]);return t}return e}function Ot(e){return JSON.stringify(ke(e))}function V(e){return Dt.createHash("sha256").update(Ot(e)).digest("hex")}var at=".workspai/workspace-graph.overrides.json",Gt=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),_t=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","node_modules","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),ct=600,dt=5,Tt=256*1024,it={inferred:1,contract:2,manual:3};function Nt(e){return e.split(f$1.sep).join("/")}function ne(e,t){return Nt(f$1.relative(e,t)||".")}function pt(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 lt(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?f$1.resolve(n.absolutePath):f$1.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 oe(e,t){let r=f$1.resolve(t);for(let{dir:o,id:s}of e.sortedDirs)if(r===o||r.startsWith(`${o}${f$1.sep}`))return s;return null}async function ve(e){try{if(!await W.pathExists(e))return null;let t=await W.readJSON(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async function je(e){try{return await W.pathExists(e)?await W.readFile(e,"utf8"):null}catch{return null}}async function ut(e,t){let r=[],o=new Map;for(let[s,n]of t.idToDir.entries()){let i=await ve(f$1.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 ve(f$1.join(n,"package.json"));if(i){let a=["dependencies","devDependencies","peerDependencies","optionalDependencies"],c=new Set;for(let d of a){let u=i[d];if(!(!u||typeof u!="object"||Array.isArray(u)))for(let p of Object.keys(u)){let l=o.get(p);!l||l===s||c.has(l)||(c.add(l),r.push({from:s,to:l,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ne(e,f$1.join(n,"package.json")),detail:`declares dependency ${p}`}]}));}}}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 je(f$1.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 d=oe(t,f$1.resolve(o,c[1]));!d||d===r||i.has(d)||(i.add(d),n.push({from:r,to:d,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ne(e,f$1.join(o,"pyproject.toml")),detail:`path dependency ${c[1]}`}]}));}return n}async function Vt(e,t,r,o){let s=await je(f$1.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 d=oe(t,f$1.resolve(o,c[1]));!d||d===r||i.has(d)||(i.add(d),n.push({from:r,to:d,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ne(e,f$1.join(o,"go.mod")),detail:`go.mod replace ${c[1]}`}]}));}return n}async function Kt(e,t){let r=[],o=[e];for(;o.length>0&&r.length<t;){let s=o.shift();if(!s)continue;let n=[];try{n=await W.readdir(s,{withFileTypes:true});}catch{continue}let i=[],a=[];for(let c of n)if(c.isDirectory()){if(_t.has(c.name)||a$4(c.name)||c.name.startsWith("."))continue;i.push(f$1.join(s,c.name));}else c.isFile()&&Gt.has(f$1.extname(c.name))&&a.push(f$1.join(s,c.name));a.sort((c,d)=>c.localeCompare(d)),i.sort((c,d)=>c.localeCompare(d));for(let c of a){if(r.length>=t)break;r.push(c);}o.push(...i);}return r}var Ht=[/\bfrom\s+["']([^"']+)["']/g,/\bimport\s+["']([^"']+)["']/g,/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g,/\brequire\s*\(\s*["']([^"']+)["']\s*\)/g];function Bt(e){let t=new Set;for(let r of Ht){r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){let s=o[1];s.startsWith(".")&&t.add(s);}}return [...t]}async function be(e,t,r,o){let s=new Map;for(let[n,i]of t.idToDir.entries()){if(o&&!o.has(n))continue;let a=await Kt(i,r);for(let c of a){let d=await W.stat(c).catch(()=>null);if(!d||d.size>Tt)continue;let u=await je(c);if(u)for(let p of Bt(u)){let l=f$1.resolve(f$1.dirname(c),p),m=oe(t,l);if(!m||m===n)continue;let v=`${n}\0${m}`,h=s.get(v);h||(h={from:n,to:m,evidence:[]},s.set(v,h)),h.evidence.length<dt&&h.evidence.push({file:ne(e,c),detail:`imports ${p}`});}}}return [...s.values()].map(n=>({from:n.from,to:n.to,kind:"code-import",source:"inferred",confidence:"medium",evidence:n.evidence}))}function Lt(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=f$1.resolve(e,s),i=t.dirToId.get(n)??oe(t,n);if(i)return i}return t.idToDir.has(r.slug)?r.slug:null}function ft(e,t,r){let o=[],s=Lt(e,t,r),n=d$2,i=new Map,a=new Map;for(let c of r.projects){let d=s.get(c.slug);if(!d)continue;let u=c.contracts??{publishes:[],consumes:[],dependsOn:[]};for(let p of u.dependsOn??[]){let l=s.get(p);!l||l===d||o.push({from:d,to:l,kind:"service-dependsOn",source:"contract",confidence:"high",evidence:[{file:n,detail:`dependsOn ${p}`}]});}for(let p of u.publishes??[])i.has(p)||i.set(p,new Set),i.get(p)?.add(d);for(let p of u.consumes??[])a.has(p)||a.set(p,new Set),a.get(p)?.add(d);}for(let[c,d]of i.entries()){let u=a.get(c);if(u)for(let p of u)for(let l of d)p!==l&&o.push({from:p,to:l,kind:"event-pub-sub",source:"contract",confidence:"high",evidence:[{file:n,detail:`consumes event ${c}`}]});}return o.push(...Ut(r,s)),o}function ye(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function Ut(e,t){let r=[],o=e.projects.map(s=>({project:s,id:t.get(s.slug)})).filter(s=>!!s.id).filter(s=>ye(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 d=ye(c);for(let u of o)u.id===n||a.has(u.id)||!(d.includes(ye(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:d$2,detail:`env ${c} references ${u.project.slug}`}]}));}}return r}async function mt(e,t){let r=await ve(f$1.join(e,at)),o=Array.isArray(r?.edges)?r?.edges:[],s=[],n=new Set(c$2);for(let i of o){if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i,c=typeof a.from=="string"?a.from:"",d=typeof a.to=="string"?a.to:"",u=typeof a.kind=="string"?a.kind:"";if(!t.has(c)||!t.has(d)||c===d||!n.has(u))continue;let p=Array.isArray(a.evidence)?a.evidence.map(l=>l&&typeof l=="object"&&typeof l.file=="string"?{file:l.file,...typeof l.detail=="string"?{detail:l.detail}:{}}:null).filter(l=>!!l):[];s.push({from:c,to:d,kind:u,source:"manual",confidence:"high",evidence:p.length>0?p:[{file:at,detail:"manual edge"}]});}return s}function qt(e){return `${e.from}\0${e.to}\0${e.kind}`}function Jt(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,dt)}function Xt(e){let t=new Map;for(let r of e){let o=qt(r),s=t.get(o);if(!s){t.set(o,{...r,evidence:[...r.evidence]});continue}let n=it[s.source],i=it[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:Jt(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 we(e){return Math.round(e*1e3)/1e3}function Yt(e){return Math.max(0,Math.min(100,Math.round(e)))}function Qt(e){return e>=75?"critical":e>=50?"high":e>=20?"medium":"low"}function Zt(e){return e==="critical"||e==="high"?"strict":e==="medium"?"elevated":"normal"}function er(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(m=>m.from===s.id||m.to===s.id),a=i.filter(m=>m.source==="contract"||m.source==="manual").length,c=i.filter(m=>m.confidence==="low").length,d=[],u=n.reach*20+n.fanIn*14+n.fanOut*8+Math.min(20,n.betweenness*4)+a*8;n.isHotspot&&(u+=24,d.push("Critical-path hotspot in dependency graph")),n.reach>0&&d.push(`Change reaches ${n.reach} dependent project(s)`),n.fanIn>0&&d.push(`${n.fanIn} direct dependent project(s)`),n.fanOut>0&&d.push(`${n.fanOut} direct dependency project(s)`),a>0&&d.push(`${a} contract/manual edge(s)`),c>0&&d.push(`${c} low-confidence inferred edge(s) need review`),i.length===0&&d.push("No dependency evidence connected to this project yet");let p=Yt(u),l=Qt(p);o.set(s.id,{weight:l,score:p,verificationPriority:Zt(l),reasons:d.slice(0,5),centrality:{fanIn:n.fanIn,fanOut:n.fanOut,reach:n.reach,betweenness:n.betweenness,isHotspot:n.isHotspot}});}return o}function tr(e,t){let r=er(e,t);return e.map(o=>({...o,operationalProfile:r.get(o.id)}))}function rr(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:we(o>1?s/(o*(o-1)):0),edgeCoverageRatio:we(o>0?n/o:1),evidenceCoverageRatio:we(s>0?t.filter(c=>c.evidence.length>0).length/s:1),hotspotCount:a.hotspots.length,hasCycle:or(e,t)}}function nr(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.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 or(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 d=[{id:c,index:0}];for(i.set(c,s);d.length>0;){let u=d[d.length-1],p=r.get(u.id)??[];if(u.index>=p.length){i.set(u.id,n),d.pop();continue}let l=p[u.index];u.index+=1;let m=i.get(l)??o;if(m===s)return true;m===o&&(i.set(l,s),d.push({id:l,index:0}));}return false};for(let c of [...r.keys()].sort())if(i.get(c)===o&&a(c))return true;return false}function gt(e,t,r,o){let s=Xt(r.filter(c=>t.has(c.from)&&t.has(c.to))),n=tr(e,s),i=rr(e,s),a=nr(e,s,i);return {schemaVersion:b$2,generatedAt:(o??new Date).toISOString(),nodes:n,edges:s,stats:i,...a.length>0?{diagnostics:a}:{}}}async function ht(e){let t=f$1.resolve(e.workspacePath),r=e.maxImportFilesPerProject??ct,o=pt(e.model),s=new Set(o.map(a=>a.id)),n=lt(t,e.model),i=[];return i.push(...await ut(t,n)),i.push(...await be(t,n,r)),e.contract&&i.push(...ft(t,n,e.contract)),i.push(...await mt(t,s)),gt(o,s,i,e.now)}async function kt(e){let t=f$1.resolve(e.workspacePath),r=e.maxImportFilesPerProject??ct,o=pt(e.model),s=new Set(o.map(a=>a.id)),n=lt(t,e.model),i=[];if(i.push(...await ut(t,n)),e.structuralChange)i.push(...await be(t,n,r));else {i.push(...await be(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(...ft(t,n,e.contract)),i.push(...await mt(t,s)),gt(o,s,i,e.now)}var Ce=h$1.workspaceModelCache.schemaVersion,Pe=i.workspaceModelCache,yt=["package.json","pyproject.toml","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","workspai.project.json",".workspai/project.json",".workspai/context.json","rapidkit.project.json",".rapidkit/project.json",".rapidkit/context.json"],wt=[i.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"],ir=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),cr=new Set([".git",".workspai",".rapidkit","node_modules","dist","build","out","target","coverage",".next",".turbo",".cache",".venv"]),dr=1500,U=null;function Se(){if(U)return U;try{U=createRequire(import.meta.url)("../package.json")?.version??"0.0.0";}catch{U="0.0.0";}return U}async function se(e){try{let t=await W.readFile(e);return Dt.createHash("sha256").update(t).digest("hex")}catch{return null}}async function pr(e){let t={};for(let s of yt){let n=await se(f$1.join(e,s));n&&(t[s]=n);}let r=[],o=[e];for(;o.length>0&&r.length<dr;){let s=o.shift();if(!s)continue;let n=[];try{n=await W.readdir(s,{withFileTypes:true});}catch{continue}let i=[];for(let a of n)if(a.isDirectory()){if(cr.has(a.name)||a$4(a.name)||a.name.startsWith("."))continue;i.push(f$1.join(s,a.name));}else if(a.isFile()&&ir.has(f$1.extname(a.name))){let c=f$1.join(s,a.name),d=await W.stat(c).catch(()=>null);if(d){let u=f$1.relative(e,c).split(f$1.sep).join("/");r.push(`${u}:${d.size}:${Math.round(d.mtimeMs)}`);}}i.sort((a,c)=>a.localeCompare(c)),o.push(...i);}return r.sort((s,n)=>s.localeCompare(n)),V({manifests:t,source:r})}async function ae(e,t){let r=f$1.resolve(e),o={},s=[...new Set(t.map(n=>f$1.relative(r,f$1.resolve(n)).split(f$1.sep).join("/")))].sort((n,i)=>n.localeCompare(i));for(let n of s)o[n]=await pr(f$1.join(r,n));return o}async function ie(e){let t=f$1.resolve(e),r={};for(let o of wt){let s=await se(f$1.join(t,o));s&&(r[o]=s);}return r}async function ce(e){let t=f$1.resolve(e.workspacePath),r=[...new Set(e.projectPaths.map(n=>f$1.relative(t,f$1.resolve(n)).split(f$1.sep).join("/")))].sort((n,i)=>n.localeCompare(i)),o=[];for(let n of r){let i={};for(let a of yt){let c=await se(f$1.join(t,n,a));c&&(i[a]=c);}o.push({project:n,manifests:i});}let s={};for(let n of wt){let i=await se(f$1.join(t,n));i&&(s[n]=i);}return V({cacheSchema:Ce,cliVersion:e.cliVersion,flags:e.flags,workspaceJson:e.workspaceJson??null,marker:e.marker??null,projects:o,workspaceFiles:s})}async function Ee(e){let t=await d$1(e,Pe)??a$5(e,Pe);try{if(!await W.pathExists(t))return null;let r=await W.readJson(t);return !r||r.schemaVersion!==Ce||typeof r.inputsHash!="string"||typeof r.cliVersion!="string"||!r.model?null:r}catch{return null}}async function de(e,t){let r={schemaVersion:Ce,...t};return e$1(e,Pe,r)}var vt="rapidkit-fact-freshness-v1",J={durable:720*60*60,derived:10080*60,evidenceBacked:1440*60,live:300,verifyBeforeUse:1440*60};function lr(e){switch(e){case "durable":return J.durable;case "derived":return J.derived;case "evidence-backed":return J.evidenceBacked;case "live":return J.live;case "verify-before-use":return J.verifyBeforeUse}}function ur(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 fr(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?lr(e.kind):e.ttlSeconds,a=ur({generatedAt:n,ttlSeconds:i,status:e.status??(s?void 0:"unknown"),now:t}),c=Date.parse(n),d=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:vt,kind:e.kind,category:e.category,generatedAt:n,ttlSeconds:i,...d?{expiresAt:d.toISOString()}:{},status:a,verifyBeforeUse:u,...e.sourceArtifact?{sourceArtifact:e.sourceArtifact}:{},...e.sourcePath?{sourcePath:e.sourcePath}:{},inputsHash:e.inputsHash??V(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:fr({...e.freshness,value:e.value})}}function bt(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:vt,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}}var mr=f.model,pe=e.model;function We(e){return e.projectTopology??e.graph}function Pt(e){return !!(e.projectTopology&&e.graph&&c$1(e.projectTopology)===c$1(e.graph))}function Fn(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 gr=["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","deps.edn","project.clj","build.sbt","docker-compose.yml","docker-compose.yaml","terraform.tf"],hr=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next",".turbo"]);function Ct(e,t){return (f$1.relative(e,t)||".").split(f$1.sep).join("/")}async function St(e){try{if(!await W.pathExists(e))return null;let t=await W.readJSON(e);return t&&typeof t=="object"?t:null}catch{return null}}async function kr(e,t){for(let r of t)if(await W.pathExists(f$1.join(e,r)))return true;return false}function xe(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 Ae(e,t){let r=f$1.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=f$1.resolve(i.dirPath);if(n.has(a))continue;if(n.add(a),a!==r&&await kr(a,gr)){s.add(a);continue}if(i.depth>=t)continue;let c=[];try{c=await W.readdir(a,{withFileTypes:true});}catch{continue}for(let d of c)!d.isDirectory()||hr.has(d.name)||a$4(d.name)||d.name.startsWith(".")&&d.name!==".config"||o.push({dirPath:f$1.join(a,d.name),depth:i.depth+1});}return Array.from(s).sort((i,a)=>i.localeCompare(a))}function Re(e){let t=new Set,r=[];for(let o of e){let s=f$1.resolve(o);t.has(s)||(t.add(s),r.push(s));}return r.sort((o,s)=>o.localeCompare(s))}function jt(e,t){let r=e?.[t];return typeof r=="string"&&r.trim()?r.trim():void 0}function yr(e,t){return e?.[t]===true}function wr(e,t,r){let o=e?.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,s=jt(o,"generator"),n=jt(o,"command_display"),i=typeof t=="string"&&t.startsWith("frontend.");if(!(!s&&!i))return {...s?{id:s}:{},...t?{kit:t}:{},displayName:r,source:yr(o,"official_generator")?"official-generator":"metadata",...n?{commandDisplay:n}:{}}}async function vr(e){let t=[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json","package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","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","README.md"],r=[];for(let o of t)await W.pathExists(f$1.join(e,o))&&r.push(o);return r}async function E(e,t,r,o=t){let s=await d$1(e,t),n=s!==null,i={path:o.split(f$1.sep).join("/"),exists:n};if(s&&r){let a=await St(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 br(e,t,r){let o=Ct(e,t),s=".workspai/reports",n=c=>E(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 jr(e,t,r){let o=i$1(t),s=j$1(t,o),n=w(t),i=f$3(s.runtime),a=await ot(t,o),c=r.contractProject?.slug?r.contractProject.slug:typeof o?.name=="string"&&o.name.trim()?o.name.trim():f$1.basename(t),d=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,p=wr(o,d,s.displayName),l=st({kitId:d,framework:s.key,runtime:s.runtime}),m=f$1.relative(e,t),h$1=m===".."||m.startsWith(`..${f$1.sep}`)?i$2(t):h(t),x=[s.runtime,...h$1.filter(A=>A!==s.runtime)];return {name:c,path:Ct(e,t),...r.includeAbsolutePaths?{absolutePath:t}:{},kind:a,category:nt(a),runtime:s.runtime,runtimeCandidates:x,framework:s.key,frameworkDisplayName:s.displayName,confidence:s.confidence,detectionSource:s.source,supportTier:s.supportTier,runtimeSupportTier:i.tier,runtimeDoctorSupport:i.doctorSupport,moduleSupport:n.moduleSupport,...d?{kit:d}:{},...u?{engine:u}:{},...p?{generator:p}:{},createCapability:l,commands:{supported:n.supportedCommands,unsupported:n.unsupportedCommands,global:n.globalCommands,fleetStages:n.fleetStages,localOnly:n.localOnlyCommands,map:n.commandMap},importantFiles:await vr(t),evidence:await br(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",evidence:"project .workspai/reports"}}}async function Me(e){for(let t of s(e,"workspace.json")){let r=await St(t);if(r)return r}return null}function Pr(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("library")?"library-workspace":e.length>1?"backend-platform":"backend-workspace"}function Cr(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 P(e,t,r,o){return {severity:e,code:t,message:r,target:o}}function Et(e){let t=[];e.workspace.name.trim()||t.push(P("error","workspace.name.missing","Workspace name could not be resolved.","workspace")),e.workspace.type==="observed-workspace"&&t.push(P("warning","workspace.marker.missing","Workspace marker is missing; model is based on filesystem observation.","workspace.marker")),e.summary.projectCount===0&&t.push(P("warning","workspace.projects.empty","No project roots were detected in this workspace.","projects")),e.contracts.exists||t.push(P("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(P("warning","project.markers.missing",`Project ${n.name} has no important manifest files recorded.`,n.path));let c=f$1.isAbsolute(n.path)?n.path:f$1.resolve(e.workspace.root,n.path);W.existsSync(c)||t.push(P("warning","project.path.missing",`Registered project ${n.name} is not available at its declared path.`,n.path)),n.runtime==="unknown"&&t.push(P("warning","project.runtime.unknown",`Project ${n.name} runtime could not be confidently detected.`,n.path));let d=["test","build"];for(let l of d)n.commands.supported.includes(l)&&n.commands.unsupported.includes(l)&&t.push(P("error","project.commands.conflict",`Project ${n.name} marks ${l} as both supported and unsupported.`,n.path));let u=new Set(n.commands.fleetStages),p=new Set(n.commands.localOnly);for(let l of n.commands.fleetStages){p.has(l)&&t.push(P("error","project.commands.scope-conflict",`Project ${n.name} marks ${l} as both fleet and local-only.`,n.path));let m=n.commands.map[l];(!m||m.status!=="supported"||m.fleetEligible!==true||m.executionScope!=="fleet")&&t.push(P("error","project.commands.fleet-stage-invalid",`Project ${n.name} advertises ${l} as a fleet stage without a supported fleet capability.`,n.path));}for(let l of n.commands.localOnly){let m=n.commands.map[l];(!m||m.status!=="supported"||m.executionScope!=="local-only"||m.fleetEligible===true)&&t.push(P("error","project.commands.local-only-invalid",`Project ${n.name} advertises ${l} as local-only without a matching local-only capability.`,n.path));}for(let l of Object.values(n.commands.map))l.status==="supported"&&(l.fleetEligible===true&&!u.has(l.command)&&t.push(P("error","project.commands.fleet-stage-missing",`Project ${n.name} capability ${l.command} is fleet-eligible but missing from fleetStages.`,n.path)),l.executionScope==="local-only"&&l.fleetEligible!==true&&!p.has(l.command)&&t.push(P("error","project.commands.local-only-missing",`Project ${n.name} capability ${l.command} is local-only but missing from localOnly commands.`,n.path)));}for(let[n,i]of r.entries())i.length>1&&t.push(P("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(P("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 Dn(e){return Et(e)}function j(e){return e.join(".")}function Sr(e,t){let r=pe,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=We(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}]`,d={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:{...d,sourcePath:j([c,"kind"])}}),b({id:`project.${a.name}.category`,label:`${a.name} category`,scope:"project",project:a.name,value:a.category,freshness:{...d,sourcePath:j([c,"category"])}}),b({id:`project.${a.name}.runtime`,label:`${a.name} runtime`,scope:"project",project:a.name,value:a.runtime,freshness:{...d,sourcePath:j([c,"runtime"])}}),b({id:`project.${a.name}.framework`,label:`${a.name} framework`,scope:"project",project:a.name,value:a.frameworkDisplayName,freshness:{...d,sourcePath:j([c,"frameworkDisplayName"])}}),b({id:`project.${a.name}.supportTier`,label:`${a.name} support tier`,scope:"project",project:a.name,value:a.supportTier,freshness:{...d,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:{...d,sourcePath:j([c,"commands","fleetStages"]),reason:"Safe command availability is derived from package and project command surfaces."}}));for(let[u,p]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:p?{path:p.path,exists:p.exists,status:p.status??null}:{exists:false},freshness:{kind:p?.exists?"evidence-backed":"verify-before-use",category:"verification",generatedAt:p?.generatedAt??o,now:t,status:p?.exists?void 0:"unknown",sourceArtifact:p?.path??r,sourcePath:j([c,"evidence",u]),verifyBeforeUse:true,reason:p?.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 le(e$1){let t=f$1.resolve(e$1.workspacePath),r=e$1.includeAbsolutePaths===true,o=e$1.includeEvidence===true,s$1=xe(e$1.observableScanDepth),n=e$1.now??new Date,[i$1,a$3,c,d,u,p]=await Promise.all([a(t),Me(t),Ie(t),a$1(t),a$2(t,{descendIntoMatchedProjects:false}),Ae(t,s$1)]),l=new Map;for(let g of c?.projects??[]){let fe=g.externalPath?f$1.resolve(g.externalPath):f$1.resolve(t,g.relativePath);l.set(fe,g);}let m=Re([...u,...p,...l.keys(),...d.map(g=>f$1.isAbsolute(g.path)?g.path:f$1.join(t,g.path))]),v=e$1.reuseProjectModels,h=await Promise.all(m.map(g=>{if(v){let fe=f$1.relative(t,f$1.resolve(g)).split(f$1.sep).join("/"),Fe=v.get(fe);if(Fe)return Promise.resolve(Fe)}return jr(t,g,{includeAbsolutePaths:r,includeEvidence:o,contractProject:l.get(f$1.resolve(g))})})),x=typeof a$3?.workspace_name=="string"?a$3.workspace_name:typeof a$3?.name=="string"?a$3.name:i$1?.name||c?.workspace.name||f$1.basename(t),A=typeof a$3?.profile=="string"?a$3.profile:typeof a$3?.mode=="string"?a$3.mode:c?.workspace.profile,H=Array.from(new Set(h.map(g=>g.kind))).sort(),ue=Array.from(new Set(h.map(g=>g.category))).sort(),B=Array.from(new Set(h.flatMap(g=>g.runtimeCandidates.length>0?g.runtimeCandidates:[g.runtime]))).sort(),X=Array.from(new Set(h.map(g=>g.framework))).sort(),F=[".workspai/policies.yml",".workspai/policies.yaml",".rapidkit/policies.yml",".rapidkit/policies.yaml"].find(g=>W.existsSync(f$1.join(t,g))),Y=s(t,"workspace.contract.json").map(g=>f$1.relative(t,g).split(f$1.sep).join("/")).find(g=>W.existsSync(f$1.join(t,g)))??i.workspaceContract,R=await W.pathExists(f$1.join(t,Y)),Q={schemaVersion:mr,generatedAt:n.toISOString(),workspace:{name:x,root:t,...A?{profile:A}:{},type:i$1?"rapidkit-workspace":"observed-workspace",...i$1?{marker:{createdBy:i$1.createdBy,version:i$1.version,createdAt:i$1.createdAt}}:{}},identity:{workspaceType:Pr(h),surfaces:H,categories:ue,runtimeFamilies:B,businessCapabilities:Cr(h)},discovery:{observableScanDepth:s$1},projects:h,policies:{mode:typeof a$3?.policy_mode=="string"?a$3.policy_mode:typeof a$3?.policyMode=="string"?a$3.policyMode:"warn",source:F??null,exists:!!F},contracts:{workspaceContractPath:Y,exists:R,status:R?"known":"missing"},evidence:{doctor:await E(t,e.doctor,o),projectDoctor:await E(t,i.doctorProject,o),doctorRemediationPlan:await E(t,i.doctorRemediationPlan,o),artifactRemediationPlan:await E(t,i.artifactRemediationPlan,o),doctorFixResult:await E(t,i.doctorFixResult,o),analyze:await E(t,e.analyze,o),readiness:await E(t,e.readiness,o),pipeline:await E(t,i.pipelineLastRun,o)},summary:{projectCount:h.length,runtimes:B,frameworks:X,firstClassProjects:h.filter(g=>g.supportTier==="first-class").length,observedProjects:h.filter(g=>g.supportTier==="observed").length}},w=await Wt(t,Q,{contractExists:R,now:n,incrementalGraph:e$1.incrementalGraph}),C={...Q,projectTopology:w,graph:w},M=Et(C),D=Sr({...C},n),xt=bt({facts:D,generatedAt:n.toISOString(),now:n});return {...C,facts:D,factFreshness:xt,validation:M}}async function On(e){if(e.cache!==true)return {model:await le(e),cache:"disabled"};let t=f$1.resolve(e.workspacePath),r=xe(e.observableScanDepth),o=Se(),[s,n,i,a$3,c]=await Promise.all([a(t),Me(t),a$1(t),a$2(t,{descendIntoMatchedProjects:false}),Ae(t,r)]),d=Re([...a$3,...c,...i.map(h=>f$1.isAbsolute(h.path)?h.path:f$1.join(t,h.path))]),u=await ce({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:d,workspaceJson:n,marker:s}),p=await Ee(t);if(p&&p.cliVersion===o&&p.inputsHash===u&&Pt(p.model))return {model:p.model,cache:"hit"};let l=await le({...e}),[m,v]=await Promise.all([ae(t,d),ie(t)]);return await de(t,{cliVersion:o,inputsHash:u,generatedAt:(e.now??new Date).toISOString(),model:l,projectSignatures:m,workspaceFileSignatures:v}),{model:l,cache:"miss"}}function Er(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 Wr(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 Gn(e){let t=f$1.resolve(e.workspacePath),r=xe(e.observableScanDepth),o=Se(),s=e.now??new Date,[n,i,a$3,c,d]=await Promise.all([a(t),Me(t),a$1(t),a$2(t,{descendIntoMatchedProjects:false}),Ae(t,r)]),u=Re([...c,...d,...a$3.map(w=>f$1.isAbsolute(w.path)?w.path:f$1.join(t,w.path))]),p=await Ee(t),l=async()=>{let w=await le({...e}),C=await ce({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:u,workspaceJson:i,marker:n}),[M,D]=await Promise.all([ae(t,u),ie(t)]);return await de(t,{cliVersion:o,inputsHash:C,generatedAt:s.toISOString(),model:w,projectSignatures:M,workspaceFileSignatures:D}),{model:w,mode:"full"}},m=p?We(p.model):void 0;if(!p||p.cliVersion!==o||!p.projectSignatures||!m||!Pt(p.model))return l();let v=await ie(t);if(!Wr(p.workspaceFileSignatures,v))return l();let h=await ae(t,u),{changed:x,added:A,removed:H}=Er(p.projectSignatures,h);if(x.size===0&&A.size===0&&H.size===0)return {model:p.model,mode:"unchanged"};let ue=new Set([...x,...A]),B=new Map;for(let w of p.model.projects){let C=w.path.split(f$1.sep).join("/");!ue.has(C)&&!H.has(C)&&B.set(C,w);}let X=new Set,F=false;for(let w of p.model.projects){let C=w.path.split(f$1.sep).join("/");x.has(C)&&X.add(w.name);}let Y=A.size>0||H.size>0,R=await le({...e,reuseProjectModels:B,incrementalGraph:{previousGraph:m,changedProjectIds:X,structuralChange:Y||F}});for(let w of p.model.projects){let C=w.path.split(f$1.sep).join("/");if(!x.has(C))continue;let M=R.projects.find(D=>D.path.split(f$1.sep).join("/")===C);if(M&&M.name!==w.name){F=true;break}}if(F)return l();let Q=await ce({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:u,workspaceJson:i,marker:n});return await de(t,{cliVersion:o,inputsHash:Q,generatedAt:s.toISOString(),model:R,projectSignatures:h,workspaceFileSignatures:v}),{model:R,mode:"incremental"}}async function Ie(e){try{let{contract:t}=await m({workspacePath:e});return t&&typeof t=="object"?t:null}catch{return null}}async function Wt(e,t,r){let o=r.contractExists?await Ie(e):null;try{return r.incrementalGraph?await kt({workspacePath:e,model:t,contract:o,now:r.now,previousGraph:r.incrementalGraph.previousGraph,changedProjectIds:r.incrementalGraph.changedProjectIds,structuralChange:r.incrementalGraph.structuralChange}):await ht({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 _n(e$1,t){let r=e$1.contracts.exists?await Ie(t):null,{buildWorkspaceKnowledgeGraph:o}=await import('./workspace-knowledge-graph-RSDP2E36.js'),s=a$3(e$1),n=await o({workspacePath:t,workspace:{name:e$1.workspace.name,...e$1.workspace.profile?{profile:e$1.workspace.profile}:{}},projects:e$1.projects.map(a=>({id:a.name,path:a.path,...a.absolutePath?{absolutePath:a.absolutePath}:{},runtime:a.runtime,runtimeCandidates:a.runtimeCandidates,framework:a.framework,kind:a.kind,category:a.category,...a.kit?{kit:a.kit}:{}})),projectTopology:We(e$1)??await Wt(t,e$1,{contractExists:e$1.contracts.exists,now:new Date(e$1.generatedAt)}),contract:r,now:new Date(e$1.generatedAt),source:{kind:"workspace-model",artifact:pe,hashAlgorithm:"sha256",hash:d(s)}}),[,i]=await f$2(t,pe,[{relativePath:e.knowledgeGraph,payload:n},{relativePath:pe,payload:s}]);return i}export{nt as a,ot as b,st as c,Gr as d,$r as e,V as f,vt as g,b as h,bt as i,mr as j,pe as k,We as l,Fn as m,Dn as n,Sr as o,le as p,On as q,Gn as r,_n as s};
@@ -1,2 +1,2 @@
1
- import {p,k,l,j}from'./chunk-NA2NXX5P.js';import {a as a$1}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {e as e$1,d,b}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-KG3TUTXU.js';import {e as e$2}from'./chunk-CCDGHPEJ.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {f,e}from'./chunk-NZ3WZYD5.js';import k$1 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 F(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 c=r.stdout??"";return {ok:true,stdout:a?.preserveWhitespace?c:c.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 c of e.split(`
1
+ import {p,k,l,j}from'./chunk-CJHWKXDN.js';import {a as a$1}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {e as e$1,d,b}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-Q2WF7D5U.js';import {e as e$2}from'./chunk-CCDGHPEJ.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {f,e}from'./chunk-NZ3WZYD5.js';import k$1 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 F(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 c=r.stdout??"";return {ok:true,stdout:a?.preserveWhitespace?c:c.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 c of e.split(`
2
2
  `)){if(!c.trim())continue;let n=c.slice(0,2),i=c.slice(3).trim();if(i&&!ge(i)){if(n==="??"){a.push(i);continue}n.includes("D")&&r.push(i),t.push(i);}}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=F(e,["rev-parse","--is-inside-work-tree"]);if(!r.ok||r.stdout!=="true")return a;let c=F(e,["rev-parse","--abbrev-ref","HEAD"]),n=F(e,["rev-parse","HEAD"]),i=F(e,["status","--porcelain=v1","--untracked-files=all"],{preserveWhitespace:true}),p=ke(i.stdout),m=p.changedFiles.length>0||p.untrackedFiles.length>0||p.deletedFiles.length>0;return {available:true,branch:c.ok?c.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=f.snapshot,L=f.diff,_=e.snapshot,ae=e.diff,he=f.impact,we=e.impact;function ye(e){if(e.model.projectTopology||!e.model.graph||e.modelHash!==e$1(e.model))return null;let t={...e.model,projectTopology:e.model.graph,graph:e.model.graph};return {...e,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$1.isAbsolute(t)?t:k$1.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$2(t,"contracts/workspace-intelligence/workspace-model-snapshot.v1.json",`Workspace model snapshot ${e}`);let r=a;if(!r.model||r.model.schemaVersion!==j)throw new Error(`Invalid workspace model snapshot: ${e}`);let c=d(r.model);if(r.modelHash!==c){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===j){a$2(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$1.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$1.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$2(t,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Workspace model diff ${e}`);let r=a;if(!r.currentModel||r.currentModel.schemaVersion!==j||!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 p({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:k,model:t}}async function Qe(e,t){return e$2(t,_,a(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 w(e,t){e.push(t);}function Me(e,t){let a=[],r=["name","profile","type"],c=["workspaceType","surfaces","runtimeFamilies","businessCapabilities"];for(let n of r){let i=e.workspace[n],p=t.workspace[n];b(i)!==b(p)&&w(a,{type:"workspace.changed",severity:"info",target:`workspace.${n}`,message:`Workspace metadata field changed: ${String(n)}`,before:i,after:p});}for(let n of c){let i=e.identity[n],p=t.identity[n];b(i)!==b(p)&&w(a,{type:"workspace.changed",severity:"info",target:`identity.${n}`,message:`Workspace identity field changed: ${String(n)}`,before:i,after:p});}return b(e.policies)!==b(t.policies)&&w(a,{type:"workspace.changed",severity:"warning",target:"policies",message:"Workspace policy summary changed.",before:e.policies,after:t.policies}),b(e.discovery)!==b(t.discovery)&&w(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&&w(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(a)===b(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])),c=new Map(t.projects.map(n=>[n.path,n]));for(let[n,i]of c.entries()){let p=r.get(n);if(!p){w(a,{type:"project.added",severity:"info",target:n,message:`Project added: ${i.name}`,after:x(i)});continue}let m=x(p),l=x(i);if(b(m)!==b(l)){let u=p.runtime!==i.runtime||p.framework!==i.framework;w(a,{type:"project.changed",severity:u?"warning":"info",target:n,message:`Project changed: ${i.name}`,before:m,after:l});}}for(let[n,i]of r.entries())c.has(n)||w(a,{type:"project.removed",severity:"warning",target:n,message:`Project removed: ${i.name}`,before:x(i)});return a.sort((n,i)=>`${n.type}:${n.target}`.localeCompare(`${i.type}:${i.target}`))}async function Pe(e){let t=k$1.resolve(e.workspacePath),a=ne(e.fromPath),r=a?We(e.fromPath):void 0,c=e.fromPath;if(a){let f=k$1.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");c=_;}let n=se(t,c),i=await be(n),p$1=e.model??await p({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),m=d(p$1),l=[...Me(i.model,p$1),...Ie(i.model,p$1),...je(i.model,p$1)],u;e.includeGitObservation!==false&&(u=e.gitObservation??Q(t,{ref:r}),u.available&&Ee(l,u,p$1));let v=l.filter(f=>f.type.startsWith("git.")).length,R=i.hash!==m,y=a?`git:${r??"HEAD"}`:k$1.relative(t,n).split(k$1.sep).join("/");return {schemaVersion:L,generatedAt:(e.now??new Date).toISOString(),fromRef:y,toRef:k,fromHash:i.hash,toHash:m,summary:{changed:R||v>0,addedProjects:l.filter(f=>f.type==="project.added").length,removedProjects:l.filter(f=>f.type==="project.removed").length,changedProjects:l.filter(f=>f.type==="project.changed").length,workspaceChanges:l.filter(f=>f.type==="workspace.changed").length,validationChanges:l.filter(f=>f.type==="validation.changed").length,gitChangedFiles:v},git:u?.available?Oe(u,r):{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:l,currentModel:p$1}}async function Ze(e,t){return e$2(t,ae,a(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 h(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;return [h(`project.${e.name}.init`,`Run init for ${e.name}`,["workspace","run","init","--scope",t,"--json"],{scope:"project",project:e.name,required:a.includes("init")}),h(`project.${e.name}.test`,`Run tests for ${e.name}`,["workspace","run","test","--scope",t,"--json"],{scope:"project",project:e.name,required:a.includes("test")}),h(`project.${e.name}.build`,`Run build for ${e.name}`,["workspace","run","build","--scope",t,"--json"],{scope:"project",project:e.name,required:a.includes("build")}),h(`project.${e.name}.start`,`Run start for ${e.name}`,["workspace","run","start","--scope",t,"--json"],{scope:"project",project:e.name,required:a.includes("start")})]}function T(){return [h("workspace.doctor","Run workspace doctor",["doctor","workspace","--json"],{scope:"workspace"}),h("workspace.contract.verify","Verify workspace contract",["workspace","contract","verify","--json"],{scope:"workspace"}),h("workspace.readiness","Run release readiness",["readiness","--json"],{scope:"workspace"}),h("workspace.analyze","Run workspace analyze",["analyze","--json"],{scope:"workspace",required:false}),h("workspace.pipeline","Run governance pipeline",["pipeline","--json"],{scope:"workspace",required:false}),h("workspace.doctor-fix","Verify doctor fix result",["doctor","workspace","--fix","--json"],{scope:"workspace",required:false})]}function Se(e,t){let a=t.split(k$1.sep).join("/");return e.projects.filter(c=>{let n=c.path.split(k$1.sep).join("/");return a===n||a.startsWith(`${n}/`)}).sort((c,n)=>n.path.length-c.path.length)[0]}function Ee(e,t,a){let r=new Set(e.map(n=>n.target)),c=(n,i)=>{let p=i.split(k$1.sep).join("/"),m=`git:${p}`;if(r.has(m))return;let l=Se(a,p),u=l?`${l.name} (${l.path})`:"workspace";w(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)c("git.file.changed",n);for(let n of t.untrackedFiles)c("git.untracked",n);for(let n of t.deletedFiles)c("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 c=`${r.scope}:${r.project??""}:${r.display}`;t.has(c)||(t.add(c),a.push(r));}return a}function De(e){return e.type==="project.removed"?"high":e.severity==="critical"?"critical":e.severity==="warning"?"high":("medium")}function $e(e,t){return e.severity==="critical"?"critical":e.target==="policies"||e.target.includes("contract")?"high":e.type==="validation.changed"?(t?.projectCount??0)===0?"low":"high":e.target==="evidence"?"low":e.severity==="warning"?"medium":"low"}function Fe(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$1.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$1.resolve(e.workspacePath),a=ne(e.fromPath),r=e.diff;if(!r&&!a){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 c$1=new Map(r.currentModel.projects.map(o=>[o.path,o])),n=new Map(r.currentModel.projects.map(o=>[o.name,o])),i=r.changes.filter(o=>o.type.startsWith("project.")),p=new Map;for(let o of i){let d=(c$1.get(o.target)??(typeof o.before?.name=="string"?n.get(o.before.name):void 0))?.path??o.target,W=p.get(d)??[];W.push(o),p.set(d,W);}let m=[];for(let[o,s]of p.entries()){let d=c$1.get(o);if(d&&!re(e.scope,d))continue;let W=Z(s.map(De)),C=d?.name??(typeof s[0]?.before?.name=="string"?String(s[0].before.name):o);m.push({id:`project:${C}`,scope:"project",target:o,title:`Project impact: ${C}`,summary:s.map(M=>M.message).join(" "),risk:W,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$1=l(r.currentModel),u=l$1?a$1(l$1):void 0,v=new Set(m.map(o=>o.project?.name).filter(o=>typeof o=="string")),R=new Map;for(let o of m)if(o.project?.name){let s=u?.byId.get(o.project.name);s&&(o.centrality={fanIn:s.fanIn,fanOut:s.fanOut,reach:s.reach,betweenness:s.betweenness,isHotspot:s.isHotspot},s.isHotspot&&(o.risk=Ce(o.risk),o.reasons=[...o.reasons,`graph.hotspot: critical-path project with ${s.reach} transitive dependent(s); risk escalated.`])),o.origin="direct",o.distance=0,R.set(o.project.name,o.risk);}let y=[],f=0;if(l$1&&v.size>0){let o=c(l$1,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 W=s.path[0],C=s.path[s.path.length-2]??W,M=R.get(W)??"medium",de=Re(M),j=u?.byId.get(s.id);f=Math.max(f,s.distance),y.push({id:`transitive:${s.id}`,scope:"project",target:d?.path??s.id,title:`Transitive impact: ${s.id}`,summary:`Depends on changed project ${W}${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}}:{}});}}y.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:$e(o,{projectCount:K}),reasons:[`${o.type}: ${o.message}`],verification:T()})),B=Ae([...m.flatMap(o=>o.verification),...y.flatMap(o=>o.verification),...P.flatMap(o=>o.verification),...r.summary.changed?T():[]]).filter(o=>o.required),pe=Z([...m.map(o=>o.risk),...y.map(o=>o.risk),...P.map(o=>o.risk)]),q=Fe({risk:pe,affectedProjects:m.length,projectCount:K,changes:r.changes}),z={changed:r.summary.changed,risk:q,affectedProjects:m.length,workspaceItems:P.length,recommendedCommands:B.length,blastRadius:{directlyAffected:m.length,transitivelyAffected:y.length,maxDistance:f,graphEdges:l$1?.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:z,affectedProjects:m.sort((o,s)=>o.target.localeCompare(s.target)),transitiveImpact:y,criticalPathHotspots:ie,workspaceImpact:P.sort((o,s)=>o.target.localeCompare(s.target)),verificationPlan:B,agentBrief:xe({changed:z.changed,risk:q,affectedProjects:m,workspaceImpact:P}),diff:r}}async function tt(e,t){return e$2(t,we,a(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};