workspai 0.61.0 → 0.63.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 (65) hide show
  1. package/README.md +7 -5
  2. package/contracts/studio-card-repair-capabilities.v1.json +65 -1
  3. package/contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json +31 -3
  4. package/contracts/workspace-intelligence/agent-customization-pack-report.v1.json +5 -1
  5. package/contracts/workspace-intelligence/agent-reports-index.v1.json +5 -1
  6. package/contracts/workspace-intelligence/project-agent-entry.v1.json +32 -4
  7. package/contracts/workspace-intelligence/project-context-agent.v1.json +34 -2
  8. package/contracts/workspace-intelligence/studio-blocker-handoff.v1.json +28 -0
  9. package/contracts/workspace-intelligence/workspace-context.v1.json +4 -1
  10. package/contracts/workspace-intelligence-chain.v1.json +4 -5
  11. package/dist/{artifact-remediation-plan-HPNQTNJ2.js → artifact-remediation-plan-XIQNI35L.js} +1 -1
  12. package/dist/autopilot-release-NUQKFKKK.js +1 -0
  13. package/dist/{chunk-NJ6WJ7VU.js → chunk-2LLMKTMO.js} +1 -1
  14. package/dist/{chunk-2FPANIX3.js → chunk-GXPOT3A7.js} +14 -12
  15. package/dist/{chunk-YGONW6VG.js → chunk-J5OMC4RZ.js} +1 -1
  16. package/dist/{chunk-WQX3JYEP.js → chunk-LNXIMF3O.js} +1 -1
  17. package/dist/chunk-ODJAKGQF.js +49 -0
  18. package/dist/{chunk-2JVRDBJC.js → chunk-PPQL5UTI.js} +1 -1
  19. package/dist/{chunk-JEGG4EEZ.js → chunk-QB3BLYUR.js} +1 -1
  20. package/dist/{chunk-4KNDIFJ5.js → chunk-QQU536KA.js} +1 -1
  21. package/dist/{chunk-GWMC6SSY.js → chunk-TTQVOCG6.js} +1 -1
  22. package/dist/{chunk-JRIEP4BY.js → chunk-TVCJKE2U.js} +1 -1
  23. package/dist/chunk-U5WVR74V.js +1 -0
  24. package/dist/{chunk-5YNZR74I.js → chunk-UDXFUASA.js} +1 -1
  25. package/dist/chunk-UIBBSKJ3.js +94 -0
  26. package/dist/chunk-VYDURWN7.js +1 -0
  27. package/dist/chunk-WRQWVSBJ.js +3 -0
  28. package/dist/chunk-YUGKQ44M.js +1 -0
  29. package/dist/chunk-Z5L2IK54.js +2 -0
  30. package/dist/{create-TPUFKW6B.js → create-2VELRQAX.js} +1 -1
  31. package/dist/{doctor-MAPZ2ZCD.js → doctor-LDZ7BIU3.js} +1 -1
  32. package/dist/{goal-lifecycle-BNLXDHED.js → goal-lifecycle-HAWBRYDF.js} +1 -1
  33. package/dist/{goal-pack-2PF775AU.js → goal-pack-HNQHQFRW.js} +1 -1
  34. package/dist/index.js +170 -170
  35. package/dist/{pipeline-BY2YL7C6.js → pipeline-TWHWU6GP.js} +1 -1
  36. package/dist/{project-agent-entry-VXCOXRJB.js → project-agent-entry-YFRLKNOB.js} +1 -1
  37. package/dist/{project-intelligence-lens-BA6JLXQH.js → project-intelligence-lens-VWBLAGQ7.js} +1 -1
  38. package/dist/{verified-goal-5OV4BALK.js → verified-goal-Y4NTKSWH.js} +1 -1
  39. package/dist/{workspace-J4OGSSNO.js → workspace-XWKEBPS3.js} +1 -1
  40. package/dist/{workspace-agent-sync-MU7W3C4S.js → workspace-agent-sync-FQU6VIEU.js} +1 -1
  41. package/dist/{workspace-context-MDACPLHD.js → workspace-context-DPDGFTWJ.js} +1 -1
  42. package/dist/workspace-explain-OU2PEVYO.js +1 -0
  43. package/dist/{workspace-explain-contract-JWFM22L4.js → workspace-explain-contract-V2IVSROX.js} +1 -1
  44. package/dist/{workspace-foundation-3X5OBEMM.js → workspace-foundation-MHKSQDKT.js} +1 -1
  45. package/dist/{workspace-intelligence-runner-DEW3CZKA.js → workspace-intelligence-runner-YQWX5VAM.js} +1 -1
  46. package/dist/{workspace-mcp-serve-S5IXSJJL.js → workspace-mcp-serve-PYKYJIE6.js} +1 -1
  47. package/dist/{workspace-onboarding-LK5IK6LE.js → workspace-onboarding-DRFJWRLH.js} +1 -1
  48. package/dist/{workspace-readme-56YZ4EAZ.js → workspace-readme-G7TZ3V5T.js} +1 -1
  49. package/dist/workspace-repair-engine-XZLHR27V.js +3 -0
  50. package/dist/workspace-run-YXI5L466.js +1 -0
  51. package/docs/agent-entry.md +32 -2
  52. package/docs/ci-workflows.md +1 -1
  53. package/package.json +1 -1
  54. package/dist/autopilot-release-7Q5JT7YN.js +0 -1
  55. package/dist/chunk-7DSYI7YN.js +0 -3
  56. package/dist/chunk-ASOFWN6J.js +0 -1
  57. package/dist/chunk-BQCGULHR.js +0 -1
  58. package/dist/chunk-PVXSIYLP.js +0 -1
  59. package/dist/chunk-RALI2ESF.js +0 -49
  60. package/dist/chunk-VDFHUYAQ.js +0 -91
  61. package/dist/chunk-ZJ62F4U3.js +0 -2
  62. package/dist/workspace-explain-NWP3JTFR.js +0 -1
  63. package/dist/workspace-repair-engine-3OLRNXD6.js +0 -3
  64. package/dist/workspace-run-JTEIX4WA.js +0 -1
  65. /package/dist/{chunk-JMFCMPWI.js → chunk-QA62UOE4.js} +0 -0
@@ -0,0 +1,49 @@
1
+ import {b as b$3,a}from'./chunk-THIOE2PB.js';import {h,g as g$2}from'./chunk-GXPOT3A7.js';import {b as b$4,g as g$1}from'./chunk-Z5L2IK54.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()}
6
+
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(`
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
+ `)}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(`
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(`
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(`
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
+ `)}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
+ `)}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(`
23
+ `)}function Nr(){return ["---",'applyTo: ".workspai/**,**/.workspai/**,.rapidkit/**,**/.rapidkit/**"',"description: Workspai evidence and intelligence artifacts","---","","When working under `.workspai/` or legacy `.rapidkit/`:","","- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.",`- Start from \`${e.agentIndex}\` for read order and blockers.`,"- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.",""].join(`
24
+ `)}function Lr(){return ["---",'applyTo: "**"',"description: Workspai workspace scope, evidence, and command discipline","---","","# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context and evidence.`,"- Prefer bounded `workspace graph search` or MCP `searchWorkspaceGraph` over loading the complete graph.","- 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.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
25
+ `)}function Gr(){return ["---","paths:",' - ".workspai/**"',' - ".rapidkit/**"',"---","","# Workspai evidence","","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(`
26
+ `)}function $r(){return ["# Legacy RapidKit evidence alias","","Compatibility path only. Use `.claude/rules/workspai-evidence.md` as the canonical rule.",""].join(`
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
+ `)}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
+ `)}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)}
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
+ `}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()}
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}
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
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()}
46
+ `,o$1),s),l$1(await p(i$1.join(t$1,t),`${jr()}
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};
@@ -1,4 +1,4 @@
1
- import {a as a$1}from'./chunk-JEI6BTZI.js';import {a}from'./chunk-PXWKMPPI.js';import {c,e,d}from'./chunk-ASOFWN6J.js';import {d as d$1,b}from'./chunk-O6R7SE6Y.js';import {g}from'./chunk-NBJ6AP7K.js';import {p as p$1,l}from'./chunk-NA2NXX5P.js';import {m,a as a$2}from'./chunk-KG3TUTXU.js';import {e as e$1}from'./chunk-CCDGHPEJ.js';import {b as b$2}from'./chunk-D65FCQIO.js';import {a as a$3}from'./chunk-AFIFZTOY.js';import v from'path';import b$1 from'fs-extra';function J(e$1){switch(e$1){case "why":return d;case "trace":return e;default:return c}}async function P(e,o,n){try{if(!await b$1.pathExists(e))return null;let r=await b$1.readJson(e);return o?b$2(o,r,e):n&&a$3(r,n,e),r}catch(r){if((o||n)&&await b$1.pathExists(e))throw r;return null}}function G(e,o){if(!e)return null;let n=o.trim().toLowerCase();return e.projects.find(r=>r.slug.toLowerCase()===n||r.relativePath.toLowerCase()===n)??null}function X(e,o,n){let r=n.trim().toLowerCase(),t=(l(e)?.nodes.map(a=>a.id)??e.projects.map(a=>a.name)).find(a=>a.toLowerCase()===r);if(t)return t;let d=e.projects.find(a=>[a.name,a.path,v.basename(a.path)].filter(u=>u.trim().length>0).some(u=>u.toLowerCase()===r));if(d)return d.name;let c=G(o,n);if(c){let a=e.projects.find(u=>u.path===c.relativePath||u.path.endsWith(`/${c.relativePath}`));if(a)return a.name}return n}function Y(e,o){if(!e)return [];let n=o.trim().toLowerCase(),r=new Set;for(let l of e.projects){l.contracts.dependsOn?.some(t=>t.toLowerCase()===n)&&r.add(l.slug);for(let t of l.contracts.consumes??[])for(let d of e.projects)d.contracts.publishes?.includes(t)&&d.slug===n&&r.add(l.slug);}return [...r].sort()}function q(e,o){if(!e)return [];let n=o.trim().toLowerCase();return e.steps.filter(r=>r.scope==="project"&&r.project?.toLowerCase()===n&&r.command?.display).map(r=>r.command.display).slice(0,8)}function p(e,o,n){return {id:e,title:o,body:n.trim()}}async function fe(e){let o=v.resolve(e.workspacePath),n=(e.now??new Date).toISOString(),r=e.model??await p$1({workspacePath:o,includeEvidence:true}),l$1=e.contract;if(l$1===void 0)try{l$1=(await m({workspacePath:o})).contract;}catch{l$1=null;}let t=e.verify;t===void 0&&(t=await P(v.join(o,d$1),d$1));let d=e.impact;if(d===void 0&&(d=await P(v.join(o,g),g)),e.target.kind==="release-blocked"){let s=t?.blockingReasons??[],i=(r.summary?.projectCount??r.projects.length)===0,g=[p("verdict",i?"Workspace scaffold posture":"Release verdict",t?i?`Scaffold posture: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Freshness: **${t.freshness.verdict}**. No registered projects yet \u2014 release gates apply after the first project is added.`:`Verdict: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Risk: **${t.impact.risk}**. Freshness: **${t.freshness.verdict}**.`:"No workspace verify report found. Run `npx workspai workspace verify --json --write` first."),p("blockers",i?"Pre-project signals":"Blocking reasons",s.length?s.map(h=>`- ${h}`).join(`
1
+ import {a as a$1}from'./chunk-JEI6BTZI.js';import {a}from'./chunk-PXWKMPPI.js';import {c,e,d}from'./chunk-YUGKQ44M.js';import {d as d$1,b}from'./chunk-O6R7SE6Y.js';import {g}from'./chunk-NBJ6AP7K.js';import {p as p$1,l}from'./chunk-NA2NXX5P.js';import {m,a as a$2}from'./chunk-KG3TUTXU.js';import {e as e$1}from'./chunk-CCDGHPEJ.js';import {b as b$2}from'./chunk-D65FCQIO.js';import {a as a$3}from'./chunk-AFIFZTOY.js';import v from'path';import b$1 from'fs-extra';function J(e$1){switch(e$1){case "why":return d;case "trace":return e;default:return c}}async function P(e,o,n){try{if(!await b$1.pathExists(e))return null;let r=await b$1.readJson(e);return o?b$2(o,r,e):n&&a$3(r,n,e),r}catch(r){if((o||n)&&await b$1.pathExists(e))throw r;return null}}function G(e,o){if(!e)return null;let n=o.trim().toLowerCase();return e.projects.find(r=>r.slug.toLowerCase()===n||r.relativePath.toLowerCase()===n)??null}function X(e,o,n){let r=n.trim().toLowerCase(),t=(l(e)?.nodes.map(a=>a.id)??e.projects.map(a=>a.name)).find(a=>a.toLowerCase()===r);if(t)return t;let d=e.projects.find(a=>[a.name,a.path,v.basename(a.path)].filter(u=>u.trim().length>0).some(u=>u.toLowerCase()===r));if(d)return d.name;let c=G(o,n);if(c){let a=e.projects.find(u=>u.path===c.relativePath||u.path.endsWith(`/${c.relativePath}`));if(a)return a.name}return n}function Y(e,o){if(!e)return [];let n=o.trim().toLowerCase(),r=new Set;for(let l of e.projects){l.contracts.dependsOn?.some(t=>t.toLowerCase()===n)&&r.add(l.slug);for(let t of l.contracts.consumes??[])for(let d of e.projects)d.contracts.publishes?.includes(t)&&d.slug===n&&r.add(l.slug);}return [...r].sort()}function q(e,o){if(!e)return [];let n=o.trim().toLowerCase();return e.steps.filter(r=>r.scope==="project"&&r.project?.toLowerCase()===n&&r.command?.display).map(r=>r.command.display).slice(0,8)}function p(e,o,n){return {id:e,title:o,body:n.trim()}}async function fe(e){let o=v.resolve(e.workspacePath),n=(e.now??new Date).toISOString(),r=e.model??await p$1({workspacePath:o,includeEvidence:true}),l$1=e.contract;if(l$1===void 0)try{l$1=(await m({workspacePath:o})).contract;}catch{l$1=null;}let t=e.verify;t===void 0&&(t=await P(v.join(o,d$1),d$1));let d=e.impact;if(d===void 0&&(d=await P(v.join(o,g),g)),e.target.kind==="release-blocked"){let s=t?.blockingReasons??[],i=(r.summary?.projectCount??r.projects.length)===0,g=[p("verdict",i?"Workspace scaffold posture":"Release verdict",t?i?`Scaffold posture: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Freshness: **${t.freshness.verdict}**. No registered projects yet \u2014 release gates apply after the first project is added.`:`Verdict: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Risk: **${t.impact.risk}**. Freshness: **${t.freshness.verdict}**.`:"No workspace verify report found. Run `npx workspai workspace verify --json --write` first."),p("blockers",i?"Pre-project signals":"Blocking reasons",s.length?s.map(h=>`- ${h}`).join(`
2
2
  `):i?"No pre-project signals in the latest verify report.":"No blocking reasons in the latest verify report.")];return t?.resolutionHints?.length&&g.push(p("resolution","Resolution hints",t.resolutionHints.map(h=>`- **${h.blockerId}** (${h.resolutionClass}): ${h.commandRetryHint??h.fixHints[0]?.detail??"See fix hints"}`).join(`
3
3
  `))),{schemaVersion:a,generatedAt:n,workspacePath:o,target:e.target,summary:t?i?b(s.length,t.summary.verdict):s.length>0||t.summary.verdict==="blocked"?`Release blocked: ${t.summary.verdict} with ${s.length} blocking reason(s).`:t.summary.verdict==="needs-attention"?"Release needs attention: advisory or incomplete verification evidence remains; no blocking reason was reported.":`Release posture: ${t.summary.verdict}; no blocking reason was reported.`:"Release posture unknown \u2014 verify report missing.",sections:g,releaseVerdict:t?.summary.verdict,evidenceFreshness:t?.freshness.verdict,blocking:!!(t&&(t.summary.verdict==="blocked"||s.length>0)),releaseRisk:t?.impact.risk,blockingReasons:s,resolutionHints:t?.resolutionHints}}if(e.target.kind==="blocker"){let s=e.target,m=t?.resolutionHints?.find(g=>g.blockerId===s.blockerId),i=t?.blockingReasons.find(g=>g.includes(s.blockerId))??t?.blockingReasons[0];return {schemaVersion:a,generatedAt:n,workspacePath:o,target:s,summary:m?`Blocker ${s.blockerId}: ${m.resolutionClass}`:`Blocker ${s.blockerId} (no structured hint)`,sections:[p("reason","Blocking signal",i??"No matching blocking reason in verify."),p("hint","Resolution class",m?`${m.resolutionClass}
4
4
 
@@ -1 +1 @@
1
- import e from'path';import N from'fs-extra';import F from'chalk';async function K(n,o={}){let t=e.resolve(n),{WORKSPACE_CONTRACT_PATH:i,syncWorkspaceContract:c,verifyWorkspaceContract:m,writeWorkspaceContractVerifyEvidence:k}=await import('./workspace-contract-3BWIRSVQ.js'),p=await c({workspacePath:t,strict:true}),{syncWorkspaceReadme:f,WORKSPACE_README_PATH:d}=await import('./workspace-readme-56YZ4EAZ.js'),h=await f({workspacePath:t,workspaceName:p.contract.workspace.name,profile:p.contract.workspace.profile??"minimal",projectCount:p.contract.projects.length}),{buildWorkspaceModel:u,writeWorkspaceModel:g}=await import('./workspace-model-ETCLINRB.js'),a=await u({workspacePath:t,includeEvidence:true}),P=await g(a,t),{buildWorkspaceImpact:W,buildWorkspaceModelSnapshot:C,diffWorkspaceModel:y,writeWorkspaceImpact:A,writeWorkspaceModelDiff:j,writeWorkspaceModelSnapshot:E}=await import('./workspace-intelligence-625UN27X.js'),{WORKSPACE_INTELLIGENCE_ARTIFACTS:s}=await import('./workspace-intelligence-runtime-registry-IW6J53LO.js'),R=e.join(t,s.snapshot),l=false;if(!await N.pathExists(R)){let r=await C({workspacePath:t,model:a});await E(r,t),l=true;}let S=await y({workspacePath:t,fromPath:s.snapshot,model:a}),b=await j(S,t),v=await W({workspacePath:t,fromPath:s.diff}),O=await A(v,t),T=await m({workspacePath:t,strict:true}),_=await k({workspacePath:t,result:T}),{syncWorkspaceAgentGrounding:M}=await import('./workspace-agent-sync-MU7W3C4S.js'),w=await M({workspacePath:t,model:a,write:true,refreshContext:true,strict:false,preset:"enterprise",targets:["all"],projectGrounding:o.projectGrounding??"managed"}),x=[i,(await import('./workspace-registry-summary-VSOBKAJG.js')).WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH,e.relative(t,h).split(e.sep).join("/")||d,e.relative(t,P).split(e.sep).join("/"),s.knowledgeGraph,...l?[s.snapshot]:[],e.relative(t,b).split(e.sep).join("/"),e.relative(t,O).split(e.sep).join("/"),e.relative(t,_).split(e.sep).join("/"),...w.writtenFiles].filter((r,I,G)=>G.indexOf(r)===I);return o.silent||console.log(F.gray(`\u2713 Workspace Intelligence synced \xB7 ${a.summary.projectCount} project(s) \xB7 model + graph + agent grounding`)),{workspacePath:t,projectCount:a.summary.projectCount,baselineCreated:l,writtenFiles:x,warnings:w.projectLenses?.skipped.map(r=>`${r.name}: ${r.reason}`)??[]}}async function D(n,o={}){let t=e.resolve(n),i=o.workspaceName??e.basename(t),{registerWorkspaceStrict:c}=await import('./workspace-J4OGSSNO.js');return await c(t,i),K(t,{silent:o.silent})}export{K as a,D as b};
1
+ import e from'path';import N from'fs-extra';import F from'chalk';async function K(n,o={}){let t=e.resolve(n),{WORKSPACE_CONTRACT_PATH:i,syncWorkspaceContract:c,verifyWorkspaceContract:m,writeWorkspaceContractVerifyEvidence:k}=await import('./workspace-contract-3BWIRSVQ.js'),p=await c({workspacePath:t,strict:true}),{syncWorkspaceReadme:f,WORKSPACE_README_PATH:d}=await import('./workspace-readme-G7TZ3V5T.js'),h=await f({workspacePath:t,workspaceName:p.contract.workspace.name,profile:p.contract.workspace.profile??"minimal",projectCount:p.contract.projects.length}),{buildWorkspaceModel:u,writeWorkspaceModel:g}=await import('./workspace-model-ETCLINRB.js'),a=await u({workspacePath:t,includeEvidence:true}),P=await g(a,t),{buildWorkspaceImpact:W,buildWorkspaceModelSnapshot:C,diffWorkspaceModel:y,writeWorkspaceImpact:A,writeWorkspaceModelDiff:j,writeWorkspaceModelSnapshot:E}=await import('./workspace-intelligence-625UN27X.js'),{WORKSPACE_INTELLIGENCE_ARTIFACTS:s}=await import('./workspace-intelligence-runtime-registry-IW6J53LO.js'),R=e.join(t,s.snapshot),l=false;if(!await N.pathExists(R)){let r=await C({workspacePath:t,model:a});await E(r,t),l=true;}let S=await y({workspacePath:t,fromPath:s.snapshot,model:a}),b=await j(S,t),v=await W({workspacePath:t,fromPath:s.diff}),O=await A(v,t),T=await m({workspacePath:t,strict:true}),_=await k({workspacePath:t,result:T}),{syncWorkspaceAgentGrounding:M}=await import('./workspace-agent-sync-FQU6VIEU.js'),w=await M({workspacePath:t,model:a,write:true,refreshContext:true,strict:false,preset:"enterprise",targets:["all"],projectGrounding:o.projectGrounding??"managed"}),x=[i,(await import('./workspace-registry-summary-VSOBKAJG.js')).WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH,e.relative(t,h).split(e.sep).join("/")||d,e.relative(t,P).split(e.sep).join("/"),s.knowledgeGraph,...l?[s.snapshot]:[],e.relative(t,b).split(e.sep).join("/"),e.relative(t,O).split(e.sep).join("/"),e.relative(t,_).split(e.sep).join("/"),...w.writtenFiles].filter((r,I,G)=>G.indexOf(r)===I);return o.silent||console.log(F.gray(`\u2713 Workspace Intelligence synced \xB7 ${a.summary.projectCount} project(s) \xB7 model + graph + agent grounding`)),{workspacePath:t,projectCount:a.summary.projectCount,baselineCreated:l,writtenFiles:x,warnings:w.projectLenses?.skipped.map(r=>`${r.name}: ${r.reason}`)??[]}}async function D(n,o={}){let t=e.resolve(n),i=o.workspaceName??e.basename(t),{registerWorkspaceStrict:c}=await import('./workspace-XWKEBPS3.js');return await c(t,i),K(t,{silent:o.silent})}export{K as a,D as b};
@@ -2,7 +2,7 @@ import {c as c$1}from'./chunk-HCFWT42C.js';import {a}from'./chunk-A5FBGRJA.js';i
2
2
  `);}async function re(e,r){let t=p.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${e}.${process.pid}.${randomUUID()}.tmp`;try{await promises.writeFile(o,r);let a=await promises.open(o,"r");try{await te(a);}finally{await a.close();}try{await promises.rename(o,e);}catch(s){let i=s.code;if(i!=="EEXIST"&&i!=="EPERM")throw s;await ne.move(o,e,{overwrite:true});}}finally{await promises.rm(o,{force:true}).catch(()=>{});}}async function q(e){try{return {exists:true,content:await promises.readFile(e)}}catch(r){if(r.code==="ENOENT")return {exists:false};throw r}}async function Q(e,r){if(!r.exists){await promises.rm(e,{force:true});return}await re(e,r.content);}async function ue(e,r){let t=p.join(e,"workspaces.json.lock"),o=randomUUID();await promises.mkdir(e,{recursive:true});let a=Date.now(),s;for(;!s;)try{s=await promises.open(t,"wx"),await s.writeFile(`${JSON.stringify({pid:process.pid,lockId:o,createdAt:new Date().toISOString()})}
3
3
  `),await te(s);}catch(i){if(i.code!=="EEXIST")throw i;let n=await promises.stat(t).catch(()=>null);if(n&&Date.now()-n.mtimeMs>ce){let d=await promises.readFile(t,"utf8").then(m=>JSON.parse(m)).catch(()=>null),u=Number(d?.pid),w=false;if(Number.isInteger(u)&&u>0)try{process.kill(u,0),w=true;}catch(m){w=m.code==="EPERM";}if(!w){await promises.rm(t,{force:true}).catch(()=>{});continue}}if(Date.now()-a>pe)throw new Error(`Timed out waiting for workspace registry lock: ${t}`);await new Promise(d=>setTimeout(d,25));}try{return await r()}finally{await s.close().catch(()=>{}),await promises.readFile(t,"utf8").then(n=>JSON.parse(n).lockId===o).catch(()=>false)&&await promises.rm(t,{force:true}).catch(()=>{});}}async function _(e){let r$1=q$1(),t=p.join(r$1,"workspaces.json"),o=p.join(r(),"workspaces.json"),a=[...new Set(s$1())];return ue(r$1,async()=>{let[s,i]=await Promise.all([q(t),q(o)]),n=await ee(a);await e(n);let d=b(n);try{await K(t,d),await K(o,d);}catch(u){let m=(await Promise.allSettled([Q(t,s),Q(o,i)])).filter(g=>g.status==="rejected").map(g=>g.reason);throw m.length>0?new AggregateError([u,...m],"Workspace registry transaction failed and could not be fully restored"):u}return d})}async function oe(e,r){let t=a(e);await _(o=>{let a=o.workspaces.find(s=>s.path===t);if(a){a.name=r,a.mode=a.mode||"full",a.projects=Array.isArray(a.projects)?a.projects:[];return}o.workspaces.push({name:r,path:t,mode:"full",projects:[]});});}async function ze(e){let r=a(e),o=(await ee()).workspaces.find(a=>a.path===r);return o?{...o,projects:o.projects.map(a=>({...a}))}:null}async function Ge(e,r){let t=a(e);await _(o=>{let a=o.workspaces.findIndex(i=>i.path===t);if(!r){a>=0&&o.workspaces.splice(a,1);return}let s=B(r);a>=0?o.workspaces[a]=s:o.workspaces.push(s);});}async function Me(e){let r=a(e);await _(t=>{t.workspaces=t.workspaces.filter(o=>o.path!==r);});}async function ke(e,r){try{await oe(e,r);}catch{console.warn(c.gray("Note: Could not register workspace in shared registry"));}}async function Ve(e,r=false){let t$1=a(e),o={workspacePath:t$1,workspaceFound:false,added:[],skipped:0};try{let a$1=await F(),s=a$1.workspaces.find(g=>g.path===t$1);if(!s){if(await ke(t$1,p.basename(p.resolve(e))),a$1=await F(),s=a$1.workspaces.find(g=>g.path===t$1),!s)return r||console.log("\u26A0\uFE0F Workspace could not be registered in registry"),o;r||console.log("\u2714 Registered workspace in shared registry");}Array.isArray(s.projects)||(s.projects=[]);let i=0,n=0,d=[],u=[],w=[e],m=new Set;for(;w.length>0;){let g=w.shift();if(!g||m.has(g))continue;m.add(g);let y=await promises.readdir(g,{withFileTypes:true});for(let h of y){if(!h.isDirectory()||h.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(h.name))continue;let j=p.join(g,h.name),f=a(j);try{let k=false;for(let $ of [...t(f,"context.json"),...t(f,"project.json")])try{await promises.access($),k=true;break}catch{}if(k){let $=p.basename(f),R=s.projects.some(C=>C.path===f);u.push({name:$,path:f}),R?n++:(s.projects.push({name:$,path:f}),i++,d.push(f),r||console.log(`\u2714 Added: ${p.relative(e,f)}`));continue}}catch{}w.push(j);}}return await _(g=>{let y=g.workspaces.find(f=>f.path===t$1);if(!y)return;let h=`${t$1}${p.sep}`,j=(y.projects||[]).filter(f=>f.path!==t$1&&!f.path.startsWith(h));y.projects=B({...y,projects:[...j,...u]}).projects;}),i>0?r||console.log(`
4
4
  \u2705 Synced ${i} project(s) to registry`):r||console.log(`
5
- \u2705 All projects already registered (${n} found)`),{workspacePath:t$1,workspaceFound:true,added:d,skipped:n}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function we(e,r,t){let o=a(e),a$1=a(t);await _(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let n=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};n>=0?i.projects[n]=d:i.projects.push(d);});}async function Ye(e,r,t){try{await we(e,r,t);}catch{}}async function He(e,r){let t=P("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(p.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(p.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-TPUFKW6B.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=fe();await promises.writeFile(p.join(e,"rapidkit"),s),await promises.chmod(p.join(e,"rapidkit"),493);let i=he();await promises.writeFile(p.join(e,"rapidkit.cmd"),i);let n=ye(r.name);await promises.writeFile(p.join(e,"README.md"),n),await promises.writeFile(p.join(e,".gitignore"),`# Workspai workspace
5
+ \u2705 All projects already registered (${n} found)`),{workspacePath:t$1,workspaceFound:true,added:d,skipped:n}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function we(e,r,t){let o=a(e),a$1=a(t);await _(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let n=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};n>=0?i.projects[n]=d:i.projects.push(d);});}async function Ye(e,r,t){try{await we(e,r,t);}catch{}}async function He(e,r){let t=P("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(p.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(p.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-2VELRQAX.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=fe();await promises.writeFile(p.join(e,"rapidkit"),s),await promises.chmod(p.join(e,"rapidkit"),493);let i=he();await promises.writeFile(p.join(e,"rapidkit.cmd"),i);let n=ye(r.name);await promises.writeFile(p.join(e,"README.md"),n),await promises.writeFile(p.join(e,".gitignore"),`# Workspai workspace
6
6
  .env
7
7
  .env.*
8
8
  !.env.example
@@ -1 +1 @@
1
- import {r as r$1}from'./chunk-VDFHUYAQ.js';import {a as a$1}from'./chunk-VRQLHCE2.js';import {b,c as c$2}from'./chunk-2JVRDBJC.js';import {a as a$2}from'./chunk-GPGEJVVO.js';import {g}from'./chunk-4KNDIFJ5.js';import {j,l as l$2}from'./chunk-RALI2ESF.js';import {c as c$1,d}from'./chunk-JRIEP4BY.js';import {a}from'./chunk-WQX3JYEP.js';import {f as f$1,g as g$1,h as h$1}from'./chunk-O6R7SE6Y.js';import {k,l as l$1,h,m as m$1,n,p as p$2,q}from'./chunk-NBJ6AP7K.js';import {a as a$3}from'./chunk-A4BK7C7M.js';import {j as j$1,e as e$2}from'./chunk-N4QQADXX.js';import {m,p as p$1,s}from'./chunk-NA2NXX5P.js';import {l,o as o$1,p as p$3}from'./chunk-KG3TUTXU.js';import {c,e as e$1}from'./chunk-CCDGHPEJ.js';import {b as b$1}from'./chunk-D65FCQIO.js';import {e,f,o,p,n as n$1,m as m$2}from'./chunk-NZ3WZYD5.js';import {c as c$3}from'./chunk-X6TNBARH.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(e.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===e.intelligenceRun,`artifactPath must be ${e.intelligenceRun}`),r(t.preflight.length===n$1.length,`preflight must contain exactly ${n$1.length} entries`);for(let[d,n]of n$1.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,o[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===m$2.length,`stages must contain exactly ${m$2.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of m$2.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,p[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=e.intelligenceRun,Ee=f.intelligenceRun,L=we;function I(t){c$3({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return c(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t){let s$1=t.workspacePath,m$2=[],u=[],h$2=false,y=async(e,o$1)=>{let c=[...o[e]];if(h$2){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$2.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o$1();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$2.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$2.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$3=async(e,o)=>{let c=[...p[e].produces];if(h$2){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o=await l({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o.contract.projects.length} projects`}});let p$4,d$1=()=>{if(!p$4)throw new Error("canonical workspace model is unavailable");return p$4};await l$3("model",async()=>(p$4={...await p$1({workspacePath:s$1,includeEvidence:true}),build:m({mode:"full",engineStatus:"disabled"})},await s(p$4,s$1),{message:`${p$4.summary.projectCount} projects modeled`}));let n$1=ge.join(s$1,e.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$1)){let c=await k({workspacePath:s$1,model:d$1()});return await l$1(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$1),o=h(e);return o?(await l$1(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$3("diff",async()=>{let e$1=await m$1({workspacePath:s$1,fromPath:e.snapshot,model:d$1()});return await n(e$1,s$1),{message:e$1.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$3("impact",async()=>{let e$1=await p$2({workspacePath:s$1,fromPath:e.diff});return await q(e$1,s$1),{message:`${e$1.summary.risk} risk; ${e$1.summary.affectedProjects} affected`}}),await l$3("doctor-evidence",async()=>{let e=await r$1({workspace:s$1,json:true,quiet:true,profile:t.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$3("contract-evidence",async()=>{let e=await o$1({workspacePath:s$1,strict:true});return await p$3({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$3("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t.strict===true});return {blocked:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$3("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$3("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:e.impact});await g$1(e$1,s$1);let o=h$1(e$1,{strict:t.strict===true});return await j$1(s$1,e$2(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$3("context",async()=>{let e=await c$1({workspacePath:s$1,model:d$1(),agent:t.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$3("agent-sync",async()=>{let e=await l$2({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"}),o=false,c=await a$3(s$1);if(c.status==="miss"){if(c.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c.reason}).`);p$4={...await p$1({workspacePath:s$1,includeEvidence:true}),build:m({mode:"full",engineStatus:"disabled"})},await s(p$4,s$1);let f=await c$1({workspacePath:s$1,model:p$4,agent:t.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$2({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$3("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$2(e,s$1);let o=t.strict===true?u.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u.some(e=>e.status==="blocked"),G=h$2?"failed":me?"blocked":"passed",fe=h$2?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$2,status:G,exitCode:fe,stages:u,artifactPath:L};ue(b$1),await e$1(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await e$1(s$1,e.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
1
+ import {r as r$1}from'./chunk-UIBBSKJ3.js';import {a as a$1}from'./chunk-VRQLHCE2.js';import {b,c as c$2}from'./chunk-PPQL5UTI.js';import {a as a$2}from'./chunk-GPGEJVVO.js';import {g}from'./chunk-QQU536KA.js';import {j,l as l$2}from'./chunk-ODJAKGQF.js';import {c as c$1,d}from'./chunk-TVCJKE2U.js';import {a}from'./chunk-LNXIMF3O.js';import {f as f$1,g as g$1,h as h$1}from'./chunk-O6R7SE6Y.js';import {k,l as l$1,h,m as m$1,n,p as p$2,q}from'./chunk-NBJ6AP7K.js';import {a as a$3}from'./chunk-A4BK7C7M.js';import {j as j$1,e as e$2}from'./chunk-N4QQADXX.js';import {m,p as p$1,s}from'./chunk-NA2NXX5P.js';import {l,o as o$1,p as p$3}from'./chunk-KG3TUTXU.js';import {c,e as e$1}from'./chunk-CCDGHPEJ.js';import {b as b$1}from'./chunk-D65FCQIO.js';import {e,f,o,p,n as n$1,m as m$2}from'./chunk-NZ3WZYD5.js';import {c as c$3}from'./chunk-X6TNBARH.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(e.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===e.intelligenceRun,`artifactPath must be ${e.intelligenceRun}`),r(t.preflight.length===n$1.length,`preflight must contain exactly ${n$1.length} entries`);for(let[d,n]of n$1.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,o[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===m$2.length,`stages must contain exactly ${m$2.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of m$2.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,p[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=e.intelligenceRun,Ee=f.intelligenceRun,L=we;function I(t){c$3({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return c(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t){let s$1=t.workspacePath,m$2=[],u=[],h$2=false,y=async(e,o$1)=>{let c=[...o[e]];if(h$2){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$2.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o$1();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$2.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$2.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$3=async(e,o)=>{let c=[...p[e].produces];if(h$2){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o=await l({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o.contract.projects.length} projects`}});let p$4,d$1=()=>{if(!p$4)throw new Error("canonical workspace model is unavailable");return p$4};await l$3("model",async()=>(p$4={...await p$1({workspacePath:s$1,includeEvidence:true}),build:m({mode:"full",engineStatus:"disabled"})},await s(p$4,s$1),{message:`${p$4.summary.projectCount} projects modeled`}));let n$1=ge.join(s$1,e.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$1)){let c=await k({workspacePath:s$1,model:d$1()});return await l$1(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$1),o=h(e);return o?(await l$1(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$3("diff",async()=>{let e$1=await m$1({workspacePath:s$1,fromPath:e.snapshot,model:d$1()});return await n(e$1,s$1),{message:e$1.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$3("impact",async()=>{let e$1=await p$2({workspacePath:s$1,fromPath:e.diff});return await q(e$1,s$1),{message:`${e$1.summary.risk} risk; ${e$1.summary.affectedProjects} affected`}}),await l$3("doctor-evidence",async()=>{let e=await r$1({workspace:s$1,json:true,quiet:true,profile:t.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$3("contract-evidence",async()=>{let e=await o$1({workspacePath:s$1,strict:true});return await p$3({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$3("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t.strict===true});return {blocked:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$3("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$3("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:e.impact});await g$1(e$1,s$1);let o=h$1(e$1,{strict:t.strict===true});return await j$1(s$1,e$2(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$3("context",async()=>{let e=await c$1({workspacePath:s$1,model:d$1(),agent:t.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$3("agent-sync",async()=>{let e=await l$2({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"}),o=false,c=await a$3(s$1);if(c.status==="miss"){if(c.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c.reason}).`);p$4={...await p$1({workspacePath:s$1,includeEvidence:true}),build:m({mode:"full",engineStatus:"disabled"})},await s(p$4,s$1);let f=await c$1({workspacePath:s$1,model:p$4,agent:t.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$2({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$3("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$2(e,s$1);let o=t.strict===true?u.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u.some(e=>e.status==="blocked"),G=h$2?"failed":me?"blocked":"passed",fe=h$2?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$2,status:G,exitCode:fe,stages:u,artifactPath:L};ue(b$1),await e$1(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await e$1(s$1,e.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
@@ -1,2 +1,2 @@
1
- import {b}from'./chunk-WQX3JYEP.js';import {c}from'./chunk-TFOOSYGO.js';import {p as p$1,h,i}from'./chunk-NA2NXX5P.js';import {a}from'./chunk-KG3TUTXU.js';import {e as e$1,d}from'./chunk-CCDGHPEJ.js';import {f,e}from'./chunk-NZ3WZYD5.js';import E from'path';import S from'fs-extra';var te=f.agentContext,se=e.agentContext;function ae(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let r=e.trim().toLowerCase();return r==="codex"||r==="claude"||r==="cursor"||r==="gemini"||r==="qwen"||r==="kimi"||r==="grok"||r==="copilot"||r==="windsurf"||r==="amazon-q"||r==="orca"?r:"generic"}function L(e){return `npx --yes --package workspai workspai ${e}`.trim()}function j(e){return `npx workspai ${e}`.trim()}async function C(e,r,i){let s=E.join(e,r);if(!await S.pathExists(s))return null;try{let a=await S.readJson(s);return !a||a.schemaVersion!==i?null:a}catch{return null}}function p(e$1){return {id:e$1.id,scope:e$1.scope,display:j(e$1.args),execute:L(e$1.args),description:e$1.description,...e$1.project?{project:e$1.project}:{},freshness:h({id:`command.${e$1.id}`,label:`${e$1.id} command`,scope:"command",value:{display:j(e$1.args),execute:L(e$1.args)},...e$1.project?{project:e$1.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e$1.generatedAt,now:e$1.now,sourceArtifact:e.model,sourcePath:`safeCommands.${e$1.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function D(e,r){return `workspace run ${r} --scope project:${e.name}`}function ne(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase())}function ie(e,r,i){let s={generatedAt:e.generatedAt,now:i},a=[p({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),p({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),p({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),p({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),p({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),p({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),p({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),p({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=r?[r]:e.projects;for(let n of c)n.commands.fleetStages.includes("test")&&a.push(p({id:`project.${n.name}.test`,scope:"project",project:n.name,args:D(n,"test"),description:`Run tests for ${n.name} through workspace orchestration.`,...s})),n.commands.fleetStages.includes("build")&&a.push(p({id:`project.${n.name}.build`,scope:"project",project:n.name,args:D(n,"build"),description:`Build ${n.name} through workspace orchestration.`,...s}));return a}function ce(e){return e.commands.fleetStages.filter(r=>r==="test"||r==="build").map(r=>`workspace run ${r}`)}function de(e,r){if(!r?.startsWith("project:"))return;let i=ne(r);if(i)return e.projects.find(s=>oe(s).includes(i))}function me(e,r,i){let s=[...e.validation?.issues??[]];r?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${r}`,target:r});let a=s.filter(n=>n.severity==="error").length,c=s.filter(n=>n.severity==="warning").length;return {status:a>0?"failed":c>0?"warning":"passed",errors:a,warnings:c,issues:s}}async function pe(e,r){let i=[],s=[];for(let[a,c]of Object.entries(e.evidence))c&&await d(r,c.path)!==null?i.push(`${a}: ${c.path}`):s.push(a);return {available:i.sort(),missing:s.sort()}}function le(e){let r=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${r} project${r===1?"":"s"}, ${i}, and ${s}.`}function ue(e){let r=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||r.push("Workspace contract is missing; dependency and API edges may be incomplete."),e.summary.observedProjects>0&&r.push("Some projects are observed rather than first-class; command support may be partial."),r}async function xe(e$1){let r=e$1.model??await p$1({workspacePath:e$1.workspacePath,includeEvidence:e$1.includeEvidence===true,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),i$1=ae(e$1.agent),s=de(r,e$1.scope),a=me(r,e$1.scope,s);if(e$1.strict===true&&a.status!=="passed"){let t=a.issues.map(u=>`${u.severity}:${u.code}:${u.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${t}`)}let c$1=e$1.now??new Date,n=r.facts??[],K=new Set((s?[s]:r.projects).map(t=>t.name)),F=n.filter(t=>t.project?K.has(t.project):true),H=(s?[s]:r.projects).map(t=>{let u=F.filter(d=>d.project===t.name);return {name:t.name,path:t.path,kind:t.kind,category:t.category,runtime:t.runtime,framework:t.frameworkDisplayName,...t.generator?{generator:t.generator}:{},createCapability:t.createCapability,supportTier:t.supportTier,safeCommands:ce(t),importantFiles:t.importantFiles,facts:u}}),A=await pe(r,e$1.workspacePath),R=E.join(e$1.workspacePath,e.knowledgeGraph),g=await S.pathExists(R)?await S.readJson(R).catch(()=>null):null,$=false;if(g?.schemaVersion===f.knowledgeGraph)try{c(g,r),$=true;}catch{}let M=le(r),I=ie(r,s,c$1),v=await C(e$1.workspacePath,e.impact,f.impact),l=await C(e$1.workspacePath,e.doctor,f.doctor),b$1=await C(e$1.workspacePath,e.analyze,f.analyze),k=await C(e$1.workspacePath,e.readiness,f.readiness),h$1=await C(e$1.workspacePath,e.verify,f.verify),w=await C(e$1.workspacePath,e.explain,f.explain),f$1=await C(e$1.workspacePath,e.diff,f.diff),B=v?.summary?{changed:v.summary.changed,risk:v.summary.risk,affectedProjects:v.summary.affectedProjects,blastRadius:v.summary.blastRadius,recommendedCommands:v.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let t=Array.isArray(l.projects)?l.projects:[],u=[];for(let d of t.slice(0,6)){let re=Array.isArray(d?.probes)?d.probes:[];for(let y of re.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&u.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return u.slice(0,8)})()}:void 0,J=b$1?.summary?{score:b$1.summary.score,verdict:b$1.summary.verdict,findingCounts:b$1.summary.findings,topFindings:(Array.isArray(b$1.findings)?b$1.findings:[]).filter(d=>d?.severity==="fail"||d?.severity==="warn").slice(0,8).map(d=>({severity:d.severity,title:d.title,target:d.target,remediation:d.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(t=>({gate:t.gate,status:t.status,summary:t.summary})):void 0}:void 0,Q=h$1?.summary?{verdict:h$1.summary.verdict,exitCode:h$1.summary.exitCode,stepsFailed:h$1.summary.stepsFailed,stepsMissing:h$1.summary.stepsMissing,blockingReasons:h$1.blockingReasons,missingEvidence:h$1.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(t=>({id:t.id,title:t.title,body:t.body})):void 0}:void 0,Z=f$1?.summary?{changed:f$1.summary.changed,addedProjects:f$1.summary.addedProjects,removedProjects:f$1.summary.removedProjects,changedProjects:f$1.summary.changedProjects,workspaceChanges:f$1.summary.workspaceChanges,validationChanges:f$1.summary.validationChanges,gitChangedFiles:f$1.summary.gitChangedFiles}:void 0,ee=I.map(t=>h({id:`context.command.${t.id}`,label:`${t.id} safe command`,scope:"command",value:{display:t.display,execute:t.execute,scope:t.scope},...t.project?{project:t.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:r.generatedAt,now:c$1,sourceArtifact:e.agentContext,sourcePath:`safeCommands.${t.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),T=[...F,...ee],x=i({facts:T,generatedAt:c$1.toISOString(),now:c$1}),W=b();return {schemaVersion:te,generatedAt:c$1.toISOString(),agent:i$1,workspaceSummary:M,modelRef:e.model,knowledgeGraph:{artifact:e.knowledgeGraph,schemaVersion:f.knowledgeGraph,available:$,...typeof g?.quality?.entityCount=="number"?{entityCount:g.quality.entityCount}:{},...typeof g?.quality?.relationCount=="number"?{relationCount:g.quality.relationCount}:{},...typeof g?.quality?.proofCount=="number"?{proofCount:g.quality.proofCount}:{},queryCommands:[j("workspace graph search <query> --limit 12 --json"),j("workspace graph entities [kind] --json"),j("workspace graph evidence <entity-or-relation> --json"),j("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:W.schemaVersion,contractPath:W.contractPath,currentStep:"context",canonicalReadOrder:[...W.consumers.agents.canonicalReadOrder]},workspace:{name:r.workspace.name,root:r.workspace.root,type:r.identity.workspaceType,...r.workspace.profile?{profile:r.workspace.profile}:{}},scope:{requested:e$1.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:I,facts:T,factFreshness:x,evidence:A,policies:{mode:r.policies.mode,source:r.policies.source},contracts:{exists:r.contracts.exists,path:r.contracts.workspaceContractPath},validation:a,agentInstructions:[`Read \`${e.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${e.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ue(r),...x.verifyBeforeUseFacts>0?[`${x.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[M,`Evidence available: ${A.available.length}. Missing evidence groups: ${A.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
1
+ import {b}from'./chunk-LNXIMF3O.js';import {c}from'./chunk-TFOOSYGO.js';import {p as p$1,h,i}from'./chunk-NA2NXX5P.js';import {a}from'./chunk-KG3TUTXU.js';import {e as e$1,d}from'./chunk-CCDGHPEJ.js';import {f,e}from'./chunk-NZ3WZYD5.js';import E from'path';import S from'fs-extra';var te=f.agentContext,se=e.agentContext;function ae(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let r=e.trim().toLowerCase();return r==="codex"||r==="claude"||r==="cursor"||r==="gemini"||r==="qwen"||r==="kimi"||r==="grok"||r==="copilot"||r==="windsurf"||r==="amazon-q"||r==="orca"?r:"generic"}function L(e){return `npx --yes --package workspai workspai ${e}`.trim()}function j(e){return `npx workspai ${e}`.trim()}async function C(e,r,i){let s=E.join(e,r);if(!await S.pathExists(s))return null;try{let a=await S.readJson(s);return !a||a.schemaVersion!==i?null:a}catch{return null}}function p(e$1){return {id:e$1.id,scope:e$1.scope,display:j(e$1.args),execute:L(e$1.args),description:e$1.description,...e$1.project?{project:e$1.project}:{},freshness:h({id:`command.${e$1.id}`,label:`${e$1.id} command`,scope:"command",value:{display:j(e$1.args),execute:L(e$1.args)},...e$1.project?{project:e$1.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e$1.generatedAt,now:e$1.now,sourceArtifact:e.model,sourcePath:`safeCommands.${e$1.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function D(e,r){return `workspace run ${r} --scope project:${e.name}`}function ne(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase())}function ie(e,r,i){let s={generatedAt:e.generatedAt,now:i},a=[p({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),p({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),p({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),p({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),p({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),p({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),p({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),p({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=r?[r]:e.projects;for(let n of c)n.commands.fleetStages.includes("test")&&a.push(p({id:`project.${n.name}.test`,scope:"project",project:n.name,args:D(n,"test"),description:`Run tests for ${n.name} through workspace orchestration.`,...s})),n.commands.fleetStages.includes("build")&&a.push(p({id:`project.${n.name}.build`,scope:"project",project:n.name,args:D(n,"build"),description:`Build ${n.name} through workspace orchestration.`,...s}));return a}function ce(e){return e.commands.fleetStages.filter(r=>r==="test"||r==="build").map(r=>`workspace run ${r}`)}function de(e,r){if(!r?.startsWith("project:"))return;let i=ne(r);if(i)return e.projects.find(s=>oe(s).includes(i))}function me(e,r,i){let s=[...e.validation?.issues??[]];r?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${r}`,target:r});let a=s.filter(n=>n.severity==="error").length,c=s.filter(n=>n.severity==="warning").length;return {status:a>0?"failed":c>0?"warning":"passed",errors:a,warnings:c,issues:s}}async function pe(e,r){let i=[],s=[];for(let[a,c]of Object.entries(e.evidence))c&&await d(r,c.path)!==null?i.push(`${a}: ${c.path}`):s.push(a);return {available:i.sort(),missing:s.sort()}}function le(e){let r=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${r} project${r===1?"":"s"}, ${i}, and ${s}.`}function ue(e){let r=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||r.push("Workspace contract is missing; dependency and API edges may be incomplete."),e.summary.observedProjects>0&&r.push("Some projects are observed rather than first-class; command support may be partial."),r}async function xe(e$1){let r=e$1.model??await p$1({workspacePath:e$1.workspacePath,includeEvidence:e$1.includeEvidence===true,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),i$1=ae(e$1.agent),s=de(r,e$1.scope),a=me(r,e$1.scope,s);if(e$1.strict===true&&a.status!=="passed"){let t=a.issues.map(u=>`${u.severity}:${u.code}:${u.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${t}`)}let c$1=e$1.now??new Date,n=r.facts??[],K=new Set((s?[s]:r.projects).map(t=>t.name)),F=n.filter(t=>t.project?K.has(t.project):true),H=(s?[s]:r.projects).map(t=>{let u=F.filter(d=>d.project===t.name);return {name:t.name,path:t.path,kind:t.kind,category:t.category,runtime:t.runtime,framework:t.frameworkDisplayName,...t.generator?{generator:t.generator}:{},createCapability:t.createCapability,supportTier:t.supportTier,safeCommands:ce(t),importantFiles:t.importantFiles,facts:u}}),A=await pe(r,e$1.workspacePath),R=E.join(e$1.workspacePath,e.knowledgeGraph),g=await S.pathExists(R)?await S.readJson(R).catch(()=>null):null,$=false;if(g?.schemaVersion===f.knowledgeGraph)try{c(g,r),$=true;}catch{}let M=le(r),I=ie(r,s,c$1),v=await C(e$1.workspacePath,e.impact,f.impact),l=await C(e$1.workspacePath,e.doctor,f.doctor),b$1=await C(e$1.workspacePath,e.analyze,f.analyze),k=await C(e$1.workspacePath,e.readiness,f.readiness),h$1=await C(e$1.workspacePath,e.verify,f.verify),w=await C(e$1.workspacePath,e.explain,f.explain),f$1=await C(e$1.workspacePath,e.diff,f.diff),B=v?.summary?{changed:v.summary.changed,risk:v.summary.risk,affectedProjects:v.summary.affectedProjects,blastRadius:v.summary.blastRadius,recommendedCommands:v.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let t=Array.isArray(l.projects)?l.projects:[],u=[];for(let d of t.slice(0,6)){let re=Array.isArray(d?.probes)?d.probes:[];for(let y of re.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&u.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return u.slice(0,8)})()}:void 0,J=b$1?.summary?{score:b$1.summary.score,verdict:b$1.summary.verdict,findingCounts:b$1.summary.findings,topFindings:(Array.isArray(b$1.findings)?b$1.findings:[]).filter(d=>d?.severity==="fail"||d?.severity==="warn").slice(0,8).map(d=>({severity:d.severity,title:d.title,target:d.target,remediation:d.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(t=>({gate:t.gate,status:t.status,summary:t.summary})):void 0}:void 0,Q=h$1?.summary?{verdict:h$1.summary.verdict,exitCode:h$1.summary.exitCode,stepsFailed:h$1.summary.stepsFailed,stepsMissing:h$1.summary.stepsMissing,blockingReasons:h$1.blockingReasons,missingEvidence:h$1.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(t=>({id:t.id,title:t.title,body:t.body})):void 0}:void 0,Z=f$1?.summary?{changed:f$1.summary.changed,addedProjects:f$1.summary.addedProjects,removedProjects:f$1.summary.removedProjects,changedProjects:f$1.summary.changedProjects,workspaceChanges:f$1.summary.workspaceChanges,validationChanges:f$1.summary.validationChanges,gitChangedFiles:f$1.summary.gitChangedFiles}:void 0,ee=I.map(t=>h({id:`context.command.${t.id}`,label:`${t.id} safe command`,scope:"command",value:{display:t.display,execute:t.execute,scope:t.scope},...t.project?{project:t.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:r.generatedAt,now:c$1,sourceArtifact:e.agentContext,sourcePath:`safeCommands.${t.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),T=[...F,...ee],x=i({facts:T,generatedAt:c$1.toISOString(),now:c$1}),W=b();return {schemaVersion:te,generatedAt:c$1.toISOString(),agent:i$1,workspaceSummary:M,modelRef:e.model,knowledgeGraph:{artifact:e.knowledgeGraph,schemaVersion:f.knowledgeGraph,available:$,...typeof g?.quality?.entityCount=="number"?{entityCount:g.quality.entityCount}:{},...typeof g?.quality?.relationCount=="number"?{relationCount:g.quality.relationCount}:{},...typeof g?.quality?.proofCount=="number"?{proofCount:g.quality.proofCount}:{},queryCommands:[j("workspace graph search <query> --limit 12 --json"),j("workspace graph entities [kind] --json"),j("workspace graph evidence <entity-or-relation> --json"),j("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:W.schemaVersion,contractPath:W.contractPath,currentStep:"context",canonicalReadOrder:[...W.consumers.agents.canonicalReadOrder]},workspace:{name:r.workspace.name,root:`workspace:${r.workspace.name}`,type:r.identity.workspaceType,...r.workspace.profile?{profile:r.workspace.profile}:{}},scope:{requested:e$1.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:I,facts:T,factFreshness:x,evidence:A,policies:{mode:r.policies.mode,source:r.policies.source},contracts:{exists:r.contracts.exists,path:r.contracts.workspaceContractPath},validation:a,agentInstructions:[`Read \`${e.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${e.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ue(r),...x.verifyBeforeUseFacts>0?[`${x.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[M,`Evidence available: ${A.available.length}. Missing evidence groups: ${A.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
2
2
  `),impactSummary:B,doctorSummary:U,analyzeSummary:J,readinessSummary:X,verifySummary:Q,explainSummary:Y,diffSummary:Z}}async function We(e,r){return e$1(r,se,a(e))}export{te as a,se as b,xe as c,We as d};
@@ -0,0 +1 @@
1
+ import {a as a$1}from'./chunk-LPCWROQ3.js';import {f as f$1,e as e$1,g as g$1,i}from'./chunk-NZ3WZYD5.js';var g=f$1.repairTransaction,v=e$1.repairTransaction,b=g$1.repairTransaction;var k="workspai.workspace-repair-proposal.v1",x="contracts/workspace-intelligence/workspace-repair-proposal.v1.json";var m="workspai.workspace-repair-capabilities.v1",y="workspai.workspace-repair-consumer-protocol.v1",w=[{id:"node",ecosystem:"JavaScript / TypeScript",manifests:["package.json"],lockfiles:["package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"],packageManagers:["npm","pnpm","yarn","bun"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["selected package manager"]},{id:"python",ecosystem:"Python",manifests:["pyproject.toml","requirements.txt"],lockfiles:["uv.lock","poetry.lock","requirements.txt"],packageManagers:["uv","poetry","pip"],support:"conditional",stages:{reconcile:"conditional",audit:"conditional",test:"conditional",build:"declared"},requiredToolFamilies:["isolated Python","selected environment manager","pip-audit or governed Doctor audit"],limitation:"A bounded isolated environment and an installed audit surface are required."},{id:"go",ecosystem:"Go",manifests:["go.mod"],lockfiles:["go.sum"],packageManagers:["go modules"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["go","govulncheck"],limitation:"govulncheck must be installed; the engine never fetches an unreviewed tool."},{id:"rust",ecosystem:"Rust",manifests:["Cargo.toml"],lockfiles:["Cargo.lock"],packageManagers:["cargo"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["cargo","cargo-audit"],limitation:"The cargo-audit subcommand must already be installed."},{id:"php-composer",ecosystem:"PHP",manifests:["composer.json"],lockfiles:["composer.lock"],packageManagers:["composer"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["composer"]},{id:"ruby-bundler",ecosystem:"Ruby",manifests:["Gemfile"],lockfiles:["Gemfile.lock"],packageManagers:["bundler"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"declared",build:"declared"},requiredToolFamilies:["bundle","bundle-audit"],limitation:"bundle-audit and the declared Rake tasks must already exist."},{id:"elixir-mix",ecosystem:"Elixir",manifests:["mix.exs"],lockfiles:["mix.lock"],packageManagers:["mix"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["mix","Hex audit task"],limitation:"The project must expose the Hex audit task used by its dependency policy."},{id:"deno",ecosystem:"Deno",manifests:["deno.json","deno.jsonc"],lockfiles:["deno.lock"],packageManagers:["deno"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["deno"]},{id:"dotnet",ecosystem:".NET",manifests:["*.sln","*.csproj","*.fsproj","*.vbproj"],lockfiles:["Directory.Packages.props","packages.lock.json"],packageManagers:["NuGet / dotnet"],support:"full",stages:{reconcile:"native",audit:"native",test:"native",build:"native"},requiredToolFamilies:["dotnet"]},{id:"jvm-maven",ecosystem:"JVM / Maven",manifests:["pom.xml"],lockfiles:[],packageManagers:["Maven Wrapper","Maven"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["mvnw or mvn","governed Doctor audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."},{id:"jvm-gradle",ecosystem:"JVM / Gradle",manifests:["build.gradle.kts","build.gradle"],lockfiles:["gradle.lockfile","gradle/libs.versions.toml"],packageManagers:["Gradle Wrapper","Gradle"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["gradlew or gradle","governed Doctor audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."},{id:"clojure",ecosystem:"Clojure",manifests:["deps.edn","project.clj"],lockfiles:[],packageManagers:["Clojure CLI","Leiningen"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"conditional",build:"conditional"},requiredToolFamilies:["clojure or lein","governed project audit"],limitation:"Tests and builds run only when the selected Clojure project surface declares a deterministic entrypoint."},{id:"scala-sbt",ecosystem:"Scala / sbt",manifests:["build.sbt"],lockfiles:[],packageManagers:["sbt"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["sbt","governed project audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."}];function T(){return {schemaVersion:m,owner:"Workspai CLI",workflow:["plan","preconditions","approval","target-precondition","checkpoint","execute","reconcile","audit","test","build","target-producer-verify","canonical-verify","close-or-rollback-or-decision"],invariants:{multiAdapterProjects:true,missingTools:"decision-required",unsupportedEcosystems:"decision-required",silentFallbackToModelExecution:false,mutationAuthority:"cli-only",targetClosure:"selected-causal-action-set",changeReceipt:"checkpoint-hash-delta",consumerTimeline:"durable-transaction-events",typedDecisionCauses:true,registeredLinkedProjectMutationBoundary:true,sourceProposalIntegrity:"project-bound-hash-pinned",completionAuthority:"cli-verification-receipt",goalSourceTransition:"closed-integrity-bound-v1",goalAttemptBudget:"durable-serialized-v1",consumerHandshakeRequired:true,ephemeralProposalsAreEvidence:false,approvalBoundToPlanHash:true,canonicalVerificationRequired:true,rollbackConflictDetection:true},consumerProtocol:{protocolVersion:y,versionProbe:{args:["--version","--json"],schemaVersion:"rapidkit-version-v1"},capabilityProbe:{args:["workspace","repair","capabilities","--json"],schemaVersion:m},invocation:{command:"workspace repair",workspaceResolution:["process-cwd","--workspace"],actions:["capabilities","plan","propose","approve","decide","execute","resume","status","list","rollback","cancel"]},contracts:{operationResult:a$1,proposal:k,transaction:g},transientPaths:[".workspai/repair/inbox/*.json",".workspai/repair/engine.lock"]},adapters:w}}var N="workspai.studio-card-repair-capabilities.v1",f="npx workspai workspace verify --json",r=e$1,a=i;function e(R,n,c,o={}){return {cardId:R,scope:o.scope??"workspace",producerCommand:n,producerArtifact:c,verifyCommand:n,verifyArtifact:c,aggregateVerifyCommand:f,targetClosure:"exact-producer-and-causal-action-set",aggregateRepair:"sequential-causal-queue",transactionScope:"one-causal-finding-family",workspacePosture:"reported-separately",repairPolicy:o.repairPolicy??"refresh-producer",remediationArtifacts:o.remediationArtifacts??[]}}var M=[e("doctor","npx workspai doctor workspace --json",r.doctor,{repairPolicy:"diagnose-and-repair",remediationArtifacts:[a.doctorRemediationPlan,a.artifactRemediationPlan]}),e("projectDoctor","npx workspai doctor project --json",a.doctorProject,{scope:"project",repairPolicy:"diagnose-and-repair",remediationArtifacts:[a.doctorRemediationPlan,a.artifactRemediationPlan]}),e("pipeline","npx workspai pipeline --json --strict",a.pipelineLastRun,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("analyze","npx workspai analyze --json",r.analyze,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("readiness","npx workspai readiness --json",r.readiness,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("bootstrap","npx workspai bootstrap --ci --json",a.bootstrapCompliance,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("workspaceSync","npx workspai workspace sync --json",a.workspaceRegistry),e("foundation","npx workspai workspace foundation ensure --json",".workspai/workspace.json"),e("contract","npx workspai workspace contract verify --strict --json",r.contractVerify,{repairPolicy:"source-repair-then-produce"}),e("autopilot","npx workspai autopilot release --json",a.autopilotReleaseLastRun,{repairPolicy:"source-repair-then-produce"}),e("workspaceRun","npx workspai workspace run test --json",a.workspaceRunLast,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("setup","npx workspai setup --json",".workspai/toolchain.lock",{repairPolicy:"source-repair-then-produce"}),e("importReadiness","npx workspai doctor project --json",a.doctorProject,{scope:"project",repairPolicy:"diagnose-and-repair",remediationArtifacts:[a.artifactRemediationPlan]}),e("snapshot","npx workspai snapshot create --json",".workspai/reports/snapshot-last-run.json"),e("workspaceModel","npx workspai workspace model --json --write",r.model),e("intelligenceSnapshot","npx workspai workspace snapshot --json",r.snapshot),e("workspaceDiff",`npx workspai workspace diff --from ${r.snapshot} --json`,r.diff),e("workspaceImpact",`npx workspai workspace impact --from ${r.diff} --json`,r.impact),e("workspaceIntelligenceRun","npx workspai workspace intelligence run --for-agent generic --strict --json",r.intelligenceRun,{repairPolicy:"source-repair-then-produce"}),e("workspaceVerify",f,r.verify,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("workspaceExplain","npx workspai workspace explain release-blocked --json --write",r.explain),e("workspaceWhy","npx workspai workspace why release-blocked --json --write",a.workspaceWhy),e("workspaceTrace",`npx workspai workspace trace --from ${r.diff} --json --write`,a.workspaceTrace),e("workspaceWatch","npx workspai workspace watch --once --json",r.model),e("workspaceContextAgent","npx workspai workspace context --for-agent --json --write",r.agentContext),e("agentGrounding","npx workspai workspace agent-sync --write --refresh-context --json --preset enterprise --target vscode",r.agentCustomizationPack),e("share",`npx workspai workspace share --output ${a.workspaceShareBundle} --json`,a.workspaceShareBundle),e("archive","npx workspai workspace export --output team-workspace.workspai-archive.zip --json",".workspai/archive-manifest.json"),e("mirror","npx workspai mirror status --json",a.mirrorOps),e("cache","npx workspai cache status --json",".workspai/cache-config.yml"),e("policy","npx workspai workspace policy show --json",".workspai/policies.yml",{repairPolicy:"source-repair-then-produce"}),e("infra","npx workspai infra plan --json",a.infraPlan,{repairPolicy:"source-repair-then-produce"})];export{g as a,v as b,b as c,k as d,x as e,m as f,w as g,T as h,N as i,M as j};
@@ -1,4 +1,4 @@
1
- import {f,e as e$2,g as g$1}from'./chunk-NVQUBUTY.js';import {b as b$4}from'./chunk-JEGG4EEZ.js';import {b as b$7,a as a$3}from'./chunk-THIOE2PB.js';import {b as b$2}from'./chunk-B6FJ6RG6.js';import {a as a$2}from'./chunk-KCJ3VS6R.js';import {e,g,f as f$1,b as b$6,c as c$1,d as d$3}from'./chunk-PTNLVI62.js';import {d,b as b$1}from'./chunk-Y5YAP4F3.js';import {d as d$4}from'./chunk-KG3TUTXU.js';import {h,e as e$1,b as b$3,d as d$1}from'./chunk-X6TNBARH.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {b,a,c,d as d$2}from'./chunk-MOSXTVPU.js';import {b as b$5,k,j,m,i,t,s,q as q$1}from'./chunk-RJIYCDVC.js';import {promises}from'fs';import*as P from'fs-extra';import p from'path';import r from'chalk';import {execa}from'execa';function st(e){let n=e.projectCount??0,t=n===1?"project":"projects",a=e.pythonEngine==="installed"?`Python ${e.pythonVersion||"3.10+"} \xB7 ${e.installMethod||"local environment"}`:e.pythonEngine==="skipped"?"Python engine not installed":"Runtime-neutral foundation";return ["","\u2713 Workspace ready",`${e.workspaceName} \xB7 ${e.profile} \xB7 ${n} registered ${t}`,`Location ${e.workspacePath}`,`Runtime ${a}`,...e.note?[`Note ${e.note}`]:[],"","Workspace Intelligence"," \u2713 Contract and project registry"," \u2713 Canonical model and proof-backed graph"," \u2713 Agent context, grounding, and evidence index","","Next",` ${g$1(e.workspacePath)}`," npx workspai create"," npx workspai workspace intelligence run --for-agent generic --strict --json","","Evidence .workspai/reports/INDEX.json","Guide README.md",""]}function q(e){let n=st(e);for(let t of n)t==="\u2713 Workspace ready"?console.log(r.green.bold(t)):t==="Workspace Intelligence"||t==="Next"?console.log(r.cyan.bold(t)):t.startsWith(" \u2713")?console.log(r.green(t)):t.startsWith("Location")||t.startsWith("Runtime")?console.log(r.gray(t)):console.log(t);}function M(){return i()}var lt="transactions";function ct(){return p.join(q$1(),lt)}async function Ve(){let e=ct();return await b$7(e),a$3({journalDirectory:e})}async function Ge(e){for(let n of s())await e.captureFile(n);}async function ae(e){let n=await Ve();try{return await Ge(n),await n.captureOwnedTree(e),n}catch(t){return K(n,t)}}async function pt(e){let n=await Ve();try{await Ge(n),await n.captureOwnedTree(p.join(e,a)),await n.captureOwnedTree(p.join(e,".venv"));let t=[c,".gitignore",p.join(a,"workspace.json"),p.join(a,"toolchain.lock"),p.join(a,"policies.yml"),p.join(a,"cache-config.yml"),d$4,a$2,"pyproject.toml","poetry.toml","poetry.lock","rapidkit","rapidkit.cmd","README.md",".rapidkit-global"];for(let a of t)await n.captureFile(p.join(e,a));return n}catch(t){return K(n,t)}}async function z(e){await e.commit(),e.journalPath&&await promises.rm(p.dirname(e.journalPath),{recursive:true,force:true}).catch(n=>e$1.debug(`Could not remove committed lifecycle journal: ${n}`));}async function K(e,n){try{await e.rollback();}catch(t){throw new AggregateError([n,t],"Workspace lifecycle failed and rollback was incomplete.")}throw n}async function B(e,n,t,a,s){let l=d(n,h(),t,s?.pythonEngine?{coreStatus:s.pythonEngine,...s.pythonEngineReason?{coreReason:s.pythonEngineReason}:{},...a?{pythonVersion:a}:{}}:void 0);a&&!s?.pythonEngine&&(l.metadata||(l.metadata={}),l.metadata.python={pythonVersion:a}),await b$1(e,l);}async function G(e){await P.outputFile(p.join(e,".gitignore"),`.venv/
1
+ import {f,e as e$2,g as g$1}from'./chunk-NVQUBUTY.js';import {b as b$4}from'./chunk-QB3BLYUR.js';import {b as b$7,a as a$3}from'./chunk-THIOE2PB.js';import {b as b$2}from'./chunk-B6FJ6RG6.js';import {a as a$2}from'./chunk-KCJ3VS6R.js';import {e,g,f as f$1,b as b$6,c as c$1,d as d$3}from'./chunk-PTNLVI62.js';import {d,b as b$1}from'./chunk-Y5YAP4F3.js';import {d as d$4}from'./chunk-KG3TUTXU.js';import {h,e as e$1,b as b$3,d as d$1}from'./chunk-X6TNBARH.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {b,a,c,d as d$2}from'./chunk-MOSXTVPU.js';import {b as b$5,k,j,m,i,t,s,q as q$1}from'./chunk-RJIYCDVC.js';import {promises}from'fs';import*as P from'fs-extra';import p from'path';import r from'chalk';import {execa}from'execa';function st(e){let n=e.projectCount??0,t=n===1?"project":"projects",a=e.pythonEngine==="installed"?`Python ${e.pythonVersion||"3.10+"} \xB7 ${e.installMethod||"local environment"}`:e.pythonEngine==="skipped"?"Python engine not installed":"Runtime-neutral foundation";return ["","\u2713 Workspace ready",`${e.workspaceName} \xB7 ${e.profile} \xB7 ${n} registered ${t}`,`Location ${e.workspacePath}`,`Runtime ${a}`,...e.note?[`Note ${e.note}`]:[],"","Workspace Intelligence"," \u2713 Contract and project registry"," \u2713 Canonical model and proof-backed graph"," \u2713 Agent context, grounding, and evidence index","","Next",` ${g$1(e.workspacePath)}`," npx workspai create"," npx workspai workspace intelligence run --for-agent generic --strict --json","","Evidence .workspai/reports/INDEX.json","Guide README.md",""]}function q(e){let n=st(e);for(let t of n)t==="\u2713 Workspace ready"?console.log(r.green.bold(t)):t==="Workspace Intelligence"||t==="Next"?console.log(r.cyan.bold(t)):t.startsWith(" \u2713")?console.log(r.green(t)):t.startsWith("Location")||t.startsWith("Runtime")?console.log(r.gray(t)):console.log(t);}function M(){return i()}var lt="transactions";function ct(){return p.join(q$1(),lt)}async function Ve(){let e=ct();return await b$7(e),a$3({journalDirectory:e})}async function Ge(e){for(let n of s())await e.captureFile(n);}async function ae(e){let n=await Ve();try{return await Ge(n),await n.captureOwnedTree(e),n}catch(t){return K(n,t)}}async function pt(e){let n=await Ve();try{await Ge(n),await n.captureOwnedTree(p.join(e,a)),await n.captureOwnedTree(p.join(e,".venv"));let t=[c,".gitignore",p.join(a,"workspace.json"),p.join(a,"toolchain.lock"),p.join(a,"policies.yml"),p.join(a,"cache-config.yml"),d$4,a$2,"pyproject.toml","poetry.toml","poetry.lock","rapidkit","rapidkit.cmd","README.md",".rapidkit-global"];for(let a of t)await n.captureFile(p.join(e,a));return n}catch(t){return K(n,t)}}async function z(e){await e.commit(),e.journalPath&&await promises.rm(p.dirname(e.journalPath),{recursive:true,force:true}).catch(n=>e$1.debug(`Could not remove committed lifecycle journal: ${n}`));}async function K(e,n){try{await e.rollback();}catch(t){throw new AggregateError([n,t],"Workspace lifecycle failed and rollback was incomplete.")}throw n}async function B(e,n,t,a,s){let l=d(n,h(),t,s?.pythonEngine?{coreStatus:s.pythonEngine,...s.pythonEngineReason?{coreReason:s.pythonEngineReason}:{},...a?{pythonVersion:a}:{}}:void 0);a&&!s?.pythonEngine&&(l.metadata||(l.metadata={}),l.metadata.python={pythonVersion:a}),await b$1(e,l);}async function G(e){await P.outputFile(p.join(e,".gitignore"),`.venv/
2
2
  __pycache__/
3
3
  *.pyc
4
4
  .env