workspai 0.51.0 → 0.52.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 (110) hide show
  1. package/README.md +1 -0
  2. package/contracts/artifact-remediation-plan.v1.json +87 -0
  3. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +24 -0
  4. package/contracts/doctor-project-evidence.v1.json +46 -0
  5. package/contracts/doctor-remediation-plan.v1.json +82 -0
  6. package/contracts/doctor-workspace-evidence.v1.json +46 -0
  7. package/contracts/extension-cli-compatibility.v1.json +6 -2
  8. package/contracts/published-contract-catalog.v1.json +22 -1
  9. package/contracts/runtime-command-surface.v1.json +104 -0
  10. package/contracts/workspace-intelligence/doctor-dependency-repair-transaction.v1.json +66 -0
  11. package/contracts/workspace-intelligence/studio-blocker-handoff.v1.json +5 -0
  12. package/contracts/workspace-intelligence/verified-goal-status.v1.json +27 -0
  13. package/contracts/workspace-intelligence/verified-goal.v1.json +163 -0
  14. package/contracts/workspace-intelligence-chain.v1.json +6 -0
  15. package/dist/analyze-J7VNZMDH.js +1 -0
  16. package/dist/artifact-remediation-plan-2UKY4TKO.js +3 -0
  17. package/dist/autopilot-release-UG23AWVH.js +1 -0
  18. package/dist/chunk-27UR373Z.js +1 -0
  19. package/dist/chunk-2PY65U6X.js +5 -0
  20. package/dist/{chunk-DQ3PI7EP.js → chunk-3D3PFPP5.js} +1 -1
  21. package/dist/chunk-4D7DIGAB.js +1 -0
  22. package/dist/{chunk-IND3TUVU.js → chunk-4UVGTFOX.js} +1 -1
  23. package/dist/{chunk-U2QL5733.js → chunk-5XJRCP3D.js} +24 -24
  24. package/dist/chunk-62K2H72S.js +1 -0
  25. package/dist/chunk-6AXRIAP2.js +86 -0
  26. package/dist/{chunk-TROHVI2V.js → chunk-6HJJHEL6.js} +1 -1
  27. package/dist/{chunk-BHYTI3RH.js → chunk-6PBSAAS5.js} +1 -1
  28. package/dist/{chunk-MVLIONQD.js → chunk-7MQZQ4UU.js} +1 -1
  29. package/dist/chunk-7RLGOEWV.js +1 -0
  30. package/dist/chunk-B4CPDK6J.js +2 -0
  31. package/dist/{chunk-SHXJ2GDR.js → chunk-DZ4VKAXB.js} +1 -1
  32. package/dist/{chunk-FKWB66NQ.js → chunk-F4KBYFZ5.js} +1 -1
  33. package/dist/{chunk-Q6TKQVKQ.js → chunk-FRJYAJH6.js} +1 -1
  34. package/dist/chunk-FUPHQOJB.js +1 -0
  35. package/dist/{chunk-BG4FWJJ3.js → chunk-GHB6QMQH.js} +1 -1
  36. package/dist/chunk-GR6442P7.js +1 -0
  37. package/dist/{chunk-DLM6C7FU.js → chunk-HPWLSLMC.js} +1 -1
  38. package/dist/{chunk-HMGPELXS.js → chunk-ICLYL3N5.js} +1 -1
  39. package/dist/{chunk-MAF3LLGK.js → chunk-IO54DFWR.js} +1 -1
  40. package/dist/{chunk-FZ76CF2W.js → chunk-KHEJO3JU.js} +1 -1
  41. package/dist/{chunk-U2LR73E2.js → chunk-LOCPNNSK.js} +1 -1
  42. package/dist/{chunk-EPVFKJF4.js → chunk-LPCL4U4L.js} +1 -1
  43. package/dist/{chunk-4WJC5QCD.js → chunk-M5ICGR55.js} +1 -1
  44. package/dist/{chunk-XBM2P45G.js → chunk-MBRU3VWJ.js} +1 -1
  45. package/dist/{chunk-VCW5HSPC.js → chunk-MZFSINY7.js} +3 -3
  46. package/dist/{chunk-E3CT7TYT.js → chunk-OTDGTAZJ.js} +1 -1
  47. package/dist/chunk-P4OSLAVD.js +3 -0
  48. package/dist/{chunk-GBAO4GSW.js → chunk-PTTZPDLX.js} +1 -1
  49. package/dist/chunk-Q6CUJ3WF.js +10 -0
  50. package/dist/{chunk-6HLPTJZ3.js → chunk-QURMI7ID.js} +1 -1
  51. package/dist/{chunk-RVQLMTTI.js → chunk-ULR66OJR.js} +1 -1
  52. package/dist/{chunk-HSZCINFX.js → chunk-WJY7ZXVJ.js} +1 -1
  53. package/dist/{chunk-VU2BKKMB.js → chunk-XHRHNVCZ.js} +1 -1
  54. package/dist/chunk-ZTKIBREF.js +1 -0
  55. package/dist/{chunk-HE4PUMU4.js → chunk-ZVOEPWQM.js} +1 -1
  56. package/dist/{create-SBFBFXKN.js → create-ESK3CQPK.js} +1 -1
  57. package/dist/{doctor-OPCMTBJB.js → doctor-DLEBZSF7.js} +1 -1
  58. package/dist/index.d.ts +26 -11
  59. package/dist/index.js +240 -240
  60. package/dist/{pipeline-7BUXAFS2.js → pipeline-NT6AYYWM.js} +1 -1
  61. package/dist/{project-intelligence-lens-BKKVPCLC.js → project-intelligence-lens-Q4SZDI2N.js} +1 -1
  62. package/dist/project-test-coverage-A677ZLW3.js +1 -0
  63. package/dist/verified-goal-MJNZROS5.js +1 -0
  64. package/dist/{workspace-U6ZQLELX.js → workspace-LSOZM2CG.js} +1 -1
  65. package/dist/{workspace-agent-sync-L4SY7B4Q.js → workspace-agent-sync-RZBQXCNJ.js} +1 -1
  66. package/dist/{workspace-archive-4JNT4S7N.js → workspace-archive-ZOWQXWJ6.js} +1 -1
  67. package/dist/{workspace-context-KOBSLZTI.js → workspace-context-IYJKO5BN.js} +1 -1
  68. package/dist/{workspace-contract-SOD3OOVF.js → workspace-contract-AZFISDLS.js} +1 -1
  69. package/dist/workspace-explain-26UGV7L4.js +1 -0
  70. package/dist/workspace-explain-contract-GIWPCCEF.js +1 -0
  71. package/dist/{workspace-feedback-ZZ4HPW2T.js → workspace-feedback-LIHEWTNV.js} +1 -1
  72. package/dist/{workspace-foundation-PUIYBQUF.js → workspace-foundation-H5UTAUXQ.js} +1 -1
  73. package/dist/{workspace-graph-stream-BLKIC7VN.js → workspace-graph-stream-KUDOZE73.js} +1 -1
  74. package/dist/{workspace-history-SPKNRHIX.js → workspace-history-HULG5EFN.js} +1 -1
  75. package/dist/{workspace-intelligence-I3ABOH2F.js → workspace-intelligence-A4UE4DZK.js} +1 -1
  76. package/dist/{workspace-intelligence-evaluation-7CABG5Y6.js → workspace-intelligence-evaluation-AOLGHYHC.js} +1 -1
  77. package/dist/workspace-intelligence-runner-42QI5RYA.js +1 -0
  78. package/dist/{workspace-intelligence-runtime-registry-ZZ3GRAL2.js → workspace-intelligence-runtime-registry-YOQ5GFFJ.js} +1 -1
  79. package/dist/{workspace-knowledge-graph-5MKEI4Z5.js → workspace-knowledge-graph-LEM6X5CM.js} +1 -1
  80. package/dist/{workspace-mcp-serve-ETNUA72W.js → workspace-mcp-serve-N2QPR7VJ.js} +1 -1
  81. package/dist/{workspace-model-HHA37SNH.js → workspace-model-FJXX3NET.js} +1 -1
  82. package/dist/{workspace-onboarding-ELHZABJE.js → workspace-onboarding-IKFISWWY.js} +1 -1
  83. package/dist/{workspace-readme-HGGZ4AZB.js → workspace-readme-E2M35RJH.js} +1 -1
  84. package/dist/{workspace-registry-summary-D2QM5JF6.js → workspace-registry-summary-HOQ3OBNT.js} +1 -1
  85. package/dist/workspace-run-GOZTUGJS.js +1 -0
  86. package/dist/{workspace-verify-4WJTLXRA.js → workspace-verify-32AWCJQG.js} +1 -1
  87. package/dist/workspace-watch-4WVNB26E.js +1 -0
  88. package/docs/README.md +1 -0
  89. package/docs/ci-workflows.md +40 -11
  90. package/docs/commands-reference.md +12 -0
  91. package/docs/doctor-command.md +16 -0
  92. package/docs/workspace-intelligence-runner.md +48 -0
  93. package/package.json +4 -2
  94. package/dist/analyze-4H33PAUB.js +0 -1
  95. package/dist/artifact-remediation-plan-TQ6KTTXD.js +0 -3
  96. package/dist/autopilot-release-BHZYM5KX.js +0 -1
  97. package/dist/chunk-2D4UOYOJ.js +0 -1
  98. package/dist/chunk-3D2PAIRH.js +0 -3
  99. package/dist/chunk-AHLMIL2T.js +0 -1
  100. package/dist/chunk-BBGNDMRU.js +0 -2
  101. package/dist/chunk-BYTFXQ6G.js +0 -1
  102. package/dist/chunk-GQRWRHSR.js +0 -86
  103. package/dist/chunk-L2E2Z4OE.js +0 -5
  104. package/dist/chunk-TDTCMZK7.js +0 -10
  105. package/dist/project-test-coverage-BALEHHTT.js +0 -1
  106. package/dist/workspace-explain-2CTMW2YW.js +0 -1
  107. package/dist/workspace-explain-contract-H7O26QJU.js +0 -1
  108. package/dist/workspace-intelligence-runner-Q2XSR3ZL.js +0 -1
  109. package/dist/workspace-run-DAAZBCN7.js +0 -1
  110. package/dist/workspace-watch-2PIFTQ6B.js +0 -1
@@ -0,0 +1,3 @@
1
+ import {l}from'./chunk-FUPHQOJB.js';import {d,c}from'./chunk-EWZZUQBR.js';import {a as a$1}from'./chunk-GR6442P7.js';import {b as b$1,a}from'./chunk-62K2H72S.js';import h from'path';import {createHash}from'crypto';import $ from'fs-extra';import {parseAllDocuments}from'yaml';var U=b$1.knowledgeGraph;var Xe=a.knowledgeGraph;function et(e,t){if(e.source.kind!=="workspace-model")throw new Error(`Workspace knowledge graph is not bound to the canonical workspace model (source: ${e.source.kind}).`);if(e.source.artifact!==a.model)throw new Error(`Workspace knowledge graph source artifact is ${e.source.artifact}; expected ${a.model}.`);if(e.source.hashAlgorithm!=="sha256")throw new Error(`Workspace knowledge graph source hash algorithm is ${e.source.hashAlgorithm}; expected sha256.`);let o=d(t);if(e.source.hash!==o)throw new Error("Workspace knowledge graph is stale: its source hash does not match the canonical workspace model.");if(e.workspace.name!==t.workspace.name||(e.workspace.profile??void 0)!==(t.workspace.profile??void 0))throw new Error("Workspace knowledge graph identity does not match the canonical workspace model.");let i=l(t);if(!i)throw new Error("Canonical workspace model has no project topology for the workspace knowledge graph.");let r=d=>({...d,generatedAt:"<ignored>"});if(c(r(e.projectTopology))!==c(r(i)))throw new Error("Workspace knowledge graph project topology does not match the canonical workspace model.")}var me=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","venv","vendor","node_modules","dist","build","target","coverage",".next",".turbo",".cache"]),x=new Set(["package.json","pyproject.toml","requirements.txt","Pipfile","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts","composer.json","Gemfile","mix.exs","pubspec.yaml","Package.swift","CMakeLists.txt","deno.json","deno.jsonc","project.clj","deps.edn","build.sbt","BUILD","BUILD.bazel","WORKSPACE.bazel"]),ge=new Set(["get","put","post","delete","options","head","patch","trace"]),L=new Set([".c",".cc",".cpp",".cs",".dart",".ex",".exs",".go",".h",".hpp",".java",".js",".jsx",".kt",".kts",".mjs",".php",".py",".r",".rb",".rs",".scala",".svelte",".swift",".ts",".tsx",".vue",".clj",".cljs",".fs",".fsx",".lua",".vb"]);function F(e){let t=h.extname(e).toLowerCase();return {".c":"c",".cc":"cpp",".cpp":"cpp",".cs":"csharp",".dart":"dart",".ex":"elixir",".exs":"elixir",".go":"go",".h":"c",".hpp":"cpp",".java":"java",".js":"javascript",".jsx":"javascript",".kt":"kotlin",".kts":"kotlin",".mjs":"javascript",".php":"php",".py":"python",".r":"r",".rb":"ruby",".rs":"rust",".scala":"scala",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescript",".vue":"vue",".clj":"clojure",".cljs":"clojure",".fs":"fsharp",".fsx":"fsharp",".lua":"lua",".vb":"visual-basic"}[t]??t.slice(1)}function B(e,t,o){let i=[],r=e.split(/\r?\n/);for(let d=0;d<r.length&&i.length<o;d+=1)for(let s of t){let a=r[d].match(s.pattern)?.[1]?.trim();if(a){i.push({name:a,line:d+1,detail:s.detail});break}}return i}var he=[{pattern:/^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/,detail:"function"},{pattern:/^\s*(?:export\s+)?(?:abstract\s+)?(?:class|interface|enum|type)\s+([A-Za-z_$][\w$]*)/,detail:"type"},{pattern:/^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*class\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*(?:public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+)*(?:class|interface|record|enum)\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*(?:pub\s+)?fn\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*(?:pub\s+)?(?:struct|trait|enum)\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*(?:public\s+|private\s+|protected\s+)?function\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*(?:class|module|struct|protocol|mixin)\s+([A-Za-z_]\w*)/,detail:"type"}],ke=[{pattern:/^\s*import(?:.+?from\s*)?["']([^"']+)["']/,detail:"import"},{pattern:/require\(["']([^"']+)["']\)/,detail:"require"},{pattern:/^\s*from\s+([A-Za-z0-9_.]+)\s+import\s+/,detail:"import"},{pattern:/^\s*import\s+([A-Za-z0-9_.]+)(?:\s|$)/,detail:"import"},{pattern:/^\s*(?:import|using|use)\s+([A-Za-z0-9_:.*\\/.-]+)/,detail:"import"},{pattern:/^\s*require(?:_relative)?\s+["']([^"']+)["']/,detail:"require"}];function ye(e,t,o){if(!t.startsWith("."))return null;let i=h.resolve(h.dirname(e),t),r=h.extname(i).toLowerCase(),d=L.has(r),s=new Set([i]);if(d){let n=i.slice(0,-r.length);if([".js",".jsx",".mjs"].includes(r))for(let a of [".ts",".tsx",".js",".jsx",".mjs"])s.add(`${n}${a}`);}else for(let n of L)s.add(`${i}${n}`),s.add(h.join(i,`index${n}`));return [...s].find(n=>o.has(h.resolve(n)))??null}var ve=[{pattern:/@(?:Get|Post|Put|Delete|Patch|Options|Head)\s*\(\s*["']([^"']*)["']/i,detail:"decorated route"},{pattern:/\b(?:app|router|server|api|route|fastify|fiber)\.(?:get|post|put|delete|patch|options|head)\s*\(\s*["']([^"']+)["']/i,detail:"router route"},{pattern:/@(?:GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|RequestMapping)\s*\([^"']*["']([^"']*)["']/,detail:"mapped route"},{pattern:/\[Http(?:Get|Post|Put|Delete|Patch)\s*\(\s*["']([^"']*)["']/i,detail:"HTTP route"},{pattern:/^\s*(?:get|post|put|delete|patch)\s+["']([^"']+)["']/i,detail:"HTTP route"}];function z(e){return createHash("sha256").update(e).digest("hex")}function w(e,t){return `wkg:${e}:${z(`${e}\0${t}`).slice(0,20)}`}function K(e){return e.replace(/\\/g,"/")}function N(e){let t=K(e).replace(/^\.\//,"");return !t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)?"unknown":t}function b(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function j(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function E(e){if(Array.isArray(e))return e.filter(o=>typeof o=="string").sort();let t=b(e);return t?Object.keys(t).sort():[]}function we(e){if(Array.isArray(e))return e.map(o=>typeof o=="string"?o.split("=",1)[0]?.trim():"").filter(o=>!!o).sort();let t=b(e);return t?Object.keys(t).sort():[]}function be(e){return Object.fromEntries(Object.entries(e).filter(t=>t[1]!==void 0).sort(([t],[o])=>t.localeCompare(o)))}async function Y(e,t){let o=[],i=[e],r=0;for(;r<i.length&&o.length<t;){let d=i[r++],s;try{s=await $.readdir(d,{withFileTypes:true});}catch{continue}s.sort((n,a)=>n.name.localeCompare(a.name));for(let n of s){if(o.length>=t)break;if(n.isSymbolicLink())continue;let a=h.join(d,n.name);n.isDirectory()?!me.has(n.name)&&!a$1(n.name)&&i.push(a):n.isFile()&&o.push(a);}}return o.sort((d,s)=>d.localeCompare(s))}async function A(e){let t=await $.readFile(e,"utf8");if(e.toLowerCase().endsWith(".json")){let o=JSON.parse(t),i=b(o);return i?[i]:[]}return parseAllDocuments(t,{logLevel:"silent"}).map(o=>b(o.toJSON())).filter(o=>o!==null)}function G(e){return [...new Set([...e.workspaceFiles,...e.projects.flatMap(t=>e.filesByProject.get(t.id)??[])])].sort((t,o)=>t.localeCompare(o))}function Q(e){return /^(?:openapi|swagger)(?:\.[^.]+)?\.(?:json|ya?ml)$/i.test(h.basename(e))}function X(e){let t=h.basename(e).toLowerCase();return /\.(?:graphql|gql|proto)$/.test(t)||/^asyncapi(?:\.[^.]+)?\.(?:json|ya?ml)$/.test(t)}function ee(e){let t=h.basename(e);return /^Dockerfile(?:\..+)?$/i.test(t)||/\.tf$/i.test(t)||t==="Chart.yaml"}function te(e){return /(?:^|[\\/])(?:README|ARCHITECTURE|CONTRIBUTING|SECURITY)\.md$/i.test(e)}function Pe(e,t){let o=K(h.relative(e,t));return /^\.github\/workflows\/.+\.ya?ml$/i.test(o)||/^(?:\.gitlab-ci\.ya?ml|azure-pipelines\.ya?ml|Jenkinsfile|bitbucket-pipelines\.ya?ml|\.woodpecker\.ya?ml)$/i.test(o)||/^\.circleci\/config\.ya?ml$/i.test(o)}function oe(e,t){let o=K(h.relative(e,t));return /(?:^|\/)(?:adr|adrs|decisions)(?:\/).+\.md$/i.test(o)||/(?:^|\/)ADR[-_0-9].+\.md$/i.test(o)}async function re(e){let t=new Set;for(let o of [e.workspacePath,...e.projects.map(i=>i.root)])for(let i of ["compose.yml","compose.yaml","docker-compose.yml","docker-compose.yaml"]){let r=h.join(o,i);await $.pathExists(r)&&t.add(r);}return [...t].sort((o,i)=>o.localeCompare(i))}async function se(e){let o=[e.workspacePath,...e.projects.map(r=>r.root)].flatMap(r=>[h.join(r,"CODEOWNERS"),h.join(r,".github","CODEOWNERS"),h.join(r,"docs","CODEOWNERS")]),i=await Promise.all(o.map(async r=>await $.pathExists(r)?r:null));return [...new Set(i.filter(r=>!!r))].sort((r,d)=>r.localeCompare(d))}function ie(e){let t=[{root:e.workspacePath,files:e.workspaceFiles},...e.projects.map(o=>({root:o.root,files:e.filesByProject.get(o.id)??[]}))];return [...new Set(t.flatMap(o=>o.files.filter(i=>Pe(o.root,i))))].sort((o,i)=>o.localeCompare(i))}async function ae(e){let t=[];for(let o of G(e))if(/\.ya?ml$/i.test(o))try{(await A(o)).some(r=>{let d=b(r.metadata);return !!(j(r.apiVersion)&&j(r.kind)&&j(d?.name))})&&t.push(o);}catch{}return t.sort((o,i)=>o.localeCompare(i))}function C(e,t){let o=h.resolve(t);return e.filter(i=>o===i.root||o.startsWith(`${i.root}${h.sep}`)).sort((i,r)=>r.root.length-i.root.length)[0]??null}var q=class{constructor(t,o,i){this.workspacePath=t;this.now=o;this.workspaceName=i;}workspacePath;now;workspaceName;entities=new Map;relations=new Map;proofs=new Map;providers=[];diagnostics=[];contentHashes=new Map;attributeConflicts=new Set;artifactPath(t,o){if(o){let i=K(h.relative(o.root,t));return N(h.posix.join(o.artifactPrefix,i))}return N(h.relative(this.workspacePath,t))}async addProof(t){let o;if(t.absolutePath){if(!this.contentHashes.has(t.absolutePath))try{this.contentHashes.set(t.absolutePath,z(await $.readFile(t.absolutePath)));}catch{this.contentHashes.set(t.absolutePath,null);}o=this.contentHashes.get(t.absolutePath)??void 0;}let i=N(t.artifact),r=w("proof",[t.provider,i,t.pointer??"",t.line??"",t.detail??""].join("\0"));return this.proofs.has(r)||this.proofs.set(r,{id:r,provider:t.provider,artifact:i,...t.pointer?{pointer:t.pointer}:{},...t.line?{line:t.line}:{},...t.column?{column:t.column}:{},...o?{contentHash:o}:{},observedAt:this.now.toISOString(),derivation:t.derivation??"extracted",trust:t.trust??"observed",confidence:t.confidence??"high",freshness:"fresh",...t.detail?{detail:t.detail}:{}}),r}addEntity(t){let o=w(t.kind,t.key),i=be(t.attributes??{}),r=this.entities.get(o),d={...r?.attributes??{}};for(let[a,f]of Object.entries(i)){if(a in d&&JSON.stringify(d[a])!==JSON.stringify(f)){let c=`${o}\0${a}`;this.attributeConflicts.has(c)||(this.attributeConflicts.add(c),this.diagnostics.push({code:"graph.knowledge.attribute_conflict",severity:"warning",message:`Conflicting ${a} values were observed for ${t.kind} ${t.label}.`,entityIds:[o],recommendation:"Inspect the entity proof paths and make the authoritative source explicit."}));continue}d[a]=f;}let s=[...new Set([...r?.identity.aliases??[],...t.aliases??[]])].sort(),n=[...new Set([...r?.proofIds??[],...t.proofIds??[]])].sort();return this.entities.set(o,{id:o,kind:t.kind,label:t.label,...t.projectId?{projectId:t.projectId}:{},identity:{key:t.key,scope:t.projectId?"project":"workspace",aliases:s,fingerprint:z(JSON.stringify({kind:t.kind,key:t.key,attributes:d}))},attributes:d,proofIds:n}),o}addRelation(t){let o=w("relation",`${t.from}\0${t.kind}\0${t.to}`),i=this.relations.get(o),r=[...new Set([...i?.proofIds??[],...t.proofIds])].sort(),d=new Set(r.map(a=>this.proofs.get(a)?.provider).filter(Boolean)).size,s=t.trust??i?.trust??"observed",n=d>=2&&s!=="ambiguous"?"corroborated":s;return this.relations.set(o,{id:o,from:t.from,to:t.to,kind:t.kind,derivation:t.derivation??i?.derivation??"extracted",trust:n,confidence:n==="corroborated"?"high":t.confidence??i?.confidence??"high",proofIds:r}),o}};function je(e,t){let o=h.basename(e);try{if(o==="package.json"||o==="composer.json"){let s=JSON.parse(t);return {ecosystem:o==="package.json"?"npm":"composer",name:j(s.name),version:j(s.version),dependencies:[...E(s.dependencies),...E(s.devDependencies),...E(s.require),...E(s["require-dev"])].filter((n,a,f)=>f.indexOf(n)===a).sort()}}if(o==="deno.json"||o==="deno.jsonc"){let s=JSON.parse(t.replace(/\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm,""));return {ecosystem:"deno",name:j(s.name),version:j(s.version),dependencies:E(s.imports)}}}catch{}let i=s=>t.match(s)?.[1]?.trim();if(o==="pyproject.toml"){let s=t.match(/^dependencies\s*=\s*\[([\s\S]*?)\]/m)?.[1]??"";return {ecosystem:"python",name:i(/^(?:name)\s*=\s*["']([^"']+)["']/m),version:i(/^(?:version)\s*=\s*["']([^"']+)["']/m),dependencies:[...[...s.matchAll(/["']([A-Za-z0-9_.-]+)/g)].map(n=>n[1]),...[...t.matchAll(/^([A-Za-z0-9_.-]+)\s*=\s*(?:["'{[])/gm)].map(n=>n[1]).filter(n=>!["name","version","description","python","dependencies"].includes(n))].filter((n,a,f)=>f.indexOf(n)===a).sort()}}if(o==="go.mod")return {ecosystem:"go",name:i(/^module\s+(\S+)/m),dependencies:[...t.matchAll(/^\s*([A-Za-z0-9_.~/-]+)\s+v\d+/gm)].map(s=>s[1]).sort()};if(o==="Cargo.toml"){let s=t.match(/^\[dependencies\]\s*$([\s\S]*?)(?=^\[|\s*$)/m)?.[1]??"";return {ecosystem:"cargo",name:i(/^name\s*=\s*["']([^"']+)["']/m),version:i(/^version\s*=\s*["']([^"']+)["']/m),dependencies:[...s.matchAll(/^([A-Za-z0-9_.-]+)\s*=/gm)].map(n=>n[1]).sort()}}if(o==="pom.xml")return {ecosystem:"maven",name:i(/<artifactId>([^<]+)<\/artifactId>/),version:i(/<version>([^<]+)<\/version>/),dependencies:[...t.matchAll(/<artifactId>([^<]+)<\/artifactId>/g)].slice(1).map(s=>s[1]).sort()};if(/\.(?:cs|fs|vb)proj$/i.test(o))return {ecosystem:"nuget",name:i(/<AssemblyName>([^<]+)<\/AssemblyName>/)??o.replace(/\.[^.]+$/,""),version:i(/<Version>([^<]+)<\/Version>/),dependencies:[...t.matchAll(/<PackageReference\s+Include=["']([^"']+)["']/g)].map(s=>s[1]).sort()};let r={"requirements.txt":"python",Pipfile:"python","build.gradle":"gradle","build.gradle.kts":"gradle",Gemfile:"ruby","mix.exs":"elixir","pubspec.yaml":"dart","Package.swift":"swift","CMakeLists.txt":"cmake","deno.json":"deno","deno.jsonc":"deno","project.clj":"clojure","deps.edn":"clojure","build.sbt":"scala",BUILD:"bazel","BUILD.bazel":"bazel","WORKSPACE.bazel":"bazel"},d=o==="requirements.txt"?t.split(/\r?\n/).map(s=>s.trim().match(/^([A-Za-z0-9_.-]+)/)?.[1]):o.startsWith("build.gradle")?[...t.matchAll(/(?:implementation|api|compileOnly|runtimeOnly|testImplementation)\s*\(?["']([^:"']+):([^:"']+)/g)].map(s=>`${s[1]}:${s[2]}`):o==="Gemfile"?[...t.matchAll(/^\s*gem\s+["']([^"']+)["']/gm)].map(s=>s[1]):o==="mix.exs"?[...t.matchAll(/\{:\s*([A-Za-z0-9_]+)\s*,/g)].map(s=>s[1]):o==="pubspec.yaml"?[...t.matchAll(/^\s{2}([A-Za-z0-9_]+):\s+/gm)].map(s=>s[1]):o==="Package.swift"?[...t.matchAll(/\.package\s*\(\s*url:\s*["']([^"']+)["']/g)].map(s=>s[1]):o==="CMakeLists.txt"?[...t.matchAll(/find_package\s*\(\s*([A-Za-z0-9_.+-]+)/gi)].map(s=>s[1]):o==="project.clj"||o==="deps.edn"?[...t.matchAll(/\[?([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\s+/g)].map(s=>s[1]):o==="build.sbt"?[...t.matchAll(/["']([^"']+)["']\s*%%?\s*["']([^"']+)["']/g)].map(s=>`${s[1]}:${s[2]}`):[];return {ecosystem:r[o]??"unknown",dependencies:d.filter(s=>!!s).filter((s,n,a)=>a.indexOf(s)===n).sort()}}var $e={id:"workspace-foundation",version:"1.0.0",async run(e){let{state:t}=e,o=await t.addProof({provider:this.id,artifact:".workspai/workspace.contract.json",absolutePath:h.join(e.workspacePath,".workspai","workspace.contract.json"),trust:"authoritative",derivation:"authored",detail:"Workspace identity and project registry boundary"}),i=t.addEntity({kind:"workspace",key:`workspace:${t.workspaceName}`,label:t.workspaceName,aliases:[t.workspaceName],proofIds:[o]});for(let r of e.projects){let d=e.filesByProject.get(r.id)??[],s=d.find(g=>/[\\/]\.(?:workspai|rapidkit)[\\/](?:project|context)\.json$/.test(g)),n=d.find(g=>x.has(h.basename(g))),a=s??n,f=await t.addProof({provider:this.id,artifact:a?t.artifactPath(a,r):N(h.posix.join(r.artifactPrefix,".workspai/project.json")),...a?{absolutePath:a}:{},trust:s?"authoritative":"observed",derivation:s?"authored":"inferred",detail:`Project ${r.id}`}),c=t.addEntity({kind:"project",key:`project:${r.id}`,label:r.id,projectId:r.id,aliases:[r.id,r.path],attributes:{path:r.path,runtime:r.runtime,runtimeCandidates:r.runtimeCandidates,framework:r.framework,kit:r.kit,kind:r.kind,category:r.category},proofIds:[f]});t.addRelation({from:i,to:c,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[f]});let m=new Set,l=[];for(let g of d){let u=h.basename(g);if(/^(?:\.env\.example|\.env\.sample|\.env\.template)$/i.test(u))try{let v=await $.readFile(g,"utf8");for(let k of v.split(/\r?\n/)){let P=k.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[1];P&&m.add(P);}}catch{}if((/(?:^|[\\/])(?:test|tests|spec|specs|__tests__)(?:[\\/]|$)/i.test(g)||/(?:\.test|\.spec|_test)\.[A-Za-z0-9]+$/i.test(u))&&l.push(g),!(!x.has(u)&&!/\.(?:cs|fs|vb)proj$/i.test(u)))try{let v=await $.readFile(g,"utf8"),k=je(g,v),P=await t.addProof({provider:this.id,artifact:t.artifactPath(g,r),absolutePath:g,pointer:"/",confidence:k.name?"high":"medium",detail:`${k.ecosystem} manifest`}),I=t.addEntity({kind:"package",key:`package:${r.id}:${k.ecosystem}:${k.name??u}`,label:k.name??`${r.id}/${u}`,projectId:r.id,aliases:[u,...k.name?[k.name]:[]],attributes:{ecosystem:k.ecosystem,version:k.version,manifest:t.artifactPath(g,r),dependencies:k.dependencies},proofIds:[P]});t.addRelation({from:c,to:I,kind:"contains",proofIds:[P]});for(let p of k.dependencies.slice(0,500)){let y=t.addEntity({kind:"module",key:`dependency:${k.ecosystem}:${p}`,label:p,aliases:[p],attributes:{ecosystem:k.ecosystem,external:true},proofIds:[P]});t.addRelation({from:I,to:y,kind:"depends-on",trust:"authoritative",derivation:"authored",proofIds:[P]});}}catch{}}if(m.size>0){let g=d.find(u=>/^\.env\.(?:example|sample|template)$/i.test(h.basename(u)));if(g){let u=await t.addProof({provider:this.id,artifact:t.artifactPath(g,r),absolutePath:g,detail:"Public environment template keys only; values are intentionally excluded"}),v=t.addEntity({kind:"environment",key:`environment:${r.id}:template`,label:`${r.id} environment contract`,projectId:r.id,attributes:{keys:[...m].sort(),valuesEmitted:false},proofIds:[u]});t.addRelation({from:c,to:v,kind:"configured-by",proofIds:[u]});}}if(l.length>0){let g=await t.addProof({provider:this.id,artifact:t.artifactPath(l[0],r),absolutePath:l[0],detail:`${l.length} test file(s) discovered`}),u=t.addEntity({kind:"test-suite",key:`tests:${r.id}`,label:`${r.id} tests`,projectId:r.id,attributes:{fileCount:l.length},proofIds:[g]});t.addRelation({from:u,to:c,kind:"tests",proofIds:[g]});}}}},Ee={id:"source-structure",version:"1.0.0",applicable(e){return e.projects.some(t=>(e.filesByProject.get(t.id)??[]).some(o=>L.has(h.extname(o).toLowerCase())))},async run(e){for(let t of e.projects){let o=(e.filesByProject.get(t.id)??[]).filter(s=>L.has(h.extname(s).toLowerCase())).slice(0,1e3),i=new Set;await Promise.all(o.map(async s=>{try{let n=await $.stat(s);n.isFile()&&n.size<=2*1024*1024&&i.add(h.resolve(s));}catch{}}));let r=0,d=0;for(let s of o){let n;try{if((await $.stat(s)).size>2*1024*1024)continue;n=await $.readFile(s,"utf8");}catch{continue}let a=e.state.artifactPath(s,t),f=await e.state.addProof({provider:this.id,artifact:a,absolutePath:s,derivation:"extracted",trust:"observed",confidence:"high",detail:`${F(s)} source file`}),c=e.state.addEntity({kind:"file",key:`file:${t.id}:${a}`,label:a,projectId:t.id,aliases:[h.basename(s)],attributes:{artifact:a,language:F(s),bytes:Buffer.byteLength(n)},proofIds:[f]});e.state.addRelation({from:w("project",`project:${t.id}`),to:c,kind:"contains",proofIds:[f]});let m=B(n,ke,250);for(let l of m){let g=await e.state.addProof({provider:this.id,artifact:a,absolutePath:s,line:l.line,derivation:"extracted",trust:"observed",confidence:"medium",detail:`${l.detail}: ${l.name}`}),u=ye(s,l.name,i);if(u){let v=e.state.artifactPath(u,t);e.state.addRelation({from:c,to:w("file",`file:${t.id}:${v}`),kind:"imports",confidence:"high",proofIds:[g]});}else {let v=l.name.startsWith(".");v&&(d+=1);let k=e.state.addEntity({kind:"module",key:`module:${t.id}:${l.name}`,label:l.name,projectId:t.id,aliases:[l.name],attributes:{specifier:l.name,resolution:v?"unresolved-local":"external"},proofIds:[g]});e.state.addRelation({from:c,to:k,kind:"imports",confidence:v?"low":"medium",proofIds:[g]});}}if(r<500){let l=B(n,he,Math.min(100,500-r));r+=l.length;for(let g of l){let u=await e.state.addProof({provider:this.id,artifact:a,absolutePath:s,line:g.line,derivation:"extracted",trust:"observed",confidence:"medium",detail:`${g.detail}: ${g.name}`}),v=e.state.addEntity({kind:"symbol",key:`symbol:${t.id}:${a}:${g.detail}:${g.name}`,label:g.name,projectId:t.id,attributes:{symbolKind:g.detail,language:F(s)},proofIds:[u]});e.state.addRelation({from:c,to:v,kind:"defines",confidence:"medium",proofIds:[u]});}}for(let l of B(n,ve,100)){let u=(n.split(/\r?\n/)[l.line-1]??"").match(/(?:@|\.|\[|^\s*)(get|post|put|delete|patch|options|head)/i)?.[1]?.toUpperCase()??"HTTP",v=await e.state.addProof({provider:this.id,artifact:a,absolutePath:s,line:l.line,derivation:"extracted",trust:"observed",confidence:"medium",detail:`${u} ${l.name}`}),k=e.state.addEntity({kind:"endpoint",key:`source-endpoint:${t.id}:${a}:${u}:${l.name}`,label:`${u} ${l.name||"/"}`,projectId:t.id,attributes:{method:u,path:l.name||"/",source:a},proofIds:[v]});e.state.addRelation({from:c,to:k,kind:"defines",confidence:"medium",proofIds:[v]});}}(o.length>=1e3||r>=500)&&e.state.diagnostics.push({code:"graph.provider.source_structure.limit_reached",severity:"info",message:`Source extraction for ${t.id} reached its bounded inventory limit.`,recommendation:"Use the standalone graph package provider configuration for deeper symbol indexing."}),d>0&&e.state.diagnostics.push({code:"graph.provider.source_structure.unresolved_local_imports",severity:"warning",message:`${d} local import(s) in ${t.id} could not be resolved to an indexed source file.`,recommendation:"Check path aliases, generated sources, extension mapping, or provider limits before treating the import graph as complete."});}}},Ie={id:"workspace-service-contract",version:"1.0.0",applicable(e){return !!e.contract?.projects.length},async run(e){if(!e.contract)return;let t=new Map;for(let o of [...e.contract.projects].sort((i,r)=>i.slug.localeCompare(r.slug))){let i=o.contracts,r=await e.state.addProof({provider:this.id,artifact:".workspai/workspace.contract.json",absolutePath:h.join(e.workspacePath,".workspai","workspace.contract.json"),pointer:`/projects/${o.slug}/contracts`,trust:"authoritative",derivation:"authored",detail:`Service contract for ${o.slug}`}),d=w("project",`project:${o.slug}`),s=e.state.addEntity({kind:"service",key:`contract-service:${o.slug}`,label:o.slug,projectId:o.slug,attributes:{ports:o.ports.map(n=>`${n.protocol}:${n.port}`),owns:[...i.owns].sort(),environmentKeys:[...i.env].sort()},proofIds:[r]});e.state.addRelation({from:d,to:s,kind:"implements",trust:"authoritative",derivation:"authored",proofIds:[r]});for(let n of [...i.apis].sort((a,f)=>a.name.localeCompare(f.name))){let a=e.state.addEntity({kind:"api",key:`contract-api:${o.slug}:${n.name}:${n.basePath}`,label:n.name,projectId:o.slug,attributes:{basePath:n.basePath},proofIds:[r]});e.state.addRelation({from:s,to:a,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[r]});}for(let n of [...i.publishes,...i.consumes].sort())t.has(n)||t.set(n,e.state.addEntity({kind:"queue",key:`event:${n}`,label:n,attributes:{protocol:"workspace-event"},proofIds:[r]}));for(let n of [...i.publishes].sort()){let a=t.get(n);a&&e.state.addRelation({from:s,to:a,kind:"publishes",trust:"authoritative",derivation:"authored",proofIds:[r]});}for(let n of [...i.consumes].sort()){let a=t.get(n);a&&e.state.addRelation({from:s,to:a,kind:"consumes",trust:"authoritative",derivation:"authored",proofIds:[r]});}}}},Ce={id:"openapi",version:"1.0.0",applicable(e){return e.projects.some(t=>(e.filesByProject.get(t.id)??[]).some(Q))},async run(e){for(let t of e.projects){let o=(e.filesByProject.get(t.id)??[]).filter(Q);for(let i of o){let r;try{r=await A(i);}catch(d){e.state.diagnostics.push({code:"graph.provider.openapi.parse_failed",severity:"warning",message:`Could not parse ${e.state.artifactPath(i,t)}: ${d instanceof Error?d.message:String(d)}`});continue}for(let d of r){if(!("openapi"in d)&&!("swagger"in d))continue;let s=b(d.info),n=j(s?.title)??`${t.id} API`,a=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(i,t),absolutePath:i,pointer:"/info",trust:"authoritative",detail:"Authored OpenAPI contract"}),f=w("project",`project:${t.id}`),c=e.state.addEntity({kind:"api",key:`api:${t.id}:${n}`,label:n,projectId:t.id,attributes:{version:j(s?.version),specification:j(d.openapi)??j(d.swagger)},proofIds:[a]});e.state.addRelation({from:f,to:c,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[a]});let m=b(b(d.components)?.schemas)??b(d.definitions),l=new Map;for(let u of Object.keys(m??{}).sort()){let v=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(i,t),absolutePath:i,pointer:`/components/schemas/${u}`,trust:"authoritative",detail:`OpenAPI schema ${u}`}),k=e.state.addEntity({kind:"schema",key:`schema:${t.id}:${n}:${u}`,label:u,projectId:t.id,proofIds:[v]});l.set(u,k),e.state.addRelation({from:c,to:k,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[v]});}let g=b(d.paths);for(let u of Object.keys(g??{}).sort()){let v=b(g?.[u]);for(let k of Object.keys(v??{}).filter(P=>ge.has(P.toLowerCase())).sort()){let P=b(v?.[k]),I=`/paths/${u.replace(/~/g,"~0").replace(/\//g,"~1")}/${k}`,p=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(i,t),absolutePath:i,pointer:I,trust:"authoritative",detail:`${k.toUpperCase()} ${u}`}),y=e.state.addEntity({kind:"endpoint",key:`endpoint:${t.id}:${n}:${k.toUpperCase()}:${u}`,label:`${k.toUpperCase()} ${u}`,projectId:t.id,aliases:E(P?.tags),attributes:{method:k.toUpperCase(),path:u,operationId:j(P?.operationId),deprecated:typeof P?.deprecated=="boolean"?P.deprecated:void 0,tags:E(P?.tags)},proofIds:[p]});e.state.addRelation({from:c,to:y,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[p]});let R=JSON.stringify(P??{});for(let[S,_]of l)R.includes(`/${S}`)&&e.state.addRelation({from:y,to:_,kind:"references",trust:"authoritative",derivation:"authored",proofIds:[p]});}}}}}}},Re={id:"interface-contracts",version:"1.0.0",applicable(e){return e.projects.some(t=>(e.filesByProject.get(t.id)??[]).some(X))},async run(e){for(let t of e.projects){let o=(e.filesByProject.get(t.id)??[]).filter(X);for(let i of o){let r=e.state.artifactPath(i,t),d=h.extname(i).toLowerCase();if(d===".graphql"||d===".gql"){let s=await $.readFile(i,"utf8"),n=await e.state.addProof({provider:this.id,artifact:r,absolutePath:i,trust:"authoritative",derivation:"authored",detail:"GraphQL schema"}),a=e.state.addEntity({kind:"api",key:`graphql:${t.id}:${r}`,label:`${t.id} GraphQL API`,projectId:t.id,attributes:{specification:"graphql",artifact:r},proofIds:[n]});e.state.addRelation({from:w("project",`project:${t.id}`),to:a,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[n]});for(let f of s.matchAll(/^\s*(?:type|input|interface|enum|scalar|union)\s+([A-Za-z_]\w*)/gm)){let c=e.state.addEntity({kind:"schema",key:`graphql-schema:${t.id}:${r}:${f[1]}`,label:f[1],projectId:t.id,proofIds:[n]});e.state.addRelation({from:a,to:c,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[n]});}continue}if(d===".proto"){let s=await $.readFile(i,"utf8"),n=z(s.replace(/\r\n/g,`
2
+ `).trim()),a=s.match(/^\s*package\s+([A-Za-z_][\w.]*)\s*;/m)?.[1],f=a||`unscoped:${n.slice(0,16)}`,c=await e.state.addProof({provider:this.id,artifact:r,absolutePath:i,trust:"authoritative",derivation:"authored",detail:"Protocol Buffers contract"});for(let m of s.matchAll(/^\s*service\s+([A-Za-z_]\w*)/gm)){let l=e.state.addEntity({kind:"api",key:`protobuf-service:${f}:${m[1]}`,label:m[1],aliases:[...a?[`${a}.${m[1]}`]:[],m[1]],attributes:{specification:"protobuf",package:a,definitionHash:n},proofIds:[c]});e.state.addRelation({from:w("project",`project:${t.id}`),to:l,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[c]});}for(let m of s.matchAll(/^\s*message\s+([A-Za-z_]\w*)/gm))e.state.addEntity({kind:"schema",key:`protobuf-message:${f}:${m[1]}`,label:m[1],aliases:[...a?[`${a}.${m[1]}`]:[],m[1]],attributes:{specification:"protobuf",package:a,definitionHash:n},proofIds:[c]});continue}try{let s=(await A(i))[0];if(!s||!("asyncapi"in s))continue;let n=await e.state.addProof({provider:this.id,artifact:r,absolutePath:i,trust:"authoritative",derivation:"authored",detail:"AsyncAPI contract"}),a=e.state.addEntity({kind:"api",key:`asyncapi:${t.id}:${r}`,label:j(b(s.info)?.title)??`${t.id} AsyncAPI`,projectId:t.id,attributes:{specification:`asyncapi ${String(s.asyncapi)}`,artifact:r},proofIds:[n]});e.state.addRelation({from:w("project",`project:${t.id}`),to:a,kind:"exposes",trust:"authoritative",derivation:"authored",proofIds:[n]});for(let f of Object.keys(b(s.channels)??{}).sort()){let c=e.state.addEntity({kind:"queue",key:`asyncapi-channel:${t.id}:${f}`,label:f,projectId:t.id,attributes:{protocol:"asyncapi"},proofIds:[n]});e.state.addRelation({from:a,to:c,kind:"publishes",trust:"authoritative",derivation:"authored",proofIds:[n]});}}catch{}}}}},We={id:"infrastructure-as-code",version:"1.0.0",applicable(e){return G(e).some(ee)},async run(e){let t=G(e).filter(ee);for(let o of t){let i=C(e.projects,o),r=i?.id??e.state.workspaceName,d=i?w("project",`project:${i.id}`):w("workspace",`workspace:${e.state.workspaceName}`),s=e.state.artifactPath(o,i),n=await $.readFile(o,"utf8"),a=await e.state.addProof({provider:this.id,artifact:s,absolutePath:o,trust:"authoritative",derivation:"authored",detail:"Infrastructure definition"});if(/^Dockerfile/i.test(h.basename(o))){let c=[...n.matchAll(/^\s*FROM\s+([^\s]+)(?:\s+AS\s+([^\s]+))?/gim)],m=e.state.addEntity({kind:"container",key:`dockerfile:${r}:${s}`,label:`${r} container image`,...i?{projectId:i.id}:{},attributes:{artifact:s,baseImages:c.map(l=>l[1])},proofIds:[a]});e.state.addRelation({from:d,to:m,kind:"deploys",trust:"authoritative",derivation:"authored",proofIds:[a]});continue}if(/\.tf$/i.test(o)){for(let c of n.matchAll(/^\s*resource\s+["']([^"']+)["']\s+["']([^"']+)["']/gm)){let m=c[1],l=/(?:db|sql|rds|database)/i.test(m)?"database":/(?:queue|kafka|sqs|pubsub|servicebus)/i.test(m)?"queue":"deployment",g=e.state.addEntity({kind:l,key:`terraform:${r}:${m}:${c[2]}`,label:`${m}.${c[2]}`,...i?{projectId:i.id}:{},attributes:{resourceType:m,artifact:s},proofIds:[a]});e.state.addRelation({from:d,to:g,kind:"deploys",trust:"authoritative",derivation:"authored",proofIds:[a]});}continue}let f=e.state.addEntity({kind:"deployment",key:`helm:${r}:${s}`,label:`${r} Helm chart`,...i?{projectId:i.id}:{},attributes:{artifact:s,format:"helm"},proofIds:[a]});e.state.addRelation({from:d,to:f,kind:"deploys",trust:"authoritative",derivation:"authored",proofIds:[a]});}}};function ne(e){let t=e.toLowerCase();return /(?:postgres|mysql|mariadb|mongo|cassandra|cockroach|mssql|oracle)/.test(t)?"database":/(?:rabbitmq|kafka|nats|pulsar|activemq|redis)/.test(t)?"queue":"container"}var Ke={id:"compose",version:"1.0.0",async applicable(e){return (await re(e)).length>0},async run(e){for(let t of await re(e)){let o;try{o=(await A(t))[0];}catch(s){e.state.diagnostics.push({code:"graph.provider.compose.parse_failed",severity:"warning",message:`Could not parse ${e.state.artifactPath(t)}: ${s instanceof Error?s.message:String(s)}`});}let i=b(o?.services);if(!i)continue;let r=C(e.projects,t),d=new Map;for(let s of Object.keys(i).sort()){let n=b(i[s]),a=n?.build,f=j(a)??j(b(a)?.context),c=f?C(e.projects,h.resolve(h.dirname(t),f)):e.projects.find(u=>u.id.toLowerCase()===s.toLowerCase()||h.basename(u.path).toLowerCase()===s.toLowerCase())??r,m=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(t,r),absolutePath:t,pointer:`/services/${s}`,trust:"authoritative",derivation:"authored",detail:`Compose service ${s}`}),l=j(n?.image),g=e.state.addEntity({kind:"service",key:`compose-service:${e.state.artifactPath(t,r)}:${s}`,label:s,...c?{projectId:c.id}:{},attributes:{image:l,ports:E(n?.ports).map(String),networks:E(n?.networks),environmentKeys:we(n?.environment)},proofIds:[m]});if(d.set(s,g),c&&e.state.addRelation({from:w("project",`project:${c.id}`),to:g,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[m]}),l){let u=e.state.addEntity({kind:ne(l),key:`image:${l}`,label:l,...c?{projectId:c.id}:{},attributes:{image:l},proofIds:[m]});e.state.addRelation({from:g,to:u,kind:ne(l)==="container"?"runs-on":"depends-on",trust:"authoritative",derivation:"authored",proofIds:[m]});}}for(let s of Object.keys(i).sort()){let n=b(i[s]),a=d.get(s);if(a)for(let f of E(n?.depends_on)){let c=d.get(f);if(!c)continue;let m=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(t,r),absolutePath:t,pointer:`/services/${s}/depends_on/${f}`,trust:"authoritative",derivation:"authored",detail:`${s} depends on ${f}`});e.state.addRelation({from:a,to:c,kind:"depends-on",trust:"authoritative",derivation:"authored",proofIds:[m]});}}}}},Ae={id:"documentation",version:"1.0.0",applicable(e){return G(e).some(te)},async run(e){let t=new Set,o=[e.workspaceFiles,...e.projects.map(i=>e.filesByProject.get(i.id)??[])];for(let i of o){let r=i.filter(te);for(let d of r){if(t.has(d))continue;t.add(d);let s=C(e.projects,d),a=(await $.readFile(d,"utf8")).match(/^#\s+(.+)$/m)?.[1]?.trim()??h.basename(d),f=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(d,s),absolutePath:d,line:1,trust:"authoritative",derivation:"authored",detail:`Documentation: ${a}`}),c=e.state.addEntity({kind:"document",key:`document:${e.state.artifactPath(d,s)}`,label:a,...s?{projectId:s.id}:{},attributes:{artifact:e.state.artifactPath(d,s)},proofIds:[f]}),m=s?w("project",`project:${s.id}`):w("workspace",`workspace:${e.state.workspaceName}`);e.state.addRelation({from:c,to:m,kind:"documents",trust:"authoritative",derivation:"authored",proofIds:[f]});}}}},Se={id:"kubernetes",version:"1.0.0",async applicable(e){return (await ae(e)).length>0},async run(e){for(let t of await ae(e)){let o=C(e.projects,t),i=o?w("project",`project:${o.id}`):w("workspace",`workspace:${e.state.workspaceName}`),r=await A(t);for(let d=0;d<r.length;d+=1){let s=r[d],n=j(s.kind),a=b(s.metadata),f=j(a?.name);if(!n||!f)continue;let c=j(a?.namespace)??"default",m=/Deployment|StatefulSet|DaemonSet/i.test(n)?"deployment":/Service|Ingress/i.test(n)?"service":/ConfigMap|Secret/i.test(n)?"environment":"deployment",l=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(t,o),absolutePath:t,pointer:`/documents/${d}`,trust:"authoritative",derivation:"authored",detail:`${n} ${c}/${f}`}),g=e.state.addEntity({kind:m,key:`kubernetes:${n}:${c}:${f}`,label:`${n}/${f}`,...o?{projectId:o.id}:{},attributes:{resourceKind:n,namespace:c,secret:n==="Secret",keys:n==="Secret"||n==="ConfigMap"?Object.keys(b(s.data)??{}).sort():void 0},proofIds:[l]});e.state.addRelation({from:i,to:g,kind:m==="deployment"?"deploys":"contains",trust:"authoritative",derivation:"authored",proofIds:[l]});let u=e.state.addEntity({kind:"environment",key:`kubernetes-namespace:${c}`,label:`Kubernetes namespace ${c}`,attributes:{namespace:c},proofIds:[l]});e.state.addRelation({from:g,to:u,kind:"runs-on",trust:"authoritative",derivation:"authored",proofIds:[l]});}}}},_e={id:"ci-workflow",version:"1.0.0",applicable(e){return ie(e).length>0},async run(e){let t=ie(e);for(let o of t){let i=C(e.projects,o),r=e.state.artifactPath(o,i),d=h.basename(o)==="Jenkinsfile",s=h.basename(o),n=[],a=[];if(d)n=[...(await $.readFile(o,"utf8")).matchAll(/\bstage\s*\(\s*["']([^"']+)["']/g)].map(l=>l[1]);else {let m;try{m=(await A(o))[0];}catch{continue}if(!m)continue;s=j(m.name)??s;let l=K(h.relative(i?.root??e.workspacePath,o));if(/^\.gitlab-ci\./i.test(l)){let g=new Set(["stages","variables","workflow","include","default","image","services","cache","before_script","after_script"]);n=Object.keys(m).filter(u=>!u.startsWith(".")&&!g.has(u)).sort();}else n=[...new Set([...Object.keys(b(m.jobs)??{}),...Object.keys(b(b(m.workflows)?.jobs)??{}),...E(m.stages)])].sort();a=E(m.on);}n.length===0&&(n=["pipeline"]);let f=await e.state.addProof({provider:this.id,artifact:r,absolutePath:o,...d?{}:{pointer:"/jobs"},trust:"authoritative",derivation:"authored",detail:"CI/CD workflow"}),c=e.state.addEntity({kind:"pipeline",key:`pipeline:${r}`,label:s,attributes:{jobs:n,triggers:a,artifact:r},proofIds:[f]});e.state.addRelation({from:i?w("project",`project:${i.id}`):w("workspace",`workspace:${e.state.workspaceName}`),to:c,kind:"contains",trust:"authoritative",derivation:"authored",proofIds:[f]});}}},Oe={id:"codeowners",version:"1.0.0",async applicable(e){return (await se(e)).length>0},async run(e){for(let t of await se(e)){let o=C(e.projects,t),r=(await $.readFile(t,"utf8")).split(/\r?\n/);for(let d=0;d<r.length;d+=1){let s=r[d].trim();if(!s||s.startsWith("#"))continue;let[n,...a]=s.split(/\s+/);for(let f of a.filter(c=>c.startsWith("@"))){let c=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(t,o),absolutePath:t,line:d+1,trust:"authoritative",derivation:"authored",detail:`${n} ${f}`}),m=e.state.addEntity({kind:"owner",key:`owner:${f.toLowerCase()}`,label:f,aliases:[f],proofIds:[c]}),l=e.projects.filter(u=>{let v=n.replace(/^\//,"").replace(/\*.*$/,""),k=h.dirname(t),P=[".github","docs"].includes(h.basename(k))?h.dirname(k):k,I=K(h.relative(P,u.root));return v&&(I==="."||I.startsWith(v.replace(/\/$/,""))||u.path.startsWith(v.replace(/\/$/,"")))}),g=l.length>0?l.map(u=>w("project",`project:${u.id}`)):o?[w("project",`project:${o.id}`)]:[w("workspace",`workspace:${e.state.workspaceName}`)];for(let u of g)e.state.addRelation({from:m,to:u,kind:"owns",trust:"authoritative",derivation:"authored",proofIds:[c]});}}}}},Ne={id:"architecture-decisions",version:"1.0.0",applicable(e){return [{root:e.workspacePath,files:e.workspaceFiles},...e.projects.map(t=>({root:t.root,files:e.filesByProject.get(t.id)??[]}))].some(t=>t.files.some(o=>oe(t.root,o)))},async run(e){let t=new Set,o=[{root:e.workspacePath,files:e.workspaceFiles},...e.projects.map(i=>({root:i.root,files:e.filesByProject.get(i.id)??[]}))];for(let i of o){let r=i.files.filter(d=>oe(i.root,d));for(let d of r){if(t.has(d))continue;t.add(d);let s=C(e.projects,d),n=await $.readFile(d,"utf8"),a=n.match(/^#\s+(.+)$/m)?.[1]?.trim()??h.basename(d,".md"),f=n.match(/^status\s*:\s*(.+)$/im)?.[1]?.trim(),c=await e.state.addProof({provider:this.id,artifact:e.state.artifactPath(d,s),absolutePath:d,line:1,trust:"authoritative",derivation:"authored",detail:`Architecture decision: ${a}`}),m=e.state.addEntity({kind:"decision",key:`decision:${e.state.artifactPath(d,s)}`,label:a,...s?{projectId:s.id}:{},attributes:{status:f,artifact:e.state.artifactPath(d,s)},proofIds:[c]}),l=s?w("project",`project:${s.id}`):w("workspace",`workspace:${e.state.workspaceName}`);e.state.addRelation({from:l,to:m,kind:"decided-by",trust:"authoritative",derivation:"authored",proofIds:[c]});}}}},De=[$e,Ee,Ie,Ce,Re,Ke,We,Se,_e,Oe,Ae,Ne];async function Te(e,t){for(let o of t.edges){let i=[];for(let r of o.evidence){let d=N(r.file);i.push(await e.addProof({provider:"project-topology",artifact:d,absolutePath:h.resolve(e.workspacePath,d),derivation:o.source==="inferred"?"inferred":"authored",trust:o.source==="inferred"?"observed":"authoritative",confidence:o.confidence,detail:r.detail??`${o.kind} relationship`}));}i.length===0&&i.push(await e.addProof({provider:"project-topology",artifact:a.model,derivation:"inferred",trust:"ambiguous",confidence:o.confidence,detail:`${o.kind} relationship without source locator`})),e.addRelation({from:w("project",`project:${o.from}`),to:w("project",`project:${o.to}`),kind:o.kind==="event-pub-sub"?"consumes":"depends-on",derivation:o.source==="inferred"?"inferred":"authored",trust:o.source==="inferred"?"observed":"authoritative",confidence:o.confidence,proofIds:i});}}function Le(e){let t=[...e.entities.values()].filter(i=>i.kind==="endpoint"),o=new Map;for(let i of t){let r=String(i.attributes.method??"").toUpperCase(),d=String(i.attributes.path??"");if(!i.projectId||!r||!d)continue;let s=`${i.projectId}\0${r}\0${d}`,n=o.get(s)??[];n.push(i),o.set(s,n);}for(let i of o.values()){if(i.length<2)continue;let r=i.find(d=>d.proofIds.some(s=>e.proofs.get(s)?.trust==="authoritative"));if(r)for(let d of i.filter(s=>s.id!==r.id))e.addRelation({from:d.id,to:r.id,kind:"implements",derivation:"extracted",trust:"corroborated",confidence:"high",proofIds:[...d.proofIds,...r.proofIds]});}}function T(e,t){let o=[...new Set(e)],i=o.filter(r=>t.has(r)).length;return {eligibleCount:o.length,boundCount:i,unknownCount:o.length-i,coverageRatio:o.length===0?null:i/o.length}}function ze(e,t){let o=e.filter(a=>a.kind==="project").map(a=>a.id),i=e.filter(a=>a.kind==="endpoint").map(a=>a.id),r=new Set(t.filter(a=>a.kind==="implements").flatMap(a=>[a.from,a.to])),d=new Set(t.filter(a=>a.kind==="tests").flatMap(a=>[a.from,a.to]).filter(a=>o.includes(a))),s=new Set(t.filter(a=>a.kind==="deploys").flatMap(a=>[a.from,a.to]).filter(a=>o.includes(a))),n=new Set(t.filter(a=>a.kind==="owns").flatMap(a=>[a.from,a.to]).filter(a=>o.includes(a)));return {apiImplementation:T(i,r),projectTests:T(o,d),projectDeployment:T(o,s),projectOwnership:T(o,n)}}async function tt(e){let t=h.resolve(e.workspacePath),o=e.now??new Date,i=e.projects.map(p=>({...p,root:p.absolutePath?h.resolve(p.absolutePath):h.resolve(t,p.path),artifactPrefix:p.absolutePath?`external/${p.id}`:K(p.path)})).sort((p,y)=>p.id.localeCompare(y.id)),r=new q(t,o,e.workspace.name),d=Math.max(100,Math.min(e.maxFilesPerProject??2e3,1e4)),s=new Map(await Promise.all(i.map(async p=>[p.id,await Y(p.root,d)]))),n=await Y(t,Math.min(d*Math.max(i.length,1),2e4)),a={workspacePath:t,projects:i,filesByProject:s,workspaceFiles:n,now:o,maxFilesPerProject:d,contract:e.contract??null,state:r};for(let p of De){let y={entities:r.entities.size,relations:r.relations.size,proofs:r.proofs.size,diagnostics:r.diagnostics.length},R="passed",S=null;try{if(!(p.applicable?await p.applicable(a):true))R="skipped";else {await p.run(a);let D=r.entities.size-y.entities,de=r.relations.size-y.relations,ce=r.proofs.size-y.proofs;D===0&&de===0&&ce===0?(R="partial",r.diagnostics.push({code:`graph.provider.${p.id}.empty_result`,severity:"warning",message:`${p.id} found an applicable source surface but produced no graph evidence.`,recommendation:"Inspect the matching source format or extend the provider before treating this graph dimension as complete."})):r.diagnostics.length>y.diagnostics&&(R="partial");}}catch(W){R="failed";let D=W instanceof Error?W.message:String(W);S=D,r.diagnostics.push({code:`graph.provider.${p.id}.failed`,severity:"warning",message:`${p.id} provider failed: ${D}`,recommendation:"Repair the referenced source artifact and rerun workspace graph emit."});}let _=r.diagnostics.slice(y.diagnostics).map(W=>`${W.code}: ${W.message}`);S&&_.length===0&&_.push(S),r.providers.push({id:p.id,version:p.version,status:R,permission:"filesystem-read",discoveredEntities:r.entities.size-y.entities,discoveredRelations:r.relations.size-y.relations,proofCount:r.proofs.size-y.proofs,diagnostics:_});}Le(r),await Te(r,e.projectTopology);let f=[...r.entities.values()].sort((p,y)=>p.id.localeCompare(y.id)),c=[...r.relations.values()].sort((p,y)=>p.id.localeCompare(y.id)),m=[...r.proofs.values()].sort((p,y)=>p.id.localeCompare(y.id)),l=f.filter(p=>p.proofIds.length>0).length,g=c.filter(p=>p.proofIds.length>0).length,u=r.providers.filter(p=>p.status!=="failed").length,v=e.projectTopology.diagnostics?.filter(p=>p.code==="graph.edges.missing").flatMap(p=>p.nodeIds??[])??[];v.length>0&&r.diagnostics.push({code:"graph.knowledge.project_relationships_unknown",severity:"warning",message:`${v.length} project(s) have no proven inter-project relationship. This is unknown topology, not proof of independence.`,entityIds:v.map(p=>w("project",`project:${p}`)),recommendation:"Author service contracts or add OpenAPI, Compose, Kubernetes, package or import evidence."});let k=r.diagnostics.filter(p=>p.code.includes("unknown")||p.code.includes("unresolved")||p.code.includes("limit_reached")||p.code.endsWith(".empty_result")).reduce((p,y)=>p+Math.max(y.entityIds?.length??0,y.relationIds?.length??0,1),0),P=ze(f,c),I=Object.values(P).reduce((p,y)=>p+y.unknownCount,0);return {schemaVersion:U,generatedAt:o.toISOString(),source:e.source,workspace:e.workspace,projectTopology:e.projectTopology,entities:f,relations:c,proofs:m,providers:[...r.providers].sort((p,y)=>p.id.localeCompare(y.id)),quality:{entityCount:f.length,relationCount:c.length,proofCount:m.length,entityProofCoverageRatio:f.length===0?1:l/f.length,relationProofCoverageRatio:c.length===0?1:g/c.length,providerSuccessRatio:r.providers.length===0?1:u/r.providers.length,conflictCount:r.diagnostics.filter(p=>p.code.includes("conflict")).length,unknownCount:k+I,bindingCoverage:P,portable:true,secretValuesEmitted:false},diagnostics:[...r.diagnostics].sort((p,y)=>p.code.localeCompare(y.code)||p.message.localeCompare(y.message))}}function ot(e,t){return w(e,t)}
3
+ export{U as a,Xe as b,et as c,tt as d,ot as e};
@@ -1,2 +1,2 @@
1
- import {p,k,l,j}from'./chunk-BYTFXQ6G.js';import {a as a$1}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {e,d,b as b$1}from'./chunk-EWZZUQBR.js';import {d as d$1}from'./chunk-BBGNDMRU.js';import {e as e$1}from'./chunk-XBM2P45G.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {b,a}from'./chunk-AHLMIL2T.js';import k$1 from'path';import V from'fs-extra';import {spawnSync}from'child_process';function ue(){let e={...process.env};return delete e.GIT_DIR,delete e.GIT_WORK_TREE,delete e.GIT_INDEX_FILE,delete e.GIT_PREFIX,e}function F(e,t,a){let r=spawnSync("git",t,{cwd:e,env:ue(),encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(r.status!==0)return {ok:false,stdout:""};let c=r.stdout??"";return {ok:true,stdout:a?.preserveWhitespace?c:c.trim()}}function ge(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return t===".workspai/AGENT-GROUNDING.md"?true:[".workspai/reports/",".workspai/cache/",".rapidkit/reports/",".rapidkit/cache/"].some(a=>t.startsWith(a))}function ke(e){let t=[],a=[],r=[];for(let c of e.split(`
1
+ import {p,k,l,j}from'./chunk-FUPHQOJB.js';import {a as a$1}from'./chunk-HTYMXMQM.js';import {c}from'./chunk-S5KTATOU.js';import {e,d,b as b$1}from'./chunk-EWZZUQBR.js';import {d as d$1}from'./chunk-B4CPDK6J.js';import {e as e$1}from'./chunk-MBRU3VWJ.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {b,a}from'./chunk-62K2H72S.js';import k$1 from'path';import V from'fs-extra';import {spawnSync}from'child_process';function ue(){let e={...process.env};return delete e.GIT_DIR,delete e.GIT_WORK_TREE,delete e.GIT_INDEX_FILE,delete e.GIT_PREFIX,e}function F(e,t,a){let r=spawnSync("git",t,{cwd:e,env:ue(),encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(r.status!==0)return {ok:false,stdout:""};let c=r.stdout??"";return {ok:true,stdout:a?.preserveWhitespace?c:c.trim()}}function ge(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return t===".workspai/AGENT-GROUNDING.md"?true:[".workspai/reports/",".workspai/cache/",".rapidkit/reports/",".rapidkit/cache/"].some(a=>t.startsWith(a))}function ke(e){let t=[],a=[],r=[];for(let c of e.split(`
2
2
  `)){if(!c.trim())continue;let n=c.slice(0,2),i=c.slice(3).trim();if(i&&!ge(i)){if(n==="??"){a.push(i);continue}n.includes("D")&&r.push(i),t.push(i);}}return {changedFiles:[...new Set(t)].sort(),untrackedFiles:[...new Set(a)].sort(),deletedFiles:[...new Set(r)].sort()}}function Q(e,t){let a={available:false,dirty:false,changedFiles:[],untrackedFiles:[],deletedFiles:[]},r=F(e,["rev-parse","--is-inside-work-tree"]);if(!r.ok||r.stdout!=="true")return a;let c=F(e,["rev-parse","--abbrev-ref","HEAD"]),n=F(e,["rev-parse","HEAD"]),i=F(e,["status","--porcelain=v1","--untracked-files=all"],{preserveWhitespace:true}),p=ke(i.stdout),m=p.changedFiles.length>0||p.untrackedFiles.length>0||p.deletedFiles.length>0;return {available:true,branch:c.ok?c.stdout:void 0,commit:n.ok?n.stdout:void 0,ref:t?.ref,dirty:m,changedFiles:p.changedFiles,untrackedFiles:p.untrackedFiles,deletedFiles:p.deletedFiles}}var oe=b.snapshot,L=b.diff,_=a.snapshot,ae=a.diff,he=b.impact,we=a.impact;function ye(e$1){if(e$1.model.projectTopology||!e$1.model.graph||e$1.modelHash!==e(e$1.model))return null;let t={...e$1.model,projectTopology:e$1.model.graph,graph:e$1.model.graph};return {...e$1,modelHash:d(t),model:t}}function ne(e){let t=e.trim().toLowerCase();return t==="git"||t.startsWith("git:")}function We(e){let t=e.trim();return t.toLowerCase()==="git"?"HEAD":t.toLowerCase().startsWith("git:")&&t.slice(4).trim()||"HEAD"}function se(e,t){return k$1.isAbsolute(t)?t:k$1.join(e,t)}async function be(e){let t=await V.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace model input is not a JSON object: ${e}`);let a=t;if(a.schemaVersion===oe){a$2(t,"contracts/workspace-intelligence/workspace-model-snapshot.v1.json",`Workspace model snapshot ${e}`);let r=a;if(!r.model||r.model.schemaVersion!==j)throw new Error(`Invalid workspace model snapshot: ${e}`);let c=d(r.model);if(r.modelHash!==c){let n=ye(r);if(!n)throw new Error(`Workspace model snapshot hash mismatch: ${e}`);return {model:n.model,hash:n.modelHash}}return {model:r.model,hash:r.modelHash}}if(a.schemaVersion===j){a$2(t,"contracts/workspace-intelligence/workspace-model.v1.json",`Workspace model ${e}`);let r=a;return {model:r,hash:d(r)}}throw a.schemaVersion===L?new Error(`workspace diff --from received a diff report (${k$1.basename(e)}). Use a workspace model snapshot or model report as baseline, e.g. ${_}. To analyze an existing diff report, run: npx workspai workspace impact --from ${k$1.basename(e)} --json`):new Error(`Unsupported workspace model input schema: ${String(a.schemaVersion)}`)}async function ve(e){let t=await V.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace diff input is not a JSON object: ${e}`);let a=t;if(a.schemaVersion!==L)return null;a$2(t,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Workspace model diff ${e}`);let r=a;if(!r.currentModel||r.currentModel.schemaVersion!==j||!r.summary||!Array.isArray(r.changes))throw new Error(`Invalid workspace model diff report: ${e}`);if(r.toHash!==d(r.currentModel))throw new Error(`Workspace model diff current-model hash mismatch: ${e}`);return r}async function Ye(e){let t=e.model??await p({workspacePath:e.workspacePath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {schemaVersion:oe,generatedAt:(e.now??new Date).toISOString(),modelHash:d(t),modelRef:k,model:t}}async function Qe(e,t){return e$1(t,_,d$1(e))}function x(e){return {name:e.name,path:e.path,kind:e.kind,category:e.category,runtime:e.runtime,framework:e.framework,generator:e.generator,supportTier:e.supportTier,commands:e.commands,importantFiles:e.importantFiles}}function w(e,t){e.push(t);}function Me(e,t){let a=[],r=["name","profile","type"],c=["workspaceType","surfaces","runtimeFamilies","businessCapabilities"];for(let n of r){let i=e.workspace[n],p=t.workspace[n];b$1(i)!==b$1(p)&&w(a,{type:"workspace.changed",severity:"info",target:`workspace.${n}`,message:`Workspace metadata field changed: ${String(n)}`,before:i,after:p});}for(let n of c){let i=e.identity[n],p=t.identity[n];b$1(i)!==b$1(p)&&w(a,{type:"workspace.changed",severity:"info",target:`identity.${n}`,message:`Workspace identity field changed: ${String(n)}`,before:i,after:p});}return b$1(e.policies)!==b$1(t.policies)&&w(a,{type:"workspace.changed",severity:"warning",target:"policies",message:"Workspace policy summary changed.",before:e.policies,after:t.policies}),b$1(e.discovery)!==b$1(t.discovery)&&w(a,{type:"workspace.changed",severity:"info",target:"discovery",message:"Workspace discovery settings changed.",before:e.discovery,after:t.discovery}),e.contracts.exists!==t.contracts.exists&&w(a,{type:"workspace.changed",severity:t.contracts.exists?"info":"warning",target:t.contracts.workspaceContractPath,message:"Workspace contract presence changed.",before:e.contracts.exists,after:t.contracts.exists}),a}function je(e,t){let a=e.validation??null,r=t.validation??null;return b$1(a)===b$1(r)?[]:[{type:"validation.changed",severity:r?.status==="failed"?"critical":"warning",target:"validation",message:"Workspace model validation changed.",before:a,after:r}]}function Ie(e,t){let a=[],r=new Map(e.projects.map(n=>[n.path,n])),c=new Map(t.projects.map(n=>[n.path,n]));for(let[n,i]of c.entries()){let p=r.get(n);if(!p){w(a,{type:"project.added",severity:"info",target:n,message:`Project added: ${i.name}`,after:x(i)});continue}let m=x(p),l=x(i);if(b$1(m)!==b$1(l)){let u=p.runtime!==i.runtime||p.framework!==i.framework;w(a,{type:"project.changed",severity:u?"warning":"info",target:n,message:`Project changed: ${i.name}`,before:m,after:l});}}for(let[n,i]of r.entries())c.has(n)||w(a,{type:"project.removed",severity:"warning",target:n,message:`Project removed: ${i.name}`,before:x(i)});return a.sort((n,i)=>`${n.type}:${n.target}`.localeCompare(`${i.type}:${i.target}`))}async function Pe(e){let t=k$1.resolve(e.workspacePath),a=ne(e.fromPath),r=a?We(e.fromPath):void 0,c=e.fromPath;if(a){let f=k$1.join(t,_);if(!await V.pathExists(f))throw new Error("Git-aware workspace diff requires an existing snapshot at .workspai/reports/workspace-model-snapshot.json. Run: npx workspai workspace snapshot --json");c=_;}let n=se(t,c),i=await be(n),p$1=e.model??await p({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),m=d(p$1),l=[...Me(i.model,p$1),...Ie(i.model,p$1),...je(i.model,p$1)],u;e.includeGitObservation!==false&&(u=e.gitObservation??Q(t,{ref:r}),u.available&&Ee(l,u,p$1));let v=l.filter(f=>f.type.startsWith("git.")).length,R=i.hash!==m,y=a?`git:${r??"HEAD"}`:k$1.relative(t,n).split(k$1.sep).join("/");return {schemaVersion:L,generatedAt:(e.now??new Date).toISOString(),fromRef:y,toRef:k,fromHash:i.hash,toHash:m,summary:{changed:R||v>0,addedProjects:l.filter(f=>f.type==="project.added").length,removedProjects:l.filter(f=>f.type==="project.removed").length,changedProjects:l.filter(f=>f.type==="project.changed").length,workspaceChanges:l.filter(f=>f.type==="workspace.changed").length,validationChanges:l.filter(f=>f.type==="validation.changed").length,gitChangedFiles:v},git:u?.available?Oe(u,r):{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:l,currentModel:p$1}}async function Ze(e,t){return e$1(t,ae,d$1(e))}function I(e){return {none:0,low:1,medium:2,high:3,critical:4}[e]}function Z(e){return e.reduce((t,a)=>I(a)>I(t)?a:t,"none")}var N=["none","low","medium","high","critical"];function Re(e){let t=Math.max(1,I(e)-1);return N[t]}function Ce(e){let t=Math.min(N.length-1,I(e)+1);return N[t]}function ee(e){return e.join(" ")}function h(e,t,a,r){return {id:e,label:t,scope:r.scope,project:r.project,display:ee(["npx","workspai",...a]),execute:ee(["npx","--yes","--package","workspai","workspai",...a]),required:r.required!==false}}function te(e){let t=`project:${e.name}`,a=e.commands.fleetStages;return [h(`project.${e.name}.init`,`Run init for ${e.name}`,["workspace","run","init","--scope",t,"--json"],{scope:"project",project:e.name,required:a.includes("init")}),h(`project.${e.name}.test`,`Run tests for ${e.name}`,["workspace","run","test","--scope",t,"--json"],{scope:"project",project:e.name,required:a.includes("test")}),h(`project.${e.name}.build`,`Run build for ${e.name}`,["workspace","run","build","--scope",t,"--json"],{scope:"project",project:e.name,required:a.includes("build")}),h(`project.${e.name}.start`,`Run start for ${e.name}`,["workspace","run","start","--scope",t,"--json"],{scope:"project",project:e.name,required:a.includes("start")})]}function T(){return [h("workspace.doctor","Run workspace doctor",["doctor","workspace","--json"],{scope:"workspace"}),h("workspace.contract.verify","Verify workspace contract",["workspace","contract","verify","--json"],{scope:"workspace"}),h("workspace.readiness","Run release readiness",["readiness","--json"],{scope:"workspace"}),h("workspace.analyze","Run workspace analyze",["analyze","--json"],{scope:"workspace",required:false}),h("workspace.pipeline","Run governance pipeline",["pipeline","--json"],{scope:"workspace",required:false}),h("workspace.doctor-fix","Verify doctor fix result",["doctor","workspace","--fix","--json"],{scope:"workspace",required:false})]}function Se(e,t){let a=t.split(k$1.sep).join("/");return e.projects.filter(c=>{let n=c.path.split(k$1.sep).join("/");return a===n||a.startsWith(`${n}/`)}).sort((c,n)=>n.path.length-c.path.length)[0]}function Ee(e,t,a){let r=new Set(e.map(n=>n.target)),c=(n,i)=>{let p=i.split(k$1.sep).join("/"),m=`git:${p}`;if(r.has(m))return;let l=Se(a,p),u=l?`${l.name} (${l.path})`:"workspace";w(e,{type:n,severity:n==="git.deleted"?"warning":"info",target:m,message:`Git ${n==="git.untracked"?"untracked":n==="git.deleted"?"deleted":"changed"} file affects ${u}: ${p}`,after:{path:p,project:l?.name,projectPath:l?.path}}),r.add(m);};for(let n of t.changedFiles)c("git.file.changed",n);for(let n of t.untrackedFiles)c("git.untracked",n);for(let n of t.deletedFiles)c("git.deleted",n);}function Oe(e,t){return {available:true,ref:t??e.ref,branch:e.branch,commit:e.commit,dirty:e.dirty,changedFiles:e.changedFiles.length,untrackedFiles:e.untrackedFiles.length,deletedFiles:e.deletedFiles.length}}function Ae(e){let t=new Set,a=[];for(let r of e){let c=`${r.scope}:${r.project??""}:${r.display}`;t.has(c)||(t.add(c),a.push(r));}return a}function De(e){return e.type==="project.removed"?"high":e.severity==="critical"?"critical":e.severity==="warning"?"high":("medium")}function $e(e,t){return e.severity==="critical"?"critical":e.target==="policies"||e.target.includes("contract")?"high":e.type==="validation.changed"?(t?.projectCount??0)===0?"low":"high":e.target==="evidence"?"low":e.severity==="warning"?"medium":"low"}function Fe(e){return e.affectedProjects>0||e.projectCount>0||!e.changes.every(a=>a.severity==="critical"?false:a.type.startsWith("git.")||a.type==="validation.changed")?e.risk:I(e.risk)>=I("high")||e.risk==="medium"?"low":e.risk}function re(e,t){if(!e||e==="workspace")return true;let a=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return [t.name,t.path,k$1.basename(t.path),t.absolutePath].filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase()).includes(a)}function xe(e){if(!e.changed)return {headline:"No workspace model impact detected.",bullets:["The current workspace model matches the provided snapshot/report."],unsafeAssumptions:["Do not claim runtime verification passed unless a report exists."]};let t=e.affectedProjects.map(a=>a.project?.name??a.target);return {headline:`Workspace impact risk: ${e.risk}.`,bullets:[`Affected projects: ${t.length?t.join(", "):"none"}.`,`Workspace-level items: ${e.workspaceImpact.length}.`,"Use the verification plan before recommending apply, rollback, or release actions."],unsafeAssumptions:["Do not infer test/build success from impact alone.","Do not apply fixes without project scope and verification evidence.","Use display commands for users and execute commands for automation."]}}async function et(e){let t=k$1.resolve(e.workspacePath),a=ne(e.fromPath),r=e.diff;if(!r&&!a){let o=se(t,e.fromPath);r=await ve(o)??void 0;}r||(r=await Pe({workspacePath:t,fromPath:e.fromPath,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,includeGitObservation:e.includeGitObservation,gitObservation:e.gitObservation,now:e.now,model:e.model}));let c$1=new Map(r.currentModel.projects.map(o=>[o.path,o])),n=new Map(r.currentModel.projects.map(o=>[o.name,o])),i=r.changes.filter(o=>o.type.startsWith("project.")),p=new Map;for(let o of i){let d=(c$1.get(o.target)??(typeof o.before?.name=="string"?n.get(o.before.name):void 0))?.path??o.target,W=p.get(d)??[];W.push(o),p.set(d,W);}let m=[];for(let[o,s]of p.entries()){let d=c$1.get(o);if(d&&!re(e.scope,d))continue;let W=Z(s.map(De)),C=d?.name??(typeof s[0]?.before?.name=="string"?String(s[0].before.name):o);m.push({id:`project:${C}`,scope:"project",target:o,title:`Project impact: ${C}`,summary:s.map(M=>M.message).join(" "),risk:W,reasons:s.map(M=>`${M.type}: ${M.message}`),project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?te(d):T()});}let l$1=l(r.currentModel),u=l$1?a$1(l$1):void 0,v=new Set(m.map(o=>o.project?.name).filter(o=>typeof o=="string")),R=new Map;for(let o of m)if(o.project?.name){let s=u?.byId.get(o.project.name);s&&(o.centrality={fanIn:s.fanIn,fanOut:s.fanOut,reach:s.reach,betweenness:s.betweenness,isHotspot:s.isHotspot},s.isHotspot&&(o.risk=Ce(o.risk),o.reasons=[...o.reasons,`graph.hotspot: critical-path project with ${s.reach} transitive dependent(s); risk escalated.`])),o.origin="direct",o.distance=0,R.set(o.project.name,o.risk);}let y=[],f=0;if(l$1&&v.size>0){let o=c(l$1,v);for(let s of o.values()){if(s.distance===0||v.has(s.id))continue;let d=n.get(s.id);if(d&&!re(e.scope,d))continue;let W=s.path[0],C=s.path[s.path.length-2]??W,M=R.get(W)??"medium",de=Re(M),j=u?.byId.get(s.id);f=Math.max(f,s.distance),y.push({id:`transitive:${s.id}`,scope:"project",target:d?.path??s.id,title:`Transitive impact: ${s.id}`,summary:`Depends on changed project ${W}${s.via?` via ${s.via}`:""} (distance ${s.distance}).`,risk:de,reasons:[`graph.dependent: depends on ${C}${s.via?` via ${s.via}`:""} (path ${s.path.join(" -> ")})`],project:d?{name:d.name,path:d.path,kind:d.kind,runtime:d.runtime,framework:d.framework,supportTier:d.supportTier,...d.generator?{generator:d.generator}:{}}:void 0,verification:d?te(d):T(),origin:"transitive",distance:s.distance,path:s.path,via:s.via,...j?{centrality:{fanIn:j.fanIn,fanOut:j.fanOut,reach:j.reach,betweenness:j.betweenness,isHotspot:j.isHotspot}}:{}});}}y.sort((o,s)=>o.target.localeCompare(s.target));let ie=u?u.hotspots.flatMap(o=>{let s=u.byId.get(o);return s?[{project:o,fanIn:s.fanIn,fanOut:s.fanOut,reach:s.reach,betweenness:s.betweenness}]:[]}):[],ce=r.changes.filter(o=>!o.type.startsWith("project.")),K=r.currentModel.summary?.projectCount??r.currentModel.projects.length,P=ce.map(o=>({id:`workspace:${o.target}`,scope:"workspace",target:o.target,title:`Workspace impact: ${o.target}`,summary:o.message,risk:$e(o,{projectCount:K}),reasons:[`${o.type}: ${o.message}`],verification:T()})),B=Ae([...m.flatMap(o=>o.verification),...y.flatMap(o=>o.verification),...P.flatMap(o=>o.verification),...r.summary.changed?T():[]]).filter(o=>o.required),pe=Z([...m.map(o=>o.risk),...y.map(o=>o.risk),...P.map(o=>o.risk)]),q=Fe({risk:pe,affectedProjects:m.length,projectCount:K,changes:r.changes}),z={changed:r.summary.changed,risk:q,affectedProjects:m.length,workspaceItems:P.length,recommendedCommands:B.length,blastRadius:{directlyAffected:m.length,transitivelyAffected:y.length,maxDistance:f,graphEdges:l$1?.edges.length??0}};return {schemaVersion:he,generatedAt:(e.now??new Date).toISOString(),fromRef:r.fromRef,diffRef:ae,workspace:{name:r.currentModel.workspace.name,profile:r.currentModel.workspace.profile,type:r.currentModel.workspace.type},summary:z,affectedProjects:m.sort((o,s)=>o.target.localeCompare(s.target)),transitiveImpact:y,criticalPathHotspots:ie,workspaceImpact:P.sort((o,s)=>o.target.localeCompare(s.target)),verificationPlan:B,agentBrief:xe({changed:z.changed,risk:q,affectedProjects:m,workspaceImpact:P}),diff:r}}async function tt(e,t){return e$1(t,we,d$1(e))}export{Q as a,oe as b,L as c,_ as d,ae as e,he as f,we as g,ye as h,ne as i,We as j,Ye as k,Qe as l,Pe as m,Ze as n,T as o,et as p,tt as q};
@@ -0,0 +1,10 @@
1
+ import {a}from'./chunk-GR6442P7.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {j,s,p as p$1,v}from'./chunk-MOSXTVPU.js';import z from'crypto';import X from'os';import l from'path';import {once}from'events';import {createWriteStream,createReadStream}from'fs';import*as G from'readline';import {Transform,Readable}from'stream';import {pipeline}from'stream/promises';import {lookup}from'dns/promises';import I from'net';import p from'fs-extra';import*as Q from'yauzl';import*as ee from'yazl';var Ue="workspai-workspace-archive-capabilities-v1",U="workspai-workspace-archive-manifest-v1",k="workspai-workspace-archive-operation-result-v1";var q="contracts/workspace-archive-manifest.v1.json",K="contracts/workspace-archive-operation-result.v1.json",qe={archiveCompression:{signature:"--archive-compression <mode>",description:"Archive compression: store (default) or deflate",appliesTo:["export"]},maxDownloadSize:{signature:"--max-download-size <size>",description:"Maximum remote archive download size (secure default: 5gb)",appliesTo:["inspect","verify","doctor","hydrate","import"]},maxExpandedSize:{signature:"--max-expanded-size <size>",description:"Maximum expanded archive payload size (secure default: 20gb)",appliesTo:["inspect","verify","doctor","hydrate","import"]},downloadTimeoutMs:{signature:"--download-timeout-ms <ms>",description:"Remote archive download timeout in milliseconds; 0 disables it",appliesTo:["inspect","verify","doctor","hydrate","import"]},allowPrivateNetwork:{signature:"--allow-private-network",description:"Allow archive downloads from loopback/private networks (unsafe for untrusted input)",appliesTo:["inspect","verify","doctor","hydrate","import"]}};var A=".workspai/archive-manifest.json",R=".rapidkit/archive-manifest.json",ue="workspai.workspace.archive",de=300*1e3,ye=5*1024*1024*1024,ve=20*1024*1024*1024,Z=2e5,we=5*1024*1024*1024,ge=1e3,M=5,ke=64*1024*1024;function Ee(r){let t=r.toLowerCase().split("%")[0];if(I.isIPv4(t)){let e=t.split(".").map(Number);return e[0]===0||e[0]===10||e[0]===127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&e[1]===168||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]>=224}return I.isIPv6(t)?t==="::"||t==="::1"||t.startsWith("fc")||t.startsWith("fd")||/^fe[89ab]/.test(t)||t.startsWith("ff")||t.startsWith("::ffff:127.")||t.startsWith("::ffff:10.")||t.startsWith("::ffff:192.168."):true}async function J(r,t){let e=new URL(r);if(e.protocol!=="https:"&&e.protocol!=="http:")throw new Error(`Workspace archive URL protocol is not supported: ${e.protocol}`);if(e.protocol!=="https:"&&!t)throw new Error("Remote workspace archives require HTTPS unless private-network access is explicitly enabled.");if(e.username||e.password)throw new Error("Workspace archive URL must not contain embedded credentials.");if(t)return e;let i=e.hostname.replace(/^\[|\]$/g,"").toLowerCase();if(i==="localhost"||i.endsWith(".localhost"))throw new Error("Workspace archive URL resolves to a private or local network address.");let a=I.isIP(i)?[{address:i}]:await lookup(i,{all:true,verbatim:true});if(a.length===0||a.some(({address:s})=>Ee(s)))throw new Error("Workspace archive URL resolves to a private or local network address.");return e}async function Ae(r,t,e){let i=await J(r,e);for(let a=0;a<=M;a+=1){let s=await fetch(i,{signal:t,redirect:"manual",credentials:"omit"});if(![301,302,303,307,308].includes(s.status))return s;let n=s.headers.get("location");if(await s.body?.cancel(),!n)throw new Error("Workspace archive redirect is missing a Location header.");if(a===M)throw new Error(`Workspace archive download exceeded ${M} redirects.`);i=await J(new URL(n,i).href,e);}throw new Error("Workspace archive redirect policy failed.")}var Pe=new Set(["__pycache__",".venv","venv","node_modules",".git","dist","build","target",".pytest_cache",".mypy_cache",".ruff_cache","htmlcov",".next",".turbo",".cache"]),We=new Set([".DS_Store","Thumbs.db",".coverage","npm-debug.log","yarn-error.log","pnpm-debug.log","workspace-link.local.json","imported-projects.json","workspace-registry.v1.json"]),be=[/^\.env$/i,/^\.env\.(?!example$|sample$|template$).+/i,/^.*\.pem$/i,/^.*\.key$/i,/^id_rsa$/i,/^id_ed25519$/i];function _(r){return r.replace(/\\/g,"/")}function te(r){return r.trim().replace(/\.workspai-archive\.zip$/i,"").replace(/\.rapidkit-archive\.zip$/i,"").replace(/\.zip$/i,"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,64)||"imported-workspace"}function re(r){let t=_(r).trim();if(!t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0"))return false;let e=t.split("/").filter(Boolean);return e.length>0&&!e.some(i=>i===".."||i===".")}function ie(r){if(!re(r))throw new Error(`Archive contains an unsafe path: ${r}`)}function Se(r,t){let e=l.relative(t,r);return e===""||!!e&&!e.startsWith("..")&&!l.isAbsolute(e)}function Re(r,t){let e=_(r),i=e.split("/").filter(Boolean);if((i[0]===".workspai"||i[0]===".rapidkit")&&["cache","reports"].includes(i[1]||"")||i.some(s=>Pe.has(s)||a(s)))return true;let a$1=i[i.length-1]||"";return e===".workspai/workspace.contract.json"||e===".rapidkit/workspace.contract.json"||We.has(a$1)||/\.(?:workspai|rapidkit)-archive\.zip$/i.test(a$1)||!t?.includeEnv&&be.some(s=>s.test(a$1))?true:a$1.endsWith(".pyc")||a$1.endsWith(".log")}async function _e(r){for(let t of [l.join(r,".workspai","workspace.contract.json"),l.join(r,".rapidkit","workspace.contract.json")])if(await p.pathExists(t))try{return await p.readJson(t)}catch(e){throw new Error(`Workspace contract could not be inspected safely for archive portability: ${t}: ${e instanceof Error?e.message:String(e)}`)}return null}function Ce(r){return (r?.projects??[]).filter(t=>typeof t.externalPath=="string"||typeof t.relativePath=="string"&&t.relativePath.startsWith("external/")).map(t=>({name:t.slug||t.relativePath||"external-project",relationship:["adopted","linked","imported","managed","restored"].includes(String(t.relationship))?t.relationship:"adopted",included:false,requiredAction:"relink"})).sort((t,e)=>t.name.localeCompare(e.name))}function xe(r){if(r)return {...r,workspace:{...r.workspace},projects:r.projects.filter(t=>typeof t.externalPath!="string"&&!t.relativePath.startsWith("external/")).map(({externalPath:t,...e})=>({...e,modules:[...e.modules],ports:e.ports.map(i=>({...i})),contracts:{owns:[...e.contracts.owns],apis:e.contracts.apis.map(i=>({...i})),publishes:[...e.contracts.publishes],consumes:[...e.contracts.consumes],dependsOn:[...e.contracts.dependsOn],env:[...e.contracts.env]}}))}}async function*ae(r,t,e){let i=(await p.readdir(t,{withFileTypes:true})).sort((a,s)=>a.name.localeCompare(s.name));for(let a of i){let s=l.join(t,a.name),n=_(l.relative(r,s));if(!(!n||Re(n,e))){if(a.isDirectory()){yield*ae(r,s,e);continue}a.isFile()&&(yield {relativePath:n,fullPath:s});}}}async function Oe(r){for(let t of s(r,"workspace.json"))try{let e=await p.readJson(t);if(typeof e.workspace_name=="string"&&e.workspace_name.trim())return e.workspace_name.trim();if(typeof e.name=="string"&&e.name.trim())return e.name.trim()}catch{}return l.basename(l.resolve(r))}async function ze(r){let t=await p.stat(r.fullPath),e=z.createHash("sha256"),i=0;for await(let s of createReadStream(r.fullPath)){let n=Buffer.isBuffer(s)?s:Buffer.from(s);i+=n.length,e.update(n);}let a=await p.stat(r.fullPath);if(t.size!==a.size||t.mtimeMs!==a.mtimeMs||i!==a.size)throw new Error(`Workspace file changed while preparing archive: ${r.relativePath}`);return {...r,size:i,mtimeMs:a.mtimeMs,sha256:e.digest("hex")}}async function E(r,t){r.write(t)||await once(r,"drain");}async function se(r){await new Promise((t,e)=>{r.once("error",e),r.end(t);});}async function*O(r){let t=G.createInterface({input:createReadStream(r),crlfDelay:1/0});for await(let e of t){let i=e.trim();i&&(yield JSON.parse(i));}}async function Ne(r){let t=createWriteStream(r.manifestPath,{flags:"wx"});try{await E(t,`{
2
+ `);for(let[i,a]of Object.entries(r.manifestBase))await E(t,` ${JSON.stringify(i)}: ${JSON.stringify(a,null,2)},
3
+ `);await E(t,` "files": [
4
+ `);let e=true;for await(let i of O(r.spoolPath)){let{mtimeMs:a,...s}=i;await E(t,`${e?"":`,
5
+ `} ${JSON.stringify(s)}`),e=false;}await E(t,`
6
+ ]
7
+ }
8
+ `),await se(t);}catch(e){throw t.destroy(),await p.remove(r.manifestPath).catch(()=>{}),e}}async function Me(r,t){let e=[];for await(let i of O(t)){let{mtimeMs:a,...s}=i;e.push(s);}return {...r,files:e}}async function Ie(r,t){try{await p.rename(r,t);}catch(e){let i=e.code;if(i!=="EEXIST"&&i!=="EPERM")throw e;await p.move(r,t,{overwrite:true});}}async function pt(r){let t=l.resolve(r.workspacePath);if(!j(t))throw new Error("Workspace export requires a Workspai workspace root with .workspai-workspace or a legacy .rapidkit-workspace marker.");let e=await Oe(t),i=await _e(t),a=Ce(i),s=xe(i),n=l.resolve(r.outputPath||`${te(e)}.workspai-archive.zip`),o={schemaVersion:U,version:1,kind:ue,workspaceName:e,exportedAt:(r.now??new Date).toISOString(),exportedBy:"workspai",archiveFormat:r.compression==="deflate"?"zip-deflate":"zip-store",containerFormat:"zip64",compression:r.compression==="deflate"?"deflate":"store",streaming:true,security:{envFilesIncluded:r.includeEnv===true,excludedByDefault:[".git","node_modules",".venv","dist","build","target",".env","*.pem","*.key","*.log"]},...a.length>0?{externalProjects:a}:{},...s?{portableContract:s}:{}},m=l.resolve(n);await p.ensureDir(l.dirname(n));let h=`${n}.${process.pid}.${z.randomUUID()}.tmp`,u=await p.mkdtemp(l.join(X.tmpdir(),"workspai-archive-export-")),y=l.join(u,"manifest-files.jsonl"),c=l.join(u,"archive-manifest.json"),f=new ee.ZipFile,w=r.now??new Date,v=r.compression==="deflate";try{let P=createWriteStream(y,{flags:"wx"});try{for await(let d of ae(t,t,{includeEnv:r.includeEnv===true})){if(l.resolve(d.fullPath)===m)continue;let g=await ze(d),x={path:g.relativePath,size:g.size,sha256:g.sha256,mtimeMs:g.mtimeMs};await E(P,`${JSON.stringify(x)}
9
+ `);}await se(P);}catch(d){throw P.destroy(),d}await Ne({manifestBase:o,spoolPath:y,manifestPath:c});for await(let d of O(y)){let g=l.join(t,...d.path.split("/"));f.addFile(g,d.path,{compress:v,forceZip64Format:d.size>=4294967295,mtime:w});}f.addFile(c,A,{compress:v,mtime:w}),f.end({forceZip64Format:true,comment:""}),await pipeline(f.outputStream,createWriteStream(h,{flags:"wx"}));for await(let d of O(y)){let g=l.join(t,...d.path.split("/")),x=await p.stat(g);if(x.size!==d.size||x.mtimeMs!==d.mtimeMs)throw new Error(`Workspace file changed while writing archive: ${d.path}`)}let W=await p.stat(h);await Ie(h,n);let b=await Me(o,y);return C({schemaVersion:k,operation:"export",status:"passed",archivePath:n,manifest:b,bytesWritten:W.size})}finally{await p.remove(u).catch(()=>{}),await p.remove(h).catch(()=>{});}}async function ne(r,t={}){if(/^https?:\/\//i.test(r)){let e=await p.mkdtemp(l.join(X.tmpdir(),"workspai-workspace-archive-")),i=l.join(e,"workspace.workspai-archive.zip"),a=new AbortController,s=t.downloadTimeoutMs??de,n=s>0?setTimeout(()=>a.abort(new Error("Download timed out")),s):null;try{let o=await Ae(r,a.signal,t.allowPrivateNetwork===true);if(!o.ok)throw new Error(`Failed to download workspace archive: HTTP ${o.status}`);if(!o.body)throw new Error("Failed to download workspace archive: response body is empty.");let m=t.maxDownloadBytes??ye,h=Number(o.headers.get("content-length"));if(Number.isFinite(h)&&h>m)throw new Error(`Workspace archive download exceeds configured limit (${h} > ${m} bytes).`);let u=0,y=new Transform({transform(f,w,v){if(u+=f.length,u>m){v(new Error(`Workspace archive download exceeds configured limit (${m} bytes).`));return}v(null,f);}}),c=Readable.fromWeb(o.body);return await pipeline(c,y,createWriteStream(i,{flags:"wx"})),{archivePath:i,cleanup:e}}catch(o){throw await p.remove(e).catch(()=>{}),a.signal.aborted?new Error(`Workspace archive download timed out after ${s}ms.`,{cause:o}):o}finally{n&&clearTimeout(n);}}return {archivePath:l.resolve(r)}}function Te(r){return new Promise((t,e)=>{Q.open(r,{autoClose:false,lazyEntries:true,decodeStrings:true,validateEntrySizes:true,strictFileNames:true},(i,a)=>{i||!a?e(i??new Error("Failed to open workspace archive.")):t(a);});})}function $e(r){return new Promise((t,e)=>{let i=[],a=s=>e(s);r.once("error",a),r.on("entry",s=>{try{if(ie(s.fileName),s.isEncrypted())throw new Error(`Encrypted workspace archive entries are not supported: ${s.fileName}`);s.fileName.endsWith("/")||i.push({name:s.fileName,size:s.uncompressedSize,compressedSize:s.compressedSize,crc32:s.crc32,entry:s}),r.readEntry();}catch(n){e(n);}}),r.once("end",()=>{r.removeListener("error",a),t(i);}),r.readEntry();})}function $(r,t){return new Promise((e,i)=>{r.openReadStream(t,(a,s)=>{a||!s?i(a??new Error(`Failed to read ${t.fileName}.`)):e(s);});})}async function Fe(r,t,e=ke){if(t.size>e)throw new Error(`Workspace archive manifest exceeds ${e} bytes.`);let i=[],a=0,s=await $(r,t.entry);for await(let n of s){let o=Buffer.isBuffer(n)?n:Buffer.from(n);if(a+=o.length,a>e)throw s.destroy(),new Error(`Workspace archive manifest exceeds ${e} bytes.`);i.push(o);}return Buffer.concat(i,a)}function Le(r){let t=JSON.parse(r.toString("utf-8"));a$1(t,q,"Workspace archive manifest");let e=new Set;for(let i of t.files){if(!re(i.path)||_(i.path)!==i.path)throw new Error(`Workspace archive manifest contains an unsafe path: ${i.path}`);if(i.path===A||i.path===R)throw new Error(`Workspace archive manifest cannot inventory itself: ${i.path}`);if(e.has(i.path))throw new Error(`Workspace archive manifest contains duplicate path: ${i.path}`);e.add(i.path);}return t}function C(r){return a$1(r,K,"Workspace archive operation result"),r}function Ve(r){return v(_(r))}function Be(r){let t=new Map;for(let e of r){if(e.name===A||e.name===R)continue;let i=Ve(e.name),a=t.get(i);if(!a){t.set(i,{...e,sourceName:e.name,targetName:i});continue}let s=e.name===i,n=a.sourceName===a.targetName;if(s&&!n){t.set(i,{...e,sourceName:e.name,targetName:i});continue}if(!(a.size===e.size&&a.crc32===e.crc32)&&!n)throw new Error(`Workspace archive contains conflicting entries for ${i}: ${a.sourceName}, ${e.name}`)}return [...t.values()].sort((e,i)=>e.targetName.localeCompare(i.targetName))}async function F(r,t={}){let e=await ne(r,t),i;try{i=await Te(e.archivePath);let a=await $e(i);if(a.length>Z)throw new Error(`Workspace archive contains too many entries (${a.length} > ${Z}).`);for(let h of a){if(h.size>we)throw new Error(`Workspace archive entry is too large: ${h.name}`);if(h.size/Math.max(1,h.compressedSize)>ge)throw new Error(`Workspace archive entry has an unsafe compression ratio: ${h.name}`)}let s=a.reduce((h,u)=>h+u.size,0),n=t.maxExpandedBytes??ve;if(s>n)throw new Error(`Workspace archive payload exceeds configured limit (${s} > ${n} bytes).`);let o=a.find(h=>h.name===A||h.name===R);if(!o)throw new Error(`Workspace archive is missing ${p$1("","archive-manifest.json").replace(/^\//,"")}.`);let m=Le(await Fe(i,o));return {archivePath:e.archivePath,entries:a,manifest:m,zipFile:i,cleanup:e.cleanup}}catch(a){throw i?.close(),e.cleanup&&await p.remove(e.cleanup).catch(()=>{}),a}}async function L(r){r.zipFile?.close(),r.cleanup&&await p.remove(r.cleanup).catch(()=>{});}async function je(r){let t=await F(r.archivePathOrUrl,r.safety);try{let e=new Map(t.entries.filter(a=>a.name!==A&&a.name!==R).map(a=>[a.name,a])),i=t.manifest.files.map(a=>({path:a.path,size:e.get(a.path)?.size??a.size,hasChecksum:typeof a.sha256=="string"&&a.sha256.length>0}));return C({schemaVersion:k,operation:"inspect",status:"passed",archivePath:t.archivePath,manifest:t.manifest,fileCount:i.length,totalBytes:i.reduce((a,s)=>a+s.size,0),entries:i})}finally{await L(t);}}async function oe(r){let t=await F(r.archivePathOrUrl,r.safety);try{let e=new Map(t.entries.filter(c=>c.name!==A&&c.name!==R).map(c=>[c.name,c])),i=new Set(t.manifest.files.map(c=>c.path)),a=[...e.keys()].filter(c=>!i.has(c)).sort(),s=[],n=[],o=[],m=0;for(let c of t.manifest.files){ie(c.path);let f=e.get(c.path);if(!f){s.push(c.path);continue}let w=z.createHash("sha256"),v=0,P=await $(t.zipFile,f.entry);for await(let b of P){let d=Buffer.isBuffer(b)?b:Buffer.from(b);v+=d.length,w.update(d);}let W={size:v,sha256:w.digest("hex")};if(v!==f.size||v!==c.size){o.push({path:c.path,expected:{size:c.size,sha256:c.sha256},actual:W});continue}if(!c.sha256){n.push(c.path);continue}if(W.sha256!==c.sha256){o.push({path:c.path,expected:{size:c.size,sha256:c.sha256},actual:W});continue}m+=1;}let h=r.requireChecksums===true&&n.length>0,u=s.length>0||o.length>0||h||a.length>0,y=n.length>0;return C({schemaVersion:k,operation:"verify",archivePath:t.archivePath,manifest:t.manifest,status:u?"failed":y?"warning":"passed",fileCount:t.manifest.files.length,totalBytes:t.manifest.files.reduce((c,f)=>c+f.size,0),verifiedFiles:m,missingChecksumFiles:n,missingArchiveEntries:s,extraArchiveEntries:a,mismatches:o})}finally{await L(t);}}async function lt(r){let t=await ne(r.archivePathOrUrl,r.safety);try{return await De({archivePath:t.archivePath,strict:r.strict})}finally{t.cleanup&&await p.remove(t.cleanup).catch(()=>{});}}async function De(r){let t=await je({archivePathOrUrl:r.archivePath}),e=await oe({archivePathOrUrl:r.archivePath,requireChecksums:r.strict===true}),i=[],a=[];i.push({id:"manifest-present",status:"passed",message:`Archive manifest found for workspace "${t.manifest.workspaceName}".`}),i.push({id:"integrity",status:e.status,message:e.status==="passed"?`Verified ${e.verifiedFiles}/${e.fileCount} files.`:"Archive integrity verification did not fully pass."});let s=t.manifest.security?.envFilesIncluded===true;i.push({id:"secrets-policy",status:s?"warning":"passed",message:s?"Archive manifest says environment/private files were intentionally included.":"Archive manifest excludes environment/private files by default."}),s&&a.push("Share this archive only through trusted internal channels."),e.missingChecksumFiles.length>0&&a.push("Re-export the archive with the latest RapidKit/Workspai tooling."),e.mismatches.length>0&&a.push("Reject this archive and request a fresh export from the owner."),(e.extraArchiveEntries.length>0||e.missingArchiveEntries.length>0)&&a.push("Regenerate the archive so ZIP entries and manifest entries match."),r.strict===true&&e.status!=="passed"&&a.push("Do not hydrate this archive in strict or production workflows.");let n=i.some(m=>m.status==="failed"),o=i.some(m=>m.status==="warning");return C({schemaVersion:k,operation:"doctor",archivePath:t.archivePath,status:n?"failed":o?"warning":"passed",workspaceName:t.manifest.workspaceName,fileCount:t.fileCount,totalBytes:t.totalBytes,checks:i,recommendedActions:a})}async function He(r,t){let e=await p.lstat(r).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(!e)return false;if(e.isSymbolicLink())throw new Error(`Output directory must not be a symbolic link: ${r}`);if(!e.isDirectory())throw new Error(`Output path is not a directory: ${r}`);if((await p.readdir(r)).length>0&&!t)throw new Error(`Output directory is not empty: ${r}. Use --force to overwrite.`);return true}async function ht(r){let t=await F(r.archivePathOrUrl,r.safety);try{let e=await oe({archivePathOrUrl:t.archivePath,requireChecksums:r.strict===true});if(e.status==="failed"){let o=[e.missingArchiveEntries.length?`missing entries: ${e.missingArchiveEntries.join(", ")}`:"",e.extraArchiveEntries.length?`unexpected entries: ${e.extraArchiveEntries.join(", ")}`:"",e.mismatches.length?`checksum/size mismatches: ${e.mismatches.map(m=>m.path).join(", ")}`:"",e.missingChecksumFiles.length&&r.strict===true?`missing checksums: ${e.missingChecksumFiles.join(", ")}`:""].filter(Boolean).join("; ");throw new Error(`Workspace archive verification failed${o?` (${o})`:""}.`)}if(e.status==="warning"&&r.strict===true)throw new Error(`Workspace archive verification requires checksums for every file: ${e.missingChecksumFiles.join(", ")}`);let i=Be(t.entries),a=t.manifest,s=l.resolve(r.outputPath||te(a.workspaceName||"imported-workspace")),n=await He(s,r.force===true);if(!r.dryRun){let o=l.dirname(s),m=`${process.pid}-${z.randomUUID()}`,h=l.join(o,`.${l.basename(s)}.hydrate-${m}.tmp`),u=l.join(o,`.${l.basename(s)}.hydrate-${m}.backup`),y=false,c=false;await p.ensureDir(o);try{await p.ensureDir(h);for(let f of i){let w=l.resolve(h,f.targetName);if(!Se(w,h))throw new Error(`Archive entry escapes output directory: ${f.targetName}`);await p.ensureDir(l.dirname(w));let v=await $(t.zipFile,f.entry);await pipeline(v,createWriteStream(w,{flags:"wx"}));}n&&(await p.rename(s,u),y=true),await p.rename(h,s),c=true,y&&await p.remove(u).catch(()=>{});}catch(f){throw y&&!await p.pathExists(s)&&await p.rename(u,s).catch(()=>{}),f}finally{await p.remove(h).catch(()=>{}),c&&await p.remove(u).catch(()=>{});}}return C({schemaVersion:k,operation:"hydrate",status:"passed",archivePath:t.archivePath,outputPath:s,dryRun:r.dryRun===true,manifest:a,files:i.map(o=>({path:o.targetName,size:o.size}))})}finally{await L(t);}}
10
+ export{Ue as a,U as b,k as c,qe as d,A as e,ue as f,Ee as g,J as h,te as i,re as j,Re as k,pt as l,je as m,oe as n,lt as o,ht as p};
@@ -1,4 +1,4 @@
1
- import {a as a$1}from'./chunk-JEI6BTZI.js';import {a}from'./chunk-BHYTI3RH.js';import {c,e,d}from'./chunk-DQ3PI7EP.js';import {d as d$1,b}from'./chunk-VU2BKKMB.js';import {g}from'./chunk-GBAO4GSW.js';import {p as p$1,l}from'./chunk-BYTFXQ6G.js';import {p as p$2,d as d$2}from'./chunk-BBGNDMRU.js';import {e as e$1}from'./chunk-XBM2P45G.js';import {b as b$1}from'./chunk-RVQLMTTI.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import j from'path';import P from'fs-extra';function J(e$1){switch(e$1){case "why":return d;case "trace":return e;default:return c}}async function E(e,o,n){try{if(!await P.pathExists(e))return null;let r=await P.readJson(e);return o?b$1(o,r,e):n&&a$2(r,n,e),r}catch(r){if((o||n)&&await P.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,j.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=j.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 p$2({workspacePath:o})).contract;}catch{l$1=null;}let t=e.verify;t===void 0&&(t=await E(j.join(o,d$1),d$1));let d=e.impact;if(d===void 0&&(d=await E(j.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-6PBSAAS5.js';import {c,e,d}from'./chunk-3D3PFPP5.js';import {d as d$1,b}from'./chunk-XHRHNVCZ.js';import {g}from'./chunk-PTTZPDLX.js';import {p as p$1,l}from'./chunk-FUPHQOJB.js';import {p as p$2,d as d$2}from'./chunk-B4CPDK6J.js';import {e as e$1}from'./chunk-MBRU3VWJ.js';import {b as b$1}from'./chunk-ULR66OJR.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import j from'path';import P from'fs-extra';function J(e$1){switch(e$1){case "why":return d;case "trace":return e;default:return c}}async function E(e,o,n){try{if(!await P.pathExists(e))return null;let r=await P.readJson(e);return o?b$1(o,r,e):n&&a$2(r,n,e),r}catch(r){if((o||n)&&await P.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,j.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=j.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 p$2({workspacePath:o})).contract;}catch{l$1=null;}let t=e.verify;t===void 0&&(t=await E(j.join(o,d$1),d$1));let d=e.impact;if(d===void 0&&(d=await E(j.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":"Release posture"}: ${t.summary.verdict} with ${s.length} blocking reason(s).`:"Release posture unknown \u2014 verify report missing.",sections:g,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,2 +1,2 @@
1
- import {a as a$1}from'./chunk-AFIFZTOY.js';import {a,c,b,i}from'./chunk-AHLMIL2T.js';import j from'path';var m=Object.keys(a).flatMap(r=>{let o=r,a$1=b[o],t=c[o];return !a$1||!t?[]:[{artifactPath:a[o],schemaVersion:a$1,contractPath:t}]}),d=[{artifactPath:".workspai/workspace-link.local.json",schemaVersion:"project-workspace-link.v1",contractPath:"contracts/project-workspace-link.v1.json"},{artifactPath:".workspai/reports/project-context-agent.json",schemaVersion:"project-context-agent.v1",contractPath:"contracts/workspace-intelligence/project-context-agent.v1.json"},{artifactPath:".workspai/workspace.contract.json",schemaVersion:1,contractPath:"contracts/workspace-contract.v1.json"},{artifactPath:".workspai/cache/workspace-model.v1.json",schemaVersion:"workspace-model-cache.v1",contractPath:"contracts/workspace-model-cache.v1.json"},{artifactPath:".workspai/workspace-registry.v1.json",schemaVersion:"workspace-registry.v1",contractPath:"contracts/workspace-registry.v1.json"},{artifactPath:".workspai/compatibility-matrix.json",schemaVersion:"rapidkit.compatibility-matrix.v1",contractPath:"contracts/compatibility-matrix.v1.json"},{artifactPath:".workspai/reports/doctor-workspace-cache.json",schemaVersion:"doctor-workspace-cache-v2",contractPath:"contracts/doctor-workspace-cache.v2.json"},{artifactPath:".workspai/reports/bootstrap-compliance.latest.json",schemaVersion:"bootstrap-compliance.v1",contractPath:"contracts/bootstrap-compliance.v1.json"},{artifactPath:".workspai/reports/mirror-ops.latest.json",schemaVersion:"mirror-ops.v1",contractPath:"contracts/mirror-ops.v1.json"},{artifactPath:".workspai/reports/transparency-evidence.latest.json",schemaVersion:"transparency-evidence.v1",contractPath:"contracts/transparency-evidence.v1.json"},{artifactPath:".workspai/reports/share-bundle.json",schemaVersion:"1.1",schemaVersionField:"schema_version",contractPath:"contracts/workspace-share-bundle.v1.json"},{artifactPath:".workspai/reports/doctor-project-last-run.json",schemaVersion:"doctor-project-evidence-v1",contractPath:"contracts/doctor-project-evidence.v1.json"},{artifactPath:".workspai/reports/project-test-coverage-last-run.json",schemaVersion:"workspai.project-test-coverage.v1",contractPath:"contracts/project-test-coverage.v1.json"},{artifactPath:".workspai/reports/doctor-remediation-plan-last-run.json",schemaVersion:"doctor-remediation-plan-v2",contractPath:"contracts/doctor-remediation-plan.v2.json"},{artifactPath:".workspai/reports/artifact-remediation-plan-last-run.json",schemaVersion:"artifact-remediation-plan-v1",contractPath:"contracts/artifact-remediation-plan.v1.json"},{artifactPath:".workspai/reports/doctor-fix-result-last-run.json",schemaVersion:"rapidkit-doctor-fix-result-v1",contractPath:"contracts/workspace-intelligence/doctor-fix-result.v1.json"},{artifactPath:".workspai/reports/pipeline-last-run.json",schemaVersion:"rapidkit-pipeline-v1",contractPath:"contracts/pipeline-last-run.v1.json"},{artifactPath:".workspai/reports/autopilot-release-last-run.json",schemaVersion:"autopilot-release-v1",contractPath:"contracts/autopilot-release.v1.json"},{artifactPath:".workspai/reports/autopilot-release.json",schemaVersion:"autopilot-release-v1",contractPath:"contracts/autopilot-release.v1.json"},{artifactPath:".workspai/reports/workspace-run-last.json",schemaVersion:"workspace-run-v1",contractPath:"contracts/workspace-run-last.v1.json"},{artifactPath:".workspai/reports/workspai-mcp-design.json",schemaVersion:"workspai-mcp-design.v1",contractPath:"contracts/workspace-intelligence/mcp-design.v1.json"},{artifactPath:".workspai/reports/rapidkit-mcp-design.json",schemaVersion:"workspai-mcp-design.v1",contractPath:"contracts/workspace-intelligence/mcp-design.v1.json"},{artifactPath:".workspai/reports/workspace-why-last-run.json",schemaVersion:b.explain,contractPath:c.explain},{artifactPath:".workspai/reports/workspace-trace-last-run.json",schemaVersion:b.explain,contractPath:c.explain},{artifactPath:".vscode/workspai-agent-hooks.json",schemaVersion:"workspai-agent-hooks.v1",contractPath:"contracts/workspace-intelligence/agent-hooks.v1.json"},{artifactPath:".workspai/reports/infra-plan.json",schemaVersion:"rapidkit.infra-plan.v1",contractPath:"contracts/infra-plan.v1.json"}],u={".workspai/workspace-link.local.json":[["adopt"],["import"],["project","workspace","relink"],["workspace","sync"]],".workspai/reports/project-context-agent.json":[["adopt"],["import"],["workspace","sync"],["workspace","agent-sync","--write"]],".workspai/workspace.contract.json":[["workspace","sync"],["workspace","contract","sync"]],[a.intelligenceRun]:[["workspace","intelligence","run"]],[a.snapshot]:[["workspace","snapshot"]],[a.history]:[["workspace","feedback","record","--json"]],[a.evaluationLive]:[["workspace","eval","init"],["workspace","eval","record","--json"]],[a.evaluationLastRun]:[["workspace","eval","report","--json"]],".workspai/cache/workspace-model.v1.json":[["workspace","model"]],".workspai/workspace-registry.v1.json":[["workspace","sync"]],".workspai/compatibility-matrix.json":[["bootstrap"]],".workspai/reports/doctor-workspace-cache.json":[["doctor","workspace"]],".workspai/reports/bootstrap-compliance.latest.json":[["bootstrap"]],".workspai/reports/mirror-ops.latest.json":[["mirror","status"]],".workspai/reports/transparency-evidence.latest.json":[["mirror","sync"]],".workspai/reports/share-bundle.json":[["workspace","share"]],".workspai/reports/doctor-project-last-run.json":[["doctor","project"]],".workspai/reports/project-test-coverage-last-run.json":[["project","coverage"]],".workspai/reports/doctor-remediation-plan-last-run.json":[["workspace","remediation-plan"]],".workspai/reports/artifact-remediation-plan-last-run.json":[["workspace","remediation-plan"]],".workspai/reports/doctor-fix-result-last-run.json":[["doctor","workspace"]],".workspai/reports/pipeline-last-run.json":[["pipeline"]],".workspai/reports/autopilot-release-last-run.json":[["autopilot","release"]],".workspai/reports/autopilot-release.json":[["autopilot","release"]],".workspai/reports/workspace-run-last.json":[["workspace","run"]],".workspai/reports/workspai-mcp-design.json":[["workspace","agent-sync","--write"]],".workspai/reports/rapidkit-mcp-design.json":[["workspace","agent-sync","--write"]],".workspai/reports/workspace-why-last-run.json":[["workspace","why"]],".workspai/reports/workspace-trace-last-run.json":[["workspace","trace"]],".vscode/workspai-agent-hooks.json":[["workspace","agent-sync"]],".workspai/reports/infra-plan.json":[["infra","plan"]]};function v(r){let o=Object.values(i).filter(t=>t.produces.includes(r)).map(t=>[...t.command]),a=u[r]??[];return [...o,...a.map(t=>[...t])]}var k=Object.freeze(Object.fromEntries([...m,...d].map(r=>[r.artifactPath,{...r,producerCommands:v(r.artifactPath)}])));function w(r){return r.split(j.sep).join("/").replace(/^\.\//,"")}var P=[{pattern:/^\.workspai\/reports\/bootstrap-compliance-[^/]+\.json$/,canonicalPath:".workspai/reports/bootstrap-compliance.latest.json"},{pattern:/^\.workspai\/reports\/mirror-ops-[^/]+\.json$/,canonicalPath:".workspai/reports/mirror-ops.latest.json"},{pattern:/^\.workspai\/reports\/transparency-evidence-[^/]+\.json$/,canonicalPath:".workspai/reports/transparency-evidence.latest.json"},{pattern:/^\.workspai\/reports\/projects\/[^/]+\/doctor-project-last-run\.json$/,canonicalPath:".workspai/reports/doctor-project-last-run.json"},{pattern:/^\.workspai\/reports\/projects\/[^/]+\/project-test-coverage-last-run\.json$/,canonicalPath:".workspai/reports/project-test-coverage-last-run.json"}];function f(r){let o=w(r),a=k[o];if(a)return a;let t=P.find(e=>e.pattern.test(o));return t?k[t.canonicalPath]??null:null}function E(r,o,a=r){let t=w(r),e=f(r);if(!e){if(t.startsWith(".workspai/reports/")&&t.endsWith(".json"))throw new Error(`${a} is a public workspace report without a registered artifact contract`);return}let h=e.schemaVersionField??"schemaVersion",i=o&&typeof o=="object"?o[h]:void 0;if(i!==e.schemaVersion)throw new Error(`${a} schemaVersion is ${String(i)}, expected ${e.schemaVersion}`);a$1(o,e.contractPath,a);}
1
+ import {a as a$1}from'./chunk-AFIFZTOY.js';import {a,c,b,i}from'./chunk-62K2H72S.js';import j from'path';var m=Object.keys(a).flatMap(r=>{let o=r,a$1=b[o],t=c[o];return !a$1||!t?[]:[{artifactPath:a[o],schemaVersion:a$1,contractPath:t}]}),d=[{artifactPath:".workspai/workspace-link.local.json",schemaVersion:"project-workspace-link.v1",contractPath:"contracts/project-workspace-link.v1.json"},{artifactPath:".workspai/reports/project-context-agent.json",schemaVersion:"project-context-agent.v1",contractPath:"contracts/workspace-intelligence/project-context-agent.v1.json"},{artifactPath:".workspai/workspace.contract.json",schemaVersion:1,contractPath:"contracts/workspace-contract.v1.json"},{artifactPath:".workspai/cache/workspace-model.v1.json",schemaVersion:"workspace-model-cache.v1",contractPath:"contracts/workspace-model-cache.v1.json"},{artifactPath:".workspai/workspace-registry.v1.json",schemaVersion:"workspace-registry.v1",contractPath:"contracts/workspace-registry.v1.json"},{artifactPath:".workspai/compatibility-matrix.json",schemaVersion:"rapidkit.compatibility-matrix.v1",contractPath:"contracts/compatibility-matrix.v1.json"},{artifactPath:".workspai/reports/doctor-workspace-cache.json",schemaVersion:"doctor-workspace-cache-v2",contractPath:"contracts/doctor-workspace-cache.v2.json"},{artifactPath:".workspai/reports/bootstrap-compliance.latest.json",schemaVersion:"bootstrap-compliance.v1",contractPath:"contracts/bootstrap-compliance.v1.json"},{artifactPath:".workspai/reports/mirror-ops.latest.json",schemaVersion:"mirror-ops.v1",contractPath:"contracts/mirror-ops.v1.json"},{artifactPath:".workspai/reports/transparency-evidence.latest.json",schemaVersion:"transparency-evidence.v1",contractPath:"contracts/transparency-evidence.v1.json"},{artifactPath:".workspai/reports/share-bundle.json",schemaVersion:"1.1",schemaVersionField:"schema_version",contractPath:"contracts/workspace-share-bundle.v1.json"},{artifactPath:".workspai/reports/doctor-project-last-run.json",schemaVersion:"doctor-project-evidence-v1",contractPath:"contracts/doctor-project-evidence.v1.json"},{artifactPath:".workspai/reports/project-test-coverage-last-run.json",schemaVersion:"workspai.project-test-coverage.v1",contractPath:"contracts/project-test-coverage.v1.json"},{artifactPath:".workspai/reports/doctor-remediation-plan-last-run.json",schemaVersion:"doctor-remediation-plan-v2",contractPath:"contracts/doctor-remediation-plan.v2.json"},{artifactPath:".workspai/reports/artifact-remediation-plan-last-run.json",schemaVersion:"artifact-remediation-plan-v1",contractPath:"contracts/artifact-remediation-plan.v1.json"},{artifactPath:".workspai/reports/doctor-fix-result-last-run.json",schemaVersion:"rapidkit-doctor-fix-result-v1",contractPath:"contracts/workspace-intelligence/doctor-fix-result.v1.json"},{artifactPath:".workspai/reports/pipeline-last-run.json",schemaVersion:"rapidkit-pipeline-v1",contractPath:"contracts/pipeline-last-run.v1.json"},{artifactPath:".workspai/reports/autopilot-release-last-run.json",schemaVersion:"autopilot-release-v1",contractPath:"contracts/autopilot-release.v1.json"},{artifactPath:".workspai/reports/autopilot-release.json",schemaVersion:"autopilot-release-v1",contractPath:"contracts/autopilot-release.v1.json"},{artifactPath:".workspai/reports/workspace-run-last.json",schemaVersion:"workspace-run-v1",contractPath:"contracts/workspace-run-last.v1.json"},{artifactPath:".workspai/reports/workspai-mcp-design.json",schemaVersion:"workspai-mcp-design.v1",contractPath:"contracts/workspace-intelligence/mcp-design.v1.json"},{artifactPath:".workspai/reports/rapidkit-mcp-design.json",schemaVersion:"workspai-mcp-design.v1",contractPath:"contracts/workspace-intelligence/mcp-design.v1.json"},{artifactPath:".workspai/reports/workspace-why-last-run.json",schemaVersion:b.explain,contractPath:c.explain},{artifactPath:".workspai/reports/workspace-trace-last-run.json",schemaVersion:b.explain,contractPath:c.explain},{artifactPath:".vscode/workspai-agent-hooks.json",schemaVersion:"workspai-agent-hooks.v1",contractPath:"contracts/workspace-intelligence/agent-hooks.v1.json"},{artifactPath:".workspai/reports/infra-plan.json",schemaVersion:"rapidkit.infra-plan.v1",contractPath:"contracts/infra-plan.v1.json"}],u={".workspai/workspace-link.local.json":[["adopt"],["import"],["project","workspace","relink"],["workspace","sync"]],".workspai/reports/project-context-agent.json":[["adopt"],["import"],["workspace","sync"],["workspace","agent-sync","--write"]],".workspai/workspace.contract.json":[["workspace","sync"],["workspace","contract","sync"]],[a.intelligenceRun]:[["workspace","intelligence","run"]],[a.snapshot]:[["workspace","snapshot"]],[a.history]:[["workspace","feedback","record","--json"]],[a.evaluationLive]:[["workspace","eval","init"],["workspace","eval","record","--json"]],[a.evaluationLastRun]:[["workspace","eval","report","--json"]],[a.verifiedGoalStatus]:[["workspace","goal","plan"],["workspace","goal","verify"]],".workspai/cache/workspace-model.v1.json":[["workspace","model"]],".workspai/workspace-registry.v1.json":[["workspace","sync"]],".workspai/compatibility-matrix.json":[["bootstrap"]],".workspai/reports/doctor-workspace-cache.json":[["doctor","workspace"]],".workspai/reports/bootstrap-compliance.latest.json":[["bootstrap"]],".workspai/reports/mirror-ops.latest.json":[["mirror","status"]],".workspai/reports/transparency-evidence.latest.json":[["mirror","sync"]],".workspai/reports/share-bundle.json":[["workspace","share"]],".workspai/reports/doctor-project-last-run.json":[["doctor","project"]],".workspai/reports/project-test-coverage-last-run.json":[["project","coverage"]],".workspai/reports/doctor-remediation-plan-last-run.json":[["workspace","remediation-plan"]],".workspai/reports/artifact-remediation-plan-last-run.json":[["workspace","remediation-plan"]],".workspai/reports/doctor-fix-result-last-run.json":[["doctor","workspace"]],".workspai/reports/pipeline-last-run.json":[["pipeline"]],".workspai/reports/autopilot-release-last-run.json":[["autopilot","release"]],".workspai/reports/autopilot-release.json":[["autopilot","release"]],".workspai/reports/workspace-run-last.json":[["workspace","run"]],".workspai/reports/workspai-mcp-design.json":[["workspace","agent-sync","--write"]],".workspai/reports/rapidkit-mcp-design.json":[["workspace","agent-sync","--write"]],".workspai/reports/workspace-why-last-run.json":[["workspace","why"]],".workspai/reports/workspace-trace-last-run.json":[["workspace","trace"]],".vscode/workspai-agent-hooks.json":[["workspace","agent-sync"]],".workspai/reports/infra-plan.json":[["infra","plan"]]};function v(r){let o=Object.values(i).filter(t=>t.produces.includes(r)).map(t=>[...t.command]),a=u[r]??[];return [...o,...a.map(t=>[...t])]}var k=Object.freeze(Object.fromEntries([...m,...d].map(r=>[r.artifactPath,{...r,producerCommands:v(r.artifactPath)}])));function w(r){return r.split(j.sep).join("/").replace(/^\.\//,"")}var P=[{pattern:/^\.workspai\/reports\/bootstrap-compliance-[^/]+\.json$/,canonicalPath:".workspai/reports/bootstrap-compliance.latest.json"},{pattern:/^\.workspai\/reports\/mirror-ops-[^/]+\.json$/,canonicalPath:".workspai/reports/mirror-ops.latest.json"},{pattern:/^\.workspai\/reports\/transparency-evidence-[^/]+\.json$/,canonicalPath:".workspai/reports/transparency-evidence.latest.json"},{pattern:/^\.workspai\/reports\/projects\/[^/]+\/doctor-project-last-run\.json$/,canonicalPath:".workspai/reports/doctor-project-last-run.json"},{pattern:/^\.workspai\/reports\/projects\/[^/]+\/project-test-coverage-last-run\.json$/,canonicalPath:".workspai/reports/project-test-coverage-last-run.json"}];function f(r){let o=w(r),a=k[o];if(a)return a;let t=P.find(e=>e.pattern.test(o));return t?k[t.canonicalPath]??null:null}function E(r,o,a=r){let t=w(r),e=f(r);if(!e){if(t.startsWith(".workspai/reports/")&&t.endsWith(".json"))throw new Error(`${a} is a public workspace report without a registered artifact contract`);return}let h=e.schemaVersionField??"schemaVersion",i=o&&typeof o=="object"?o[h]:void 0;if(i!==e.schemaVersion)throw new Error(`${a} schemaVersion is ${String(i)}, expected ${e.schemaVersion}`);a$1(o,e.contractPath,a);}
2
2
  export{f as a,E as b};
@@ -1,2 +1,2 @@
1
- import {b as b$1}from'./chunk-EPVFKJF4.js';import {c}from'./chunk-3D2PAIRH.js';import {p,h,i as i$1}from'./chunk-BYTFXQ6G.js';import {d}from'./chunk-BBGNDMRU.js';import {e,d as d$1}from'./chunk-XBM2P45G.js';import {b,a}from'./chunk-AHLMIL2T.js';import I from'path';import R from'fs-extra';var G=b.agentContext,V=a.agentContext;function q(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="orca"?t:"generic"}function M(e){return `npx --yes --package workspai workspai ${e}`.trim()}function l(e){return `npx workspai ${e}`.trim()}function i(e){return {id:e.id,scope:e.scope,display:l(e.args),execute:M(e.args),description:e.description,...e.project?{project:e.project}:{},freshness:h({id:`command.${e.id}`,label:`${e.id} command`,scope:"command",value:{display:l(e.args),execute:M(e.args)},...e.project?{project:e.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e.generatedAt,now:e.now,sourceArtifact:a.model,sourcePath:`safeCommands.${e.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function F(e,t){return `workspace run ${t} --scope project:${e.name}`}function L(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function D(e){return [e.name,e.path,I.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function K(e,t,n){let r={generatedAt:e.generatedAt,now:n},c=[i({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...r}),i({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...r}),i({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...r}),i({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...r}),i({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...r}),i({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...r}),i({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...r}),i({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...r})],a=t?[t]:e.projects;for(let s of a)s.commands.fleetStages.includes("test")&&c.push(i({id:`project.${s.name}.test`,scope:"project",project:s.name,args:F(s,"test"),description:`Run tests for ${s.name} through workspace orchestration.`,...r})),s.commands.fleetStages.includes("build")&&c.push(i({id:`project.${s.name}.build`,scope:"project",project:s.name,args:F(s,"build"),description:`Build ${s.name} through workspace orchestration.`,...r}));return c}function H(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function z(e,t){if(!t?.startsWith("project:"))return;let n=L(t);if(n)return e.projects.find(r=>D(r).includes(n))}function B(e,t,n){let r=[...e.validation?.issues??[]];t?.startsWith("project:")&&!n&&r.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let c=r.filter(s=>s.severity==="error").length,a=r.filter(s=>s.severity==="warning").length;return {status:c>0?"failed":a>0?"warning":"passed",errors:c,warnings:a,issues:r}}async function U(e,t){let n=[],r=[];for(let[c,a]of Object.entries(e.evidence))a&&await d$1(t,a.path)!==null?n.push(`${c}: ${a.path}`):r.push(c);return {available:n.sort(),missing:r.sort()}}function X(e){let t=e.summary.projectCount,n=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",r=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${n}, and ${r}.`}function J(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),e.summary.observedProjects>0&&t.push("Some projects are observed rather than first-class; command support may be partial."),t}async function pe(e){let t=e.model??await p({workspacePath:e.workspacePath,includeEvidence:e.includeEvidence===true,observableScanDepth:e.observableScanDepth,now:e.now}),n=q(e.agent),r=z(t,e.scope),c$1=B(t,e.scope,r);if(e.strict===true&&c$1.status!=="passed"){let o=c$1.issues.map(m=>`${m.severity}:${m.code}:${m.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${o}`)}let a$1=e.now??new Date,s=t.facts??[],T=new Set((r?[r]:t.projects).map(o=>o.name)),w=s.filter(o=>o.project?T.has(o.project):true),_=(r?[r]:t.projects).map(o=>{let m=w.filter(N=>N.project===o.name);return {name:o.name,path:o.path,kind:o.kind,category:o.category,runtime:o.runtime,framework:o.frameworkDisplayName,...o.generator?{generator:o.generator}:{},createCapability:o.createCapability,supportTier:o.supportTier,safeCommands:H(o),importantFiles:o.importantFiles,facts:m}}),u=await U(t,e.workspacePath),y=I.join(e.workspacePath,a.knowledgeGraph),d=await R.pathExists(y)?await R.readJson(y).catch(()=>null):null,C=false;if(d?.schemaVersion===b.knowledgeGraph)try{c(d,t),C=true;}catch{}let v=X(t),j=K(t,r,a$1),O=j.map(o=>h({id:`context.command.${o.id}`,label:`${o.id} safe command`,scope:"command",value:{display:o.display,execute:o.execute,scope:o.scope},...o.project?{project:o.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:a$1,sourceArtifact:a.agentContext,sourcePath:`safeCommands.${o.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),b$2=[...w,...O],f=i$1({facts:b$2,generatedAt:a$1.toISOString(),now:a$1}),h$1=b$1();return {schemaVersion:G,generatedAt:a$1.toISOString(),agent:n,workspaceSummary:v,modelRef:a.model,knowledgeGraph:{artifact:a.knowledgeGraph,schemaVersion:b.knowledgeGraph,available:C,...typeof d?.quality?.entityCount=="number"?{entityCount:d.quality.entityCount}:{},...typeof d?.quality?.relationCount=="number"?{relationCount:d.quality.relationCount}:{},...typeof d?.quality?.proofCount=="number"?{proofCount:d.quality.proofCount}:{},queryCommands:[l("workspace graph search <query> --limit 12 --json"),l("workspace graph entities [kind] --json"),l("workspace graph evidence <entity-or-relation> --json"),l("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:h$1.schemaVersion,contractPath:h$1.contractPath,currentStep:"context",canonicalReadOrder:[...h$1.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:t.workspace.root,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e.scope??"workspace",...r?{activeProject:r.name}:{}},projects:_,safeCommands:j,facts:b$2,factFreshness:f,evidence:u,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:c$1,agentInstructions:[`Read \`${a.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 \`${a.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:[...J(t),...f.verifyBeforeUseFacts>0?[`${f.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[v,`Evidence available: ${u.available.length}. Missing evidence groups: ${u.missing.join(", ")||"none"}.`,r?`Active project scope: ${r.name} (${r.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
1
+ import {b as b$1}from'./chunk-LPCL4U4L.js';import {c}from'./chunk-P4OSLAVD.js';import {p,h,i as i$1}from'./chunk-FUPHQOJB.js';import {d}from'./chunk-B4CPDK6J.js';import {e,d as d$1}from'./chunk-MBRU3VWJ.js';import {b,a}from'./chunk-62K2H72S.js';import I from'path';import R from'fs-extra';var G=b.agentContext,V=a.agentContext;function q(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="orca"?t:"generic"}function M(e){return `npx --yes --package workspai workspai ${e}`.trim()}function l(e){return `npx workspai ${e}`.trim()}function i(e){return {id:e.id,scope:e.scope,display:l(e.args),execute:M(e.args),description:e.description,...e.project?{project:e.project}:{},freshness:h({id:`command.${e.id}`,label:`${e.id} command`,scope:"command",value:{display:l(e.args),execute:M(e.args)},...e.project?{project:e.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e.generatedAt,now:e.now,sourceArtifact:a.model,sourcePath:`safeCommands.${e.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function F(e,t){return `workspace run ${t} --scope project:${e.name}`}function L(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function D(e){return [e.name,e.path,I.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function K(e,t,n){let r={generatedAt:e.generatedAt,now:n},c=[i({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...r}),i({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...r}),i({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...r}),i({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...r}),i({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...r}),i({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...r}),i({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...r}),i({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...r})],a=t?[t]:e.projects;for(let s of a)s.commands.fleetStages.includes("test")&&c.push(i({id:`project.${s.name}.test`,scope:"project",project:s.name,args:F(s,"test"),description:`Run tests for ${s.name} through workspace orchestration.`,...r})),s.commands.fleetStages.includes("build")&&c.push(i({id:`project.${s.name}.build`,scope:"project",project:s.name,args:F(s,"build"),description:`Build ${s.name} through workspace orchestration.`,...r}));return c}function H(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function z(e,t){if(!t?.startsWith("project:"))return;let n=L(t);if(n)return e.projects.find(r=>D(r).includes(n))}function B(e,t,n){let r=[...e.validation?.issues??[]];t?.startsWith("project:")&&!n&&r.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let c=r.filter(s=>s.severity==="error").length,a=r.filter(s=>s.severity==="warning").length;return {status:c>0?"failed":a>0?"warning":"passed",errors:c,warnings:a,issues:r}}async function U(e,t){let n=[],r=[];for(let[c,a]of Object.entries(e.evidence))a&&await d$1(t,a.path)!==null?n.push(`${c}: ${a.path}`):r.push(c);return {available:n.sort(),missing:r.sort()}}function X(e){let t=e.summary.projectCount,n=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",r=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${n}, and ${r}.`}function J(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),e.summary.observedProjects>0&&t.push("Some projects are observed rather than first-class; command support may be partial."),t}async function pe(e){let t=e.model??await p({workspacePath:e.workspacePath,includeEvidence:e.includeEvidence===true,observableScanDepth:e.observableScanDepth,now:e.now}),n=q(e.agent),r=z(t,e.scope),c$1=B(t,e.scope,r);if(e.strict===true&&c$1.status!=="passed"){let o=c$1.issues.map(m=>`${m.severity}:${m.code}:${m.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${o}`)}let a$1=e.now??new Date,s=t.facts??[],T=new Set((r?[r]:t.projects).map(o=>o.name)),w=s.filter(o=>o.project?T.has(o.project):true),_=(r?[r]:t.projects).map(o=>{let m=w.filter(N=>N.project===o.name);return {name:o.name,path:o.path,kind:o.kind,category:o.category,runtime:o.runtime,framework:o.frameworkDisplayName,...o.generator?{generator:o.generator}:{},createCapability:o.createCapability,supportTier:o.supportTier,safeCommands:H(o),importantFiles:o.importantFiles,facts:m}}),u=await U(t,e.workspacePath),y=I.join(e.workspacePath,a.knowledgeGraph),d=await R.pathExists(y)?await R.readJson(y).catch(()=>null):null,C=false;if(d?.schemaVersion===b.knowledgeGraph)try{c(d,t),C=true;}catch{}let v=X(t),j=K(t,r,a$1),O=j.map(o=>h({id:`context.command.${o.id}`,label:`${o.id} safe command`,scope:"command",value:{display:o.display,execute:o.execute,scope:o.scope},...o.project?{project:o.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:a$1,sourceArtifact:a.agentContext,sourcePath:`safeCommands.${o.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),b$2=[...w,...O],f=i$1({facts:b$2,generatedAt:a$1.toISOString(),now:a$1}),h$1=b$1();return {schemaVersion:G,generatedAt:a$1.toISOString(),agent:n,workspaceSummary:v,modelRef:a.model,knowledgeGraph:{artifact:a.knowledgeGraph,schemaVersion:b.knowledgeGraph,available:C,...typeof d?.quality?.entityCount=="number"?{entityCount:d.quality.entityCount}:{},...typeof d?.quality?.relationCount=="number"?{relationCount:d.quality.relationCount}:{},...typeof d?.quality?.proofCount=="number"?{proofCount:d.quality.proofCount}:{},queryCommands:[l("workspace graph search <query> --limit 12 --json"),l("workspace graph entities [kind] --json"),l("workspace graph evidence <entity-or-relation> --json"),l("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:h$1.schemaVersion,contractPath:h$1.contractPath,currentStep:"context",canonicalReadOrder:[...h$1.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:t.workspace.root,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e.scope??"workspace",...r?{activeProject:r.name}:{}},projects:_,safeCommands:j,facts:b$2,factFreshness:f,evidence:u,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:c$1,agentInstructions:[`Read \`${a.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 \`${a.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:[...J(t),...f.verifyBeforeUseFacts>0?[`${f.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[v,`Evidence available: ${u.available.length}. Missing evidence groups: ${u.missing.join(", ")||"none"}.`,r?`Active project scope: ${r.name} (${r.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
2
2
  `)}}async function de(e$1,t){return e(t,V,d(e$1))}export{G as a,V as b,pe as c,de as d};
@@ -1 +1 @@
1
- import {b as b$2,c,d as d$1}from'./chunk-HMGPELXS.js';import {c as c$1}from'./chunk-BG4FWJJ3.js';import {a as a$2,b as b$3}from'./chunk-PYCJWW4B.js';import {p as p$1,a as a$1,o,g,d as d$4,f}from'./chunk-GBAO4GSW.js';import {p,l,f as f$1}from'./chunk-BYTFXQ6G.js';import {d}from'./chunk-EWZZUQBR.js';import {d as d$3}from'./chunk-BBGNDMRU.js';import {d as d$2,e}from'./chunk-XBM2P45G.js';import {a as a$3}from'./chunk-AFIFZTOY.js';import {b as b$1,a,c as c$2}from'./chunk-AHLMIL2T.js';import m from'path';import v from'fs-extra';var ae="rapidkit-blocker-resolution-v1";function ce(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return f$1({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function ke(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function ye(e){let t=ke(e.reason),r=ce({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",studioActionId:"run-analyze"}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:ae,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function de(e){return Array.from(new Set(e.blockingReasons.map(r=>r.trim()).filter(Boolean))).slice(0,12).map((r,s)=>ye({reason:r,blockerId:`blocker-${s+1}`,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}))}function he(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function ve(e){return e.length===0||e.every(t=>he(t))}function le(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&ve(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function Ye(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var fe=b$1.verify,J=a.verify;function be(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ue(e){let t=await v.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$3(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$3(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let o=s.transitiveImpact.reduce((u,d)=>Math.max(u,d.distance??0),0);s.summary.blastRadius.maxDistance!==o&&i.push("blastRadius.maxDistance does not match transitive impact distances");let k=l(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==k&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function we(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Re(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function Ce(e,t){if(e.id==="workspace.doctor")return m.join(t,a.doctor);if(e.id==="workspace.contract.verify")return m.join(t,a.contractVerify);if(e.id==="workspace.readiness")return m.join(t,a.readiness);if(e.id==="workspace.analyze")return m.join(t,".workspai","reports","analyze-last-run.json");if(e.id==="workspace.pipeline")return m.join(t,".workspai","reports","pipeline-last-run.json");if(e.id==="workspace.doctor-fix")return m.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e.id.startsWith("project.")&&e.id.includes("."))return m.join(t,".workspai","reports","workspace-run-last.json")}function b(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function Ae(e){let t=b(e.healthScore),r=b(e.summary),s=typeof t?.errors=="number"?t.errors:0,i=typeof t?.percent=="number"?t.percent:void 0;return s>0||r?.hasSystemErrors===true?{status:"fail",message:`Doctor evidence reports ${s} error(s).`}:typeof i=="number"&&i<70?{status:"warn",message:`Doctor health score is ${i}%.`}:{status:"pass",message:"Doctor evidence is present and healthy."}}function je(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function Ee(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Se(e){let t=b(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function We(e){let t=e.schemaVersion==="rapidkit-doctor-fix-result-v1"?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s.length>0)return {status:"fail",message:`Doctor fix result reports ${s.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function xe(e,t){let r=await d$2(e,".workspai/reports/doctor-remediation-plan-last-run.json");if(!r)return false;try{let s=b(await v.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let o=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!o||!t)return true;let k=Date.parse(o),u=Date.parse(t);return !Number.isFinite(k)||!Number.isFinite(u)?true:k>=u}catch{return false}}function Pe(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Ie(e){let t=b(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function Ve(e,t,r){let s=Pe(t),i=c$1(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let o=i.stage;if(s&&o!==s)return {status:"missing",message:`Workspace run evidence is for stage "${o}", expected "${s}".`};let k=Array.isArray(i.projects)?i.projects:[],u=t.project?.toLowerCase();if(!u)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=k.find(g=>{let c=b(g);if(!c)return false;let n=typeof c.projectName=="string"?c.projectName.toLowerCase():"",a=["projectPath","relativePath","path"].map(f=>c[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return n===u||a.some(f=>f.endsWith(`/${u}`)||f===u)});if(d){let g=C(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(g)return {status:"fail",message:g};let c=b(d),n=typeof c?.status=="string"?c.status:"unknown";return n==="failed"?{status:"fail",message:`Workspace run evidence failed for ${t.project}.`}:n==="passed"?{status:"pass",message:`Workspace run evidence passed for ${t.project}.`}:n==="skipped"?{status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}:{status:"warn",message:`Workspace run evidence status is ${n} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function C(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function $e(e){if(e.id==="workspace.doctor")return c$2.doctor;if(e.id==="workspace.readiness")return c$2.readiness;if(e.id==="workspace.contract.verify")return c$2.contractVerify;if(e.id==="workspace.analyze")return c$2.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function Fe(e,t,r,s){let i=Ce(e,t),o=i?m.relative(t,i).split(m.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let k=i?await d$2(t,o??""):null;if(!i||!k)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:o,message:o?`Missing evidence report: ${o}`:"No evidence mapping exists for this command."};let u;try{u=await v.readJson(k);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=b(u);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:"Evidence report is not a JSON object."};let g=$e(e);if(g)try{a$3(d,g,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=C(d.generatedAt,s,"Doctor evidence");n?c={status:"fail",message:n}:c=Ae(d);}else if(e.id==="workspace.readiness"){let n=C(d.generatedAt,s,"Release readiness evidence");n?c={status:"fail",message:n}:c=je(d);}else if(e.id==="workspace.contract.verify"){let n=C(d.generatedAt,s,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=Ee(d);}else if(e.id==="workspace.analyze"){let n=C(d.generatedAt,s,"Analyze evidence");n?c={status:"fail",message:n}:c=Se(d);}else if(e.id==="workspace.pipeline"){let n=C(d.generatedAt,s,"Pipeline evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion==="rapidkit-doctor-fix-result-v1"?d:d.fixResult,a=b(n),f=typeof a?.generatedAt=="string"?a.generatedAt:void 0,y=C(f,s,"Doctor fix result");y?c={status:"fail",message:y}:await xe(t,f)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=We(d);}else if(e.id.startsWith("project."))c=Ve(d,e,s);else {let n=C(d.generatedAt,s,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:o,message:c.message}}function Oe(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,o=e.filter(n=>n.status==="missing").length,k=e.filter(n=>n.status==="skipped").length,u=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,g="ready",c=0;return u.length>0||t.blockingReasons.length>0?(g="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(g="needs-attention",c=1),{verdict:g,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:o,stepsSkipped:k}}function Be(e,t){let r=S(e.affectedProjects.map(a=>a.project?.name).filter(a=>typeof a=="string")),s=new Set(r.map(a=>a.toLowerCase())),i=S(e.transitiveImpact.map(a=>a.project?.name).filter(a=>typeof a=="string").filter(a=>!s.has(a.toLowerCase()))),o=new Map;for(let a of t){if(a.scope!=="project"||!a.project)continue;let f=a.project.toLowerCase(),y=o.get(f)??[];y.push(a),o.set(f,y);}let k=[],u=[],d=[],g=[],c=false,n=(a,f)=>{let y=o.get(a.toLowerCase())??[];if(y.length===0){d.push(a);return}let W=y.filter(p=>p.status==="fail"),w=W.filter(p=>p.required),x=y.filter(p=>p.status==="missing"),A=x.filter(p=>p.required),P=y.some(p=>p.status==="pass"||p.status==="warn");if(w.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has failed verification evidence (${w.map(p=>p.id).join(", ")}).`);return}if(W.length>0){u.push(a),c=true;return}if(A.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has missing required verification evidence (${A.map(p=>p.id).join(", ")}).`);return}if(x.length>0){u.push(a),c=true;return}if(P){k.push(a);return}d.push(a);};for(let a of r)n(a,"directly-changed");for(let a of i)n(a,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:S(k),uncovered:S(u),unverifiable:S(d)},blockingReasons:g,needsAttention:c}}function S(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function _e(e){let t=m.resolve(e.workspacePath);if(e.fromImpactPath){let o=be(t,e.fromImpactPath);return {impact:await ue(o),fromImpactRef:m.relative(t,o).split(m.sep).join("/"),impactFromDisk:true}}let r=m.join(t,g);if(await v.pathExists(r))return {impact:await ue(r),fromImpactRef:g,impactFromDisk:true};let s=m.join(t,d$4);if(await v.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$4,scope:e.scope,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),fromImpactRef:d$4,impactFromDisk:false};let i=await p({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {impact:{schemaVersion:f,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",diffRef:a.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:l(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:b$1.diff,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",toRef:a.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function De(e,t){if(t)return e.generatedAt}async function pt(e){let t=m.resolve(e.workspacePath),{impact:r,fromImpactRef:s,impactFromDisk:i}=await _e(e),o$1=r.diff.currentModel,k=i?await p({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):o$1,u=[];if(i){let l=await p$1({workspacePath:t,fromPath:r.diff.fromRef,diff:r.diff,scope:e.scope,now:e.now}),_=[r.affectedProjects,r.transitiveImpact,r.verificationPlan],D=[l.affectedProjects,l.transitiveImpact,l.verificationPlan];JSON.stringify(_)!==JSON.stringify(D)&&u.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(k)!==r.diff.toHash&&u.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r.diff.git;if(i&&d$2?.available){let l=a$1(t,{ref:d$2.ref}),_=r.diff.changes.filter(h=>h.type.startsWith("git.")).map(h=>`${h.type}:${h.target.replace(/^git:/,"")}`).sort(),D=[...l.changedFiles.map(h=>`git.file.changed:${h}`),...l.untrackedFiles.map(h=>`git.untracked:${h}`),...l.deletedFiles.map(h=>`git.deleted:${h}`)].sort();(!l.available||l.commit!==d$2.commit||JSON.stringify(D)!==JSON.stringify(_))&&u.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let g=De(r,i),c$1=we([...o(),...r.verificationPlan]).filter(l=>Re(e.scope,l)),n=[];for(let l of c$1)n.push(await Fe(l,t,o$1.contracts.exists===true,g));let a=Be(r,n),f=a$2(l(o$1)??{nodes:[],edges:[]}),y=b$2(o$1),W=await Ne(t),w=c(y,W?.freshness?.projectHashes),x={verdict:w.verdict,baseline:w.baseline,changed:w.changed,added:w.added,removed:w.removed,projectHashes:d$1(y)},A=b$3(f),P=o$1.policies?.mode??"warn",p$2=await He(o$1,t),B=Me(P,p$2),j=Oe(n,{blockingReasons:[...a.blockingReasons,...A,...B.blockingReasons,...u],needsAttention:a.needsAttention||B.needsAttention}),pe=n.filter(l=>l.status==="missing"&&l.evidencePath).map(l=>l.evidencePath),I=[...n.filter(l=>l.required&&(l.status==="fail"||l.status==="missing")).map(l=>`${l.id}: ${l.message}`),...a.blockingReasons,...A,...B.blockingReasons,...u],me=p$2.filter(l=>l.severity==="error").length,ge=o$1.summary?.projectCount??o$1.projects.length,G=le({projectCount:ge,verdict:j.verdict,exitCode:j.exitCode,blockingReasons:I,policyErrorCount:me});j.verdict=G.verdict,j.exitCode=G.exitCode;let U=I.length>0?de({blockingReasons:I,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:J}):[];return {schemaVersion:fe,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r.summary.changed,risk:r.summary.risk,affectedProjects:r.summary.affectedProjects,recommendedCommands:r.summary.recommendedCommands},summary:j,steps:n,missingEvidence:pe,blockingReasons:I,...U.length>0?{resolutionHints:U}:{},verificationPlan:c$1,affectedSubgraph:a.subgraph,graphIntegrity:f,freshness:x,policyMode:P,policyViolations:p$2}}async function He(e,t){let r=[];for(let i of e.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await d$2(t,a.contractVerify);try{if(s&&await v.pathExists(s)){let i=await v.readJson(s);if(Array.isArray(i.violations))for(let o of i.violations)typeof o=="string"&&o.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:o});}}catch{}return r.sort((i,o)=>i.source!==o.source?i.source.localeCompare(o.source):i.code!==o.code?i.code.localeCompare(o.code):i.message.localeCompare(o.message))}function Me(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function Ne(e){let t=m.join(e,J);try{if(!await v.pathExists(t))return null;let r=await v.readJson(t);return r&&r.schemaVersion===fe?r:null}catch{return null}}async function mt(e$1,t){return e(t,J,d$3(e$1))}function Te(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function gt(e,t){return Te(e,t).exitCode}export{ae as a,Ye as b,fe as c,J as d,Be as e,pt as f,mt as g,Te as h,gt as i};
1
+ import {b as b$2,c,d as d$1}from'./chunk-ICLYL3N5.js';import {c as c$1}from'./chunk-GHB6QMQH.js';import {a as a$2,b as b$3}from'./chunk-PYCJWW4B.js';import {p as p$1,a as a$1,o,g,d as d$4,f}from'./chunk-PTTZPDLX.js';import {p,l,f as f$1}from'./chunk-FUPHQOJB.js';import {d}from'./chunk-EWZZUQBR.js';import {d as d$3}from'./chunk-B4CPDK6J.js';import {d as d$2,e}from'./chunk-MBRU3VWJ.js';import {a as a$3}from'./chunk-AFIFZTOY.js';import {b as b$1,a,c as c$2}from'./chunk-62K2H72S.js';import m from'path';import v from'fs-extra';var ae="rapidkit-blocker-resolution-v1";function ce(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return f$1({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function ke(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function ye(e){let t=ke(e.reason),r=ce({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",studioActionId:"run-analyze"}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:ae,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function de(e){return Array.from(new Set(e.blockingReasons.map(r=>r.trim()).filter(Boolean))).slice(0,12).map((r,s)=>ye({reason:r,blockerId:`blocker-${s+1}`,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}))}function he(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function ve(e){return e.length===0||e.every(t=>he(t))}function le(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&ve(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function Ye(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var fe=b$1.verify,J=a.verify;function be(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ue(e){let t=await v.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$3(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$3(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let o=s.transitiveImpact.reduce((u,d)=>Math.max(u,d.distance??0),0);s.summary.blastRadius.maxDistance!==o&&i.push("blastRadius.maxDistance does not match transitive impact distances");let k=l(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==k&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function we(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Re(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function Ce(e,t){if(e.id==="workspace.doctor")return m.join(t,a.doctor);if(e.id==="workspace.contract.verify")return m.join(t,a.contractVerify);if(e.id==="workspace.readiness")return m.join(t,a.readiness);if(e.id==="workspace.analyze")return m.join(t,".workspai","reports","analyze-last-run.json");if(e.id==="workspace.pipeline")return m.join(t,".workspai","reports","pipeline-last-run.json");if(e.id==="workspace.doctor-fix")return m.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e.id.startsWith("project.")&&e.id.includes("."))return m.join(t,".workspai","reports","workspace-run-last.json")}function b(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function Ae(e){let t=b(e.healthScore),r=b(e.summary),s=typeof t?.errors=="number"?t.errors:0,i=typeof t?.percent=="number"?t.percent:void 0;return s>0||r?.hasSystemErrors===true?{status:"fail",message:`Doctor evidence reports ${s} error(s).`}:typeof i=="number"&&i<70?{status:"warn",message:`Doctor health score is ${i}%.`}:{status:"pass",message:"Doctor evidence is present and healthy."}}function je(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function Ee(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Se(e){let t=b(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function We(e){let t=e.schemaVersion==="rapidkit-doctor-fix-result-v1"?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s.length>0)return {status:"fail",message:`Doctor fix result reports ${s.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function xe(e,t){let r=await d$2(e,".workspai/reports/doctor-remediation-plan-last-run.json");if(!r)return false;try{let s=b(await v.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let o=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!o||!t)return true;let k=Date.parse(o),u=Date.parse(t);return !Number.isFinite(k)||!Number.isFinite(u)?true:k>=u}catch{return false}}function Pe(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Ie(e){let t=b(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function Ve(e,t,r){let s=Pe(t),i=c$1(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let o=i.stage;if(s&&o!==s)return {status:"missing",message:`Workspace run evidence is for stage "${o}", expected "${s}".`};let k=Array.isArray(i.projects)?i.projects:[],u=t.project?.toLowerCase();if(!u)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=k.find(g=>{let c=b(g);if(!c)return false;let n=typeof c.projectName=="string"?c.projectName.toLowerCase():"",a=["projectPath","relativePath","path"].map(f=>c[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return n===u||a.some(f=>f.endsWith(`/${u}`)||f===u)});if(d){let g=C(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(g)return {status:"fail",message:g};let c=b(d),n=typeof c?.status=="string"?c.status:"unknown";return n==="failed"?{status:"fail",message:`Workspace run evidence failed for ${t.project}.`}:n==="passed"?{status:"pass",message:`Workspace run evidence passed for ${t.project}.`}:n==="skipped"?{status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}:{status:"warn",message:`Workspace run evidence status is ${n} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function C(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function $e(e){if(e.id==="workspace.doctor")return c$2.doctor;if(e.id==="workspace.readiness")return c$2.readiness;if(e.id==="workspace.contract.verify")return c$2.contractVerify;if(e.id==="workspace.analyze")return c$2.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function Fe(e,t,r,s){let i=Ce(e,t),o=i?m.relative(t,i).split(m.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let k=i?await d$2(t,o??""):null;if(!i||!k)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:o,message:o?`Missing evidence report: ${o}`:"No evidence mapping exists for this command."};let u;try{u=await v.readJson(k);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=b(u);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:"Evidence report is not a JSON object."};let g=$e(e);if(g)try{a$3(d,g,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=C(d.generatedAt,s,"Doctor evidence");n?c={status:"fail",message:n}:c=Ae(d);}else if(e.id==="workspace.readiness"){let n=C(d.generatedAt,s,"Release readiness evidence");n?c={status:"fail",message:n}:c=je(d);}else if(e.id==="workspace.contract.verify"){let n=C(d.generatedAt,s,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=Ee(d);}else if(e.id==="workspace.analyze"){let n=C(d.generatedAt,s,"Analyze evidence");n?c={status:"fail",message:n}:c=Se(d);}else if(e.id==="workspace.pipeline"){let n=C(d.generatedAt,s,"Pipeline evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion==="rapidkit-doctor-fix-result-v1"?d:d.fixResult,a=b(n),f=typeof a?.generatedAt=="string"?a.generatedAt:void 0,y=C(f,s,"Doctor fix result");y?c={status:"fail",message:y}:await xe(t,f)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=We(d);}else if(e.id.startsWith("project."))c=Ve(d,e,s);else {let n=C(d.generatedAt,s,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:o,message:c.message}}function Oe(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,o=e.filter(n=>n.status==="missing").length,k=e.filter(n=>n.status==="skipped").length,u=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,g="ready",c=0;return u.length>0||t.blockingReasons.length>0?(g="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(g="needs-attention",c=1),{verdict:g,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:o,stepsSkipped:k}}function Be(e,t){let r=S(e.affectedProjects.map(a=>a.project?.name).filter(a=>typeof a=="string")),s=new Set(r.map(a=>a.toLowerCase())),i=S(e.transitiveImpact.map(a=>a.project?.name).filter(a=>typeof a=="string").filter(a=>!s.has(a.toLowerCase()))),o=new Map;for(let a of t){if(a.scope!=="project"||!a.project)continue;let f=a.project.toLowerCase(),y=o.get(f)??[];y.push(a),o.set(f,y);}let k=[],u=[],d=[],g=[],c=false,n=(a,f)=>{let y=o.get(a.toLowerCase())??[];if(y.length===0){d.push(a);return}let W=y.filter(p=>p.status==="fail"),w=W.filter(p=>p.required),x=y.filter(p=>p.status==="missing"),A=x.filter(p=>p.required),P=y.some(p=>p.status==="pass"||p.status==="warn");if(w.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has failed verification evidence (${w.map(p=>p.id).join(", ")}).`);return}if(W.length>0){u.push(a),c=true;return}if(A.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has missing required verification evidence (${A.map(p=>p.id).join(", ")}).`);return}if(x.length>0){u.push(a),c=true;return}if(P){k.push(a);return}d.push(a);};for(let a of r)n(a,"directly-changed");for(let a of i)n(a,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:S(k),uncovered:S(u),unverifiable:S(d)},blockingReasons:g,needsAttention:c}}function S(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function _e(e){let t=m.resolve(e.workspacePath);if(e.fromImpactPath){let o=be(t,e.fromImpactPath);return {impact:await ue(o),fromImpactRef:m.relative(t,o).split(m.sep).join("/"),impactFromDisk:true}}let r=m.join(t,g);if(await v.pathExists(r))return {impact:await ue(r),fromImpactRef:g,impactFromDisk:true};let s=m.join(t,d$4);if(await v.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$4,scope:e.scope,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),fromImpactRef:d$4,impactFromDisk:false};let i=await p({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {impact:{schemaVersion:f,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",diffRef:a.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:l(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:b$1.diff,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",toRef:a.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function De(e,t){if(t)return e.generatedAt}async function pt(e){let t=m.resolve(e.workspacePath),{impact:r,fromImpactRef:s,impactFromDisk:i}=await _e(e),o$1=r.diff.currentModel,k=i?await p({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):o$1,u=[];if(i){let l=await p$1({workspacePath:t,fromPath:r.diff.fromRef,diff:r.diff,scope:e.scope,now:e.now}),_=[r.affectedProjects,r.transitiveImpact,r.verificationPlan],D=[l.affectedProjects,l.transitiveImpact,l.verificationPlan];JSON.stringify(_)!==JSON.stringify(D)&&u.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(k)!==r.diff.toHash&&u.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r.diff.git;if(i&&d$2?.available){let l=a$1(t,{ref:d$2.ref}),_=r.diff.changes.filter(h=>h.type.startsWith("git.")).map(h=>`${h.type}:${h.target.replace(/^git:/,"")}`).sort(),D=[...l.changedFiles.map(h=>`git.file.changed:${h}`),...l.untrackedFiles.map(h=>`git.untracked:${h}`),...l.deletedFiles.map(h=>`git.deleted:${h}`)].sort();(!l.available||l.commit!==d$2.commit||JSON.stringify(D)!==JSON.stringify(_))&&u.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let g=De(r,i),c$1=we([...o(),...r.verificationPlan]).filter(l=>Re(e.scope,l)),n=[];for(let l of c$1)n.push(await Fe(l,t,o$1.contracts.exists===true,g));let a=Be(r,n),f=a$2(l(o$1)??{nodes:[],edges:[]}),y=b$2(o$1),W=await Ne(t),w=c(y,W?.freshness?.projectHashes),x={verdict:w.verdict,baseline:w.baseline,changed:w.changed,added:w.added,removed:w.removed,projectHashes:d$1(y)},A=b$3(f),P=o$1.policies?.mode??"warn",p$2=await He(o$1,t),B=Me(P,p$2),j=Oe(n,{blockingReasons:[...a.blockingReasons,...A,...B.blockingReasons,...u],needsAttention:a.needsAttention||B.needsAttention}),pe=n.filter(l=>l.status==="missing"&&l.evidencePath).map(l=>l.evidencePath),I=[...n.filter(l=>l.required&&(l.status==="fail"||l.status==="missing")).map(l=>`${l.id}: ${l.message}`),...a.blockingReasons,...A,...B.blockingReasons,...u],me=p$2.filter(l=>l.severity==="error").length,ge=o$1.summary?.projectCount??o$1.projects.length,G=le({projectCount:ge,verdict:j.verdict,exitCode:j.exitCode,blockingReasons:I,policyErrorCount:me});j.verdict=G.verdict,j.exitCode=G.exitCode;let U=I.length>0?de({blockingReasons:I,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:J}):[];return {schemaVersion:fe,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r.summary.changed,risk:r.summary.risk,affectedProjects:r.summary.affectedProjects,recommendedCommands:r.summary.recommendedCommands},summary:j,steps:n,missingEvidence:pe,blockingReasons:I,...U.length>0?{resolutionHints:U}:{},verificationPlan:c$1,affectedSubgraph:a.subgraph,graphIntegrity:f,freshness:x,policyMode:P,policyViolations:p$2}}async function He(e,t){let r=[];for(let i of e.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await d$2(t,a.contractVerify);try{if(s&&await v.pathExists(s)){let i=await v.readJson(s);if(Array.isArray(i.violations))for(let o of i.violations)typeof o=="string"&&o.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:o});}}catch{}return r.sort((i,o)=>i.source!==o.source?i.source.localeCompare(o.source):i.code!==o.code?i.code.localeCompare(o.code):i.message.localeCompare(o.message))}function Me(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function Ne(e){let t=m.join(e,J);try{if(!await v.pathExists(t))return null;let r=await v.readJson(t);return r&&r.schemaVersion===fe?r:null}catch{return null}}async function mt(e$1,t){return e(t,J,d$3(e$1))}function Te(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function gt(e,t){return Te(e,t).exitCode}export{ae as a,Ye as b,fe as c,J as d,Be as e,pt as f,mt as g,Te as h,gt as i};
@@ -0,0 +1 @@
1
+ import t from'path';function o(e){return `"${e.replace(/"/g,'\\"')}"`}function n(e){let r=`scripts.${e.scriptName}=${e.scriptValue}`;return `cd ${o(e.projectPath)} && npm pkg set ${o(r)}`}function s(e){return `workspai:doctor:repair ${Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}`}function d(e){let r=t.join(e.projectPath,e.relativePath),i={type:"file-create",path:r,content:e.content,overwrite:false};return {id:`${e.issueId}.file-create`,issueId:e.issueId,title:e.title,status:"available",fixKind:"file-create",risk:e.risk??"safe",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:e.requiresReview??false,files:[r],command:s(i),operation:i,verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function g(e){let r=t.join(e.projectPath,e.relativePath),i={type:"file-append",path:r,lines:e.lines,ensureNewline:true};return {id:`${e.issueId}.file-append`,issueId:e.issueId,title:e.title,status:"available",fixKind:"file-append",risk:e.risk??"safe",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:e.requiresReview??false,files:[r],command:s(i),operation:i,verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function m(e){let r=t.join(e.projectPath,e.sourceRelativePath),i=t.join(e.projectPath,e.targetRelativePath),a={type:"file-copy",sourcePath:r,path:i,overwrite:false};return {id:`${e.issueId}.file-copy`,issueId:e.issueId,title:e.title,status:"available",fixKind:"file-copy",risk:e.risk??"safe",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:e.requiresReview??false,files:[r,i],command:s(a),operation:a,verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function u(e){return e.lint&&e.lint.trim().length>0?"npm run lint":e.build&&e.build.trim().length>0?"npm run build":null}function f(e){let r=`frontend-script-${e.scriptName}`,i=t.join(e.projectPath,"package.json"),a=["npx workspai doctor project --json","npx workspai workspace verify --json"];return e.scriptValue?{id:`${r}.package-json-script`,issueId:r,title:`Add package.json ${e.scriptName} script`,status:"available",fixKind:"package-json-script",risk:"guarded",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:false,files:[i],command:n({projectPath:e.projectPath,scriptName:e.scriptName,scriptValue:e.scriptValue}),operation:{type:"package-json-script",path:i,scriptName:e.scriptName,scriptValue:e.scriptValue},verifyCommand:"npx workspai doctor project --json",refreshCommands:a,reason:`Reuse the existing ${e.scriptValue} validation path as the ${e.scriptName} gate for ${e.frameworkDisplayName}.`}:{id:`${r}.manual`,issueId:r,title:`Define ${e.scriptName} script`,status:"manual",fixKind:"manual",risk:"guarded",canAutoFix:false,canEditFiles:false,requiresApproval:true,requiresReview:true,files:[i],refreshCommands:a,reason:`No safe ${e.frameworkDisplayName} fallback script could be inferred from existing package.json scripts.`,limitations:["Add a real test/lint/build command that matches the project quality gate before release."]}}function k(e){let r=t.join(e.projectPath,"package.json");return {id:`${e.issueId}.package-json-script`,issueId:e.issueId,title:e.title,status:"available",fixKind:"package-json-script",risk:e.risk??"guarded",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:e.requiresReview??false,files:[r],command:n({projectPath:e.projectPath,scriptName:e.scriptName,scriptValue:e.scriptValue}),operation:{type:"package-json-script",path:r,scriptName:e.scriptName,scriptValue:e.scriptValue},verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function y(e){let r=t.join(e.projectPath,"Makefile"),i={type:"makefile-target",path:r,target:e.targetName,command:e.command,phony:true};return {id:`${e.issueId}.makefile-target`,issueId:e.issueId,title:e.title,status:"available",fixKind:"file-append",risk:e.risk??"guarded",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:e.requiresReview??true,files:[r],command:s(i),operation:i,verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function v(e){return {id:`${e.issueId}.command`,issueId:e.issueId,title:e.title,status:"available",fixKind:e.fixKind??"command",risk:e.risk??"guarded",canAutoFix:true,canEditFiles:false,requiresApproval:true,requiresReview:e.requiresReview??true,files:e.files.map(r=>t.join(e.projectPath,r)),command:`cd ${o(e.projectPath)} && ${e.command}`,...e.invocation?{invocation:{cwd:e.projectPath,executable:e.invocation.executable,args:[...e.invocation.args]}}:{},...e.strategy?{strategy:e.strategy.map(r=>({...r}))}:{},...e.transaction?{transaction:structuredClone(e.transaction)}:{},verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}export{s as a,d as b,g as c,m as d,u as e,f,k as g,y as h,v as i};
@@ -1 +1 @@
1
- import {d as d$1,c,e}from'./chunk-XBM2P45G.js';import {b,a as a$1}from'./chunk-AHLMIL2T.js';import k from'fs-extra';var y=b.history,a=a$1.history,d=50;function A(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return typeof e.generatedAt!="string"?null:e.kind==="agent-action"?typeof e.actionId!="string"||typeof e.summary!="string"||e.outcome!=="ok"&&e.outcome!=="failed"?null:{kind:"agent-action",generatedAt:e.generatedAt,actionId:e.actionId,scope:typeof e.scope=="string"?e.scope:"workspace",summary:e.summary,outcome:e.outcome,...typeof e.evidenceSha256=="string"?{evidenceSha256:e.evidenceSha256}:{}}:e.kind==="doctor-fix"?e.scope!=="workspace"&&e.scope!=="project"||typeof e.summary!="string"||e.outcome!=="ok"&&e.outcome!=="failed"?null:{kind:"doctor-fix",generatedAt:e.generatedAt,scope:e.scope,summary:e.summary,outcome:e.outcome,applied:typeof e.applied=="number"?e.applied:0,failed:typeof e.failed=="number"?e.failed:0,skipped:typeof e.skipped=="number"?e.skipped:0,remainingBlockers:typeof e.remainingBlockers=="number"?e.remainingBlockers:0}:typeof e.verdict!="string"||typeof e.risk!="string"||typeof e.gatePassed!="boolean"?null:{kind:"verify",generatedAt:e.generatedAt,verdict:e.verdict,risk:String(e.risk),affectedProjects:typeof e.affectedProjects=="number"?e.affectedProjects:0,freshness:e.freshness??"unknown",gatePassed:e.gatePassed,blockingReasons:typeof e.blockingReasons=="number"?e.blockingReasons:0,policyViolations:typeof e.policyViolations=="number"?e.policyViolations:0}}function S(t,e){return {kind:"verify",generatedAt:t.generatedAt,verdict:t.summary.verdict,risk:t.impact.risk,affectedProjects:t.impact.affectedProjects,freshness:t.freshness.verdict,gatePassed:e,blockingReasons:t.blockingReasons.length,policyViolations:t.policyViolations.length}}function F(t){return {kind:"agent-action",generatedAt:t.generatedAt,actionId:t.actionId,scope:t.scope,summary:t.summary,outcome:t.outcome,...t.evidenceSha256?{evidenceSha256:t.evidenceSha256}:{}}}function V(t,e){let o=t.appliedFixes.filter(i=>i.outcome==="applied").length,r=t.appliedFixes.filter(i=>i.outcome==="failed").length,n=t.appliedFixes.filter(i=>i.outcome==="skipped").length,s=t.appliedFixes.filter(i=>i.outcome==="guidance").length,c=t.remainingBlockers.length,g=r>0||c>0?"failed":"ok";return {kind:"doctor-fix",generatedAt:t.generatedAt,scope:e,summary:`${o} applied, ${r} failed, ${n} skipped, ${s} guidance, ${c} blocker(s) remaining`,outcome:g,applied:o,failed:r,skipped:n,remainingBlockers:c}}async function E(t){let e=await d$1(t,a);try{if(!e||!await k.pathExists(e))return null;let o=await k.readJson(e);return o?.schemaVersion!==y||!Array.isArray(o.entries)?null:{schemaVersion:y,retention:typeof o.retention=="number"?o.retention:d,entries:o.entries.map(r=>A(r)).filter(r=>r!=null)}}catch{return null}}function x(t,e,o=d){let r=Math.max(1,Math.floor(o)),n=[...t?.entries??[],e],s=n.slice(Math.max(0,n.length-r));return {schemaVersion:y,retention:r,entries:s}}async function v(t,e$1,o){return c(t,a,async()=>{let r=await d$1(t,a),n=await E(t);if(r&&!n)throw new Error(`Workspace history is unreadable or invalid; refusing to overwrite: ${r}`);let s=x(n,e$1,o?.retention??d);return await e(t,a,s),s})}export{y as a,a as b,d as c,A as d,S as e,F as f,V as g,E as h,x as i,v as j};
1
+ import {d as d$1,c,e}from'./chunk-MBRU3VWJ.js';import {b,a as a$1}from'./chunk-62K2H72S.js';import k from'fs-extra';var y=b.history,a=a$1.history,d=50;function A(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return typeof e.generatedAt!="string"?null:e.kind==="agent-action"?typeof e.actionId!="string"||typeof e.summary!="string"||e.outcome!=="ok"&&e.outcome!=="failed"?null:{kind:"agent-action",generatedAt:e.generatedAt,actionId:e.actionId,scope:typeof e.scope=="string"?e.scope:"workspace",summary:e.summary,outcome:e.outcome,...typeof e.evidenceSha256=="string"?{evidenceSha256:e.evidenceSha256}:{}}:e.kind==="doctor-fix"?e.scope!=="workspace"&&e.scope!=="project"||typeof e.summary!="string"||e.outcome!=="ok"&&e.outcome!=="failed"?null:{kind:"doctor-fix",generatedAt:e.generatedAt,scope:e.scope,summary:e.summary,outcome:e.outcome,applied:typeof e.applied=="number"?e.applied:0,failed:typeof e.failed=="number"?e.failed:0,skipped:typeof e.skipped=="number"?e.skipped:0,remainingBlockers:typeof e.remainingBlockers=="number"?e.remainingBlockers:0}:typeof e.verdict!="string"||typeof e.risk!="string"||typeof e.gatePassed!="boolean"?null:{kind:"verify",generatedAt:e.generatedAt,verdict:e.verdict,risk:String(e.risk),affectedProjects:typeof e.affectedProjects=="number"?e.affectedProjects:0,freshness:e.freshness??"unknown",gatePassed:e.gatePassed,blockingReasons:typeof e.blockingReasons=="number"?e.blockingReasons:0,policyViolations:typeof e.policyViolations=="number"?e.policyViolations:0}}function S(t,e){return {kind:"verify",generatedAt:t.generatedAt,verdict:t.summary.verdict,risk:t.impact.risk,affectedProjects:t.impact.affectedProjects,freshness:t.freshness.verdict,gatePassed:e,blockingReasons:t.blockingReasons.length,policyViolations:t.policyViolations.length}}function F(t){return {kind:"agent-action",generatedAt:t.generatedAt,actionId:t.actionId,scope:t.scope,summary:t.summary,outcome:t.outcome,...t.evidenceSha256?{evidenceSha256:t.evidenceSha256}:{}}}function V(t,e){let o=t.appliedFixes.filter(i=>i.outcome==="applied").length,r=t.appliedFixes.filter(i=>i.outcome==="failed").length,n=t.appliedFixes.filter(i=>i.outcome==="skipped").length,s=t.appliedFixes.filter(i=>i.outcome==="guidance").length,c=t.remainingBlockers.length,g=r>0||c>0?"failed":"ok";return {kind:"doctor-fix",generatedAt:t.generatedAt,scope:e,summary:`${o} applied, ${r} failed, ${n} skipped, ${s} guidance, ${c} blocker(s) remaining`,outcome:g,applied:o,failed:r,skipped:n,remainingBlockers:c}}async function E(t){let e=await d$1(t,a);try{if(!e||!await k.pathExists(e))return null;let o=await k.readJson(e);return o?.schemaVersion!==y||!Array.isArray(o.entries)?null:{schemaVersion:y,retention:typeof o.retention=="number"?o.retention:d,entries:o.entries.map(r=>A(r)).filter(r=>r!=null)}}catch{return null}}function x(t,e,o=d){let r=Math.max(1,Math.floor(o)),n=[...t?.entries??[],e],s=n.slice(Math.max(0,n.length-r));return {schemaVersion:y,retention:r,entries:s}}async function v(t,e$1,o){return c(t,a,async()=>{let r=await d$1(t,a),n=await E(t);if(r&&!n)throw new Error(`Workspace history is unreadable or invalid; refusing to overwrite: ${r}`);let s=x(n,e$1,o?.retention??d);return await e(t,a,s),s})}export{y as a,a as b,d as c,A as d,S as e,F as f,V as g,E as h,x as i,v as j};
@@ -1 +1 @@
1
- export{c as PYTHON_FREE_WORKSPACE_PROFILES,a as buildWorkspaceManifest,f as createProject,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,b as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-MAF3LLGK.js';
1
+ export{c as PYTHON_FREE_WORKSPACE_PROFILES,a as buildWorkspaceManifest,f as createProject,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,b as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-IO54DFWR.js';
@@ -1 +1 @@
1
- export{a as DOCTOR_WORKSPACE_REPORT_PATH,m as applyEnvKeyAddFix,i as applyFileAppendFix,j as applyFileCopyFix,h as applyFileCreateFix,l as applyJsonEditFix,n as applyMakefileTargetFix,g as applyPackageScriptFix,f as assertOperationPathInsideProject,e as buildRepairOperationIdentity,p as computeDoctorFixAwareExitCode,o as computeDoctorGateExitCode,k as decodeJsonPointerSegment,d as parseInternalRepairCommand,c as parsePackageScriptFix,b as resolveDoctorPolicyProfile,q as runDoctor}from'./chunk-GQRWRHSR.js';
1
+ export{a as DOCTOR_WORKSPACE_REPORT_PATH,m as applyEnvKeyAddFix,i as applyFileAppendFix,j as applyFileCopyFix,h as applyFileCreateFix,l as applyJsonEditFix,n as applyMakefileTargetFix,g as applyPackageScriptFix,f as assertOperationPathInsideProject,e as buildRepairOperationIdentity,p as computeDoctorFixAwareExitCode,o as computeDoctorGateExitCode,k as decodeJsonPointerSegment,d as parseInternalRepairCommand,c as parsePackageScriptFix,b as resolveDoctorPolicyProfile,q as runDoctor}from'./chunk-6AXRIAP2.js';