workspai 0.71.0 → 0.72.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +5 -2
  2. package/contracts/artifact-remediation-plan.v1.json +49 -0
  3. package/contracts/workspace-repair-capabilities.v1.json +7 -1
  4. package/dist/analyze-5ENZTHOT.js +1 -0
  5. package/dist/{artifact-remediation-plan-URQL5MBN.js → artifact-remediation-plan-WDK5ISRU.js} +1 -1
  6. package/dist/autopilot-release-QMZSHOLF.js +1 -0
  7. package/dist/{chunk-YC676TPF.js → chunk-2RF75G5T.js} +1 -1
  8. package/dist/chunk-4AW5QP5J.js +5 -0
  9. package/dist/{chunk-LOXR5QUX.js → chunk-4PDEWMOG.js} +1 -1
  10. package/dist/{chunk-H64KAPJJ.js → chunk-5NL53T5C.js} +1 -1
  11. package/dist/{chunk-IGJA6GBQ.js → chunk-62YBFWHY.js} +1 -1
  12. package/dist/chunk-6WOFOOM7.js +7 -0
  13. package/dist/chunk-7Q7X4X5I.js +1 -0
  14. package/dist/chunk-BVWDG66W.js +1 -0
  15. package/dist/chunk-CQBM6BBP.js +2 -0
  16. package/dist/chunk-CY4QZ3PE.js +3 -0
  17. package/dist/{chunk-IOKEF3DE.js → chunk-FYIPYGMW.js} +1 -1
  18. package/dist/{chunk-K2LKJBQ4.js → chunk-I7P6XQJI.js} +1 -1
  19. package/dist/{chunk-5HURQABR.js → chunk-ISGLADQI.js} +1 -1
  20. package/dist/{chunk-V52R2W2Q.js → chunk-IX5Z6EK6.js} +1 -1
  21. package/dist/{chunk-ACCWXKZW.js → chunk-JPPZDLY3.js} +2 -2
  22. package/dist/{chunk-AUVWD3WV.js → chunk-JQINCVK5.js} +1 -1
  23. package/dist/{chunk-GL3KLNIG.js → chunk-KVPTZMEV.js} +1 -1
  24. package/dist/{chunk-7V3YDKMG.js → chunk-L4WG3NI7.js} +1 -1
  25. package/dist/{chunk-HMKDU7OU.js → chunk-L5ZD2GD3.js} +1 -1
  26. package/dist/{chunk-554W2TXP.js → chunk-LLEKVSMX.js} +1 -1
  27. package/dist/{chunk-L5IV2SI4.js → chunk-LLSY6L7E.js} +1 -1
  28. package/dist/{chunk-QHHSSIMZ.js → chunk-N2PAAQKI.js} +1 -1
  29. package/dist/{chunk-TD5TQZEG.js → chunk-QVUVJU56.js} +1 -1
  30. package/dist/{chunk-FFE2JZZJ.js → chunk-QYXX6G5O.js} +8 -8
  31. package/dist/{chunk-CX6PAQTQ.js → chunk-RQKDJVX3.js} +65 -65
  32. package/dist/{chunk-C563KVBD.js → chunk-S66NO5BX.js} +1 -1
  33. package/dist/{chunk-M2R6UXJB.js → chunk-SATPH22S.js} +1 -1
  34. package/dist/{chunk-2KJNASF3.js → chunk-SS7X2YF5.js} +1 -1
  35. package/dist/{chunk-4CE3GI4Y.js → chunk-T6KHOIEY.js} +1 -1
  36. package/dist/{chunk-AUQLOQ2S.js → chunk-T6LCDLJ7.js} +1 -1
  37. package/dist/{chunk-XY537LCX.js → chunk-TDQ2PRHV.js} +1 -1
  38. package/dist/{chunk-26VNCHVV.js → chunk-U3RX7KDY.js} +1 -1
  39. package/dist/chunk-V4LCPLV6.js +1 -0
  40. package/dist/{chunk-GYN6RPNU.js → chunk-WMC2H7MJ.js} +1 -1
  41. package/dist/{chunk-YS34N35Y.js → chunk-WPZUKU2B.js} +1 -1
  42. package/dist/chunk-X5ZNFXFI.js +1 -0
  43. package/dist/{create-HSHAZYAK.js → create-FOPYAWAR.js} +1 -1
  44. package/dist/{doctor-VZ2MZ7EI.js → doctor-Z3Z5L67W.js} +1 -1
  45. package/dist/{goal-lifecycle-NKSCALES.js → goal-lifecycle-ZH7AQIOX.js} +1 -1
  46. package/dist/{goal-pack-MPKW4K6F.js → goal-pack-OP453Q6U.js} +1 -1
  47. package/dist/index.js +101 -101
  48. package/dist/{pipeline-RIA5UXUC.js → pipeline-LPZHMO7S.js} +1 -1
  49. package/dist/{project-agent-entry-GQAPCSOT.js → project-agent-entry-QGPM7CU7.js} +1 -1
  50. package/dist/{project-intelligence-lens-5I2GQBWC.js → project-intelligence-lens-U7PLWYXX.js} +1 -1
  51. package/dist/{project-test-coverage-4RRCHY5W.js → project-test-coverage-4BGDDBBL.js} +1 -1
  52. package/dist/{proof-carrying-change-T33C2SSD.js → proof-carrying-change-6LQ6JO5J.js} +1 -1
  53. package/dist/{verified-goal-MK5MXGRY.js → verified-goal-JIRVX7KO.js} +1 -1
  54. package/dist/{workspace-AZKZPG45.js → workspace-3K2YGPU7.js} +1 -1
  55. package/dist/{workspace-agent-sync-CGK44F3O.js → workspace-agent-sync-TFQNKRD3.js} +1 -1
  56. package/dist/{workspace-context-S6ZWRUFZ.js → workspace-context-ZDXF6S7S.js} +1 -1
  57. package/dist/{workspace-contract-Y7WRHLYR.js → workspace-contract-E7GVWM7W.js} +1 -1
  58. package/dist/{workspace-explain-CSJL3GJR.js → workspace-explain-YB66UFAS.js} +1 -1
  59. package/dist/{workspace-foundation-LLND2WIF.js → workspace-foundation-J62BMOQS.js} +1 -1
  60. package/dist/{workspace-graph-stream-PHFO2J2E.js → workspace-graph-stream-SJUCBPS4.js} +1 -1
  61. package/dist/workspace-graph-token-efficiency-BTIS6JXL.js +1 -0
  62. package/dist/{workspace-intelligence-ND2N3B2A.js → workspace-intelligence-3IAAM3H3.js} +1 -1
  63. package/dist/{workspace-intelligence-benchmark-S5OXVNLC.js → workspace-intelligence-benchmark-UCGDKMDF.js} +1 -1
  64. package/dist/{workspace-intelligence-runner-LHHJM2AT.js → workspace-intelligence-runner-OELXKX3D.js} +1 -1
  65. package/dist/{workspace-knowledge-graph-NOGGGENE.js → workspace-knowledge-graph-WNQMNAVL.js} +1 -1
  66. package/dist/{workspace-knowledge-graph-query-WHCGPBGS.js → workspace-knowledge-graph-query-3GPXGWYN.js} +1 -1
  67. package/dist/workspace-knowledge-graph-snapshot-MTFTCVFF.js +1 -0
  68. package/dist/{workspace-mcp-serve-6NVF7AS6.js → workspace-mcp-serve-X7ZYJA3X.js} +1 -1
  69. package/dist/{workspace-model-VOQOEDVU.js → workspace-model-5FA2636K.js} +1 -1
  70. package/dist/{workspace-onboarding-ZRLUMBLE.js → workspace-onboarding-CZSQDNKO.js} +1 -1
  71. package/dist/{workspace-registry-summary-NWZK5IKS.js → workspace-registry-summary-WKENOFEA.js} +1 -1
  72. package/dist/workspace-repair-engine-RXHJX4CQ.js +3 -0
  73. package/dist/workspace-run-IDRHBKEB.js +1 -0
  74. package/dist/{workspace-verify-4EQI3MCW.js → workspace-verify-37QL2JYE.js} +1 -1
  75. package/dist/{workspace-watch-BPRU2X7K.js → workspace-watch-P5X6TAFK.js} +1 -1
  76. package/docs/ci-workflows.md +1 -1
  77. package/docs/commands-reference.md +16 -2
  78. package/docs/contracts/ARTIFACT_CATALOG.md +4 -1
  79. package/docs/doctor-command.md +20 -0
  80. package/docs/workspace-knowledge-graph.md +11 -0
  81. package/docs/workspace-repair-engine.md +9 -1
  82. package/docs/workspace-run.md +13 -0
  83. package/package.json +1 -4
  84. package/scripts/enterprise-package-smoke.mjs +14 -2
  85. package/dist/analyze-4YQ67OCK.js +0 -1
  86. package/dist/autopilot-release-V3A3YCDD.js +0 -1
  87. package/dist/chunk-DWL3PPLA.js +0 -1
  88. package/dist/chunk-EZPLMAW2.js +0 -1
  89. package/dist/chunk-IRLKWRLP.js +0 -3
  90. package/dist/chunk-RMGSMDJW.js +0 -5
  91. package/dist/chunk-TKXRP2B4.js +0 -1
  92. package/dist/chunk-U5ENEDJA.js +0 -7
  93. package/dist/chunk-WCJU3CFG.js +0 -1
  94. package/dist/chunk-ZOE43SGQ.js +0 -1
  95. package/dist/workspace-graph-token-efficiency-WNAFAN2F.js +0 -1
  96. package/dist/workspace-knowledge-graph-snapshot-7XHZNRFK.js +0 -1
  97. package/dist/workspace-repair-engine-VUOCH66O.js +0 -3
  98. package/dist/workspace-run-3YZTVOU6.js +0 -1
  99. package/scripts/check-cli-resolution.cjs +0 -72
@@ -1,2 +1,2 @@
1
- import {z as z$1}from'./chunk-M2R6UXJB.js';import {j,m as m$1}from'./chunk-U5ENEDJA.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2,g,f,h}from'./chunk-FE5R6EUV.js';import {b}from'./chunk-K33JJVQZ.js';import {l}from'./chunk-OCGZNSOE.js';import {t,p,s,q}from'./chunk-ODK4LCEL.js';import {c}from'./chunk-64XWHDZ3.js';import {a}from'./chunk-XWKGZRHN.js';import {t as t$1,u,q as q$1}from'./chunk-VQZ5PI5J.js';import*as m from'path';import m__default from'path';import k from'fs-extra';import Ce from'crypto';var ye="unknown-run";function se(e){let t=c();return !t||t===ye?e:{...e,runId:t}}async function ce(e,t){await k.ensureDir(m.dirname(e));let r=`${e}.${process.pid}.${Date.now()}.${Ce.randomUUID()}.tmp`;try{await k.writeJSON(r,t,{spaces:2}),await k.move(r,e,{overwrite:true});}finally{await k.remove(r).catch(()=>{});}}function ie(e){return q$1(e,"imported-projects.json")}async function I(e){let t=(await Promise.all(t$1(e,"imported-projects.json").map(async r=>await k.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!t)return [];try{let r=await k.readJSON(t);if(!r||typeof r!="object"||r.version!==1||!Array.isArray(r.projects))throw new Error("expected a version 1 registry with a projects array");let o=r.projects,n=o.filter(i=>{if(!i||typeof i!="object")return false;let c=i;return typeof c.name=="string"&&typeof c.path=="string"&&typeof c.stack=="string"&&typeof c.confidence=="string"&&typeof c.importedAt=="string"});if(n.length!==o.length)throw new Error("one or more project entries are invalid");return n}catch(r){throw new Error(`Imported-project registry is invalid: ${t}`,{cause:r})}}async function He(e,t){if(t.length===0)return;let r=ie(e);await a(`${r}.lock`,async()=>{let o=await I(e),n=new Map;for(let c of o)n.set(c.path,c);for(let c of t)n.set(c.path,c);let i=Array.from(n.values()).sort((c,u)=>c.name.localeCompare(u.name)).map(c=>({...c}));await ce(r,{version:1,updatedAt:new Date().toISOString(),projects:i});},{timeoutMs:3e4,staleMs:6e4,purpose:"imported-projects-registry-upsert"});}async function Je(e,t){if(t.length===0)return;let r=ie(e);await a(`${r}.lock`,async()=>{let o=await I(e),n=new Set(t.map(c=>m.resolve(c))),i=o.filter(c=>!n.has(m.resolve(c.path)));await ce(r,{version:1,updatedAt:new Date().toISOString(),projects:i});},{timeoutMs:3e4,staleMs:6e4,purpose:"imported-projects-registry-remove"});}var ze="workspace-dependency-graph.v1",pe=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],de=["inferred","contract","manual"];var v=t.workspaceContract,Ee=p.contractVerify,_=s.workspaceContract.schemaVersion,ve=q.contractVerify,N=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function fe(e){return e.replace(/\\/g,"/")}function z(e){let t=fe(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function le(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function je(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function ue(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(i=>{if(!i||typeof i!="object"||Array.isArray(i))return null;let c=i,u=Number(c.port);if(!Number.isInteger(u)||u<1||u>65535)return null;let g=c.protocol==="https"||c.protocol==="grpc"||c.protocol==="tcp"||c.protocol==="udp"?c.protocol:"http";return {name:typeof c.name=="string"&&c.name.trim()?c.name:"http",port:u,protocol:g}}).filter(i=>i!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,n=Number(e.port??o?.default_port);return Number.isInteger(n)&&n>=1&&n<=65535?[{name:"http",port:n,protocol:"http"}]:[]}async function be(e){let t=m__default.join(e,"Dockerfile");if(!await k.pathExists(t))return [];try{let r=await k.readFile(t,"utf8"),o=new Map;for(let n of r.matchAll(/^\s*EXPOSE\s+(.+)$/gim))for(let i of n[1].split(/\s+/)){let c=i.match(/^(\d{1,5})(?:\/(tcp|udp))?$/i),u=Number(c?.[1]);if(!c||!Number.isInteger(u)||u<1||u>65535)continue;let g=c[2]?.toLowerCase();o.set(u,{name:"http",port:u,protocol:g==="udp"?"udp":"http"});}return [...o.values()].sort((n,i)=>n.port-i.port)}catch{return []}}async function D(e){for(let t of e)if(await k.pathExists(t))return t;return null}async function We(e){for(let t of t$1(e,"workspace.json"))try{let r=await k.readJson(t);return {name:typeof r.workspace_name=="string"&&r.workspace_name.trim()||typeof r.name=="string"&&r.name.trim()||m__default.basename(e),profile:typeof r.profile=="string"?r.profile:void 0}}catch{}return {name:m__default.basename(e)}}async function Se(e){let t=[],r=[e],o=new Set,n=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let i=r.shift();if(!i||o.has(i))continue;o.add(i);let c=await D(u(i,"project.json")),u$1=await D(u(i,"context.json"));if(c||u$1){t.push(c??u$1??"");continue}let g;try{g=await k.readdir(i,{withFileTypes:true});}catch{continue}for(let d of g)!d.isDirectory()||n.has(d.name)||a$1(d.name)||r.push(m__default.join(i,d.name));}return t.sort()}function Ae(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function Re(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return r.includes("vscode-extension")?null:r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:r.startsWith("adopted.")?null:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function U(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function B(e,t,r){let o=e!==void 0&&e.source===void 0,n=Re(t.kit,t.runtime),i=e?.ports||[],c=t.ports||[],u=(t.kit||"").toLowerCase().includes("vscode-extension"),g=t.source==="adopted-local"&&e?.source!==void 0,d=t.source!==void 0&&e?.source!==void 0,p=(u&&c.length===0?[]:g?c.length>0?c:n?[{name:"http",port:U(n,r),protocol:"http"}]:[]:i.length>0?i:c.length>0?c:n?[{name:"http",port:U(n,r),protocol:"http"}]:[]).map(w=>({...w,port:U(w.port,r)}));for(let w of p)r.add(w.port);let f={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&z(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:d?t.runtime:e?.runtime||t.runtime,framework:d?t.framework:e?.framework||t.framework,kit:d?t.kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:p,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},h=JSON.stringify(e||null)!==JSON.stringify(f);return {project:f,changed:h}}async function he(e){let t=m__default.resolve(e.workspacePath),r=await We(t),o=await Se(t),n=await I(t),i=new Map(n.map(s=>[m__default.resolve(s.path),s])),c=[];for(let s of n){let p=m__default.resolve(s.path),f=await D(u(p,"project.json"))??await D(u(p,"context.json"));!f||o.some(h=>m__default.resolve(h)===m__default.resolve(f))||c.push({projectJsonPath:f,registryEntry:s});}let u$1=[],g=[...o.map(s=>({projectJsonPath:s,registryEntry:i.get(m__default.resolve(m__default.dirname(m__default.dirname(s))))})),...c];for(let{projectJsonPath:s,registryEntry:p}of g){let f=m__default.dirname(m__default.dirname(s)),h=fe(m__default.relative(t,f)),w=p!==void 0&&!z(h),C=le(p?.name||m__default.basename(f),m__default.basename(f)),b=w?`external/${C}`:h||C,P=await k.readJson(s),a=typeof P.kit_name=="string"&&P.kit_name||typeof P.kit=="string"&&P.kit||void 0,E=j(P)?m$1(f,P):void 0,j$1=E!==void 0&&E.key!=="unknown",T=j$1?E.runtime:typeof P.runtime=="string"?P.runtime:void 0,y=j$1?E.key:typeof P.framework=="string"&&P.framework||Ae(a),$=p?.relationship==="adopted"?"adopted":"imported",K=j$1?`${$}.${E.key}`:a;u$1.push({slug:p?.name||b||m__default.basename(f),relativePath:b,source:p?.source??"workspace",relationship:p?.relationship,externalPath:w?f:void 0,runtime:T,framework:y,kit:K,modules:je(P.modules),ports:ue(P).length>0?ue(P):await be(f),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let d=new Map;for(let s of u$1){let p=le(s.slug,s.relativePath),f=d.get(p);(!f||f.source!=="workspace"&&s.source==="workspace")&&d.set(p,s);}return {schemaVersion:_,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...d.values()]}}async function dt(e){let t=m__default.resolve(e.outputPath||a$2(e.workspacePath,v));if(await k.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await he({workspacePath:e.workspacePath,now:e.now}),o=new Set,n={...r,projects:r.projects.map(c=>B(void 0,c,o).project)},i=await Pe({workspacePath:e.workspacePath,contractPath:t,contract:n});if(e.strict&&i.status==="failed")throw new N(i);return await ke({workspacePath:e.workspacePath,contractPath:t,contract:n,now:e.now}),{contractPath:t,contract:n}}async function lt(e){let t=m__default.resolve(e.workspacePath),r=a$2(t,v),o=await g(t,v)??r,n=await he({workspacePath:t,now:e.now}),i=await k.pathExists(o)?await k.readJson(o):null,c=new Map((i?.projects||[]).map(h=>[h.slug,h])),u=new Set,g$1=[],d=[],s=[];for(let h of n.projects){let w=c.get(h.slug),C=B(w,h,u);w?C.changed&&d.push(h.slug):g$1.push(h.slug),s.push(C.project),c.delete(h.slug);}for(let h of c.values()){if(h.source)continue;let w=B(h,h,u);s.push(w.project);}let p={schemaVersion:_,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...i?.workspace||{},...n.workspace,name:n.workspace.name||i?.workspace?.name||m__default.basename(t)},projects:s.sort((h,w)=>h.slug.localeCompare(w.slug))},f=await Pe({workspacePath:t,contractPath:r,contract:p});if(e.strict&&f.status==="failed")throw new N(f);return await ke({workspacePath:t,contractPath:r,contract:p,now:e.now}),{contractPath:r,contract:p,addedProjects:g$1,updatedProjects:d,verification:f}}async function me(e){return await k.pathExists(e)?{exists:true,contents:await k.readFile(e)}:{exists:false}}async function ge(e,t){if(!t.exists){await k.remove(e);return}await k.outputFile(e,t.contents);}async function ke(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-NWZK5IKS.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),n=a$2(e.workspacePath,r),i=c=>{if(!c||typeof c!="object"||Array.isArray(c))return JSON.stringify(c);let{generatedAt:u,...g}=c;return JSON.stringify(g)};if(await k.pathExists(e.contractPath)&&await k.pathExists(n)){let[c,u]=await Promise.all([k.readJson(e.contractPath),k.readJson(n)]);if(i(c)===i(e.contract)&&i(u)===i(o))return}b(v,e.contract),b(r,o),await f(e.workspacePath,v,async()=>{let[c,u]=await Promise.all([me(e.contractPath),me(n)]);try{if(e.contractPath===a$2(e.workspacePath,v)?await h(e.workspacePath,v,e.contract):(await k.ensureDir(m__default.dirname(e.contractPath)),await k.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await h(e.workspacePath,r,o);}catch(g){let s=(await Promise.allSettled([ge(e.contractPath,c),ge(n,u)])).filter(p=>p.status==="rejected");throw s.length>0?new AggregateError([g,...s.map(p=>p.reason)],"Workspace contract publication failed and rollback was incomplete."):g}});}async function we(e){let t=e.contractPath??(await g(e.workspacePath,v)||a$2(e.workspacePath,v)),r=await k.readJson(t);return {contractPath:t,contract:r}}var xe={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function _e(e,t){return t.externalPath?m__default.resolve(t.externalPath):m__default.resolve(e,t.relativePath)}async function Ge(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(xe))for(let n of o)await k.pathExists(m__default.join(e,n))&&t[r].push(n);try{let r=await k.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,n)=>o.localeCompare(n));return t}function x(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function Oe(e){try{let t=await k.readJson(m__default.join(e,"package.json")),r={runtime:x(t.dependencies),development:x(t.devDependencies),peer:x(t.peerDependencies),optional:x(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:x(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function Ie(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await k.readFile(m__default.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,n)=>o.localeCompare(n))}catch{}return []}function Ne(e,t){try{let r=z$1(e);if(r.engine!=="unknown")return r;let o=k.pathExistsSync(m__default.join(e,"package.json"))?"npm":k.pathExistsSync(m__default.join(e,"pyproject.toml"))?"python":k.pathExistsSync(m__default.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",runtimeCandidates:["unknown"],compositeRuntime:false,lifecycleCoverage:"complete",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function De(e,t,r){let o=e.projects.map(n=>({id:n.slug,path:n.relativePath,runtime:n.runtime,framework:n.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function ut(e){let{contractPath:t,contract:r}=await we(e),o=e.now??new Date,n=o.toISOString(),{buildWorkspaceModel:i,workspaceModelProjectTopology:c}=await import('./workspace-model-VOQOEDVU.js'),{hashWorkspaceModel:u}=await import('./workspace-model-hash-ZXYPIGCW.js'),g=await i({workspacePath:e.workspacePath,includeEvidence:false,now:o}),d=c(g)??De(r,n,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(d.nodes.map(a=>[a.id,a.operationalProfile])),{buildWorkspaceKnowledgeGraph:p$1}=await import('./workspace-knowledge-graph-NOGGGENE.js'),f=await p$1({workspacePath:e.workspacePath,workspace:{name:g.workspace.name,...g.workspace.profile?{profile:g.workspace.profile}:{}},contract:r,projectTopology:d,now:o,projects:g.projects.map(a=>({id:a.name,path:a.path,...a.absolutePath?{absolutePath:a.absolutePath}:{},runtime:a.runtime,runtimeCandidates:a.runtimeCandidates,framework:a.framework,...a.kit?{kit:a.kit}:{}})),source:{kind:"workspace-model",artifact:p.model,hashAlgorithm:"sha256",hash:u(g)}}),h=await Promise.all(r.projects.map(async a=>{let l=_e(e.workspacePath,a),[E,j,T]=await Promise.all([Ge(l),Oe(l),Ie(l)]),y=Ne(l,a);return {id:a.slug,label:a.slug,relativePath:a.relativePath,source:a.source,relationship:a.relationship,externalPath:a.externalPath,runtime:a.runtime??y.runtime,framework:a.framework??y.framework,kit:a.kit,modules:a.modules,ports:a.ports,apis:a.contracts.apis,owns:a.contracts.owns,env:[...new Set([...a.contracts.env,...T])].sort(($,K)=>$.localeCompare(K)),contracts:{owns:[...a.contracts.owns],apis:[...a.contracts.apis],publishes:[...a.contracts.publishes],consumes:[...a.contracts.consumes],dependsOn:[...a.contracts.dependsOn],env:[...a.contracts.env]},capabilities:{engine:y.engine,supportTier:y.frameworkSupportTier,runtimeSupportTier:y.runtimeSupportTier,doctorSupport:y.runtimeDoctorSupport,moduleSupport:y.moduleSupport,fleetStages:[...y.fleetStages],localOnlyCommands:[...y.localOnlyCommands],supportedCommands:[...y.supportedCommands]},files:E,...j?{package:j}:{},...s.get(a.slug)?{operationalProfile:s.get(a.slug)}:{}}})),w=new Set(h.map(a=>a.id)),C=new Map,b=[];for(let a of r.projects){for(let l of a.contracts.dependsOn||[])w.has(l)&&b.push({from:l,to:a.slug,type:"dependency",label:"dependsOn"});for(let l of a.contracts.publishes||[])C.has(l)||C.set(l,new Set),C.get(l)?.add(a.slug);}for(let a of r.projects)for(let l of a.contracts.consumes||[]){let E=C.get(l);if(E)for(let j of E)j!==a.slug&&b.push({from:j,to:a.slug,type:"event",label:l});}let P={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:n,nodes:h.sort((a,l)=>a.id.localeCompare(l.id)),edges:b.sort((a,l)=>`${a.from}:${a.to}:${a.type}:${a.label}`.localeCompare(`${l.from}:${l.to}:${l.type}:${l.label}`)),dependencyGraph:d,knowledgeGraph:f,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:h.length,dependencyEdges:b.filter(a=>a.type==="dependency").length,eventEdges:b.filter(a=>a.type==="event").length,portCount:h.reduce((a,l)=>a+l.ports.length,0),apiCount:h.reduce((a,l)=>a+l.apis.length,0),relationshipEdges:d.stats.edgeCount,inferredEdges:d.stats.inferredEdges,authoritativeEdges:d.stats.authoritativeEdges,orphanProjects:d.stats.orphanCount,hotspotProjects:d.stats.hotspotCount,evidenceCoverageRatio:d.stats.evidenceCoverageRatio,edgeCoverageRatio:d.stats.edgeCoverageRatio,connectedProjects:d.stats.connectedNodeCount,lowConfidenceEdges:d.stats.lowConfidenceEdges,hasCycle:d.stats.hasCycle,manifestCount:h.reduce((a,l)=>a+l.files.manifests.length,0),entrypointCount:h.reduce((a,l)=>a+l.files.entrypoints.length,0),diagnostics:d.diagnostics?.length??0,relationshipKinds:Object.fromEntries(pe.map(a=>[a,d.edges.filter(l=>l.kind===a).length])),relationshipSources:Object.fromEntries(de.map(a=>[a,d.edges.filter(l=>l.source===a).length])),entityCount:f.quality.entityCount,knowledgeRelations:f.quality.relationCount,proofCount:f.quality.proofCount,providerCount:f.providers.length,knowledgeUnknowns:f.quality.unknownCount}};return {contractPath:t,graph:P}}async function Pe(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,v),contract:e.contract}:await we(e),{contractPath:r,contract:o}=t,n=[],i=[];o.kind!=="rapidkit.workspace.contract"&&n.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==_&&n.push(`Contract schemaVersion must be ${_}.`),o.workspace?.name||n.push("Contract workspace.name is required."),Array.isArray(o.projects)||n.push("Contract projects must be an array.");let c=new Set,u=new Map;for(let s of o.projects||[]){if(!s.slug){n.push("Every project must declare slug.");continue}c.has(s.slug)&&n.push(`Duplicate project slug: ${s.slug}.`),c.add(s.slug),s.relativePath?z(s.relativePath)||n.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):n.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||n.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),m__default.isAbsolute(s.externalPath)||n.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let p of s.ports||[]){(!Number.isInteger(p.port)||p.port<1||p.port>65535)&&n.push(`Project ${s.slug} declares invalid port: ${p.port}.`);let f=u.get(p.port);f&&n.push(`Port ${p.port} is claimed by both ${f} and ${s.slug}.`),u.set(p.port,s.slug);}for(let p of s.contracts?.apis||[])(!p.name?.trim()||!p.basePath?.startsWith("/"))&&n.push(`Project ${s.slug} declares invalid API contract.`);for(let p of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])p.trim()||n.push(`Project ${s.slug} declares an empty event contract.`);for(let p of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(p)||n.push(`Project ${s.slug} declares invalid env contract: ${p}.`);for(let p of s.contracts?.dependsOn||[])c.has(p);}for(let s of o.projects||[])for(let p of s.contracts?.dependsOn||[])c.has(p)||n.push(`Project ${s.slug} depends on unknown project: ${p}.`);i.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===_?"passed":"failed",message:"Contract schema and kind are valid."}),i.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),i.push({id:"ports",status:n.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),i.push({id:"dependencies",status:n.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),i.push({id:"contracts",status:n.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let g=await l(e.workspacePath);if(g.moduleCount>0){for(let s of g.issues)n.push(`${m__default.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);i.push({id:"module-paths",status:g.status,message:g.status==="passed"?`All ${g.moduleCount} registered module(s) resolve under canonical paths.`:`${g.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&i.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:n.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:i,violations:n}}async function mt(e){let t=m__default.resolve(e.workspacePath),r={schemaVersion:ve,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return h(t,Ee,se(r))}
1
+ import {z as z$1}from'./chunk-SATPH22S.js';import {j,m as m$1}from'./chunk-6WOFOOM7.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2,g,f,h}from'./chunk-FE5R6EUV.js';import {b}from'./chunk-K33JJVQZ.js';import {l}from'./chunk-OCGZNSOE.js';import {t,p,s,q}from'./chunk-ODK4LCEL.js';import {c}from'./chunk-64XWHDZ3.js';import {a}from'./chunk-XWKGZRHN.js';import {t as t$1,u,q as q$1}from'./chunk-VQZ5PI5J.js';import*as m from'path';import m__default from'path';import k from'fs-extra';import Ce from'crypto';var ye="unknown-run";function se(e){let t=c();return !t||t===ye?e:{...e,runId:t}}async function ce(e,t){await k.ensureDir(m.dirname(e));let r=`${e}.${process.pid}.${Date.now()}.${Ce.randomUUID()}.tmp`;try{await k.writeJSON(r,t,{spaces:2}),await k.move(r,e,{overwrite:true});}finally{await k.remove(r).catch(()=>{});}}function ie(e){return q$1(e,"imported-projects.json")}async function I(e){let t=(await Promise.all(t$1(e,"imported-projects.json").map(async r=>await k.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!t)return [];try{let r=await k.readJSON(t);if(!r||typeof r!="object"||r.version!==1||!Array.isArray(r.projects))throw new Error("expected a version 1 registry with a projects array");let o=r.projects,n=o.filter(i=>{if(!i||typeof i!="object")return false;let c=i;return typeof c.name=="string"&&typeof c.path=="string"&&typeof c.stack=="string"&&typeof c.confidence=="string"&&typeof c.importedAt=="string"});if(n.length!==o.length)throw new Error("one or more project entries are invalid");return n}catch(r){throw new Error(`Imported-project registry is invalid: ${t}`,{cause:r})}}async function He(e,t){if(t.length===0)return;let r=ie(e);await a(`${r}.lock`,async()=>{let o=await I(e),n=new Map;for(let c of o)n.set(c.path,c);for(let c of t)n.set(c.path,c);let i=Array.from(n.values()).sort((c,u)=>c.name.localeCompare(u.name)).map(c=>({...c}));await ce(r,{version:1,updatedAt:new Date().toISOString(),projects:i});},{timeoutMs:3e4,staleMs:6e4,purpose:"imported-projects-registry-upsert"});}async function Je(e,t){if(t.length===0)return;let r=ie(e);await a(`${r}.lock`,async()=>{let o=await I(e),n=new Set(t.map(c=>m.resolve(c))),i=o.filter(c=>!n.has(m.resolve(c.path)));await ce(r,{version:1,updatedAt:new Date().toISOString(),projects:i});},{timeoutMs:3e4,staleMs:6e4,purpose:"imported-projects-registry-remove"});}var ze="workspace-dependency-graph.v1",pe=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],de=["inferred","contract","manual"];var v=t.workspaceContract,Ee=p.contractVerify,_=s.workspaceContract.schemaVersion,ve=q.contractVerify,N=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function fe(e){return e.replace(/\\/g,"/")}function z(e){let t=fe(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function le(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function je(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function ue(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(i=>{if(!i||typeof i!="object"||Array.isArray(i))return null;let c=i,u=Number(c.port);if(!Number.isInteger(u)||u<1||u>65535)return null;let g=c.protocol==="https"||c.protocol==="grpc"||c.protocol==="tcp"||c.protocol==="udp"?c.protocol:"http";return {name:typeof c.name=="string"&&c.name.trim()?c.name:"http",port:u,protocol:g}}).filter(i=>i!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,n=Number(e.port??o?.default_port);return Number.isInteger(n)&&n>=1&&n<=65535?[{name:"http",port:n,protocol:"http"}]:[]}async function be(e){let t=m__default.join(e,"Dockerfile");if(!await k.pathExists(t))return [];try{let r=await k.readFile(t,"utf8"),o=new Map;for(let n of r.matchAll(/^\s*EXPOSE\s+(.+)$/gim))for(let i of n[1].split(/\s+/)){let c=i.match(/^(\d{1,5})(?:\/(tcp|udp))?$/i),u=Number(c?.[1]);if(!c||!Number.isInteger(u)||u<1||u>65535)continue;let g=c[2]?.toLowerCase();o.set(u,{name:"http",port:u,protocol:g==="udp"?"udp":"http"});}return [...o.values()].sort((n,i)=>n.port-i.port)}catch{return []}}async function D(e){for(let t of e)if(await k.pathExists(t))return t;return null}async function We(e){for(let t of t$1(e,"workspace.json"))try{let r=await k.readJson(t);return {name:typeof r.workspace_name=="string"&&r.workspace_name.trim()||typeof r.name=="string"&&r.name.trim()||m__default.basename(e),profile:typeof r.profile=="string"?r.profile:void 0}}catch{}return {name:m__default.basename(e)}}async function Se(e){let t=[],r=[e],o=new Set,n=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let i=r.shift();if(!i||o.has(i))continue;o.add(i);let c=await D(u(i,"project.json")),u$1=await D(u(i,"context.json"));if(c||u$1){t.push(c??u$1??"");continue}let g;try{g=await k.readdir(i,{withFileTypes:true});}catch{continue}for(let d of g)!d.isDirectory()||n.has(d.name)||a$1(d.name)||r.push(m__default.join(i,d.name));}return t.sort()}function Ae(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function Re(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return r.includes("vscode-extension")?null:r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:r.startsWith("adopted.")?null:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function U(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function B(e,t,r){let o=e!==void 0&&e.source===void 0,n=Re(t.kit,t.runtime),i=e?.ports||[],c=t.ports||[],u=(t.kit||"").toLowerCase().includes("vscode-extension"),g=t.source==="adopted-local"&&e?.source!==void 0,d=t.source!==void 0&&e?.source!==void 0,p=(u&&c.length===0?[]:g?c.length>0?c:n?[{name:"http",port:U(n,r),protocol:"http"}]:[]:i.length>0?i:c.length>0?c:n?[{name:"http",port:U(n,r),protocol:"http"}]:[]).map(w=>({...w,port:U(w.port,r)}));for(let w of p)r.add(w.port);let f={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&z(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:d?t.runtime:e?.runtime||t.runtime,framework:d?t.framework:e?.framework||t.framework,kit:d?t.kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:p,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},h=JSON.stringify(e||null)!==JSON.stringify(f);return {project:f,changed:h}}async function he(e){let t=m__default.resolve(e.workspacePath),r=await We(t),o=await Se(t),n=await I(t),i=new Map(n.map(s=>[m__default.resolve(s.path),s])),c=[];for(let s of n){let p=m__default.resolve(s.path),f=await D(u(p,"project.json"))??await D(u(p,"context.json"));!f||o.some(h=>m__default.resolve(h)===m__default.resolve(f))||c.push({projectJsonPath:f,registryEntry:s});}let u$1=[],g=[...o.map(s=>({projectJsonPath:s,registryEntry:i.get(m__default.resolve(m__default.dirname(m__default.dirname(s))))})),...c];for(let{projectJsonPath:s,registryEntry:p}of g){let f=m__default.dirname(m__default.dirname(s)),h=fe(m__default.relative(t,f)),w=p!==void 0&&!z(h),C=le(p?.name||m__default.basename(f),m__default.basename(f)),b=w?`external/${C}`:h||C,P=await k.readJson(s),a=typeof P.kit_name=="string"&&P.kit_name||typeof P.kit=="string"&&P.kit||void 0,E=j(P)?m$1(f,P):void 0,j$1=E!==void 0&&E.key!=="unknown",T=j$1?E.runtime:typeof P.runtime=="string"?P.runtime:void 0,y=j$1?E.key:typeof P.framework=="string"&&P.framework||Ae(a),$=p?.relationship==="adopted"?"adopted":"imported",K=j$1?`${$}.${E.key}`:a;u$1.push({slug:p?.name||b||m__default.basename(f),relativePath:b,source:p?.source??"workspace",relationship:p?.relationship,externalPath:w?f:void 0,runtime:T,framework:y,kit:K,modules:je(P.modules),ports:ue(P).length>0?ue(P):await be(f),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let d=new Map;for(let s of u$1){let p=le(s.slug,s.relativePath),f=d.get(p);(!f||f.source!=="workspace"&&s.source==="workspace")&&d.set(p,s);}return {schemaVersion:_,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...d.values()]}}async function dt(e){let t=m__default.resolve(e.outputPath||a$2(e.workspacePath,v));if(await k.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await he({workspacePath:e.workspacePath,now:e.now}),o=new Set,n={...r,projects:r.projects.map(c=>B(void 0,c,o).project)},i=await Pe({workspacePath:e.workspacePath,contractPath:t,contract:n});if(e.strict&&i.status==="failed")throw new N(i);return await ke({workspacePath:e.workspacePath,contractPath:t,contract:n,now:e.now}),{contractPath:t,contract:n}}async function lt(e){let t=m__default.resolve(e.workspacePath),r=a$2(t,v),o=await g(t,v)??r,n=await he({workspacePath:t,now:e.now}),i=await k.pathExists(o)?await k.readJson(o):null,c=new Map((i?.projects||[]).map(h=>[h.slug,h])),u=new Set,g$1=[],d=[],s=[];for(let h of n.projects){let w=c.get(h.slug),C=B(w,h,u);w?C.changed&&d.push(h.slug):g$1.push(h.slug),s.push(C.project),c.delete(h.slug);}for(let h of c.values()){if(h.source)continue;let w=B(h,h,u);s.push(w.project);}let p={schemaVersion:_,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...i?.workspace||{},...n.workspace,name:n.workspace.name||i?.workspace?.name||m__default.basename(t)},projects:s.sort((h,w)=>h.slug.localeCompare(w.slug))},f=await Pe({workspacePath:t,contractPath:r,contract:p});if(e.strict&&f.status==="failed")throw new N(f);return await ke({workspacePath:t,contractPath:r,contract:p,now:e.now}),{contractPath:r,contract:p,addedProjects:g$1,updatedProjects:d,verification:f}}async function me(e){return await k.pathExists(e)?{exists:true,contents:await k.readFile(e)}:{exists:false}}async function ge(e,t){if(!t.exists){await k.remove(e);return}await k.outputFile(e,t.contents);}async function ke(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-WKENOFEA.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),n=a$2(e.workspacePath,r),i=c=>{if(!c||typeof c!="object"||Array.isArray(c))return JSON.stringify(c);let{generatedAt:u,...g}=c;return JSON.stringify(g)};if(await k.pathExists(e.contractPath)&&await k.pathExists(n)){let[c,u]=await Promise.all([k.readJson(e.contractPath),k.readJson(n)]);if(i(c)===i(e.contract)&&i(u)===i(o))return}b(v,e.contract),b(r,o),await f(e.workspacePath,v,async()=>{let[c,u]=await Promise.all([me(e.contractPath),me(n)]);try{if(e.contractPath===a$2(e.workspacePath,v)?await h(e.workspacePath,v,e.contract):(await k.ensureDir(m__default.dirname(e.contractPath)),await k.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await h(e.workspacePath,r,o);}catch(g){let s=(await Promise.allSettled([ge(e.contractPath,c),ge(n,u)])).filter(p=>p.status==="rejected");throw s.length>0?new AggregateError([g,...s.map(p=>p.reason)],"Workspace contract publication failed and rollback was incomplete."):g}});}async function we(e){let t=e.contractPath??(await g(e.workspacePath,v)||a$2(e.workspacePath,v)),r=await k.readJson(t);return {contractPath:t,contract:r}}var xe={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function _e(e,t){return t.externalPath?m__default.resolve(t.externalPath):m__default.resolve(e,t.relativePath)}async function Ge(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(xe))for(let n of o)await k.pathExists(m__default.join(e,n))&&t[r].push(n);try{let r=await k.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,n)=>o.localeCompare(n));return t}function x(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function Oe(e){try{let t=await k.readJson(m__default.join(e,"package.json")),r={runtime:x(t.dependencies),development:x(t.devDependencies),peer:x(t.peerDependencies),optional:x(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:x(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function Ie(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await k.readFile(m__default.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,n)=>o.localeCompare(n))}catch{}return []}function Ne(e,t){try{let r=z$1(e);if(r.engine!=="unknown")return r;let o=k.pathExistsSync(m__default.join(e,"package.json"))?"npm":k.pathExistsSync(m__default.join(e,"pyproject.toml"))?"python":k.pathExistsSync(m__default.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",runtimeCandidates:["unknown"],compositeRuntime:false,lifecycleCoverage:"complete",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function De(e,t,r){let o=e.projects.map(n=>({id:n.slug,path:n.relativePath,runtime:n.runtime,framework:n.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function ut(e){let{contractPath:t,contract:r}=await we(e),o=e.now??new Date,n=o.toISOString(),{buildWorkspaceModel:i,workspaceModelProjectTopology:c}=await import('./workspace-model-5FA2636K.js'),{hashWorkspaceModel:u}=await import('./workspace-model-hash-ZXYPIGCW.js'),g=await i({workspacePath:e.workspacePath,includeEvidence:false,now:o}),d=c(g)??De(r,n,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(d.nodes.map(a=>[a.id,a.operationalProfile])),{buildWorkspaceKnowledgeGraph:p$1}=await import('./workspace-knowledge-graph-WNQMNAVL.js'),f=await p$1({workspacePath:e.workspacePath,workspace:{name:g.workspace.name,...g.workspace.profile?{profile:g.workspace.profile}:{}},contract:r,projectTopology:d,now:o,projects:g.projects.map(a=>({id:a.name,path:a.path,...a.absolutePath?{absolutePath:a.absolutePath}:{},runtime:a.runtime,runtimeCandidates:a.runtimeCandidates,framework:a.framework,...a.kit?{kit:a.kit}:{}})),source:{kind:"workspace-model",artifact:p.model,hashAlgorithm:"sha256",hash:u(g)}}),h=await Promise.all(r.projects.map(async a=>{let l=_e(e.workspacePath,a),[E,j,T]=await Promise.all([Ge(l),Oe(l),Ie(l)]),y=Ne(l,a);return {id:a.slug,label:a.slug,relativePath:a.relativePath,source:a.source,relationship:a.relationship,externalPath:a.externalPath,runtime:a.runtime??y.runtime,framework:a.framework??y.framework,kit:a.kit,modules:a.modules,ports:a.ports,apis:a.contracts.apis,owns:a.contracts.owns,env:[...new Set([...a.contracts.env,...T])].sort(($,K)=>$.localeCompare(K)),contracts:{owns:[...a.contracts.owns],apis:[...a.contracts.apis],publishes:[...a.contracts.publishes],consumes:[...a.contracts.consumes],dependsOn:[...a.contracts.dependsOn],env:[...a.contracts.env]},capabilities:{engine:y.engine,supportTier:y.frameworkSupportTier,runtimeSupportTier:y.runtimeSupportTier,doctorSupport:y.runtimeDoctorSupport,moduleSupport:y.moduleSupport,fleetStages:[...y.fleetStages],localOnlyCommands:[...y.localOnlyCommands],supportedCommands:[...y.supportedCommands]},files:E,...j?{package:j}:{},...s.get(a.slug)?{operationalProfile:s.get(a.slug)}:{}}})),w=new Set(h.map(a=>a.id)),C=new Map,b=[];for(let a of r.projects){for(let l of a.contracts.dependsOn||[])w.has(l)&&b.push({from:l,to:a.slug,type:"dependency",label:"dependsOn"});for(let l of a.contracts.publishes||[])C.has(l)||C.set(l,new Set),C.get(l)?.add(a.slug);}for(let a of r.projects)for(let l of a.contracts.consumes||[]){let E=C.get(l);if(E)for(let j of E)j!==a.slug&&b.push({from:j,to:a.slug,type:"event",label:l});}let P={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:n,nodes:h.sort((a,l)=>a.id.localeCompare(l.id)),edges:b.sort((a,l)=>`${a.from}:${a.to}:${a.type}:${a.label}`.localeCompare(`${l.from}:${l.to}:${l.type}:${l.label}`)),dependencyGraph:d,knowledgeGraph:f,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:h.length,dependencyEdges:b.filter(a=>a.type==="dependency").length,eventEdges:b.filter(a=>a.type==="event").length,portCount:h.reduce((a,l)=>a+l.ports.length,0),apiCount:h.reduce((a,l)=>a+l.apis.length,0),relationshipEdges:d.stats.edgeCount,inferredEdges:d.stats.inferredEdges,authoritativeEdges:d.stats.authoritativeEdges,orphanProjects:d.stats.orphanCount,hotspotProjects:d.stats.hotspotCount,evidenceCoverageRatio:d.stats.evidenceCoverageRatio,edgeCoverageRatio:d.stats.edgeCoverageRatio,connectedProjects:d.stats.connectedNodeCount,lowConfidenceEdges:d.stats.lowConfidenceEdges,hasCycle:d.stats.hasCycle,manifestCount:h.reduce((a,l)=>a+l.files.manifests.length,0),entrypointCount:h.reduce((a,l)=>a+l.files.entrypoints.length,0),diagnostics:d.diagnostics?.length??0,relationshipKinds:Object.fromEntries(pe.map(a=>[a,d.edges.filter(l=>l.kind===a).length])),relationshipSources:Object.fromEntries(de.map(a=>[a,d.edges.filter(l=>l.source===a).length])),entityCount:f.quality.entityCount,knowledgeRelations:f.quality.relationCount,proofCount:f.quality.proofCount,providerCount:f.providers.length,knowledgeUnknowns:f.quality.unknownCount}};return {contractPath:t,graph:P}}async function Pe(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,v),contract:e.contract}:await we(e),{contractPath:r,contract:o}=t,n=[],i=[];o.kind!=="rapidkit.workspace.contract"&&n.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==_&&n.push(`Contract schemaVersion must be ${_}.`),o.workspace?.name||n.push("Contract workspace.name is required."),Array.isArray(o.projects)||n.push("Contract projects must be an array.");let c=new Set,u=new Map;for(let s of o.projects||[]){if(!s.slug){n.push("Every project must declare slug.");continue}c.has(s.slug)&&n.push(`Duplicate project slug: ${s.slug}.`),c.add(s.slug),s.relativePath?z(s.relativePath)||n.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):n.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||n.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),m__default.isAbsolute(s.externalPath)||n.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let p of s.ports||[]){(!Number.isInteger(p.port)||p.port<1||p.port>65535)&&n.push(`Project ${s.slug} declares invalid port: ${p.port}.`);let f=u.get(p.port);f&&n.push(`Port ${p.port} is claimed by both ${f} and ${s.slug}.`),u.set(p.port,s.slug);}for(let p of s.contracts?.apis||[])(!p.name?.trim()||!p.basePath?.startsWith("/"))&&n.push(`Project ${s.slug} declares invalid API contract.`);for(let p of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])p.trim()||n.push(`Project ${s.slug} declares an empty event contract.`);for(let p of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(p)||n.push(`Project ${s.slug} declares invalid env contract: ${p}.`);for(let p of s.contracts?.dependsOn||[])c.has(p);}for(let s of o.projects||[])for(let p of s.contracts?.dependsOn||[])c.has(p)||n.push(`Project ${s.slug} depends on unknown project: ${p}.`);i.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===_?"passed":"failed",message:"Contract schema and kind are valid."}),i.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),i.push({id:"ports",status:n.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),i.push({id:"dependencies",status:n.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),i.push({id:"contracts",status:n.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let g=await l(e.workspacePath);if(g.moduleCount>0){for(let s of g.issues)n.push(`${m__default.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);i.push({id:"module-paths",status:g.status,message:g.status==="passed"?`All ${g.moduleCount} registered module(s) resolve under canonical paths.`:`${g.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&i.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:n.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:i,violations:n}}async function mt(e){let t=m__default.resolve(e.workspacePath),r={schemaVersion:ve,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return h(t,Ee,se(r))}
2
2
  export{I as a,He as b,Je as c,se as d,ze as e,pe as f,v as g,Ee as h,_ as i,ve as j,N as k,Se as l,he as m,dt as n,lt as o,we as p,ut as q,Pe as r,mt as s};
@@ -0,0 +1 @@
1
+ var ne="workspace-knowledge-search.v1";function m(e){return e.trim().toLowerCase()}var U=new WeakMap;function B(e){let t=U.get(e);if(t)return t;let a=new Map(e.relations.map(o=>[o.id,o])),s=new Map(e.entities.map(o=>[o.id,o])),r=new Map(e.proofs.map(o=>[o.id,o])),i=new Map,l=new Map,p=(o,u)=>{let g=l.get(o)??[];g.push(u),l.set(o,g);};for(let o of e.entities){let u=[o.id,o.label,o.identity.key,...o.kind==="project"&&o.projectId?[o.projectId]:[],...o.identity.aliases];for(let g of new Set(u.map(m))){let y=i.get(g)??[];y.push(o),i.set(g,y);}}for(let o of e.relations)p(o.from,{from:o.from,to:o.to,relationId:o.id,kind:o.kind,direction:"forward",proofIds:o.proofIds}),p(o.to,{from:o.to,to:o.from,relationId:o.id,kind:o.kind,direction:"reverse",proofIds:o.proofIds});for(let o of i.values())o.sort((u,g)=>u.id.localeCompare(g.id));for(let o of l.values())o.sort((u,g)=>u.to.localeCompare(g.to)||u.relationId.localeCompare(g.relationId));let d={entitiesById:s,relationsById:a,entitiesByAlias:i,proofsById:r,adjacency:l};return U.set(e,d),d}function D(e,t,a){let s=B(e),r=s.relationsById.get(t);if(r)return {found:true,targetType:"relation",relation:r};let i=m(t),l=(s.entitiesByAlias.get(i)??[]).filter(p=>!a||p.projectId===a);return l.length===1?{found:true,targetType:"entity",entity:l[0]}:{found:false,query:t,candidates:l.map(p=>p.id).sort()}}function Se(e,t,a){let s=D(e,t,a);if(!s.found)return {query:t,found:false,target:null,proofs:[],candidates:s.candidates};let r=s.targetType==="entity"?s.entity:s.relation,i=new Set(r.proofIds);return {query:t,found:true,target:r,candidates:[],proofs:[...i].map(l=>B(e).proofsById.get(l)).filter(l=>!!l).sort((l,p)=>l.id.localeCompare(p.id))}}function Ee(e,t,a,s){let r=D(e,t,s),i=D(e,a,s);if(!r.found||r.targetType!=="entity"||!i.found||i.targetType!=="entity")return {from:t,to:a,found:false,resolvedFrom:r.found&&r.targetType==="entity"?r.entity.id:null,resolvedTo:i.found&&i.targetType==="entity"?i.entity.id:null,entityPath:[],hops:[],proofs:[]};let l=B(e),p=[r.entity.id],d=new Map,o=new Set(p),u=0;for(;u<p.length&&!o.has(i.entity.id);){let f=p[u++];for(let h of l.adjacency.get(f)??[])o.has(h.to)||(o.add(h.to),d.set(h.to,h),p.push(h.to));}if(!o.has(i.entity.id))return {from:t,to:a,found:false,resolvedFrom:r.entity.id,resolvedTo:i.entity.id,entityPath:[],hops:[],proofs:[]};let g=[],y=i.entity.id;for(;y!==r.entity.id;){let f=d.get(y);if(!f)break;g.push(f),y=f.from;}g.reverse();let I=new Set(g.flatMap(f=>f.proofIds));return {from:t,to:a,found:true,resolvedFrom:r.entity.id,resolvedTo:i.entity.id,entityPath:[r.entity.id,...g.map(f=>f.to)],hops:g,proofs:[...I].map(f=>l.proofsById.get(f)).filter(f=>!!f).sort((f,h)=>f.id.localeCompare(h.id))}}function We(e,t,a){return e.entities.filter(s=>(!t||s.kind===t)&&(!a||s.projectId===a)).sort((s,r)=>s.kind.localeCompare(r.kind)||s.label.localeCompare(r.label))}var k={relations:12,relatedEntities:12,proofs:8,proofIdsPerItem:4,aliasesPerEntity:8,attributeArrayItems:8,attributeStringCharacters:256};function oe(e){let t=[],a=new Set;for(let s=0;s<k.proofIdsPerItem&&t.length<k.proofs;s+=1)for(let r of e){let i=r.proofIds[s];if(!(!i||a.has(i))&&(a.add(i),t.push(i),t.length>=k.proofs))break}return t}function se(e,t,a){let s=e.identity.aliases.slice(0,k.aliasesPerEntity);a.aliases+=e.identity.aliases.length-s.length;let r=Object.fromEntries(Object.entries(e.attributes).map(([l,p])=>{if(Array.isArray(p)){let d=p.slice(0,k.attributeArrayItems);return a.attributeValues+=p.length-d.length,[l,d]}return typeof p=="string"&&p.length>k.attributeStringCharacters?(a.attributeValues+=1,[l,p.slice(0,k.attributeStringCharacters)]):[l,p]})),i=e.proofIds.filter(l=>t.has(l)).slice(0,k.proofIdsPerItem);return a.proofReferences+=e.proofIds.length-i.length,{...e,identity:{...e.identity,aliases:s},attributes:r,proofIds:i}}function ae(e){let t=Object.values(e.attributes).flatMap(a=>Array.isArray(a)?a:[a]);return [e.id,e.kind,e.label,e.projectId??"",e.identity.key,...e.identity.aliases,...t.map(a=>String(a??""))].join(" ").toLowerCase()}var re=new Set(["a","an","and","are","as","at","be","been","being","by","can","check","could","did","do","does","find","for","from","give","had","has","have","how","i","in","into","is","it","its","may","might","of","on","or","our","show","should","that","the","their","them","then","there","these","they","this","those","tell","to","was","we","were","what","when","where","which","who","why","will","with","would","you","your"]),ie=new Map([["authenticate","auth"],["authenticated","auth"],["authentication","auth"],["authorization","auth"],["authorizing","auth"],["config","configuration"],["configs","configuration"],["dependencies","dependency"],["connected","connect"],["connecting","connect"],["connection","connect"],["connections","connect"],["diagnostics","diagnostic"],["reliable","reliability"],["tested","test"],["testing","test"],["tests","test"],["verification","verify"],["verified","verify"],["verifies","verify"],["verifying","verify"]]);function v(e){let t=a=>m(a).replace(/\bc\+\+/gu," cplusplus ").replace(/\bc#/gu," csharp ").split(/[^a-z0-9]+/u).filter(s=>s.length>1||s==="c"||s==="r").map(s=>ie.get(s)??s);return [...new Set([...t(e),...t(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2"))])]}function ce(e){let t=m(e.label),a=m(e.identity.key),s=e.identity.aliases.map(m),r=ae(e);return {entity:e,label:t,identity:a,aliases:s,haystack:r,labelTokens:new Set(v(e.label)),identityTokens:new Set(v(e.identity.key)),aliasTokens:new Set(e.identity.aliases.flatMap(v)),allTokens:new Set(v(r))}}function E(e,t){return e.has(t)||t.length>=3&&[...e].some(a=>a.startsWith(t))}function A(e,t){return E(e.labelTokens,t)||E(e.identityTokens,t)||E(e.aliasTokens,t)||E(e.allTokens,t)}function le(e,t,a,s){let{label:r,identity:i,aliases:l,haystack:p}=e,d=0;(r===t||i===t||l.includes(t))&&(d+=1e4),(r.startsWith(t)||i.startsWith(t))&&(d+=250),p.includes(t)&&(d+=100);let o=0;for(let u of a){let g=s.get(u)??1,y=E(e.labelTokens,u),I=E(e.identityTokens,u),f=E(e.aliasTokens,u),h=A(e,u);h&&(o+=1),r===u?d+=80*g:y&&(d+=36*g),I&&(d+=24*g),f&&(d+=20*g),h&&(d+=10*g);}return a.length>0&&(d+=o/a.length*120),d}function de(e,t){if(["build","compiled","dist","generated","fixture","fixtures","testdata","target","third","vendor","vendored"].some(i=>t.has(i)))return 0;let s=typeof e.attributes.artifact=="string"?e.attributes.artifact:"",r=`${e.label}/${e.identity.key}/${s}`.toLowerCase();return /(?:^|\/)(?:__fixtures__|__testfixtures__|build|compiled|dist|fixture|fixtures|generated|node_modules|target|testdata|third_party|vendor)(?:\/|$)/u.test(r)?5e3:0}function F(e,t){let a=new Set;for(let s of t){let r=e.allTokens.has(s)?s:void 0,i=r===void 0&&s.length>=3?[...e.allTokens].find(p=>p.startsWith(s)&&!a.has(p)):void 0,l=r??i;l&&!a.has(l)&&a.add(l);}return a.size}var pe=new Map([["c","c"],["clojure","clojure"],["cplusplus","cpp"],["cpp","cpp"],["typescript","typescript"],["ts","typescript"],["javascript","javascript"],["js","javascript"],["nodejs","javascript"],["python","python"],["py","python"],["go","go"],["golang","go"],["csharp","csharp"],["ada","ada"],["assembly","assembly"],["asm","assembly"],["cuda","cuda"],["dotnet","csharp"],["dart","dart"],["elixir","elixir"],["fsharp","fsharp"],["fortran","fortran"],["java","java"],["kotlin","kotlin"],["hlsl","hlsl"],["llvmir","llvm-ir"],["mlir","mlir"],["lua","lua"],["php","php"],["r","r"],["ruby","ruby"],["rust","rust"],["tablegen","tablegen"],["scala","scala"],["svelte","svelte"],["swift","swift"],["vue","vue"]]);function ge(e){return new Set(e.map(t=>pe.get(t)).filter(t=>!!t))}function $(e){let t=e.attributes.language;return typeof t=="string"?m(t):null}function he(e){return {project:1e3,service:900,api:900,package:850,endpoint:800,container:700,deployment:700,environment:650,pipeline:600,"test-suite":550,owner:500,decision:450,document:400}[e.kind]??0}var ue=new Set(["language","languages","binding","bindings","bridge","bridges","dependency","dependencies","depends","core","runtime","owner","owners","ownership","maintainer","ci","pipeline","pipelines","workflow","deploy","deployment","infrastructure","container","doc","docs","document","documentation","service","services","api","rpc","schema","schemas","message","protobuf","proto","contract"]),fe=new Set(["app","application","applications","call","calls","code","communicate","communication","connect","define","defined","expose","exposed","handle","handled","implement","implementation","integrate","integration","interact","interaction","project","provide","provided","system","use","used","uses","using"]);function ye(e){return ue.has(e)||fe.has(e)}function we(e,t){let a=t.has("language")||t.has("languages"),s=t.has("binding")||t.has("bindings")||t.has("bridge")||t.has("bridges"),r=t.has("dependency")||t.has("dependencies")||t.has("depends"),i=t.has("core")||t.has("runtime"),l=t.has("owner")||t.has("owners")||t.has("ownership")||t.has("maintainer"),p=t.has("ci")||t.has("pipeline")||t.has("pipelines")||t.has("workflow"),d=t.has("deploy")||t.has("deployment")||t.has("infrastructure")||t.has("container"),o=t.has("doc")||t.has("docs")||t.has("document")||t.has("documentation"),u=t.has("service")||t.has("services")||t.has("api")||t.has("rpc"),g=t.has("schema")||t.has("schemas")||t.has("message")||t.has("protobuf")||t.has("proto")||t.has("contract"),y=typeof e.attributes.mechanism=="string"?m(e.attributes.mechanism):"",I=typeof e.attributes.specification=="string"?m(e.attributes.specification):"",f=m(e.label),h=0;if(a&&e.kind==="language"){let O=typeof e.attributes.fileCount=="number"?e.attributes.fileCount:0;h+=900+Math.min(O,1e4)/10;}return s&&e.kind==="protocol"&&(h+=800),r&&e.kind==="package"&&(h+=650),i&&e.kind==="package"&&/(?:^|[_-])core(?:$|[_-])/u.test(f)&&(h+=700),i&&e.kind==="protocol"&&y.includes("core")&&(h+=300),l&&e.kind==="owner"&&(h+=850),p&&e.kind==="pipeline"&&(h+=800),d&&["deployment","container","environment"].includes(e.kind)&&(h+=775),o&&["document","decision"].includes(e.kind)&&(h+=725),u&&["api","endpoint","service"].includes(e.kind)&&(h+=700),g&&(e.kind==="schema"||(e.kind==="api"||e.kind==="protocol")&&(I.includes("protobuf")||y.includes("protobuf")))&&(h+=750),h}function ke(e){return [e.has("language")||e.has("languages"),e.has("binding")||e.has("bindings")||e.has("bridge")||e.has("bridges"),e.has("dependency")||e.has("dependencies")||e.has("depends"),e.has("core")||e.has("runtime"),e.has("owner")||e.has("ownership")||e.has("maintainer"),e.has("ci")||e.has("pipeline")||e.has("workflow"),e.has("deploy")||e.has("deployment")||e.has("infrastructure"),e.has("doc")||e.has("docs")||e.has("documentation"),e.has("service")||e.has("api")||e.has("rpc"),e.has("schema")||e.has("protobuf")||e.has("proto")||e.has("contract")].filter(Boolean).length>=3}function Te(e,t){let a=m(t.query),s=[...new Set(v(t.query))],r=new Set(v(t.projectId??"")),i=t.projectId?s.filter(n=>!r.has(n)):s,l=!!(t.projectId&&s.length>0&&i.length===0),p=i.filter(n=>!re.has(n)),d=p.length>0?p:i,o=ge(d),u=new Set(d),g=d.filter(n=>!ye(n)),y=ke(u),I=d.length<=1?d.length:Math.min(2,Math.ceil(d.length/3)),f=t.minimumTermMatches===void 0?I:Math.min(I,Math.max(1,Math.trunc(t.minimumTermMatches))),h=Math.max(1,Math.min(Math.trunc(t.limit??12),100)),O=Math.max(0,Math.min(Math.trunc(t.relationsPerEntity??4),20)),G=new Set;if(t.projectId){let n=new Set(e.entities.filter(c=>c.kind==="project"&&(c.projectId===t.projectId||c.label===t.projectId)).map(c=>c.id));for(let c of e.relations)n.has(c.from)&&G.add(c.to),n.has(c.to)&&G.add(c.from);}let P=e.entities.filter(n=>(!t.kind||n.kind===t.kind)&&(!t.projectId||n.projectId===t.projectId||n.projectId===void 0&&G.has(n.id))).map(ce),Y=new Map(d.map(n=>{let c=P.filter(w=>A(w,n)).length;return [n,Math.log((P.length+1)/(c+1))+1]})),X=g.some(n=>P.some(c=>A(c,n))),M=P.map(n=>{let c=F(n,d),w=F(n,g),b=$(n.entity),S=b&&o.has(b)?400:0,_=we(n.entity,u),j=g.length===0||g.some(te=>A(n,te))?_:0;return {entity:n.entity,matchedTerms:c,matchedQualifiers:w,intentScore:j,score:l?he(n.entity):le(n,a,d,Y)+w*300+S+j-de(n.entity,u)}}).filter(n=>{let c=$(n.entity);return (o.size===0||c===null||o.has(c))&&(a.length===0||n.score>0&&(!X||g.length===0||n.matchedQualifiers>0)&&(l||n.matchedTerms>=f||n.intentScore>0&&(y||d.length<=2)))}).sort((n,c)=>c.score-n.score||n.entity.kind.localeCompare(c.entity.kind)||n.entity.label.localeCompare(c.entity.label)),W=(y?(()=>{let n=[],c=[],w=new Map,b=new Set;for(let S of M){let _=w.get(S.entity.kind)??0,j=m(S.entity.label);_<2&&!b.has(j)?(n.push(S),w.set(S.entity.kind,_+1),b.add(j)):c.push(S);}return [...n,...c]})():M).slice(0,h).map(n=>n.entity),R=new Set(W.map(n=>n.id)),L=new Map,H=e.relations.filter(n=>{if(!(R.has(n.from)||R.has(n.to)))return false;let w=R.has(n.from)?n.from:n.to,b=L.get(w)??0;return b>=O?false:(L.set(w,b+1),true)}),K=t.projection==="agent",T=K?H.slice(0,k.relations):H,z=B(e),N=[...new Set(T.flatMap(n=>[n.from,n.to]).filter(n=>!R.has(n)))].map(n=>z.entitiesById.get(n)).filter(n=>!!n).map(({id:n,kind:c,label:w,projectId:b})=>({id:n,kind:c,label:w,...b?{projectId:b}:{}})).sort((n,c)=>n.kind.localeCompare(c.kind)||n.label.localeCompare(c.label)),Q=K?N.slice(0,k.relatedEntities):N,q=new Set([...W.flatMap(n=>n.proofIds),...T.flatMap(n=>n.proofIds)]),Z=K?oe([...W,...T]):[...q],x=new Set(Z),C={entities:M.length-W.length,relations:H.length-T.length,relatedEntities:N.length-Q.length,proofs:q.size-x.size,proofReferences:0,aliases:0,attributeValues:0},V=K?W.map(n=>se(n,x,C)):W,J=K?T.map(n=>{let c=n.proofIds.filter(w=>x.has(w)).slice(0,k.proofIdsPerItem);return C.proofReferences+=n.proofIds.length-c.length,{...n,proofIds:c}}):T,ee=[...x].map(n=>z.proofsById.get(n)).filter(n=>!!n).sort((n,c)=>n.id.localeCompare(c.id));return {schemaVersion:ne,graphSourceHash:e.source.hash,query:t.query,kind:t.kind??null,...t.projectId?{projectId:t.projectId}:{},limit:h,totalMatches:M.length,truncated:M.length>V.length||K&&Object.values(C).some(n=>n>0),entities:V,relatedEntities:Q,relations:J,proofs:ee,...K?{budget:{mode:"agent",limits:{...k},omitted:C}}:{}}}export{ne as a,D as b,Se as c,Ee as d,We as e,Te as f};
@@ -1 +1 @@
1
- export{b as buildWorkspaceManifest,f as createProject,a as initializeStandaloneGitRepository,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,c as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-LOXR5QUX.js';
1
+ export{b as buildWorkspaceManifest,f as createProject,a as initializeStandaloneGitRepository,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,c as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-4PDEWMOG.js';
@@ -1 +1 @@
1
- export{d as DOCTOR_WORKSPACE_REPORT_PATH,q as applyEnvKeyAddFix,m as applyFileAppendFix,n as applyFileCopyFix,l as applyFileCreateFix,p as applyJsonEditFix,r as applyMakefileTargetFix,k as applyPackageScriptFix,i as assertOperationPathInsideProject,j as assertOperationPathInsideProjectResolved,h as buildRepairOperationIdentity,t as computeDoctorFixAwareExitCode,s as computeDoctorGateExitCode,o as decodeJsonPointerSegment,g as parseInternalRepairCommand,f as parsePackageScriptFix,e as resolveDoctorPolicyProfile,u as runDoctor}from'./chunk-CX6PAQTQ.js';
1
+ export{d as DOCTOR_WORKSPACE_REPORT_PATH,q as applyEnvKeyAddFix,m as applyFileAppendFix,n as applyFileCopyFix,l as applyFileCreateFix,p as applyJsonEditFix,r as applyMakefileTargetFix,k as applyPackageScriptFix,i as assertOperationPathInsideProject,j as assertOperationPathInsideProjectResolved,h as buildRepairOperationIdentity,t as computeDoctorFixAwareExitCode,s as computeDoctorGateExitCode,o as decodeJsonPointerSegment,g as parseInternalRepairCommand,f as parsePackageScriptFix,e as resolveDoctorPolicyProfile,u as runDoctor}from'./chunk-RQKDJVX3.js';
@@ -1 +1 @@
1
- export{f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,k as buildGoalLifecycleResult,l as inspectGoalLifecycle,q as linkGoalChangeTransaction,p as linkGoalRepairTransaction,n as prepareGoalVerification,m as transitionGoalLifecycle,o as verifyGoalLifecycle}from'./chunk-H64KAPJJ.js';
1
+ export{f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,k as buildGoalLifecycleResult,l as inspectGoalLifecycle,q as linkGoalChangeTransaction,p as linkGoalRepairTransaction,n as prepareGoalVerification,m as transitionGoalLifecycle,o as verifyGoalLifecycle}from'./chunk-5NL53T5C.js';
@@ -1 +1 @@
1
- import {c as c$3}from'./chunk-GL3KLNIG.js';import {c}from'./chunk-K2LKJBQ4.js';import {j,i,d as d$1,f as f$1,c as c$2,e,h}from'./chunk-H64KAPJJ.js';export{b as GOAL_AGENT_HANDOFF_SCHEMA_VERSION,f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,g as GOAL_LIFECYCLE_RESULT_SCHEMA_VERSION,d as GOAL_PACK_LAST_RUN_PATH,a as GOAL_PACK_SCHEMA_VERSION,c as GOAL_PLAN_RESULT_SCHEMA_VERSION}from'./chunk-H64KAPJJ.js';import {f as f$2}from'./chunk-EZPLMAW2.js';import {a as a$1}from'./chunk-XY537LCX.js';import {b}from'./chunk-EBQS5T7Q.js';import {b as b$1}from'./chunk-FFE2JZZJ.js';import {f,i as i$1}from'./chunk-FE5R6EUV.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {q,p}from'./chunk-ODK4LCEL.js';import C from'path';import _ from'fs-extra';var ve=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/,ye=/(?:^|\s)(?:\/(?:home|Users|private|var|tmp|mnt|opt|srv|root|workspace|workspaces|data|Volumes|etc|usr|run|dev|proc|sys)\/[^\s]+|[A-Za-z]:[\\/][^\s]+|\\\\[^\\\s]+\\[^\s]+)/,Pe=/(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:github_pat_|gh[pousr]_|glpat-|npm_|xox[baprs]-|sk-(?:proj-)?)[A-Za-z0-9_-]{12,}|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[A-Za-z0-9_-]{20,}|\bBearer\s+[A-Za-z0-9._~+/-]{16,}|[a-z][a-z0-9+.-]*:\/\/[^\s:/]+:[^\s@/]+@|\b(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^\s]{6,})/i,je=[{category:"test-coverage",patterns:[/\b(?:test\s+)?coverage\b/i,/\bcoverage\s+(?:to|above|at least)\b/i]},{category:"dependency-security",patterns:[/\b(?:dependency|dependencies|package|packages)\b.*\b(?:security|vulnerab|audit)\b/i,/\b(?:security|vulnerab|audit)\b.*\b(?:dependency|dependencies|package|packages)\b/i]},{category:"release-readiness",patterns:[/\brelease[ -]readiness\b/i,/\bready (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare\b[^\n]{0,80}\bfor release\b/i]},{category:"defect-repair",patterns:[/\b(?:fix|repair|resolve|debug)\b.*\b(?:bug|error|failure|issue|regression)\b/i]},{category:"performance",patterns:[/\b(?:performance|latency|throughput|cpu|optimi[sz]e|faster|slower)\b/i,/\b(?:memory\s+(?:allocation|consumption|footprint|leak|pressure|usage)|out[ -]of[ -]memory|heap|ram)\b/i]},{category:"refactor",patterns:[/\b(?:refactor|restructure|decouple|extract|simplify|cleanup|clean up)\b/i]},{category:"documentation",patterns:[/\b(?:document|documentation|readme|guide|tutorial|docs)\b/i]},{category:"feature-change",patterns:[/\b(?:add|build|create|enforce|enhance|harden|implement|improve|introduce|support)\b/i]},{category:"system-understanding",patterns:[/\b(?:understand|explain|map|find|where|how|architecture|analy[sz]e|search)\b/i]}];function Ge(e){if(typeof e!="string")throw new Error("Goal intent must be text.");let t=e.trim().replace(/\s+/g," ");if(!t)throw new Error("Goal intent cannot be empty.");if(t.length>2e3)throw new Error("Goal intent exceeds the 2000 character safety limit.");if(ve.test(t))throw new Error("Goal intent contains unsupported control characters.");if(ye.test(t))throw new Error("Goal intent contains a machine-local absolute path. Use a workspace-relative path or project scope.");if(Pe.test(t))throw new Error("Goal intent appears to contain secret material and was not persisted.");return t}function Ce(e){let t=e.match(/\b(?:coverage\D{0,24})?((?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?))\s*(?:%|percent(?:age)?(?:\s+points?)?)/i);if(!t||!/coverage/i.test(e))return null;let r=Number(t[1]);return Number.isFinite(r)&&r>=0&&r<=100?r:null}var re=[{runtime:"cpp",patterns:[/\bc\+\+/i,/\bcpp\b/i]},{runtime:"dotnet",patterns:[/\.net\b/i,/\bdotnet\b/i,/\bc#/i,/\bcsharp\b/i]},{runtime:"node",patterns:[/\bnode(?:\.js)?\b/i,/\btypescript\b/i,/\bjavascript\b/i,/\b(?:js|ts)\b/i]},{runtime:"python",patterns:[/\bpython\b/i,/\bpytest\b/i]},{runtime:"go",patterns:[/\bgolang\b/i,/\bgo(?:\s+(?:test|coverage|tests))\b/i]},{runtime:"java",patterns:[/\bjava\b/i,/\bjunit\b/i,/\bjacoco\b/i]},{runtime:"rust",patterns:[/\brust\b/i,/\bcargo\b/i]},{runtime:"php",patterns:[/\bphp\b/i,/\bphpunit\b/i]},{runtime:"ruby",patterns:[/\bruby\b/i,/\brspec\b/i]},{runtime:"kotlin",patterns:[/\bkotlin\b/i]},{runtime:"scala",patterns:[/\bscala\b/i]},{runtime:"clojure",patterns:[/\bclojure\b/i]},{runtime:"elixir",patterns:[/\belixir\b/i]},{runtime:"deno",patterns:[/\bdeno\b/i]},{runtime:"bun",patterns:[/\bbun\b/i]},{runtime:"c",patterns:[/\bc(?:\s+(?:test|coverage|tests|code))\b/i]}];function Ae(e){return re.filter(t=>t.patterns.some(r=>r.test(e))).map(t=>t.runtime)}function K(e,t={}){let r=Ge(e),n=je.filter(u=>u.patterns.some(j=>j.test(r))).map(u=>u.category),a=n.some(u=>u!=="feature-change")?n.filter(u=>u!=="feature-change"):n,s=a[0]??"feature-change",l=Ce(r),d=Ae(r),p=d.length===0&&t.selectedCoverageRuntime?[t.selectedCoverageRuntime]:d,m=[...new Set((t.availableCoverageRuntimes??[]).filter(u=>re.some(j=>j.runtime===u)))].sort(),b=[];return a.length>1&&a[0]!=="test-coverage"&&b.push(`The intent also contains signals for: ${a.slice(1).join(", ")}.`),s==="test-coverage"&&l===null&&b.push("A numeric test coverage target is required for machine verification."),s==="test-coverage"&&p.length>1&&b.push(`The Goal names multiple coverage runtimes: ${p.join(", ")}. Select one runtime per Goal.`),s==="test-coverage"&&p.length===0&&m.length>1&&b.push(`Coverage scope is ambiguous across detected runtimes: ${m.join(", ")}. Name one runtime or language in the Goal.`),s==="test-coverage"&&p.length===1&&m.length>0&&!m.includes(p[0])&&b.push(`The requested ${p[0]} coverage runtime is not present in the selected scope. Detected runtimes: ${m.join(", ")}.`),{original:r,normalized:r.toLocaleLowerCase("en-US"),statement:r.replace(/[.!?]+$/,""),category:s,confidence:a.length===1?"high":a.length>1?"medium":"low",ambiguities:b,...l===null?{}:{requestedTarget:{metric:"test-coverage-percent",operator:"at-least",value:l,...p.length===1?{runtime:p[0]}:{}}}}}function oe(e){let t={"test-coverage":["test suite coverage configuration instrumentation","CI tests LCOV Cobertura JaCoCo LLVM coverage"],"dependency-security":["dependency manifest lockfile security audit vulnerability"],"release-readiness":["release pipeline readiness gates build test deploy"],"defect-repair":["failure error test implementation call path"],"feature-change":["API implementation module dependency tests"],refactor:["module dependency ownership implementation tests"],performance:["performance benchmark latency throughput runtime"],documentation:["documentation README guide architecture decision"],"system-understanding":["architecture service API dependency ownership"]};return [...new Set([e.statement,...t[e.category]])].slice(0,3)}var ae="contracts/workspace-intelligence/goal-pack.v1.json",se="contracts/workspace-intelligence/goal-agent-handoff.v1.json",Re="contracts/workspace-intelligence/goal-plan-result.v1.json",pe="contracts/workspace-intelligence/goal-index.v1.json",ue=new Set(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"]);function Se(e,t){let r=e.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)??[],n=new Set(t.map(m=>m.toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"")).filter(Boolean)),a=[];for(let m=0;m<r.length;){let b=0;for(let u=Math.min(4,r.length-m);u>=1;u-=1){let j=r.slice(m,m+u).join("").toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"");if(n.has(j)){b=u;break}}if(b>0){m+=b;continue}a.push(r[m]),m+=1;}let s=a.findIndex((m,b)=>{let u=m.toLocaleLowerCase("en-US"),j=a[b+1]?.toLocaleLowerCase("en-US");return u==="without"&&["breaking","changing","modifying","removing"].includes(j??"")||u==="while"&&["keeping","maintaining","preserving"].includes(j??"")}),l=s>=2?a.slice(0,s):a,d=l.length>=2?l.join(" "):e;if(s<2)return [d];let p=a.slice(s).filter(m=>!["without","while","breaking","changing","modifying","removing","keeping","maintaining","preserving"].includes(m.toLocaleLowerCase("en-US")));return p.length>0?[d,p.join(" ")]:[d]}function ie(e){return e.split(C.sep).join("/")}function V(e,t){return C.resolve(t.absolutePath??C.join(e,t.path))}function ce(e){let t=e.requested.trim().replace(/^project:/,"");if(!t)throw new Error("Project goal scope must name a project.");let r=C.isAbsolute(t)?C.resolve(t):null,n=e.model.projects.filter(a=>a.name===t||ie(a.path)===ie(t)||r!==null&&V(e.workspacePath,a)===r);if(n.length!==1)throw new Error(n.length===0?`Project goal scope was not found in the canonical model: ${t}`:`Project goal scope is ambiguous in the canonical model: ${t}`);return n[0]}async function Ee(e){let t=await a$1(e);if(t.status==="miss")throw new Error(`Canonical model and live graph evidence are required (${t.reason}). Run \`workspai workspace intelligence run --for-agent generic --strict --json\` or retry with --refresh.`);let{model:r,graph:n}=t;return a(r,"contracts/workspace-intelligence/workspace-model.v1.json","Goal source model"),a(n,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Goal source graph"),b$1(n,r),{model:r,graph:n}}function le(e){let t=e.scope.trim();if(t==="workspace")return {kind:"workspace",projects:e.model.projects.map(n=>n.name).sort(),selectionSource:e.selectionSource,resolution:"selected"};let r=t.startsWith("projects:")?"projects:":t.startsWith("project:")&&t.slice(8).includes(",")?"project:":null;if(r){let n=t.slice(r.length).split(",").map(l=>l.trim()).filter(Boolean);if(n.length<2)throw new Error("A project-set Goal scope must name at least two projects.");let a=n.map(l=>ce({workspacePath:e.workspacePath,model:e.model,requested:l})),s=[...new Set(a.map(l=>l.name))].sort();if(s.length!==n.length)throw new Error("A project-set Goal scope must not contain duplicate projects.");return {kind:"project-set",projects:s,selectionSource:e.selectionSource,resolution:"selected"}}if(t)return {kind:"project",projects:[ce({workspacePath:e.workspacePath,model:e.model,requested:t}).name],selectionSource:e.selectionSource,resolution:"selected"};throw new Error("Goal scope cannot be empty.")}async function Ie(e){if(e.explicitScope?.trim())return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:e.explicitScope,selectionSource:"explicit"}),selectionRequired:false};if(e.invocationProjectPath){let t=C.resolve(e.invocationProjectPath),r=e.model.projects.filter(n=>V(e.workspacePath,n)===t);if(r.length!==1)throw new Error("The invocation project is not represented uniquely in the canonical workspace model. Refresh intelligence or pass --scope explicitly.");return {scope:{kind:"project",projects:[r[0].name],selectionSource:"invocation-project",resolution:"selected"},selectionRequired:false}}if(e.model.projects.length===1)return {scope:{kind:"project",projects:[e.model.projects[0].name],selectionSource:"single-project-workspace",resolution:"selected"},selectionRequired:false};if(e.selectScope){let t=await e.selectScope({workspaceName:e.model.workspace.name,projects:e.model.projects.map(n=>({name:n.name,runtime:n.runtime,runtimeCandidates:[...n.runtimeCandidates].sort(),framework:n.framework})).sort((n,a)=>n.name.localeCompare(a.name))}),r=t.kind==="workspace"?"workspace":t.projects.length===1?`project:${t.projects[0]}`:`projects:${t.projects.join(",")}`;return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:r,selectionSource:"interactive"}),selectionRequired:false}}return {scope:{kind:"workspace",projects:e.model.projects.map(t=>t.name).sort(),selectionSource:"workspace",resolution:"selection-required"},selectionRequired:true}}function Te(e,t){if(t.kind==="workspace")return {entities:e.quality.entityCount,relationships:e.quality.relationCount,proofs:e.quality.proofCount,unresolved:e.quality.unknownCount,proofCoveragePercent:Number((e.quality.relationProofCoverageRatio*100).toFixed(2))};let r=new Set(t.projects),n=e.entities.filter(p=>p.projectId!==void 0&&r.has(p.projectId)),a=new Set(n.map(p=>p.id)),s=e.relations.filter(p=>a.has(p.from)||a.has(p.to)),l=new Set([...n.flatMap(p=>p.proofIds),...s.flatMap(p=>p.proofIds)]),d=s.filter(p=>p.proofIds.length>0).length;return {entities:n.length,relationships:s.length,proofs:l.size,unresolved:s.length-d,proofCoveragePercent:s.length===0?100:Number((d/s.length*100).toFixed(2))}}function xe(e){let t=new Map;for(let n of e){let a=t.get(n.kind)??[];a.push(n),t.set(n.kind,a);}let r=[];for(let n=0;[...t.values()].some(a=>n<a.length);n+=1)for(let a of t.values()){let s=a[n];s&&r.push(s);}return r}async function _e(e){let t=C.join(e.workspacePath,p.intelligenceRun),r=await _.readJson(t).catch(()=>null),a=(Array.isArray(r?.stages)?r.stages:[]).filter(o=>o.status==="blocked"||o.status==="failed").map(o=>String(o.id??"unknown")).sort(),s=r?.status,l={status:s==="passed"?"passed":s==="blocked"||s==="failed"?"blocked":"unknown",artifact:p.intelligenceRun,blockedStages:a},d={status:"not-applicable",runtime:null,runtimeChoices:[],runner:null,existingEvidence:[],prerequisites:[]};if(e.intent.category==="test-coverage"){let o=e.intent.requestedTarget?.runtime;if(e.intent.ambiguities.some(P=>P.startsWith("Coverage scope is ambiguous")||P.startsWith("The Goal names multiple coverage runtimes")||P.startsWith("The selected projects do not share a common canonical coverage runtime")||P.startsWith("The requested ")))d={status:"requires-setup",runtime:o??null,runtimeChoices:e.coverageRuntimeChoices,runner:null,existingEvidence:[],prerequisites:["Select exactly one detected runtime or language for this coverage Goal."]};else {let P=o?e.projects.filter(c=>c.runtimeCandidates.includes(o)):e.projects,i=await Promise.all(P.map(async c=>({project:c,capability:await c$3(V(e.workspacePath,c),o??(ue.has(c.runtime)?c.runtime:"unknown"))}))),h=i.map(c=>c.capability.status);d={status:h.includes("unsupported")?"unsupported":h.includes("requires-setup")?"requires-setup":"available",runtime:i.length===1?i[0].capability.runtime:[...new Set(i.map(c=>c.capability.runtime))].join(","),runtimeChoices:e.coverageRuntimeChoices,runner:i.length===1?i[0].capability.runner:[...new Set(i.flatMap(c=>c.capability.runner?[c.capability.runner]:[]))].join(",")||null,existingEvidence:i.flatMap(c=>c.capability.existingEvidence.map(A=>({project:c.project.name,...A}))).filter((c,A,w)=>w.findIndex(k=>k.project===c.project&&k.path===c.path&&k.sha256===c.sha256)===A).sort((c,A)=>c.project.localeCompare(A.project)||c.path.localeCompare(A.path)),prerequisites:[...new Set(i.flatMap(c=>c.capability.prerequisites))].sort()};}}let p$1=oe(e.intent),m=[...Se(p$1[0],e.projects.map(o=>o.name)),...p$1.slice(1)].filter((o,y,P)=>P.indexOf(o)===y).slice(0,3),b=m.map((o,y)=>{let P=o.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)?.length??0,i=y===0&&P>=4?2:1,h=e.projects.map(w=>{let k=G=>f$2(e.graph,{query:o,projectId:w.name,...G?{kind:G}:{},limit:60,relationsPerEntity:0,minimumTermMatches:i}).entities,S=k(),de=[...new Set(e.graph.entities.filter(G=>G.projectId===w.name||G.projectId===void 0&&G.identity.scope==="workspace").map(G=>G.kind))].flatMap(G=>k(G).slice(0,8)),U=[...S,...de];return U.filter((G,me)=>U.findIndex(ge=>ge.id===G.id)===me)}),c=[],A=new Set;for(let w=0;h.some(k=>w<k.length);w+=1)for(let k of h){let S=k[w];!S||A.has(S.id)||(A.add(S.id),c.push(S));}return xe(c)}),u={"test-coverage":["test-suite"],"dependency-security":["package","module"],"release-readiness":["pipeline","deployment","lifecycle-stage"],"defect-repair":["test-suite","lifecycle-stage"],"feature-change":["project","runtime-unit","api","package","module","test-suite"],refactor:["package","module","api","test-suite"],performance:["lifecycle-stage","test-suite","pipeline"],documentation:["document","decision"],"system-understanding":["project","service","api","package","protocol"]},j=new Set(e.projects.map(o=>o.name)),v=e.graph.entities.filter(o=>o.proofIds.length>0&&(!o.projectId||j.has(o.projectId))&&u[e.intent.category].includes(o.kind)).sort((o,y)=>u[e.intent.category].indexOf(o.kind)-u[e.intent.category].indexOf(y.kind)||o.label.localeCompare(y.label)),f=[],M=new Set,E=o=>{!o||f.length>=20||M.has(o.id)||(M.add(o.id),f.push(o));},I=(e.intent.statement.match(/[A-Za-z][A-Za-z0-9+#.-]{1,}/g)??[]).length>=2,g=I?b[0]??[]:[];for(let o of g.slice(0,12))E(o);if(!I)for(let o of v)E(o);for(let o=0;f.length<20&&b.slice(1).some(y=>o<y.length);o+=1)for(let y of b.slice(1))E(y[o]);if(I)for(let o of v)E(o);for(let o of g.slice(12))E(o);let T=f.map(o=>({entityId:o.id,kind:o.kind,label:o.label,proofIds:o.proofIds.slice(0,12)})),L=b[0]?.length??0;return {workspaceIntelligence:l,measurement:d,retrieval:{status:I&&L>=3?"grounded":T.length>0?"partial":"empty",strategy:"deterministic-category-v1",queries:m,anchors:T}}}async function Le(e$1){let t=C.join(e$1,f$1);if(!await _.pathExists(t))return {schemaVersion:e,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let r=await _.readJson(t);a(r,pe,"Goal index");try{i(r);}catch(n){let a=h(r);if(!(a!==null&&n instanceof Error&&n.message==="Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")||!a)throw n;return a}return r}function Ne(e$1,t,r){let n=e$1.goals.find(l=>l.id===t.id),a=t.state==="ready-to-plan",s={id:t.id,fingerprint:t.fingerprint,objective:t.intent.statement,category:t.intent.category,state:t.state,lifecycle:n?.lifecycle==="cancelled"?"cancelled":a?"active":"planned",scope:t.scope,createdAt:n?.createdAt??t.generatedAt,updatedAt:r,goalPack:t.artifacts.goalPack,agentHandoff:t.artifacts.agentHandoff,...n?.verifiedGoalId?{verifiedGoalId:n.verifiedGoalId}:{},...n?.repairTransactionId?{repairTransactionId:n.repairTransactionId}:{},...n?.repairTransactionIds?{repairTransactionIds:n.repairTransactionIds}:{},...n?.changeTransactionId?{changeTransactionId:n.changeTransactionId}:{},...n?.changeTransactionIds?{changeTransactionIds:n.changeTransactionIds}:{},...n?.verificationReceipt?{verificationReceipt:n.verificationReceipt}:{}};return {schemaVersion:e,generatedAt:r,activeGoalId:s.lifecycle==="active"?t.id:e$1.activeGoalId===t.id?null:e$1.activeGoalId,goals:[...e$1.goals.filter(l=>l.id!==t.id).map(l=>s.lifecycle==="active"&&l.lifecycle==="active"?{...l,lifecycle:"planned",updatedAt:r}:l),s].sort((l,d)=>l.id.localeCompare(d.id))}}async function et(e){let t=b({startPath:C.resolve(e.startPath),explicitWorkspacePath:e.workspacePath,strict:true,requireProjectMembership:true});if(!t)throw new Error("No canonical Workspai workspace could be resolved.");let r=C.resolve(t.workspacePath);e.refresh&&await c({workspacePath:r,strict:false,agent:"generic"});let{model:n,graph:a$1}=await Ee(r),s=await Ie({workspacePath:r,invocationProjectPath:t.projectPath,model:n,explicitScope:e.scope,selectScope:e.selectScope}),l=s.scope,d$2=n.projects.filter(i=>l.projects.includes(i.name));if(d$2.length===0)throw new Error("A Goal Pack requires at least one registered project in its selected scope.");let p$1=e.maxAttempts??5;if(!Number.isInteger(p$1)||p$1<1||p$1>25)throw new Error("--max-attempts must be an integer from 1 to 25.");let m=new Date().toISOString(),b$1=d(n),u=d$2.map(i=>({name:i.name,runtimes:[...new Set(i.runtimeCandidates.filter(h=>ue.has(h)))].sort()})),j$1=[...new Set(u.flatMap(i=>i.runtimes))].sort(),v=u.length<=1?j$1:u[0].runtimes.filter(i=>u.every(h=>h.runtimes.includes(i))),f$2=K(e.intent,{availableCoverageRuntimes:v,...e.runtime?{selectedCoverageRuntime:e.runtime}:v.length===1?{selectedCoverageRuntime:v[0]}:{}});if(e.runtime&&!v.includes(e.runtime)){let i=e.runtime,h=u.filter(c=>!c.runtimes.includes(i)).map(c=>c.name);throw new Error(d$2.length>1&&h.length>0?`--runtime ${e.runtime} is not canonical for every project in the selected Goal scope. Missing from: ${h.join(", ")}. Split the projects into runtime-compatible Goal scopes.`:`--runtime ${e.runtime} is not present in the canonical Workspace Model for the selected Goal scope. Available runtimes: ${v.join(", ")||"none"}.`)}if(e.runtime&&f$2.category!=="test-coverage")throw new Error("--runtime is valid only for a test-coverage Goal.");if(e.runtime&&f$2.requestedTarget?.runtime&&f$2.requestedTarget.runtime!==e.runtime)throw new Error(`--runtime ${e.runtime} conflicts with the ${f$2.requestedTarget.runtime} runtime named in the Goal intent.`);if(!s.selectionRequired&&f$2.category==="test-coverage"&&f$2.requestedTarget&&!f$2.requestedTarget.runtime&&v.length>1&&!e.runtime&&e.selectCoverageRuntime){let i=await e.selectCoverageRuntime({workspaceName:n.workspace.name,scope:l,projects:d$2.map(h=>({name:h.name,runtime:h.runtime,runtimeCandidates:[...h.runtimeCandidates].sort()})),runtimes:v});if(!v.includes(i))throw new Error("The selected coverage runtime is outside the canonical Goal scope.");f$2=K(e.intent,{availableCoverageRuntimes:v,selectedCoverageRuntime:i});}!s.selectionRequired&&f$2.category==="test-coverage"&&d$2.length>1&&v.length===0&&(f$2={...f$2,ambiguities:[`The selected projects do not share a common canonical coverage runtime: ${u.map(i=>`${i.name} (${i.runtimes.join(", ")||"none"})`).join("; ")}. Split them into runtime-compatible Goal scopes so every selected project is verified.`,...f$2.ambiguities]}),s.selectionRequired&&(f$2={...f$2,ambiguities:[`Goal scope is unresolved across ${l.projects.length} registered projects: ${l.projects.join(", ")}. Select one project, multiple projects, or the entire workspace.`,...f$2.ambiguities]});let M=await _e({workspacePath:r,projects:d$2,graph:a$1,intent:f$2,coverageRuntimeChoices:v}),E={generatedAt:m,intent:f$2,workspaceName:n.workspace.name,scope:l,sourceBinding:{model:{artifact:p.model,schemaVersion:q.model,hashAlgorithm:"sha256",hashSemantics:"workspace-model-structural-v1",hash:b$1,generatedAt:n.generatedAt},graph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,hashAlgorithm:"sha256",hashSemantics:"canonical-json-v1",hash:c$1(a$1),generatedAt:a$1.generatedAt,modelHash:a$1.source.hash,...a$1.source.inputs?.hash?{inputHash:a$1.source.inputs.hash}:{}}},preflight:M,baseline:{projectCount:d$2.length,runtimes:[...new Set(d$2.flatMap(i=>i.runtimeCandidates))].sort(),frameworks:[...new Set(d$2.map(i=>i.framework))].sort(),graph:Te(a$1,l)},maxAttempts:p$1,consumer:e.consumer??"generic"},I={digestCanonical:c$1},{goalPack:g,handoff:T}=j(E,I);a(g,ae,"Goal Pack"),a(T,se,"Goal agent handoff");let L=false,o=async()=>{let i=C.join(r,g.artifacts.goalPack),h=C.join(r,g.artifacts.agentHandoff),[c,A]=await Promise.all([_.pathExists(i),_.pathExists(h)]);if(c!==A)throw new Error(`Goal Pack instance is incomplete and cannot be resumed: ${g.id}`);if(!c)return;let[w,k]=await Promise.all([_.readJson(i),_.readJson(h)]);a(w,ae,"Persisted Goal Pack"),a(k,se,"Persisted goal agent handoff");let S=j({...E,generatedAt:w.generatedAt,sourceBinding:w.sourceBinding},I);if(w.id!==g.id||k.goalId!==g.id||c$1(w)!==c$1(S.goalPack)||c$1(k)!==c$1(S.handoff))throw new Error(`Goal Pack instance failed immutable integrity validation: ${g.id}`);g=w,T=k,L=true;};if(e.dryRun)await o();else {let i$2=`.workspai/goals/${g.id}/publication`;await f(r,i$2,async()=>{await o();let h=Ne(await Le(r),g,new Date().toISOString());a(h,pe,"Goal index"),i(h),await i$1(r,d$1,L?[{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]:[{relativePath:g.artifacts.goalPack,payload:g},{relativePath:g.artifacts.agentHandoff,payload:T},{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]);});}let y=[g.artifacts.goalPack,g.artifacts.agentHandoff,d$1,f$1],P={schemaVersion:c$2,result:g.state==="needs-confirmation"?"needs-confirmation":g.state==="blocked"?"blocked":g.state==="needs-evidence"?"needs-evidence":"planned",resolution:{source:t.source,invocationScope:t.projectPath?"project":"workspace"},goalPack:g,agentHandoff:T,writtenArtifacts:e.dryRun?[]:L?[d$1,f$1]:y,dryRun:e.dryRun===true,resumed:L};return a(P,Re,"Goal plan result"),P}export{et as planGoalPack};
1
+ import {c as c$3}from'./chunk-KVPTZMEV.js';import {c}from'./chunk-I7P6XQJI.js';import {j,i,d as d$1,f as f$1,c as c$2,e,h}from'./chunk-5NL53T5C.js';export{b as GOAL_AGENT_HANDOFF_SCHEMA_VERSION,f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,g as GOAL_LIFECYCLE_RESULT_SCHEMA_VERSION,d as GOAL_PACK_LAST_RUN_PATH,a as GOAL_PACK_SCHEMA_VERSION,c as GOAL_PLAN_RESULT_SCHEMA_VERSION}from'./chunk-5NL53T5C.js';import {f as f$2}from'./chunk-X5ZNFXFI.js';import {a as a$1}from'./chunk-TDQ2PRHV.js';import {b}from'./chunk-EBQS5T7Q.js';import {b as b$1}from'./chunk-QYXX6G5O.js';import {f,i as i$1}from'./chunk-FE5R6EUV.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {q,p}from'./chunk-ODK4LCEL.js';import C from'path';import _ from'fs-extra';var ve=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/,ye=/(?:^|\s)(?:\/(?:home|Users|private|var|tmp|mnt|opt|srv|root|workspace|workspaces|data|Volumes|etc|usr|run|dev|proc|sys)\/[^\s]+|[A-Za-z]:[\\/][^\s]+|\\\\[^\\\s]+\\[^\s]+)/,Pe=/(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:github_pat_|gh[pousr]_|glpat-|npm_|xox[baprs]-|sk-(?:proj-)?)[A-Za-z0-9_-]{12,}|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[A-Za-z0-9_-]{20,}|\bBearer\s+[A-Za-z0-9._~+/-]{16,}|[a-z][a-z0-9+.-]*:\/\/[^\s:/]+:[^\s@/]+@|\b(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^\s]{6,})/i,je=[{category:"test-coverage",patterns:[/\b(?:test\s+)?coverage\b/i,/\bcoverage\s+(?:to|above|at least)\b/i]},{category:"dependency-security",patterns:[/\b(?:dependency|dependencies|package|packages)\b.*\b(?:security|vulnerab|audit)\b/i,/\b(?:security|vulnerab|audit)\b.*\b(?:dependency|dependencies|package|packages)\b/i]},{category:"release-readiness",patterns:[/\brelease[ -]readiness\b/i,/\bready (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare\b[^\n]{0,80}\bfor release\b/i]},{category:"defect-repair",patterns:[/\b(?:fix|repair|resolve|debug)\b.*\b(?:bug|error|failure|issue|regression)\b/i]},{category:"performance",patterns:[/\b(?:performance|latency|throughput|cpu|optimi[sz]e|faster|slower)\b/i,/\b(?:memory\s+(?:allocation|consumption|footprint|leak|pressure|usage)|out[ -]of[ -]memory|heap|ram)\b/i]},{category:"refactor",patterns:[/\b(?:refactor|restructure|decouple|extract|simplify|cleanup|clean up)\b/i]},{category:"documentation",patterns:[/\b(?:document|documentation|readme|guide|tutorial|docs)\b/i]},{category:"feature-change",patterns:[/\b(?:add|build|create|enforce|enhance|harden|implement|improve|introduce|support)\b/i]},{category:"system-understanding",patterns:[/\b(?:understand|explain|map|find|where|how|architecture|analy[sz]e|search)\b/i]}];function Ge(e){if(typeof e!="string")throw new Error("Goal intent must be text.");let t=e.trim().replace(/\s+/g," ");if(!t)throw new Error("Goal intent cannot be empty.");if(t.length>2e3)throw new Error("Goal intent exceeds the 2000 character safety limit.");if(ve.test(t))throw new Error("Goal intent contains unsupported control characters.");if(ye.test(t))throw new Error("Goal intent contains a machine-local absolute path. Use a workspace-relative path or project scope.");if(Pe.test(t))throw new Error("Goal intent appears to contain secret material and was not persisted.");return t}function Ce(e){let t=e.match(/\b(?:coverage\D{0,24})?((?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?))\s*(?:%|percent(?:age)?(?:\s+points?)?)/i);if(!t||!/coverage/i.test(e))return null;let r=Number(t[1]);return Number.isFinite(r)&&r>=0&&r<=100?r:null}var re=[{runtime:"cpp",patterns:[/\bc\+\+/i,/\bcpp\b/i]},{runtime:"dotnet",patterns:[/\.net\b/i,/\bdotnet\b/i,/\bc#/i,/\bcsharp\b/i]},{runtime:"node",patterns:[/\bnode(?:\.js)?\b/i,/\btypescript\b/i,/\bjavascript\b/i,/\b(?:js|ts)\b/i]},{runtime:"python",patterns:[/\bpython\b/i,/\bpytest\b/i]},{runtime:"go",patterns:[/\bgolang\b/i,/\bgo(?:\s+(?:test|coverage|tests))\b/i]},{runtime:"java",patterns:[/\bjava\b/i,/\bjunit\b/i,/\bjacoco\b/i]},{runtime:"rust",patterns:[/\brust\b/i,/\bcargo\b/i]},{runtime:"php",patterns:[/\bphp\b/i,/\bphpunit\b/i]},{runtime:"ruby",patterns:[/\bruby\b/i,/\brspec\b/i]},{runtime:"kotlin",patterns:[/\bkotlin\b/i]},{runtime:"scala",patterns:[/\bscala\b/i]},{runtime:"clojure",patterns:[/\bclojure\b/i]},{runtime:"elixir",patterns:[/\belixir\b/i]},{runtime:"deno",patterns:[/\bdeno\b/i]},{runtime:"bun",patterns:[/\bbun\b/i]},{runtime:"c",patterns:[/\bc(?:\s+(?:test|coverage|tests|code))\b/i]}];function Ae(e){return re.filter(t=>t.patterns.some(r=>r.test(e))).map(t=>t.runtime)}function K(e,t={}){let r=Ge(e),n=je.filter(u=>u.patterns.some(j=>j.test(r))).map(u=>u.category),a=n.some(u=>u!=="feature-change")?n.filter(u=>u!=="feature-change"):n,s=a[0]??"feature-change",l=Ce(r),d=Ae(r),p=d.length===0&&t.selectedCoverageRuntime?[t.selectedCoverageRuntime]:d,m=[...new Set((t.availableCoverageRuntimes??[]).filter(u=>re.some(j=>j.runtime===u)))].sort(),b=[];return a.length>1&&a[0]!=="test-coverage"&&b.push(`The intent also contains signals for: ${a.slice(1).join(", ")}.`),s==="test-coverage"&&l===null&&b.push("A numeric test coverage target is required for machine verification."),s==="test-coverage"&&p.length>1&&b.push(`The Goal names multiple coverage runtimes: ${p.join(", ")}. Select one runtime per Goal.`),s==="test-coverage"&&p.length===0&&m.length>1&&b.push(`Coverage scope is ambiguous across detected runtimes: ${m.join(", ")}. Name one runtime or language in the Goal.`),s==="test-coverage"&&p.length===1&&m.length>0&&!m.includes(p[0])&&b.push(`The requested ${p[0]} coverage runtime is not present in the selected scope. Detected runtimes: ${m.join(", ")}.`),{original:r,normalized:r.toLocaleLowerCase("en-US"),statement:r.replace(/[.!?]+$/,""),category:s,confidence:a.length===1?"high":a.length>1?"medium":"low",ambiguities:b,...l===null?{}:{requestedTarget:{metric:"test-coverage-percent",operator:"at-least",value:l,...p.length===1?{runtime:p[0]}:{}}}}}function oe(e){let t={"test-coverage":["test suite coverage configuration instrumentation","CI tests LCOV Cobertura JaCoCo LLVM coverage"],"dependency-security":["dependency manifest lockfile security audit vulnerability"],"release-readiness":["release pipeline readiness gates build test deploy"],"defect-repair":["failure error test implementation call path"],"feature-change":["API implementation module dependency tests"],refactor:["module dependency ownership implementation tests"],performance:["performance benchmark latency throughput runtime"],documentation:["documentation README guide architecture decision"],"system-understanding":["architecture service API dependency ownership"]};return [...new Set([e.statement,...t[e.category]])].slice(0,3)}var ae="contracts/workspace-intelligence/goal-pack.v1.json",se="contracts/workspace-intelligence/goal-agent-handoff.v1.json",Re="contracts/workspace-intelligence/goal-plan-result.v1.json",pe="contracts/workspace-intelligence/goal-index.v1.json",ue=new Set(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"]);function Se(e,t){let r=e.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)??[],n=new Set(t.map(m=>m.toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"")).filter(Boolean)),a=[];for(let m=0;m<r.length;){let b=0;for(let u=Math.min(4,r.length-m);u>=1;u-=1){let j=r.slice(m,m+u).join("").toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"");if(n.has(j)){b=u;break}}if(b>0){m+=b;continue}a.push(r[m]),m+=1;}let s=a.findIndex((m,b)=>{let u=m.toLocaleLowerCase("en-US"),j=a[b+1]?.toLocaleLowerCase("en-US");return u==="without"&&["breaking","changing","modifying","removing"].includes(j??"")||u==="while"&&["keeping","maintaining","preserving"].includes(j??"")}),l=s>=2?a.slice(0,s):a,d=l.length>=2?l.join(" "):e;if(s<2)return [d];let p=a.slice(s).filter(m=>!["without","while","breaking","changing","modifying","removing","keeping","maintaining","preserving"].includes(m.toLocaleLowerCase("en-US")));return p.length>0?[d,p.join(" ")]:[d]}function ie(e){return e.split(C.sep).join("/")}function V(e,t){return C.resolve(t.absolutePath??C.join(e,t.path))}function ce(e){let t=e.requested.trim().replace(/^project:/,"");if(!t)throw new Error("Project goal scope must name a project.");let r=C.isAbsolute(t)?C.resolve(t):null,n=e.model.projects.filter(a=>a.name===t||ie(a.path)===ie(t)||r!==null&&V(e.workspacePath,a)===r);if(n.length!==1)throw new Error(n.length===0?`Project goal scope was not found in the canonical model: ${t}`:`Project goal scope is ambiguous in the canonical model: ${t}`);return n[0]}async function Ee(e){let t=await a$1(e);if(t.status==="miss")throw new Error(`Canonical model and live graph evidence are required (${t.reason}). Run \`workspai workspace intelligence run --for-agent generic --strict --json\` or retry with --refresh.`);let{model:r,graph:n}=t;return a(r,"contracts/workspace-intelligence/workspace-model.v1.json","Goal source model"),a(n,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Goal source graph"),b$1(n,r),{model:r,graph:n}}function le(e){let t=e.scope.trim();if(t==="workspace")return {kind:"workspace",projects:e.model.projects.map(n=>n.name).sort(),selectionSource:e.selectionSource,resolution:"selected"};let r=t.startsWith("projects:")?"projects:":t.startsWith("project:")&&t.slice(8).includes(",")?"project:":null;if(r){let n=t.slice(r.length).split(",").map(l=>l.trim()).filter(Boolean);if(n.length<2)throw new Error("A project-set Goal scope must name at least two projects.");let a=n.map(l=>ce({workspacePath:e.workspacePath,model:e.model,requested:l})),s=[...new Set(a.map(l=>l.name))].sort();if(s.length!==n.length)throw new Error("A project-set Goal scope must not contain duplicate projects.");return {kind:"project-set",projects:s,selectionSource:e.selectionSource,resolution:"selected"}}if(t)return {kind:"project",projects:[ce({workspacePath:e.workspacePath,model:e.model,requested:t}).name],selectionSource:e.selectionSource,resolution:"selected"};throw new Error("Goal scope cannot be empty.")}async function Ie(e){if(e.explicitScope?.trim())return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:e.explicitScope,selectionSource:"explicit"}),selectionRequired:false};if(e.invocationProjectPath){let t=C.resolve(e.invocationProjectPath),r=e.model.projects.filter(n=>V(e.workspacePath,n)===t);if(r.length!==1)throw new Error("The invocation project is not represented uniquely in the canonical workspace model. Refresh intelligence or pass --scope explicitly.");return {scope:{kind:"project",projects:[r[0].name],selectionSource:"invocation-project",resolution:"selected"},selectionRequired:false}}if(e.model.projects.length===1)return {scope:{kind:"project",projects:[e.model.projects[0].name],selectionSource:"single-project-workspace",resolution:"selected"},selectionRequired:false};if(e.selectScope){let t=await e.selectScope({workspaceName:e.model.workspace.name,projects:e.model.projects.map(n=>({name:n.name,runtime:n.runtime,runtimeCandidates:[...n.runtimeCandidates].sort(),framework:n.framework})).sort((n,a)=>n.name.localeCompare(a.name))}),r=t.kind==="workspace"?"workspace":t.projects.length===1?`project:${t.projects[0]}`:`projects:${t.projects.join(",")}`;return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:r,selectionSource:"interactive"}),selectionRequired:false}}return {scope:{kind:"workspace",projects:e.model.projects.map(t=>t.name).sort(),selectionSource:"workspace",resolution:"selection-required"},selectionRequired:true}}function Te(e,t){if(t.kind==="workspace")return {entities:e.quality.entityCount,relationships:e.quality.relationCount,proofs:e.quality.proofCount,unresolved:e.quality.unknownCount,proofCoveragePercent:Number((e.quality.relationProofCoverageRatio*100).toFixed(2))};let r=new Set(t.projects),n=e.entities.filter(p=>p.projectId!==void 0&&r.has(p.projectId)),a=new Set(n.map(p=>p.id)),s=e.relations.filter(p=>a.has(p.from)||a.has(p.to)),l=new Set([...n.flatMap(p=>p.proofIds),...s.flatMap(p=>p.proofIds)]),d=s.filter(p=>p.proofIds.length>0).length;return {entities:n.length,relationships:s.length,proofs:l.size,unresolved:s.length-d,proofCoveragePercent:s.length===0?100:Number((d/s.length*100).toFixed(2))}}function xe(e){let t=new Map;for(let n of e){let a=t.get(n.kind)??[];a.push(n),t.set(n.kind,a);}let r=[];for(let n=0;[...t.values()].some(a=>n<a.length);n+=1)for(let a of t.values()){let s=a[n];s&&r.push(s);}return r}async function _e(e){let t=C.join(e.workspacePath,p.intelligenceRun),r=await _.readJson(t).catch(()=>null),a=(Array.isArray(r?.stages)?r.stages:[]).filter(o=>o.status==="blocked"||o.status==="failed").map(o=>String(o.id??"unknown")).sort(),s=r?.status,l={status:s==="passed"?"passed":s==="blocked"||s==="failed"?"blocked":"unknown",artifact:p.intelligenceRun,blockedStages:a},d={status:"not-applicable",runtime:null,runtimeChoices:[],runner:null,existingEvidence:[],prerequisites:[]};if(e.intent.category==="test-coverage"){let o=e.intent.requestedTarget?.runtime;if(e.intent.ambiguities.some(P=>P.startsWith("Coverage scope is ambiguous")||P.startsWith("The Goal names multiple coverage runtimes")||P.startsWith("The selected projects do not share a common canonical coverage runtime")||P.startsWith("The requested ")))d={status:"requires-setup",runtime:o??null,runtimeChoices:e.coverageRuntimeChoices,runner:null,existingEvidence:[],prerequisites:["Select exactly one detected runtime or language for this coverage Goal."]};else {let P=o?e.projects.filter(c=>c.runtimeCandidates.includes(o)):e.projects,i=await Promise.all(P.map(async c=>({project:c,capability:await c$3(V(e.workspacePath,c),o??(ue.has(c.runtime)?c.runtime:"unknown"))}))),h=i.map(c=>c.capability.status);d={status:h.includes("unsupported")?"unsupported":h.includes("requires-setup")?"requires-setup":"available",runtime:i.length===1?i[0].capability.runtime:[...new Set(i.map(c=>c.capability.runtime))].join(","),runtimeChoices:e.coverageRuntimeChoices,runner:i.length===1?i[0].capability.runner:[...new Set(i.flatMap(c=>c.capability.runner?[c.capability.runner]:[]))].join(",")||null,existingEvidence:i.flatMap(c=>c.capability.existingEvidence.map(A=>({project:c.project.name,...A}))).filter((c,A,w)=>w.findIndex(k=>k.project===c.project&&k.path===c.path&&k.sha256===c.sha256)===A).sort((c,A)=>c.project.localeCompare(A.project)||c.path.localeCompare(A.path)),prerequisites:[...new Set(i.flatMap(c=>c.capability.prerequisites))].sort()};}}let p$1=oe(e.intent),m=[...Se(p$1[0],e.projects.map(o=>o.name)),...p$1.slice(1)].filter((o,y,P)=>P.indexOf(o)===y).slice(0,3),b=m.map((o,y)=>{let P=o.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)?.length??0,i=y===0&&P>=4?2:1,h=e.projects.map(w=>{let k=G=>f$2(e.graph,{query:o,projectId:w.name,...G?{kind:G}:{},limit:60,relationsPerEntity:0,minimumTermMatches:i}).entities,S=k(),de=[...new Set(e.graph.entities.filter(G=>G.projectId===w.name||G.projectId===void 0&&G.identity.scope==="workspace").map(G=>G.kind))].flatMap(G=>k(G).slice(0,8)),U=[...S,...de];return U.filter((G,me)=>U.findIndex(ge=>ge.id===G.id)===me)}),c=[],A=new Set;for(let w=0;h.some(k=>w<k.length);w+=1)for(let k of h){let S=k[w];!S||A.has(S.id)||(A.add(S.id),c.push(S));}return xe(c)}),u={"test-coverage":["test-suite"],"dependency-security":["package","module"],"release-readiness":["pipeline","deployment","lifecycle-stage"],"defect-repair":["test-suite","lifecycle-stage"],"feature-change":["project","runtime-unit","api","package","module","test-suite"],refactor:["package","module","api","test-suite"],performance:["lifecycle-stage","test-suite","pipeline"],documentation:["document","decision"],"system-understanding":["project","service","api","package","protocol"]},j=new Set(e.projects.map(o=>o.name)),v=e.graph.entities.filter(o=>o.proofIds.length>0&&(!o.projectId||j.has(o.projectId))&&u[e.intent.category].includes(o.kind)).sort((o,y)=>u[e.intent.category].indexOf(o.kind)-u[e.intent.category].indexOf(y.kind)||o.label.localeCompare(y.label)),f=[],M=new Set,E=o=>{!o||f.length>=20||M.has(o.id)||(M.add(o.id),f.push(o));},I=(e.intent.statement.match(/[A-Za-z][A-Za-z0-9+#.-]{1,}/g)??[]).length>=2,g=I?b[0]??[]:[];for(let o of g.slice(0,12))E(o);if(!I)for(let o of v)E(o);for(let o=0;f.length<20&&b.slice(1).some(y=>o<y.length);o+=1)for(let y of b.slice(1))E(y[o]);if(I)for(let o of v)E(o);for(let o of g.slice(12))E(o);let T=f.map(o=>({entityId:o.id,kind:o.kind,label:o.label,proofIds:o.proofIds.slice(0,12)})),L=b[0]?.length??0;return {workspaceIntelligence:l,measurement:d,retrieval:{status:I&&L>=3?"grounded":T.length>0?"partial":"empty",strategy:"deterministic-category-v1",queries:m,anchors:T}}}async function Le(e$1){let t=C.join(e$1,f$1);if(!await _.pathExists(t))return {schemaVersion:e,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let r=await _.readJson(t);a(r,pe,"Goal index");try{i(r);}catch(n){let a=h(r);if(!(a!==null&&n instanceof Error&&n.message==="Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")||!a)throw n;return a}return r}function Ne(e$1,t,r){let n=e$1.goals.find(l=>l.id===t.id),a=t.state==="ready-to-plan",s={id:t.id,fingerprint:t.fingerprint,objective:t.intent.statement,category:t.intent.category,state:t.state,lifecycle:n?.lifecycle==="cancelled"?"cancelled":a?"active":"planned",scope:t.scope,createdAt:n?.createdAt??t.generatedAt,updatedAt:r,goalPack:t.artifacts.goalPack,agentHandoff:t.artifacts.agentHandoff,...n?.verifiedGoalId?{verifiedGoalId:n.verifiedGoalId}:{},...n?.repairTransactionId?{repairTransactionId:n.repairTransactionId}:{},...n?.repairTransactionIds?{repairTransactionIds:n.repairTransactionIds}:{},...n?.changeTransactionId?{changeTransactionId:n.changeTransactionId}:{},...n?.changeTransactionIds?{changeTransactionIds:n.changeTransactionIds}:{},...n?.verificationReceipt?{verificationReceipt:n.verificationReceipt}:{}};return {schemaVersion:e,generatedAt:r,activeGoalId:s.lifecycle==="active"?t.id:e$1.activeGoalId===t.id?null:e$1.activeGoalId,goals:[...e$1.goals.filter(l=>l.id!==t.id).map(l=>s.lifecycle==="active"&&l.lifecycle==="active"?{...l,lifecycle:"planned",updatedAt:r}:l),s].sort((l,d)=>l.id.localeCompare(d.id))}}async function et(e){let t=b({startPath:C.resolve(e.startPath),explicitWorkspacePath:e.workspacePath,strict:true,requireProjectMembership:true});if(!t)throw new Error("No canonical Workspai workspace could be resolved.");let r=C.resolve(t.workspacePath);e.refresh&&await c({workspacePath:r,strict:false,agent:"generic"});let{model:n,graph:a$1}=await Ee(r),s=await Ie({workspacePath:r,invocationProjectPath:t.projectPath,model:n,explicitScope:e.scope,selectScope:e.selectScope}),l=s.scope,d$2=n.projects.filter(i=>l.projects.includes(i.name));if(d$2.length===0)throw new Error("A Goal Pack requires at least one registered project in its selected scope.");let p$1=e.maxAttempts??5;if(!Number.isInteger(p$1)||p$1<1||p$1>25)throw new Error("--max-attempts must be an integer from 1 to 25.");let m=new Date().toISOString(),b$1=d(n),u=d$2.map(i=>({name:i.name,runtimes:[...new Set(i.runtimeCandidates.filter(h=>ue.has(h)))].sort()})),j$1=[...new Set(u.flatMap(i=>i.runtimes))].sort(),v=u.length<=1?j$1:u[0].runtimes.filter(i=>u.every(h=>h.runtimes.includes(i))),f$2=K(e.intent,{availableCoverageRuntimes:v,...e.runtime?{selectedCoverageRuntime:e.runtime}:v.length===1?{selectedCoverageRuntime:v[0]}:{}});if(e.runtime&&!v.includes(e.runtime)){let i=e.runtime,h=u.filter(c=>!c.runtimes.includes(i)).map(c=>c.name);throw new Error(d$2.length>1&&h.length>0?`--runtime ${e.runtime} is not canonical for every project in the selected Goal scope. Missing from: ${h.join(", ")}. Split the projects into runtime-compatible Goal scopes.`:`--runtime ${e.runtime} is not present in the canonical Workspace Model for the selected Goal scope. Available runtimes: ${v.join(", ")||"none"}.`)}if(e.runtime&&f$2.category!=="test-coverage")throw new Error("--runtime is valid only for a test-coverage Goal.");if(e.runtime&&f$2.requestedTarget?.runtime&&f$2.requestedTarget.runtime!==e.runtime)throw new Error(`--runtime ${e.runtime} conflicts with the ${f$2.requestedTarget.runtime} runtime named in the Goal intent.`);if(!s.selectionRequired&&f$2.category==="test-coverage"&&f$2.requestedTarget&&!f$2.requestedTarget.runtime&&v.length>1&&!e.runtime&&e.selectCoverageRuntime){let i=await e.selectCoverageRuntime({workspaceName:n.workspace.name,scope:l,projects:d$2.map(h=>({name:h.name,runtime:h.runtime,runtimeCandidates:[...h.runtimeCandidates].sort()})),runtimes:v});if(!v.includes(i))throw new Error("The selected coverage runtime is outside the canonical Goal scope.");f$2=K(e.intent,{availableCoverageRuntimes:v,selectedCoverageRuntime:i});}!s.selectionRequired&&f$2.category==="test-coverage"&&d$2.length>1&&v.length===0&&(f$2={...f$2,ambiguities:[`The selected projects do not share a common canonical coverage runtime: ${u.map(i=>`${i.name} (${i.runtimes.join(", ")||"none"})`).join("; ")}. Split them into runtime-compatible Goal scopes so every selected project is verified.`,...f$2.ambiguities]}),s.selectionRequired&&(f$2={...f$2,ambiguities:[`Goal scope is unresolved across ${l.projects.length} registered projects: ${l.projects.join(", ")}. Select one project, multiple projects, or the entire workspace.`,...f$2.ambiguities]});let M=await _e({workspacePath:r,projects:d$2,graph:a$1,intent:f$2,coverageRuntimeChoices:v}),E={generatedAt:m,intent:f$2,workspaceName:n.workspace.name,scope:l,sourceBinding:{model:{artifact:p.model,schemaVersion:q.model,hashAlgorithm:"sha256",hashSemantics:"workspace-model-structural-v1",hash:b$1,generatedAt:n.generatedAt},graph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,hashAlgorithm:"sha256",hashSemantics:"canonical-json-v1",hash:c$1(a$1),generatedAt:a$1.generatedAt,modelHash:a$1.source.hash,...a$1.source.inputs?.hash?{inputHash:a$1.source.inputs.hash}:{}}},preflight:M,baseline:{projectCount:d$2.length,runtimes:[...new Set(d$2.flatMap(i=>i.runtimeCandidates))].sort(),frameworks:[...new Set(d$2.map(i=>i.framework))].sort(),graph:Te(a$1,l)},maxAttempts:p$1,consumer:e.consumer??"generic"},I={digestCanonical:c$1},{goalPack:g,handoff:T}=j(E,I);a(g,ae,"Goal Pack"),a(T,se,"Goal agent handoff");let L=false,o=async()=>{let i=C.join(r,g.artifacts.goalPack),h=C.join(r,g.artifacts.agentHandoff),[c,A]=await Promise.all([_.pathExists(i),_.pathExists(h)]);if(c!==A)throw new Error(`Goal Pack instance is incomplete and cannot be resumed: ${g.id}`);if(!c)return;let[w,k]=await Promise.all([_.readJson(i),_.readJson(h)]);a(w,ae,"Persisted Goal Pack"),a(k,se,"Persisted goal agent handoff");let S=j({...E,generatedAt:w.generatedAt,sourceBinding:w.sourceBinding},I);if(w.id!==g.id||k.goalId!==g.id||c$1(w)!==c$1(S.goalPack)||c$1(k)!==c$1(S.handoff))throw new Error(`Goal Pack instance failed immutable integrity validation: ${g.id}`);g=w,T=k,L=true;};if(e.dryRun)await o();else {let i$2=`.workspai/goals/${g.id}/publication`;await f(r,i$2,async()=>{await o();let h=Ne(await Le(r),g,new Date().toISOString());a(h,pe,"Goal index"),i(h),await i$1(r,d$1,L?[{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]:[{relativePath:g.artifacts.goalPack,payload:g},{relativePath:g.artifacts.agentHandoff,payload:T},{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]);});}let y=[g.artifacts.goalPack,g.artifacts.agentHandoff,d$1,f$1],P={schemaVersion:c$2,result:g.state==="needs-confirmation"?"needs-confirmation":g.state==="blocked"?"blocked":g.state==="needs-evidence"?"needs-evidence":"planned",resolution:{source:t.source,invocationScope:t.projectPath?"project":"workspace"},goalPack:g,agentHandoff:T,writtenArtifacts:e.dryRun?[]:L?[d$1,f$1]:y,dryRun:e.dryRun===true,resumed:L};return a(P,Re,"Goal plan result"),P}export{et as planGoalPack};