workspai 0.67.0 → 0.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/contracts/workspace-activity-board.v1.json +6 -0
  2. package/contracts/workspace-activity-event.v1.json +31 -1
  3. package/contracts/workspace-activity-monitor-snapshot.v1.json +35 -2
  4. package/contracts/workspace-intelligence/workspace-knowledge-search.v1.json +1 -0
  5. package/dist/analyze-JDEWUBC6.js +1 -0
  6. package/dist/{artifact-remediation-plan-GFFHC2ZU.js → artifact-remediation-plan-I7IKC5MR.js} +1 -1
  7. package/dist/autopilot-release-OELUFNLL.js +1 -0
  8. package/dist/capabilities-command-RAAYENQ6.js +1 -0
  9. package/dist/chunk-25AWHAB5.js +2 -0
  10. package/dist/{chunk-KQ2TMI26.js → chunk-2C5XJBYI.js} +1 -1
  11. package/dist/{chunk-TP7VKEUF.js → chunk-2KX6KHEC.js} +1 -1
  12. package/dist/{chunk-2RPFCBS4.js → chunk-3BMYMZQB.js} +1 -1
  13. package/dist/{chunk-BRYJTW6S.js → chunk-3KU3YUWD.js} +1 -1
  14. package/dist/{chunk-ENZPM52J.js → chunk-3NF3M3RE.js} +1 -1
  15. package/dist/{chunk-HQLBO23O.js → chunk-3XF7O66C.js} +3 -3
  16. package/dist/{chunk-H77ZNH5O.js → chunk-3Z4SVBMR.js} +1 -1
  17. package/dist/{chunk-NVND4727.js → chunk-46QH3ZVI.js} +1 -1
  18. package/dist/{chunk-VI4ZRAY6.js → chunk-5OV2WXAR.js} +1 -1
  19. package/dist/{chunk-Y35VLVF6.js → chunk-5XUAAQSV.js} +2 -2
  20. package/dist/{chunk-BHFRP7TV.js → chunk-5YZ2W57R.js} +1 -1
  21. package/dist/{chunk-B4IVVTMQ.js → chunk-64XWHDZ3.js} +1 -1
  22. package/dist/{chunk-KENOAC2Q.js → chunk-7DDEMDG2.js} +1 -1
  23. package/dist/{chunk-IQQMFRWM.js → chunk-7DZNZ3GM.js} +1 -1
  24. package/dist/{chunk-N4QFNOAI.js → chunk-BG6IX6HA.js} +1 -1
  25. package/dist/{chunk-2MVIRJJR.js → chunk-BMAFHX6A.js} +1 -1
  26. package/dist/{chunk-XDPTAV2T.js → chunk-C2VTO5WT.js} +1 -1
  27. package/dist/{chunk-JCGSIDMC.js → chunk-CSZPE637.js} +1 -1
  28. package/dist/{chunk-5OA33JH2.js → chunk-D5LLTUTY.js} +1 -1
  29. package/dist/{chunk-4RV4JVGR.js → chunk-DFVG4DDZ.js} +1 -1
  30. package/dist/{chunk-OCNPOYMA.js → chunk-EHLGPLIU.js} +1 -1
  31. package/dist/{chunk-6254CWUY.js → chunk-GVQKAINC.js} +1 -1
  32. package/dist/{chunk-HYE5UHPV.js → chunk-IXXQMD34.js} +1 -1
  33. package/dist/{chunk-GIQ4SDRJ.js → chunk-JYMO7QXQ.js} +1 -1
  34. package/dist/{chunk-THIG2YQP.js → chunk-KDY4X7SQ.js} +1 -1
  35. package/dist/{chunk-L5Q2S5GY.js → chunk-KFTJVVJR.js} +1 -1
  36. package/dist/{chunk-SX6A656X.js → chunk-KY2GOSO5.js} +1 -1
  37. package/dist/chunk-LDBULT2T.js +4 -0
  38. package/dist/{chunk-PSYQ6IJA.js → chunk-LEOFD3W5.js} +1 -1
  39. package/dist/{chunk-5EVDW7JM.js → chunk-N5HPMATQ.js} +1 -1
  40. package/dist/{chunk-CZVT7T2X.js → chunk-OFYY4725.js} +1 -1
  41. package/dist/{chunk-3O7LZPKA.js → chunk-P3622IM5.js} +1 -1
  42. package/dist/{chunk-TABXSDTR.js → chunk-PKKSRXUS.js} +1 -1
  43. package/dist/{chunk-ARUFY5W3.js → chunk-Q7UGDNSM.js} +1 -1
  44. package/dist/{chunk-2M62CU3O.js → chunk-RVAOJOXA.js} +1 -1
  45. package/dist/{chunk-EHCKITR4.js → chunk-TCLKGPXF.js} +1 -1
  46. package/dist/{chunk-SRLWHOLF.js → chunk-TMRCPT7S.js} +1 -1
  47. package/dist/{chunk-VWBMDGPY.js → chunk-VIN7NJW3.js} +1 -1
  48. package/dist/chunk-W37NOQVG.js +1 -0
  49. package/dist/{chunk-SVYY55IS.js → chunk-W5VKBDSD.js} +1 -1
  50. package/dist/{chunk-YYY2WXOH.js → chunk-WRZSQDZV.js} +1 -1
  51. package/dist/{create-72ITVZXV.js → create-U5PQHOZ4.js} +1 -1
  52. package/dist/{demo-kit-5UQH2OXC.js → demo-kit-RKTHTXHJ.js} +1 -1
  53. package/dist/{doctor-CVYUESRQ.js → doctor-D7YI7LSA.js} +1 -1
  54. package/dist/{dotnet-webapi-clean-YEHYIGOT.js → dotnet-webapi-clean-XL4IBUQV.js} +1 -1
  55. package/dist/{goal-lifecycle-H55AGFCB.js → goal-lifecycle-BMS6GSIU.js} +1 -1
  56. package/dist/{goal-pack-6OBZOPCD.js → goal-pack-RBSVQMMX.js} +1 -1
  57. package/dist/{gofiber-standard-C44IIQYH.js → gofiber-standard-OHHMCNMJ.js} +1 -1
  58. package/dist/{gogin-standard-X7VKACVR.js → gogin-standard-BAZXPOKL.js} +1 -1
  59. package/dist/index.js +23 -23
  60. package/dist/{live-command-5VXPR43F.js → live-command-GNAASZ7U.js} +1 -1
  61. package/dist/{pipeline-SKYOXWHW.js → pipeline-QOMXH2EK.js} +1 -1
  62. package/dist/{project-agent-entry-5IUBEREI.js → project-agent-entry-MH7364BE.js} +1 -1
  63. package/dist/{project-intelligence-lens-LQCN65P2.js → project-intelligence-lens-ZCCHUKVI.js} +1 -1
  64. package/dist/{project-test-coverage-KD4LLFGV.js → project-test-coverage-JPWTBSSJ.js} +1 -1
  65. package/dist/{rust-axum-JKZTZDRZ.js → rust-axum-CCJ6UCBW.js} +1 -1
  66. package/dist/{springboot-standard-PI4FLTAN.js → springboot-standard-M5JQEJML.js} +1 -1
  67. package/dist/{verified-goal-HN7G532B.js → verified-goal-XUXU2X5H.js} +1 -1
  68. package/dist/{workspace-5W7FYGDQ.js → workspace-B33BFZZ3.js} +1 -1
  69. package/dist/{workspace-agent-sync-OZCDQORK.js → workspace-agent-sync-T3MJO2MX.js} +1 -1
  70. package/dist/{workspace-context-L65BR5L6.js → workspace-context-KOCEP4MJ.js} +1 -1
  71. package/dist/{workspace-contract-JYHNEJPV.js → workspace-contract-MQ3QE52V.js} +1 -1
  72. package/dist/{workspace-explain-SUBK6FLO.js → workspace-explain-DTFCKYXK.js} +1 -1
  73. package/dist/{workspace-feedback-MWGCT5R2.js → workspace-feedback-3YLIUFQ7.js} +1 -1
  74. package/dist/{workspace-foundation-VIB3PXNH.js → workspace-foundation-O7O3QIS4.js} +1 -1
  75. package/dist/{workspace-graph-stream-45JHE4MG.js → workspace-graph-stream-XTGGBD7D.js} +1 -1
  76. package/dist/workspace-graph-token-efficiency-5LJKQU2J.js +1 -0
  77. package/dist/{workspace-history-JKW3VJO3.js → workspace-history-7HDZZ4G5.js} +1 -1
  78. package/dist/{workspace-intelligence-3C47PK4L.js → workspace-intelligence-TFEQBPUP.js} +1 -1
  79. package/dist/{workspace-intelligence-benchmark-SRDIHX3X.js → workspace-intelligence-benchmark-PLVUBGWO.js} +1 -1
  80. package/dist/{workspace-intelligence-runner-OWN5ZI6W.js → workspace-intelligence-runner-6ZAV6RO4.js} +1 -1
  81. package/dist/{workspace-knowledge-graph-AKG5NUU6.js → workspace-knowledge-graph-AUXYL3L6.js} +1 -1
  82. package/dist/{workspace-knowledge-graph-query-DXA4CROE.js → workspace-knowledge-graph-query-A7TKONWY.js} +1 -1
  83. package/dist/workspace-knowledge-graph-snapshot-GPBDAKAU.js +1 -0
  84. package/dist/{workspace-mcp-serve-PK226GMV.js → workspace-mcp-serve-TDUXJUAA.js} +1 -1
  85. package/dist/{workspace-model-R4ISKDB2.js → workspace-model-GVXNLSQM.js} +1 -1
  86. package/dist/{workspace-onboarding-Y5RPEFUD.js → workspace-onboarding-ECZ2KJ2A.js} +1 -1
  87. package/dist/{workspace-readme-PL5V3UDH.js → workspace-readme-6N5Y2ZSJ.js} +1 -1
  88. package/dist/{workspace-registry-summary-STGUGROG.js → workspace-registry-summary-5SFBTRGQ.js} +1 -1
  89. package/dist/{workspace-repair-engine-FNLL5ZDK.js → workspace-repair-engine-CKJCTWKX.js} +1 -1
  90. package/dist/workspace-run-ZZ5WHL7W.js +1 -0
  91. package/dist/{workspace-verify-AXVX3PF3.js → workspace-verify-D3QTMAUI.js} +1 -1
  92. package/dist/{workspace-watch-RLBEJKXE.js → workspace-watch-XYJEW2Z2.js} +1 -1
  93. package/docs/ci-workflows.md +1 -1
  94. package/docs/commands-reference.md +3 -1
  95. package/docs/contracts/README.md +1 -1
  96. package/docs/workspace-knowledge-graph.md +1 -0
  97. package/docs/workspace-live-activity.md +18 -4
  98. package/package.json +1 -1
  99. package/dist/analyze-IC2KRVCG.js +0 -1
  100. package/dist/autopilot-release-RECEZAZI.js +0 -1
  101. package/dist/capabilities-command-X4WZIJNR.js +0 -1
  102. package/dist/chunk-5TY74LLW.js +0 -2
  103. package/dist/chunk-UTV4DTNM.js +0 -1
  104. package/dist/chunk-ZI2E7P6O.js +0 -4
  105. package/dist/workspace-graph-token-efficiency-NPECU6Y5.js +0 -1
  106. package/dist/workspace-knowledge-graph-snapshot-SNI5K2RL.js +0 -1
  107. package/dist/workspace-run-GFBFGUFM.js +0 -1
@@ -1,3 +1,3 @@
1
- import {a as a$1,b as b$1}from'./chunk-Y4Z6CEII.js';import {b as b$2}from'./chunk-AO2ZI42U.js';import {a,e,b}from'./chunk-XDPTAV2T.js';import {i,h as h$1}from'./chunk-ZGHJIQXL.js';import h from'path';import {existsSync}from'fs';import X from'fs-extra';var Y=[{artifactKind:"bootstrap-compliance",cardId:"bootstrap",fileNames:["bootstrap-compliance.latest.json"]},{artifactKind:"doctor-workspace",cardId:"doctor",fileNames:["doctor-remediation-plan-last-run.json","doctor-last-run.json"]},{artifactKind:"analyze",cardId:"analyze",fileNames:["analyze-last-run.json"]},{artifactKind:"readiness",cardId:"readiness",fileNames:["release-readiness-last-run.json"]},{artifactKind:"pipeline",cardId:"pipeline",fileNames:["pipeline-last-run.json"]},{artifactKind:"workspace-run",cardId:"workspaceRun",fileNames:["workspace-run-last.json"]},{artifactKind:"workspace-verify",cardId:"workspaceVerify",fileNames:["workspace-verify-last-run.json"]}];function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function w(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0):[]}function I(e){return [...new Set(e.map(r=>r.trim()).filter(Boolean))]}function V(e){return (e.notes.includes("Doctor finding status: blocking")?16:0)+(e.transaction?8:0)+(e.operation?4:0)+(e.invocation?2:0)+(e.strategy?.length?1:0)}function ee(e){let r=V(e.incoming)>V(e.existing),o=structuredClone(r?e.incoming:e.existing),i=r?e.existing:e.incoming,t=i.sourceStepId;return o.order=e.existing.order,o.files=I([...o.files,...i.files]),o.notes=I([...o.notes,...i.notes.filter(a=>!a.startsWith("Source Doctor capability:")&&!a.startsWith("Doctor finding status:")),...t?[`Also satisfies Doctor capability: ${t}`]:[]]),o}function te(e,r,o){return o?r:h.relative(e,r).split(h.sep).join("/")}function D(e){return e.includeAbsolutePaths?e.projectPath:b$1({workspacePath:e.workspacePath,projectPath:e.projectPath,projectName:e.projectName}).contractRelativePath}function z(e){let r=h.isAbsolute(e.filePath)?h.resolve(e.filePath):h.resolve(e.projectPath,e.filePath);if(e.includeAbsolutePaths)return r;let o=h.relative(e.projectPath,r);return !o||o===".."||o.startsWith(`..${h.sep}`)||h.isAbsolute(o)?void 0:`${D(e)}/${o.split(h.sep).join("/")}`}function re(e){let r=e?.trim()||"npx workspai bootstrap";if(!/(?:^|\s)--ci(?:\s|$)/.test(r)&&/(?:^|\s)--json(?:\s|$)/.test(r))return r.replace(/(?:^|\s)--json(?:\s|$)/,i=>{let t=i.startsWith(" ")?" ":"",a=i.endsWith(" ")?" ":"";return `${t}--ci --json${a}`}).trim();let o=/(?:^|\s)--ci(?:\s|$)/.test(r)?r:`${r} --ci`;return /(?:^|\s)--json(?:\s|$)/.test(o)?o:`${o} --json`}function q(e,r){return h.basename(e).toLowerCase().replace(/\.cmd$/,"")==="npx"&&r[0]==="workspai"&&!r.includes("--no-install")?["--no-install",...r]:r}function oe(e){return `${JSON.stringify({schemaVersion:h$1.compatibilityMatrix.schemaVersion,generatedAt:e,source:"workspai workspace remediation-plan",runtimes:{},notes:["Minimal enterprise baseline. Add runtime and toolchain entries as governance matures."]},null,2)}
1
+ import {a as a$1,b as b$1}from'./chunk-Y4Z6CEII.js';import {b as b$2}from'./chunk-AO2ZI42U.js';import {a,e,b}from'./chunk-C2VTO5WT.js';import {i,h as h$1}from'./chunk-ZGHJIQXL.js';import h from'path';import {existsSync}from'fs';import X from'fs-extra';var Y=[{artifactKind:"bootstrap-compliance",cardId:"bootstrap",fileNames:["bootstrap-compliance.latest.json"]},{artifactKind:"doctor-workspace",cardId:"doctor",fileNames:["doctor-remediation-plan-last-run.json","doctor-last-run.json"]},{artifactKind:"analyze",cardId:"analyze",fileNames:["analyze-last-run.json"]},{artifactKind:"readiness",cardId:"readiness",fileNames:["release-readiness-last-run.json"]},{artifactKind:"pipeline",cardId:"pipeline",fileNames:["pipeline-last-run.json"]},{artifactKind:"workspace-run",cardId:"workspaceRun",fileNames:["workspace-run-last.json"]},{artifactKind:"workspace-verify",cardId:"workspaceVerify",fileNames:["workspace-verify-last-run.json"]}];function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function w(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0):[]}function I(e){return [...new Set(e.map(r=>r.trim()).filter(Boolean))]}function V(e){return (e.notes.includes("Doctor finding status: blocking")?16:0)+(e.transaction?8:0)+(e.operation?4:0)+(e.invocation?2:0)+(e.strategy?.length?1:0)}function ee(e){let r=V(e.incoming)>V(e.existing),o=structuredClone(r?e.incoming:e.existing),i=r?e.existing:e.incoming,t=i.sourceStepId;return o.order=e.existing.order,o.files=I([...o.files,...i.files]),o.notes=I([...o.notes,...i.notes.filter(a=>!a.startsWith("Source Doctor capability:")&&!a.startsWith("Doctor finding status:")),...t?[`Also satisfies Doctor capability: ${t}`]:[]]),o}function te(e,r,o){return o?r:h.relative(e,r).split(h.sep).join("/")}function D(e){return e.includeAbsolutePaths?e.projectPath:b$1({workspacePath:e.workspacePath,projectPath:e.projectPath,projectName:e.projectName}).contractRelativePath}function z(e){let r=h.isAbsolute(e.filePath)?h.resolve(e.filePath):h.resolve(e.projectPath,e.filePath);if(e.includeAbsolutePaths)return r;let o=h.relative(e.projectPath,r);return !o||o===".."||o.startsWith(`..${h.sep}`)||h.isAbsolute(o)?void 0:`${D(e)}/${o.split(h.sep).join("/")}`}function re(e){let r=e?.trim()||"npx workspai bootstrap";if(!/(?:^|\s)--ci(?:\s|$)/.test(r)&&/(?:^|\s)--json(?:\s|$)/.test(r))return r.replace(/(?:^|\s)--json(?:\s|$)/,i=>{let t=i.startsWith(" ")?" ":"",a=i.endsWith(" ")?" ":"";return `${t}--ci --json${a}`}).trim();let o=/(?:^|\s)--ci(?:\s|$)/.test(r)?r:`${r} --ci`;return /(?:^|\s)--json(?:\s|$)/.test(o)?o:`${o} --json`}function q(e,r){return h.basename(e).toLowerCase().replace(/\.cmd$/,"")==="npx"&&r[0]==="workspai"&&!r.includes("--no-install")?["--no-install",...r]:r}function oe(e){return `${JSON.stringify({schemaVersion:h$1.compatibilityMatrix.schemaVersion,generatedAt:e,source:"workspai workspace remediation-plan",runtimes:{},notes:["Minimal enterprise baseline. Add runtime and toolchain entries as governance matures."]},null,2)}
2
2
  `}function ie(e){return `${JSON.stringify({schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:e,note:"Minimal enterprise baseline. Set enabled: true and add artifact entries to activate mirroring."},null,2)}
3
3
  `}function ae(e){let r=e.payload,o=w(r.blockers),i=w(r.blockingReasons),t=w(r.failures),a=w(r.reasons),d=w(r.policyViolations),s=g(r.summary),f=w(s?.blockers);if(e.artifactKind==="analyze"){let c=(Array.isArray(r.findings)?r.findings:[]).map(y=>g(y)).filter(y=>!!y).map(y=>String(y.message??y.title??y.id??"").trim()).filter(Boolean);return I([...o,...c,...i])}if(e.artifactKind==="workspace-run"){let b=g(r.stages),c=Object.entries(b??{}).flatMap(([y,m])=>{let n=g(m);return (Array.isArray(n?.projects)?n.projects:[]).map(p=>g(p)).filter(p=>!!p).filter(p=>p.status==="failed"||p.ok===false).map(p=>`${y}: ${String(p.project??p.name??"project")} failed`)});return I([...o,...c,...i])}return I([...o,...i,...t,...a,...d,...f])}function j(e){let r=e.findingId?.trim()||e.sourceStepId?.trim()||e.id,o=e.findingStatus??"blocking",i=e.causalKey?.trim()||[e.cardId,e.projectName??e.scope??"workspace",r].map(t=>String(t).trim().toLowerCase()).join(":");return {id:e.id,artifactKind:e.artifactKind,cardId:e.cardId,title:e.title,order:e.order,phase:e.phase,scope:e.scope??"workspace",...e.projectName?{projectName:e.projectName}:{},...e.projectPath?{projectPath:e.projectPath}:{},...e.sourceStepId?{sourceStepId:e.sourceStepId}:{},findingId:r,findingStatus:o,causalKey:i,...e.dependsOn?{dependsOn:e.dependsOn}:{},...e.strategy?{strategy:structuredClone(e.strategy)}:{},...e.transaction?{transaction:structuredClone(e.transaction)}:{},status:e.status??"ready",mode:e.mode,risk:e.risk,requiresApproval:true,blocker:e.blocker,summary:e.summary,...e.command?{command:e.command}:{},...e.invocation?{invocation:structuredClone(e.invocation)}:{},verifyCommand:e.verifyCommand,cwd:e.cwd??"workspace",files:e.files??[],...e.operation?{operation:e.operation}:{},rollback:e.rollback??(e.operation?{available:true,strategy:"idempotent"}:{available:false,strategy:"none"}),notes:e.notes??[]}}function ne(e){return (Array.isArray(e.report.payload.steps)?e.report.payload.steps:[]).flatMap((o,i)=>{let t=g(o),a=typeof t?.id=="string"?t.id.trim():"",d=typeof t?.projectName=="string"?t.projectName.trim():"",s=typeof t?.projectPath=="string"?t.projectPath.trim():"",f=typeof t?.originalCommand=="string"?t.originalCommand.trim():"";if(!t||!a||!d||!s)return [];let b=g(t.studioStatus),c=b?.state==="ready"||b?.state==="review-required"||b?.state==="blocked"||b?.state==="guidance-only"?b.state:"guidance-only",y=t.risk==="safe"||t.risk==="guarded"||t.risk==="invasive"?t.risk:"guarded",m=g(t.preview),n=D({workspacePath:e.workspacePath,projectPath:s,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}),u=J({capability:{...t,command:f},absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),p=U({capability:t,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),P=M({operation:t.operation,absoluteProjectPath:s}),k=t.findingStatus==="blocking"||t.findingStatus==="advisory"||t.findingStatus==="informational"?t.findingStatus:"unknown",l=typeof t.diagnosisFindingId=="string"&&t.diagnosisFindingId.trim()?t.diagnosisFindingId.trim():typeof t.issueId=="string"&&t.issueId.trim()?t.issueId.trim():a,A=typeof t.causalKey=="string"&&t.causalKey.trim()?t.causalKey.trim():void 0,S=t.executableInCurrentEnvironment===true&&!!u,$=H({strategy:t.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),R=g(t.transaction),x=R?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(R):void 0;return x&&(x.projectPath=n),[j({id:`doctor.${a}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof m?.title=="string"&&m.title.trim()?m.title.trim():`Repair ${d}`,order:e.startOrder+i,phase:typeof t.phase=="string"?t.phase:"doctor-remediation",blocker:typeof m?.summary=="string"&&m.summary.trim()?m.summary.trim():`Doctor remediation is pending for ${d}.`,summary:typeof m?.summary=="string"&&m.summary.trim()?m.summary.trim():`Execute the CLI-authored Doctor step for ${d}.`,mode:S?"run-command":"manual-guidance",risk:y,status:c,...S&&u?{command:u}:{},...S&&p?{invocation:p}:{},...P?{operation:P}:{},verifyCommand:typeof t.verifyCommand=="string"&&t.verifyCommand.trim()?t.verifyCommand.trim():"npx workspai doctor project --json",files:w(t.files).map(v=>z({workspacePath:e.workspacePath,projectPath:s,projectName:d,filePath:v,includeAbsolutePaths:e.includeAbsolutePaths})).filter(v=>!!v),notes:[`Source Doctor step: ${a}`,`Doctor finding id: ${l}`,`Doctor finding status: ${k}`,...typeof b?.reason=="string"?[b.reason]:[]],scope:"project",projectName:d,projectPath:n,sourceStepId:a,findingId:l,findingStatus:k,causalKey:A,dependsOn:w(t.dependsOn).map(v=>`doctor.${v}`),strategy:$,transaction:x,cwd:"project",...g(t.rollback)?.available===true?{rollback:{available:true,strategy:"manual"}}:{}})]})}function J(e){let r=typeof e.capability.command=="string"?e.capability.command.trim():"";if(e.includeAbsolutePaths&&r)return r;let o=M({operation:e.capability.operation,absoluteProjectPath:e.absoluteProjectPath});if(o)return b$2(o);let i=g(e.capability.invocation),t=typeof i?.executable=="string"?i.executable.trim():"",a=q(t,w(i?.args));if(t)return [t,...a].map(s=>/^[a-zA-Z0-9_./:@=+-]+$/.test(s)?s:JSON.stringify(s)).join(" ");if(!r)return;let d=e.absoluteProjectPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return r.replace(new RegExp(`^cd\\s+["']?${d}["']?\\s*&&\\s*`,"i"),"").replaceAll(e.absoluteProjectPath,".")}function U(e){let r=g(e.capability.invocation),o=typeof r?.executable=="string"?r.executable.trim():"",i=w(r?.args);if(!(!o||i.length!==(Array.isArray(r?.args)?r.args.length:0)))return {cwd:e.includeAbsolutePaths?e.absoluteProjectPath:".",executable:o,args:q(o,i)}}function M(e){let r=g(e.operation);if(!r||typeof r.type!="string")return;let o=structuredClone(r);for(let i of ["path","sourcePath"]){let t=o[i];if(typeof t!="string")continue;let a=h.isAbsolute(t)?h.relative(e.absoluteProjectPath,t):t;if(!a||a===".."||a.startsWith(`..${h.sep}`)||h.isAbsolute(a))return;o[i]=a.split(h.sep).join("/");}return o}function H(e){if(!Array.isArray(e.strategy))return;let r=structuredClone(e.strategy);if(!e.includeAbsolutePaths)for(let o of r)o.invocation&&(o.invocation.cwd=".");return r}function se(e){let r=Array.isArray(e.report.payload.projects)?e.report.payload.projects:e.report.payload.project?[e.report.payload.project]:[],o=new Set,i=[];for(let t of r){let a=g(t);if(!a)continue;let d=typeof a.name=="string"?a.name.trim():"",s=typeof a.path=="string"?a.path.trim():"";if(!d||!s)continue;let f=Array.isArray(a.repairCapabilities)?a.repairCapabilities:Array.isArray(a.probes)?a.probes.map(m=>g(m)?.repairCapability).filter(m=>m!==void 0):[],b=new Map,c=new Map,y=g(a.diagnosis);for(let m of Array.isArray(y?.findings)?y.findings:[]){let n=g(m),u=g(n?.repair),p=typeof u?.capabilityId=="string"?u.capabilityId.trim():"",P=typeof n?.id=="string"?n.id.trim():"",k=typeof n?.causalKey=="string"?n.causalKey.trim():"",l=n?.status==="blocking"||n?.status==="advisory"||n?.status==="informational"||n?.status==="unknown"?n.status:"unknown";p&&P&&k&&c.set(p,{findingId:P,causalKey:k,findingStatus:l});}for(let m of Array.isArray(a.probes)?a.probes:[]){let n=g(m),u=g(n?.repairCapability),p=typeof u?.id=="string"?u.id.trim():"";p&&b.set(p,n?.status==="fail"?"blocking":"advisory");}for(let m of f){let n=g(m),u=typeof n?.id=="string"?n.id.trim():"";if(!n||!u)continue;let p=`${d}:${u}`;if(o.has(p))continue;o.add(p);let P=n.risk==="safe"||n.risk==="guarded"||n.risk==="invasive"?n.risk:"guarded",k=J({capability:n,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),l=U({capability:n,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),A=M({operation:n.operation,absoluteProjectPath:s}),S=n.status==="available"&&!!k,$=g(n.transaction),R=$?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone($):void 0,x=c.get(u),v=x?.findingStatus??b.get(u)??(R?"blocking":"advisory");R&&(R.projectPath=D({workspacePath:e.workspacePath,projectPath:s,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}));let Z=H({strategy:n.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),G=w(n.files).map(C=>z({workspacePath:e.workspacePath,projectPath:s,projectName:d,filePath:C,includeAbsolutePaths:e.includeAbsolutePaths})).filter(C=>!!C),E=j({id:`doctor.${d}.${u}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof n.title=="string"&&n.title.trim()?n.title.trim():`Repair ${d}`,order:e.startOrder+i.length,phase:R?"dependency-remediation":"doctor-remediation",blocker:typeof n.reason=="string"&&n.reason.trim()?n.reason.trim():`Doctor remediation is pending for ${d}.`,summary:typeof n.reason=="string"&&n.reason.trim()?n.reason.trim():`Execute the Doctor-authored repair capability for ${d}.`,mode:S?n.canEditFiles===true?"edit-file":"run-command":"manual-guidance",risk:P,status:S?"ready":n.status==="manual"?"guidance-only":"blocked",...k?{command:k}:{},...l?{invocation:l}:{},verifyCommand:typeof n.verifyCommand=="string"&&n.verifyCommand.trim()?n.verifyCommand.trim():"npx workspai doctor project --json",files:G,notes:[`Source Doctor capability: ${u}`,`Doctor finding status: ${v}`,...w(n.limitations)],scope:"project",projectName:d,projectPath:D({workspacePath:e.workspacePath,projectPath:s,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}),sourceStepId:u,findingId:x?.findingId??(typeof n.issueId=="string"&&n.issueId.trim()?n.issueId.trim():u),findingStatus:v,causalKey:x?.causalKey,strategy:Z,transaction:R,cwd:"project",...A?{operation:A,rollback:{available:true,strategy:"manual"}}:{}}),O=k?i.findIndex(C=>C.projectName===d&&C.command===k&&C.cwd==="project"):-1;if(O>=0){i[O]=ee({existing:i[O],incoming:E});continue}i.push(E);}}return i}function ce(e){let r=[],o=re("npx workspai bootstrap --json");for(let i$1 of e.blockers)i$1.includes("profile.enterprise.ci")&&r.push(j({id:"bootstrap.enterprise-ci",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Run bootstrap in deterministic CI mode",order:10,phase:"bootstrap-preflight",blocker:i$1,summary:"Enterprise bootstrap compliance requires --ci for deterministic execution.",mode:"run-command",risk:"safe",command:o,verifyCommand:o})),i$1.includes("profile.enterprise.compatibility-matrix")&&r.push(j({id:"bootstrap.compatibility-matrix",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise compatibility matrix baseline",order:20,phase:"bootstrap-config",blocker:i$1,summary:"Create the missing compatibility matrix baseline without overwriting user data.",mode:"edit-file",risk:"safe",verifyCommand:o,files:[i.compatibilityMatrix],operation:{type:"file-create",path:i.compatibilityMatrix,content:oe(e.generatedAt),overwrite:false}})),i$1.includes("profile.enterprise.mirror-config")&&r.push(j({id:"bootstrap.mirror-config",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise mirror config baseline",order:30,phase:"bootstrap-config",blocker:i$1,summary:"Create the missing mirror configuration baseline without enabling mirroring.",mode:"edit-file",risk:"safe",verifyCommand:o,files:[".workspai/mirror-config.json"],operation:{type:"file-create",path:".workspai/mirror-config.json",content:ie(e.generatedAt),overwrite:false}}));return r}function de(e){let r=Array.isArray(e.report.payload.steps)?e.report.payload.steps:[],o=[],i=new Map;for(let t of r){let a=g(t),d=g(a?.command),s=typeof a?.id=="string"?a.id.trim():"",f=typeof a?.project=="string"?a.project.trim():"",b=typeof a?.status=="string"?a.status:"",c=typeof d?.display=="string"?d.display.trim():"",y=a?.required===true;if(!s.startsWith("project.")||!f||!y||b!=="fail"&&b!=="missing"||!/^npx\s+workspai\s+workspace\s+run\s+/i.test(c))continue;let m=s.split(".").at(-1)??"stage",n=`workspaceVerify.${s}`,u=i.get(f),p=/(?:^|\s)--no-gates(?:\s|$)/.test(c)?c:`${c} --no-gates`;o.push(j({id:n,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof a.label=="string"&&a.label.trim()?a.label.trim():`Run ${m} for ${f}`,order:e.startOrder+o.length,phase:"fleet-run",blocker:typeof a.message=="string"&&a.message.trim()?a.message.trim():`${m} evidence is not current for ${f}.`,summary:`Produce fresh ${m} evidence for ${f} without re-entering the blocked aggregate gates.`,mode:"run-command",risk:m==="start"?"guarded":"safe",status:"ready",command:p,verifyCommand:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",scope:"project",projectName:f,projectPath:f,sourceStepId:s,...u?{dependsOn:[u]}:{},cwd:"workspace",notes:[`Source Workspace Verify step: ${s}`,"Aggregate verification must run only after this project evidence producer completes."]})),i.set(f,n);}return o}function le(e){let r=I(e.blockers.flatMap(i=>{let t=i.match(/(?:project runtimes?|workspace)\s*\(([^)]+)\)\s+(?:is|are) not pinned/i);return t?.[1]?t[1].split(",").map(a=>a.trim().toLowerCase()).filter(a=>/^(python|node|go|java|dotnet|rust|php)$/.test(a)):[]})),o=[];for(let i of r){let t=`readiness.toolchain.${i}.setup`,a=e.blockers.find(d=>d.toLowerCase().includes(`(${i})`))??`The ${i} runtime is not pinned in the canonical workspace toolchain.`;o.push(j({id:t,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Pin ${i} in the workspace toolchain`,order:e.startOrder+o.length,phase:"toolchain-reconciliation",blocker:a,summary:`Detect and persist the current ${i} runtime in the canonical workspace toolchain lock.`,mode:"run-command",risk:"safe",command:`npx workspai setup ${i} --json`,verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Run from the workspace root so the canonical toolchain.lock is updated."]})),o.push(j({id:`readiness.toolchain.${i}.bootstrap`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Reconcile the ${i} workspace foundation`,order:e.startOrder+o.length,phase:"toolchain-reconciliation",blocker:`The ${i} runtime pin must be reconciled with the workspace foundation.`,summary:"Refresh the workspace foundation after the runtime pin is written.",mode:"run-command",risk:"guarded",command:"npx workspai bootstrap --ci --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:[t]}));}return o}function pe(e){if(e.report.artifactKind==="readiness"&&/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(e.blocker))return j({id:`${e.report.cardId}.doctor-owner.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:"Resolve dependency vulnerability through Doctor",order:e.order,phase:"dependency-remediation",blocker:e.blocker,summary:"Release Readiness is the aggregate gate; use the project-scoped Doctor remediation capability that owns this dependency failure.",mode:"verify-before-fix",risk:"guarded",status:"review-required",command:"npx workspai doctor workspace --plan --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Read doctor-remediation-plan-last-run.json and execute the matching surface-security-hygiene capability before rerunning Readiness.","Do not treat a Readiness refresh as remediation for a source dependency vulnerability."]});let o={analyze:{title:"Refresh analyze evidence",phase:"analysis",command:"npx workspai analyze --strict --json",verify:"npx workspai analyze --strict --json"},readiness:{title:"Refresh release readiness",phase:"release-readiness",command:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",verify:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json"},pipeline:{title:"Rerun governance pipeline",phase:"governance-pipeline",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"},"workspace-run":{title:"Rerun failed workspace stage",phase:"fleet-run",command:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json",verify:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json"},"workspace-verify":{title:"Refresh workspace verify gate",phase:"verification",command:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",verify:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json"},"doctor-workspace":{title:"Use Doctor remediation plan",phase:"doctor-remediation",command:"npx workspai doctor workspace --plan --json",verify:"npx workspai doctor workspace --json"}}[e.report.artifactKind]??{title:"Refresh artifact evidence",phase:"evidence-refresh",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"};return j({id:`${e.report.cardId}.refresh.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:o.title,order:e.order,phase:o.phase,blocker:e.blocker,summary:"No deterministic file operation is available for this artifact yet; refresh the evidence and continue with the card-specific plan.",mode:e.report.artifactKind==="doctor-workspace"?"verify-before-fix":"run-command",risk:"guarded",status:e.report.artifactKind==="doctor-workspace"?"review-required":"ready",command:o.command,verifyCommand:o.verify,notes:e.report.artifactKind==="doctor-workspace"?["Read doctor-remediation-plan-last-run.json for ordered file-level steps."]:[]})}async function fe(e){let r=[a(e,".workspai/reports"),b(e,".workspai/reports")],o=[],i=new Set;for(let t of Y)for(let a of t.fileNames){let d=(await Promise.all(r.map(s=>h.join(s,a)))).find(s=>existsSync(s));if(!(!d||i.has(`${t.artifactKind}:${a}`))){i.add(`${t.artifactKind}:${a}`);try{let s=await X.readJSON(d),f=g(s);if(!f)continue;o.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:a,absolutePath:d,payload:f});break}catch{o.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:a,absolutePath:d,payload:{blockers:[`${t.artifactKind}: report exists but could not be parsed.`]}});break}}}return o}async function Pe(e){let r=h.resolve(e.workspacePath),o=e.includeAbsolutePaths===true,i=e.ciMode===true,t=new Date().toISOString(),a$2=a(r,".workspai/reports"),d=await fe(r),s=[],f=1;for(let c of d){if(c.artifactKind==="doctor-workspace"){let l=Array.isArray(c.payload.steps)?ne({report:c,workspacePath:r,includeAbsolutePaths:o,startOrder:f}):se({report:c,workspacePath:r,includeAbsolutePaths:o,startOrder:f});s.push(...l),f+=l.length;continue}let y=ae(c);if(y.length===0)continue;if(c.artifactKind==="bootstrap-compliance"){s.push(...ce({blockers:y,generatedAt:t})),f=s.length+1;continue}if(c.artifactKind==="workspace-verify"){let l=de({report:c,startOrder:f,ciMode:i});if(l.length>0){s.push(...l),f+=l.length;continue}}if(c.artifactKind==="readiness"){let l=le({report:c,blockers:y,startOrder:f,ciMode:i});if(l.length>0){s.push(...l),f+=l.length;continue}}let m=s.some(l=>l.transaction?.kind==="dependency-security"),n=c.artifactKind==="readiness"&&y.some(l=>/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(l));if(m&&n)continue;let u=y[0],p=pe({report:c,blocker:u,order:f,ciMode:i}),k={readiness:new Set(["bootstrap","doctor"]),pipeline:new Set(["bootstrap","doctor","analyze","readiness"]),workspaceVerify:new Set(["bootstrap","doctor","readiness","workspaceRun"])}[c.cardId];if(c.cardId==="pipeline"){let l=["doctor","analyze","readiness"].find(A=>u.toLowerCase().includes(A));l&&(k=new Set([l]));}if(k){let l=s.filter(A=>k.has(A.cardId)&&A.risk!=="invasive"&&A.status!=="blocked"&&A.status!=="guidance-only").map(A=>A.id);l.length>0&&(p.dependsOn=I([...p.dependsOn??[],...l]),p.notes.push("This aggregate gate must run after its contract-owned upstream remediation actions."));}y.length>1&&p.notes.push(...y.slice(1,8).map(l=>`Related blocker: ${l}`)),s.push(p),f+=1;}let b={safe:s.filter(c=>c.risk==="safe").length,guarded:s.filter(c=>c.risk==="guarded").length,invasive:s.filter(c=>c.risk==="invasive").length};return {schemaVersion:a$1,generatedAt:t,workspace:{name:h.basename(r),...o?{path:r}:{}},source:{command:"workspace remediation-plan",reportsDir:te(r,a$2,o),includeAbsolutePaths:o,ciMode:i},summary:{artifactsScanned:d.length,cardsCovered:I(s.map(c=>c.cardId)).length,totalActions:s.length,executableActions:s.filter(c=>c.status==="ready").length,risk:b},actions:s}}async function Re(e$1,r){return e(r,i.artifactRemediationPlan,e$1)}export{Pe as a,Re as b};
@@ -1 +1 @@
1
- import {r as r$1}from'./chunk-KQ2TMI26.js';import {a as a$1}from'./chunk-VWBMDGPY.js';import {b,c as c$2}from'./chunk-KENOAC2Q.js';import {a as a$2}from'./chunk-3O7LZPKA.js';import {j,l as l$1}from'./chunk-6254CWUY.js';import {g}from'./chunk-HQLBO23O.js';import {j as j$1,e as e$2}from'./chunk-5EVDW7JM.js';import {c as c$1,d}from'./chunk-JCGSIDMC.js';import {a}from'./chunk-3OGPTLI2.js';import {f as f$1,g as g$1,h as h$1}from'./chunk-YYY2WXOH.js';import {k,l,h,m,n as n$1,p as p$1,q as q$1}from'./chunk-BRYJTW6S.js';import {a as a$3}from'./chunk-ENZPM52J.js';import {n,q,t}from'./chunk-TP7VKEUF.js';import {o as o$1,r as r$2,s}from'./chunk-EHCKITR4.js';import {c,e as e$1}from'./chunk-XDPTAV2T.js';import {b as b$1}from'./chunk-IKUFNK46.js';import {e,f,o,p,n as n$2,m as m$1}from'./chunk-ZGHJIQXL.js';import {c as c$3}from'./chunk-TABXSDTR.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(e.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===e.intelligenceRun,`artifactPath must be ${e.intelligenceRun}`),r(t.preflight.length===n$2.length,`preflight must contain exactly ${n$2.length} entries`);for(let[d,n]of n$2.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,o[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===m$1.length,`stages must contain exactly ${m$1.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of m$1.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,p[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=e.intelligenceRun,Ee=f.intelligenceRun,L=we;function I(t){c$3({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return c(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t$1){let s$1=t$1.workspacePath,m$1=[],u=[],h$2=false,y=async(e,o$1)=>{let c=[...o[e]];if(h$2){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$1.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o$1();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$1.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$1.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$2=async(e,o)=>{let c=[...p[e].produces];if(h$2){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o=await o$1({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o.contract.projects.length} projects`}});let p$2,d$1=()=>{if(!p$2)throw new Error("canonical workspace model is unavailable");return p$2};await l$2("model",async()=>(p$2={...await q({workspacePath:s$1,includeEvidence:true}),build:n({mode:"full",engineStatus:"disabled"})},await t(p$2,s$1),{message:`${p$2.summary.projectCount} projects modeled`}));let n$2=ge.join(s$1,e.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$2)){let c=await k({workspacePath:s$1,model:d$1()});return await l(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$2),o=h(e);return o?(await l(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$2("diff",async()=>{let e$1=await m({workspacePath:s$1,fromPath:e.snapshot,model:d$1()});return await n$1(e$1,s$1),{message:e$1.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$2("impact",async()=>{let e$1=await p$1({workspacePath:s$1,fromPath:e.diff});return await q$1(e$1,s$1),{message:`${e$1.summary.risk} risk; ${e$1.summary.affectedProjects} affected`}}),await l$2("doctor-evidence",async()=>{let e=await r$1({workspace:s$1,json:true,quiet:true,profile:t$1.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$2("contract-evidence",async()=>{let e=await r$2({workspacePath:s$1,strict:true});return await s({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$2("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t$1.strict===true});return {blocked:e.summary.verdict==="blocked"||t$1.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t$1.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$2("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t$1.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t$1.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$2("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:e.impact});await g$1(e$1,s$1);let o=h$1(e$1,{strict:t$1.strict===true});return await j$1(s$1,e$2(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$2("context",async()=>{let e=await c$1({workspacePath:s$1,model:d$1(),agent:t$1.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$2("agent-sync",async()=>{let e=await l$1({workspacePath:s$1,agent:t$1.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t$1.strict===true,preset:"enterprise"}),o=false,c=await a$3(s$1);if(c.status==="miss"){if(c.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c.reason}).`);p$2={...await q({workspacePath:s$1,includeEvidence:true}),build:n({mode:"full",engineStatus:"disabled"})},await t(p$2,s$1);let f=await c$1({workspacePath:s$1,model:p$2,agent:t$1.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$1({workspacePath:s$1,agent:t$1.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t$1.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t$1.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$2("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$2(e,s$1);let o=t$1.strict===true?u.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u.some(e=>e.status==="blocked"),G=h$2?"failed":me?"blocked":"passed",fe=h$2?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$1,status:G,exitCode:fe,stages:u,artifactPath:L};ue(b$1),await e$1(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await e$1(s$1,e.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
1
+ import {r as r$1}from'./chunk-2C5XJBYI.js';import {a as a$1}from'./chunk-VIN7NJW3.js';import {b,c as c$2}from'./chunk-7DDEMDG2.js';import {a as a$2}from'./chunk-P3622IM5.js';import {j,l as l$1}from'./chunk-GVQKAINC.js';import {g}from'./chunk-3XF7O66C.js';import {j as j$1,e as e$2}from'./chunk-N5HPMATQ.js';import {c as c$1,d}from'./chunk-CSZPE637.js';import {a}from'./chunk-3OGPTLI2.js';import {f as f$1,g as g$1,h as h$1}from'./chunk-WRZSQDZV.js';import {k,l,h,m,n as n$1,p as p$1,q as q$1}from'./chunk-3KU3YUWD.js';import {a as a$3}from'./chunk-3NF3M3RE.js';import {n,q,t}from'./chunk-2KX6KHEC.js';import {o as o$1,r as r$2,s}from'./chunk-TCLKGPXF.js';import {c,e as e$1}from'./chunk-C2VTO5WT.js';import {b as b$1}from'./chunk-IKUFNK46.js';import {e,f,o,p,n as n$2,m as m$1}from'./chunk-ZGHJIQXL.js';import {c as c$3}from'./chunk-PKKSRXUS.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(e.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===e.intelligenceRun,`artifactPath must be ${e.intelligenceRun}`),r(t.preflight.length===n$2.length,`preflight must contain exactly ${n$2.length} entries`);for(let[d,n]of n$2.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,o[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===m$1.length,`stages must contain exactly ${m$1.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of m$1.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,p[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=e.intelligenceRun,Ee=f.intelligenceRun,L=we;function I(t){c$3({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return c(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t$1){let s$1=t$1.workspacePath,m$1=[],u=[],h$2=false,y=async(e,o$1)=>{let c=[...o[e]];if(h$2){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$1.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o$1();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$1.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$1.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$2=async(e,o)=>{let c=[...p[e].produces];if(h$2){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o=await o$1({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o.contract.projects.length} projects`}});let p$2,d$1=()=>{if(!p$2)throw new Error("canonical workspace model is unavailable");return p$2};await l$2("model",async()=>(p$2={...await q({workspacePath:s$1,includeEvidence:true}),build:n({mode:"full",engineStatus:"disabled"})},await t(p$2,s$1),{message:`${p$2.summary.projectCount} projects modeled`}));let n$2=ge.join(s$1,e.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$2)){let c=await k({workspacePath:s$1,model:d$1()});return await l(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$2),o=h(e);return o?(await l(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$2("diff",async()=>{let e$1=await m({workspacePath:s$1,fromPath:e.snapshot,model:d$1()});return await n$1(e$1,s$1),{message:e$1.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$2("impact",async()=>{let e$1=await p$1({workspacePath:s$1,fromPath:e.diff});return await q$1(e$1,s$1),{message:`${e$1.summary.risk} risk; ${e$1.summary.affectedProjects} affected`}}),await l$2("doctor-evidence",async()=>{let e=await r$1({workspace:s$1,json:true,quiet:true,profile:t$1.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$2("contract-evidence",async()=>{let e=await r$2({workspacePath:s$1,strict:true});return await s({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$2("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t$1.strict===true});return {blocked:e.summary.verdict==="blocked"||t$1.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t$1.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$2("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t$1.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t$1.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$2("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:e.impact});await g$1(e$1,s$1);let o=h$1(e$1,{strict:t$1.strict===true});return await j$1(s$1,e$2(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$2("context",async()=>{let e=await c$1({workspacePath:s$1,model:d$1(),agent:t$1.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$2("agent-sync",async()=>{let e=await l$1({workspacePath:s$1,agent:t$1.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t$1.strict===true,preset:"enterprise"}),o=false,c=await a$3(s$1);if(c.status==="miss"){if(c.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c.reason}).`);p$2={...await q({workspacePath:s$1,includeEvidence:true}),build:n({mode:"full",engineStatus:"disabled"})},await t(p$2,s$1);let f=await c$1({workspacePath:s$1,model:p$2,agent:t$1.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$1({workspacePath:s$1,agent:t$1.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t$1.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t$1.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$2("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$2(e,s$1);let o=t$1.strict===true?u.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u.some(e=>e.status==="blocked"),G=h$2?"failed":me?"blocked":"passed",fe=h$2?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$1,status:G,exitCode:fe,stages:u,artifactPath:L};ue(b$1),await e$1(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await e$1(s$1,e.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
@@ -1 +1 @@
1
- var J="workspace-knowledge-search.v1";function b(e){return e.trim().toLowerCase()}var U=new WeakMap;function x(e){let t=U.get(e);if(t)return t;let s=new Map(e.relations.map(a=>[a.id,a])),o=new Map(e.entities.map(a=>[a.id,a])),r=new Map(e.proofs.map(a=>[a.id,a])),i=new Map,d=new Map,h=(a,p)=>{let g=d.get(a)??[];g.push(p),d.set(a,g);};for(let a of e.entities){let p=[a.id,a.label,a.identity.key,...a.kind==="project"&&a.projectId?[a.projectId]:[],...a.identity.aliases];for(let g of new Set(p.map(b))){let k=i.get(g)??[];k.push(a),i.set(g,k);}}for(let a of e.relations)h(a.from,{from:a.from,to:a.to,relationId:a.id,kind:a.kind,direction:"forward",proofIds:a.proofIds}),h(a.to,{from:a.to,to:a.from,relationId:a.id,kind:a.kind,direction:"reverse",proofIds:a.proofIds});for(let a of i.values())a.sort((p,g)=>p.id.localeCompare(g.id));for(let a of d.values())a.sort((p,g)=>p.to.localeCompare(g.to)||p.relationId.localeCompare(g.relationId));let l={entitiesById:o,relationsById:s,entitiesByAlias:i,proofsById:r,adjacency:d};return U.set(e,l),l}function D(e,t){let s=x(e),o=s.relationsById.get(t);if(o)return {found:true,targetType:"relation",relation:o};let r=b(t),i=s.entitiesByAlias.get(r)??[];return i.length===1?{found:true,targetType:"entity",entity:i[0]}:{found:false,query:t,candidates:i.map(d=>d.id).sort()}}function ke(e,t){let s=D(e,t);if(!s.found)return {query:t,found:false,target:null,proofs:[],candidates:s.candidates};let o=s.targetType==="entity"?s.entity:s.relation,r=new Set(o.proofIds);return {query:t,found:true,target:o,candidates:[],proofs:[...r].map(i=>x(e).proofsById.get(i)).filter(i=>!!i).sort((i,d)=>i.id.localeCompare(d.id))}}function me(e,t,s){let o=D(e,t),r=D(e,s);if(!o.found||o.targetType!=="entity"||!r.found||r.targetType!=="entity")return {from:t,to:s,found:false,resolvedFrom:o.found&&o.targetType==="entity"?o.entity.id:null,resolvedTo:r.found&&r.targetType==="entity"?r.entity.id:null,entityPath:[],hops:[],proofs:[]};let i=x(e),d=[o.entity.id],h=new Map,l=new Set(d),a=0;for(;a<d.length&&!l.has(r.entity.id);){let u=d[a++];for(let w of i.adjacency.get(u)??[])l.has(w.to)||(l.add(w.to),h.set(w.to,w),d.push(w.to));}if(!l.has(r.entity.id))return {from:t,to:s,found:false,resolvedFrom:o.entity.id,resolvedTo:r.entity.id,entityPath:[],hops:[],proofs:[]};let p=[],g=r.entity.id;for(;g!==o.entity.id;){let u=h.get(g);if(!u)break;p.push(u),g=u.from;}p.reverse();let k=new Set(p.flatMap(u=>u.proofIds));return {from:t,to:s,found:true,resolvedFrom:o.entity.id,resolvedTo:r.entity.id,entityPath:[o.entity.id,...p.map(u=>u.to)],hops:p,proofs:[...k].map(u=>i.proofsById.get(u)).filter(u=>!!u).sort((u,w)=>u.id.localeCompare(w.id))}}function be(e,t,s){return e.entities.filter(o=>(!t||o.kind===t)&&(!s||o.projectId===s)).sort((o,r)=>o.kind.localeCompare(r.kind)||o.label.localeCompare(r.label))}var m={relations:12,relatedEntities:12,proofs:8,proofIdsPerItem:4,aliasesPerEntity:8,attributeArrayItems:8,attributeStringCharacters:256};function ee(e){let t=[],s=new Set;for(let o=0;o<m.proofIdsPerItem&&t.length<m.proofs;o+=1)for(let r of e){let i=r.proofIds[o];if(!(!i||s.has(i))&&(s.add(i),t.push(i),t.length>=m.proofs))break}return t}function te(e,t,s){let o=e.identity.aliases.slice(0,m.aliasesPerEntity);s.aliases+=e.identity.aliases.length-o.length;let r=Object.fromEntries(Object.entries(e.attributes).map(([d,h])=>{if(Array.isArray(h)){let l=h.slice(0,m.attributeArrayItems);return s.attributeValues+=h.length-l.length,[d,l]}return typeof h=="string"&&h.length>m.attributeStringCharacters?(s.attributeValues+=1,[d,h.slice(0,m.attributeStringCharacters)]):[d,h]})),i=e.proofIds.filter(d=>t.has(d)).slice(0,m.proofIdsPerItem);return s.proofReferences+=e.proofIds.length-i.length,{...e,identity:{...e.identity,aliases:o},attributes:r,proofIds:i}}function ne(e){let t=Object.values(e.attributes).flatMap(s=>Array.isArray(s)?s:[s]);return [e.id,e.kind,e.label,e.projectId??"",e.identity.key,...e.identity.aliases,...t.map(s=>String(s??""))].join(" ").toLowerCase()}var oe=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"]),se=new Map([["authenticate","auth"],["authenticated","auth"],["authentication","auth"],["authorization","auth"],["authorizing","auth"],["config","configuration"],["configs","configuration"],["dependencies","dependency"],["diagnostics","diagnostic"],["reliable","reliability"],["tested","test"],["testing","test"],["tests","test"],["verification","verify"],["verified","verify"],["verifies","verify"],["verifying","verify"]]);function M(e){let t=s=>b(s).replace(/\bc\+\+/gu," cplusplus ").replace(/\bc#/gu," csharp ").split(/[^a-z0-9]+/u).filter(o=>o.length>1||o==="c"||o==="r").map(o=>se.get(o)??o);return [...new Set([...t(e),...t(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2"))])]}function ae(e){let t=b(e.label),s=b(e.identity.key),o=e.identity.aliases.map(b),r=ne(e);return {entity:e,label:t,identity:s,aliases:o,haystack:r,labelTokens:new Set(M(e.label)),identityTokens:new Set(M(e.identity.key)),aliasTokens:new Set(e.identity.aliases.flatMap(M)),allTokens:new Set(M(r))}}function W(e,t){return e.has(t)||t.length>=3&&[...e].some(s=>s.startsWith(t))}function N(e,t){return W(e.labelTokens,t)||W(e.identityTokens,t)||W(e.aliasTokens,t)||W(e.allTokens,t)}function re(e,t,s,o){let{label:r,identity:i,aliases:d,haystack:h}=e,l=0;(r===t||i===t||d.includes(t))&&(l+=1e4),(r.startsWith(t)||i.startsWith(t))&&(l+=250),h.includes(t)&&(l+=100);let a=0;for(let p of s){let g=o.get(p)??1,k=W(e.labelTokens,p),u=W(e.identityTokens,p),w=W(e.aliasTokens,p),f=N(e,p);f&&(a+=1),r===p?l+=80*g:k&&(l+=36*g),u&&(l+=24*g),w&&(l+=20*g),f&&(l+=10*g);}return s.length>0&&(l+=a/s.length*120),l}function ie(e,t){let s=new Set;for(let o of t){let r=e.allTokens.has(o)?o:void 0,i=r===void 0&&o.length>=3?[...e.allTokens].find(h=>h.startsWith(o)&&!s.has(h)):void 0,d=r??i;d&&!s.has(d)&&s.add(d);}return s.size}var ce=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 le(e){return new Set(e.map(t=>ce.get(t)).filter(t=>!!t))}function Q(e){let t=e.attributes.language;return typeof t=="string"?b(t):null}function de(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 pe=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"]);function ge(e,t){let s=t.has("language")||t.has("languages"),o=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"),d=t.has("owner")||t.has("owners")||t.has("ownership")||t.has("maintainer"),h=t.has("ci")||t.has("pipeline")||t.has("pipelines")||t.has("workflow"),l=t.has("deploy")||t.has("deployment")||t.has("infrastructure")||t.has("container"),a=t.has("doc")||t.has("docs")||t.has("document")||t.has("documentation"),p=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"),k=typeof e.attributes.mechanism=="string"?b(e.attributes.mechanism):"",u=typeof e.attributes.specification=="string"?b(e.attributes.specification):"",w=b(e.label),f=0;if(s&&e.kind==="language"){let B=typeof e.attributes.fileCount=="number"?e.attributes.fileCount:0;f+=900+Math.min(B,1e4)/10;}return o&&e.kind==="protocol"&&(f+=800),r&&e.kind==="package"&&(f+=650),i&&e.kind==="package"&&/(?:^|[_-])core(?:$|[_-])/u.test(w)&&(f+=700),i&&e.kind==="protocol"&&k.includes("core")&&(f+=300),d&&e.kind==="owner"&&(f+=850),h&&e.kind==="pipeline"&&(f+=800),l&&["deployment","container","environment"].includes(e.kind)&&(f+=775),a&&["document","decision"].includes(e.kind)&&(f+=725),p&&["api","endpoint","service"].includes(e.kind)&&(f+=700),g&&(e.kind==="schema"||(e.kind==="api"||e.kind==="protocol")&&(u.includes("protobuf")||k.includes("protobuf")))&&(f+=750),f}function he(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 Ie(e,t){let s=b(t.query),o=[...new Set(M(t.query))],r=new Set(M(t.projectId??"")),i=t.projectId?o.filter(n=>!r.has(n)):o,d=!!(t.projectId&&o.length>0&&i.length===0),h=i.filter(n=>!oe.has(n)),l=h.length>0?h:i,a=le(l),p=new Set(l),g=l.filter(n=>!pe.has(n)),k=he(p),u=l.length<=1?l.length:Math.min(2,Math.ceil(l.length/3)),w=t.minimumTermMatches===void 0?u:Math.min(u,Math.max(1,Math.trunc(t.minimumTermMatches))),f=Math.max(1,Math.min(Math.trunc(t.limit??12),100)),B=Math.max(0,Math.min(Math.trunc(t.relationsPerEntity??4),20)),_=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)&&_.add(c.to),n.has(c.to)&&_.add(c.from);}let O=e.entities.filter(n=>(!t.kind||n.kind===t.kind)&&(!t.projectId||n.projectId===t.projectId||n.projectId===void 0&&_.has(n.id))).map(ae),Y=new Map(l.map(n=>{let c=O.filter(y=>N(y,n)).length;return [n,Math.log((O.length+1)/(c+1))+1]})),v=O.map(n=>{let c=ie(n,l),y=Q(n.entity),I=y&&a.has(y)?400:0,S=ge(n.entity,p),j=g.length===0||g.some(A=>N(n,A))?S:0;return {entity:n.entity,matchedTerms:c,intentScore:j,score:d?de(n.entity):re(n,s,l,Y)+I+j}}).filter(n=>{let c=Q(n.entity);return (a.size===0||c===null||a.has(c))&&(s.length===0||n.score>0&&(d||n.matchedTerms>=w||n.intentScore>0&&(k||l.length<=2)))}).sort((n,c)=>c.score-n.score||n.entity.kind.localeCompare(c.entity.kind)||n.entity.label.localeCompare(c.entity.label)),E=(k?(()=>{let n=[],c=[],y=new Map,I=new Set;for(let S of v){let j=y.get(S.entity.kind)??0,A=b(S.entity.label);j<2&&!I.has(A)?(n.push(S),y.set(S.entity.kind,j+1),I.add(A)):c.push(S);}return [...n,...c]})():v).slice(0,f).map(n=>n.entity),P=new Set(E.map(n=>n.id)),L=new Map,G=e.relations.filter(n=>{if(!(P.has(n.from)||P.has(n.to)))return false;let y=P.has(n.from)?n.from:n.to,I=L.get(y)??0;return I>=B?false:(L.set(y,I+1),true)}),K=t.projection==="agent",T=K?G.slice(0,m.relations):G,z=x(e),H=[...new Set(T.flatMap(n=>[n.from,n.to]).filter(n=>!P.has(n)))].map(n=>z.entitiesById.get(n)).filter(n=>!!n).map(({id:n,kind:c,label:y,projectId:I})=>({id:n,kind:c,label:y,...I?{projectId:I}:{}})).sort((n,c)=>n.kind.localeCompare(c.kind)||n.label.localeCompare(c.label)),q=K?H.slice(0,m.relatedEntities):H,V=new Set([...E.flatMap(n=>n.proofIds),...T.flatMap(n=>n.proofIds)]),$=K?ee([...E,...T]):[...V],R=new Set($),C={entities:v.length-E.length,relations:G.length-T.length,relatedEntities:H.length-q.length,proofs:V.size-R.size,proofReferences:0,aliases:0,attributeValues:0},F=K?E.map(n=>te(n,R,C)):E,X=K?T.map(n=>{let c=n.proofIds.filter(y=>R.has(y)).slice(0,m.proofIdsPerItem);return C.proofReferences+=n.proofIds.length-c.length,{...n,proofIds:c}}):T,Z=[...R].map(n=>z.proofsById.get(n)).filter(n=>!!n).sort((n,c)=>n.id.localeCompare(c.id));return {schemaVersion:J,query:t.query,kind:t.kind??null,...t.projectId?{projectId:t.projectId}:{},limit:f,totalMatches:v.length,truncated:v.length>F.length||K&&Object.values(C).some(n=>n>0),entities:F,relatedEntities:q,relations:X,proofs:Z,...K?{budget:{mode:"agent",limits:{...m},omitted:C}}:{}}}export{J as a,D as b,ke as c,me as d,be as e,Ie as f};
1
+ var J="workspace-knowledge-search.v1";function b(e){return e.trim().toLowerCase()}var U=new WeakMap;function x(e){let t=U.get(e);if(t)return t;let s=new Map(e.relations.map(a=>[a.id,a])),o=new Map(e.entities.map(a=>[a.id,a])),r=new Map(e.proofs.map(a=>[a.id,a])),i=new Map,d=new Map,h=(a,p)=>{let g=d.get(a)??[];g.push(p),d.set(a,g);};for(let a of e.entities){let p=[a.id,a.label,a.identity.key,...a.kind==="project"&&a.projectId?[a.projectId]:[],...a.identity.aliases];for(let g of new Set(p.map(b))){let k=i.get(g)??[];k.push(a),i.set(g,k);}}for(let a of e.relations)h(a.from,{from:a.from,to:a.to,relationId:a.id,kind:a.kind,direction:"forward",proofIds:a.proofIds}),h(a.to,{from:a.to,to:a.from,relationId:a.id,kind:a.kind,direction:"reverse",proofIds:a.proofIds});for(let a of i.values())a.sort((p,g)=>p.id.localeCompare(g.id));for(let a of d.values())a.sort((p,g)=>p.to.localeCompare(g.to)||p.relationId.localeCompare(g.relationId));let l={entitiesById:o,relationsById:s,entitiesByAlias:i,proofsById:r,adjacency:d};return U.set(e,l),l}function D(e,t){let s=x(e),o=s.relationsById.get(t);if(o)return {found:true,targetType:"relation",relation:o};let r=b(t),i=s.entitiesByAlias.get(r)??[];return i.length===1?{found:true,targetType:"entity",entity:i[0]}:{found:false,query:t,candidates:i.map(d=>d.id).sort()}}function ke(e,t){let s=D(e,t);if(!s.found)return {query:t,found:false,target:null,proofs:[],candidates:s.candidates};let o=s.targetType==="entity"?s.entity:s.relation,r=new Set(o.proofIds);return {query:t,found:true,target:o,candidates:[],proofs:[...r].map(i=>x(e).proofsById.get(i)).filter(i=>!!i).sort((i,d)=>i.id.localeCompare(d.id))}}function me(e,t,s){let o=D(e,t),r=D(e,s);if(!o.found||o.targetType!=="entity"||!r.found||r.targetType!=="entity")return {from:t,to:s,found:false,resolvedFrom:o.found&&o.targetType==="entity"?o.entity.id:null,resolvedTo:r.found&&r.targetType==="entity"?r.entity.id:null,entityPath:[],hops:[],proofs:[]};let i=x(e),d=[o.entity.id],h=new Map,l=new Set(d),a=0;for(;a<d.length&&!l.has(r.entity.id);){let u=d[a++];for(let w of i.adjacency.get(u)??[])l.has(w.to)||(l.add(w.to),h.set(w.to,w),d.push(w.to));}if(!l.has(r.entity.id))return {from:t,to:s,found:false,resolvedFrom:o.entity.id,resolvedTo:r.entity.id,entityPath:[],hops:[],proofs:[]};let p=[],g=r.entity.id;for(;g!==o.entity.id;){let u=h.get(g);if(!u)break;p.push(u),g=u.from;}p.reverse();let k=new Set(p.flatMap(u=>u.proofIds));return {from:t,to:s,found:true,resolvedFrom:o.entity.id,resolvedTo:r.entity.id,entityPath:[o.entity.id,...p.map(u=>u.to)],hops:p,proofs:[...k].map(u=>i.proofsById.get(u)).filter(u=>!!u).sort((u,w)=>u.id.localeCompare(w.id))}}function be(e,t,s){return e.entities.filter(o=>(!t||o.kind===t)&&(!s||o.projectId===s)).sort((o,r)=>o.kind.localeCompare(r.kind)||o.label.localeCompare(r.label))}var m={relations:12,relatedEntities:12,proofs:8,proofIdsPerItem:4,aliasesPerEntity:8,attributeArrayItems:8,attributeStringCharacters:256};function ee(e){let t=[],s=new Set;for(let o=0;o<m.proofIdsPerItem&&t.length<m.proofs;o+=1)for(let r of e){let i=r.proofIds[o];if(!(!i||s.has(i))&&(s.add(i),t.push(i),t.length>=m.proofs))break}return t}function te(e,t,s){let o=e.identity.aliases.slice(0,m.aliasesPerEntity);s.aliases+=e.identity.aliases.length-o.length;let r=Object.fromEntries(Object.entries(e.attributes).map(([d,h])=>{if(Array.isArray(h)){let l=h.slice(0,m.attributeArrayItems);return s.attributeValues+=h.length-l.length,[d,l]}return typeof h=="string"&&h.length>m.attributeStringCharacters?(s.attributeValues+=1,[d,h.slice(0,m.attributeStringCharacters)]):[d,h]})),i=e.proofIds.filter(d=>t.has(d)).slice(0,m.proofIdsPerItem);return s.proofReferences+=e.proofIds.length-i.length,{...e,identity:{...e.identity,aliases:o},attributes:r,proofIds:i}}function ne(e){let t=Object.values(e.attributes).flatMap(s=>Array.isArray(s)?s:[s]);return [e.id,e.kind,e.label,e.projectId??"",e.identity.key,...e.identity.aliases,...t.map(s=>String(s??""))].join(" ").toLowerCase()}var oe=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"]),se=new Map([["authenticate","auth"],["authenticated","auth"],["authentication","auth"],["authorization","auth"],["authorizing","auth"],["config","configuration"],["configs","configuration"],["dependencies","dependency"],["diagnostics","diagnostic"],["reliable","reliability"],["tested","test"],["testing","test"],["tests","test"],["verification","verify"],["verified","verify"],["verifies","verify"],["verifying","verify"]]);function M(e){let t=s=>b(s).replace(/\bc\+\+/gu," cplusplus ").replace(/\bc#/gu," csharp ").split(/[^a-z0-9]+/u).filter(o=>o.length>1||o==="c"||o==="r").map(o=>se.get(o)??o);return [...new Set([...t(e),...t(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2"))])]}function ae(e){let t=b(e.label),s=b(e.identity.key),o=e.identity.aliases.map(b),r=ne(e);return {entity:e,label:t,identity:s,aliases:o,haystack:r,labelTokens:new Set(M(e.label)),identityTokens:new Set(M(e.identity.key)),aliasTokens:new Set(e.identity.aliases.flatMap(M)),allTokens:new Set(M(r))}}function W(e,t){return e.has(t)||t.length>=3&&[...e].some(s=>s.startsWith(t))}function N(e,t){return W(e.labelTokens,t)||W(e.identityTokens,t)||W(e.aliasTokens,t)||W(e.allTokens,t)}function re(e,t,s,o){let{label:r,identity:i,aliases:d,haystack:h}=e,l=0;(r===t||i===t||d.includes(t))&&(l+=1e4),(r.startsWith(t)||i.startsWith(t))&&(l+=250),h.includes(t)&&(l+=100);let a=0;for(let p of s){let g=o.get(p)??1,k=W(e.labelTokens,p),u=W(e.identityTokens,p),w=W(e.aliasTokens,p),f=N(e,p);f&&(a+=1),r===p?l+=80*g:k&&(l+=36*g),u&&(l+=24*g),w&&(l+=20*g),f&&(l+=10*g);}return s.length>0&&(l+=a/s.length*120),l}function ie(e,t){let s=new Set;for(let o of t){let r=e.allTokens.has(o)?o:void 0,i=r===void 0&&o.length>=3?[...e.allTokens].find(h=>h.startsWith(o)&&!s.has(h)):void 0,d=r??i;d&&!s.has(d)&&s.add(d);}return s.size}var ce=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 le(e){return new Set(e.map(t=>ce.get(t)).filter(t=>!!t))}function Q(e){let t=e.attributes.language;return typeof t=="string"?b(t):null}function de(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 pe=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"]);function ge(e,t){let s=t.has("language")||t.has("languages"),o=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"),d=t.has("owner")||t.has("owners")||t.has("ownership")||t.has("maintainer"),h=t.has("ci")||t.has("pipeline")||t.has("pipelines")||t.has("workflow"),l=t.has("deploy")||t.has("deployment")||t.has("infrastructure")||t.has("container"),a=t.has("doc")||t.has("docs")||t.has("document")||t.has("documentation"),p=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"),k=typeof e.attributes.mechanism=="string"?b(e.attributes.mechanism):"",u=typeof e.attributes.specification=="string"?b(e.attributes.specification):"",w=b(e.label),f=0;if(s&&e.kind==="language"){let B=typeof e.attributes.fileCount=="number"?e.attributes.fileCount:0;f+=900+Math.min(B,1e4)/10;}return o&&e.kind==="protocol"&&(f+=800),r&&e.kind==="package"&&(f+=650),i&&e.kind==="package"&&/(?:^|[_-])core(?:$|[_-])/u.test(w)&&(f+=700),i&&e.kind==="protocol"&&k.includes("core")&&(f+=300),d&&e.kind==="owner"&&(f+=850),h&&e.kind==="pipeline"&&(f+=800),l&&["deployment","container","environment"].includes(e.kind)&&(f+=775),a&&["document","decision"].includes(e.kind)&&(f+=725),p&&["api","endpoint","service"].includes(e.kind)&&(f+=700),g&&(e.kind==="schema"||(e.kind==="api"||e.kind==="protocol")&&(u.includes("protobuf")||k.includes("protobuf")))&&(f+=750),f}function he(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 Ie(e,t){let s=b(t.query),o=[...new Set(M(t.query))],r=new Set(M(t.projectId??"")),i=t.projectId?o.filter(n=>!r.has(n)):o,d=!!(t.projectId&&o.length>0&&i.length===0),h=i.filter(n=>!oe.has(n)),l=h.length>0?h:i,a=le(l),p=new Set(l),g=l.filter(n=>!pe.has(n)),k=he(p),u=l.length<=1?l.length:Math.min(2,Math.ceil(l.length/3)),w=t.minimumTermMatches===void 0?u:Math.min(u,Math.max(1,Math.trunc(t.minimumTermMatches))),f=Math.max(1,Math.min(Math.trunc(t.limit??12),100)),B=Math.max(0,Math.min(Math.trunc(t.relationsPerEntity??4),20)),_=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)&&_.add(c.to),n.has(c.to)&&_.add(c.from);}let O=e.entities.filter(n=>(!t.kind||n.kind===t.kind)&&(!t.projectId||n.projectId===t.projectId||n.projectId===void 0&&_.has(n.id))).map(ae),Y=new Map(l.map(n=>{let c=O.filter(y=>N(y,n)).length;return [n,Math.log((O.length+1)/(c+1))+1]})),v=O.map(n=>{let c=ie(n,l),y=Q(n.entity),I=y&&a.has(y)?400:0,S=ge(n.entity,p),j=g.length===0||g.some(A=>N(n,A))?S:0;return {entity:n.entity,matchedTerms:c,intentScore:j,score:d?de(n.entity):re(n,s,l,Y)+I+j}}).filter(n=>{let c=Q(n.entity);return (a.size===0||c===null||a.has(c))&&(s.length===0||n.score>0&&(d||n.matchedTerms>=w||n.intentScore>0&&(k||l.length<=2)))}).sort((n,c)=>c.score-n.score||n.entity.kind.localeCompare(c.entity.kind)||n.entity.label.localeCompare(c.entity.label)),E=(k?(()=>{let n=[],c=[],y=new Map,I=new Set;for(let S of v){let j=y.get(S.entity.kind)??0,A=b(S.entity.label);j<2&&!I.has(A)?(n.push(S),y.set(S.entity.kind,j+1),I.add(A)):c.push(S);}return [...n,...c]})():v).slice(0,f).map(n=>n.entity),P=new Set(E.map(n=>n.id)),L=new Map,H=e.relations.filter(n=>{if(!(P.has(n.from)||P.has(n.to)))return false;let y=P.has(n.from)?n.from:n.to,I=L.get(y)??0;return I>=B?false:(L.set(y,I+1),true)}),K=t.projection==="agent",T=K?H.slice(0,m.relations):H,z=x(e),G=[...new Set(T.flatMap(n=>[n.from,n.to]).filter(n=>!P.has(n)))].map(n=>z.entitiesById.get(n)).filter(n=>!!n).map(({id:n,kind:c,label:y,projectId:I})=>({id:n,kind:c,label:y,...I?{projectId:I}:{}})).sort((n,c)=>n.kind.localeCompare(c.kind)||n.label.localeCompare(c.label)),q=K?G.slice(0,m.relatedEntities):G,V=new Set([...E.flatMap(n=>n.proofIds),...T.flatMap(n=>n.proofIds)]),$=K?ee([...E,...T]):[...V],R=new Set($),C={entities:v.length-E.length,relations:H.length-T.length,relatedEntities:G.length-q.length,proofs:V.size-R.size,proofReferences:0,aliases:0,attributeValues:0},F=K?E.map(n=>te(n,R,C)):E,X=K?T.map(n=>{let c=n.proofIds.filter(y=>R.has(y)).slice(0,m.proofIdsPerItem);return C.proofReferences+=n.proofIds.length-c.length,{...n,proofIds:c}}):T,Z=[...R].map(n=>z.proofsById.get(n)).filter(n=>!!n).sort((n,c)=>n.id.localeCompare(c.id));return {schemaVersion:J,graphSourceHash:e.source.hash,query:t.query,kind:t.kind??null,...t.projectId?{projectId:t.projectId}:{},limit:f,totalMatches:v.length,truncated:v.length>F.length||K&&Object.values(C).some(n=>n>0),entities:F,relatedEntities:q,relations:X,proofs:Z,...K?{budget:{mode:"agent",limits:{...m},omitted:C}}:{}}}export{J as a,D as b,ke as c,me as d,be as e,Ie as f};
@@ -1,2 +1,2 @@
1
- import {b}from'./chunk-IKUFNK46.js';import {d}from'./chunk-5TY74LLW.js';import {w as w$1,x}from'./chunk-VQZ5PI5J.js';import l from'path';import {randomUUID}from'crypto';import {open,link,copyFile}from'fs/promises';import s from'fs-extra';function I(t,r){let a=l.resolve(t),e=r.trim();if(!e||l.isAbsolute(e))throw new Error(`Workspace artifact path must be non-empty and relative: ${r}`);let i=l.resolve(a,e),n=l.relative(a,i);if(n===".."||n.startsWith(`..${l.sep}`)||l.isAbsolute(n))throw new Error(`Workspace artifact path escapes workspace root: ${r}`);return i}function w(t,r){return I(t,w$1(r))}function F(t,r){return I(t,x(r))}async function M(t,r){let a=l.resolve(t);await s.ensureDir(a);let e=l.dirname(r);await s.ensureDir(e);let[i,n]=await Promise.all([s.realpath(a),s.realpath(e)]),f=l.relative(i,n);if(f===".."||f.startsWith(`..${l.sep}`)||l.isAbsolute(f))throw new Error(`Workspace artifact parent resolves outside workspace root: ${e}`)}async function $(t,r){let a=l.resolve(t),[e,i]=await Promise.all([s.realpath(a),s.realpath(r)]),n=l.relative(e,i);if(n===".."||n.startsWith(`..${l.sep}`)||l.isAbsolute(n))throw new Error(`Workspace artifact resolves outside workspace root: ${r}`)}function L(t){let r=t?.code;return process.platform==="win32"&&(r==="EPERM"||r==="EINVAL"||r==="ENOSYS")}function R(t,r=process.platform){if(r!=="win32")return false;let a=t?.code;return a==="EPERM"||a==="EACCES"||a==="EBUSY"}async function h(t){let r=process.platform==="win32"?6:1,a;for(let e=0;e<r;e+=1)try{await s.remove(t);return}catch(i){if(a=i,!R(i)||e===r-1)throw i;await new Promise(n=>setTimeout(n,10*2**e));}throw a}var g=new Map;async function C(t,r){let a=g.get(t)??Promise.resolve(),e,i=new Promise(f=>{e=f;}),n=a.catch(()=>{}).then(()=>i);g.set(t,n),await a.catch(()=>{});try{return await r()}finally{e(),g.get(t)===n&&g.delete(t);}}async function N(t){try{await t.sync();}catch(r){if(!L(r))throw r}}async function y(t,r,a){await M(t,r);let e=l.dirname(r),i=`${l.basename(r)}.`,n=Date.now();for(let o of await s.readdir(e)){if(!o.startsWith(i)||!o.endsWith(".tmp"))continue;let p=l.join(e,o),u=await s.stat(p).catch(()=>null);u&&n-u.mtimeMs>3e4&&await s.remove(p).catch(()=>{});}let f=`${r}.${process.pid}.${randomUUID()}.tmp`;try{await a(f);let o=await open(f,"r");try{await N(o);}finally{await o.close();}let p=Number(process.env.WORKSPAI_TEST_ATOMIC_WRITE_DELAY_MS??0);Number.isFinite(p)&&p>0&&await new Promise(u=>setTimeout(u,Math.min(p,3e4)));try{await s.rename(f,r);}catch(u){let c=u.code;if(c!=="EEXIST"&&c!=="EPERM")throw u;await s.move(f,r,{overwrite:true});}}finally{await s.remove(f).catch(()=>{});}}async function O(t,r,a,e={}){let i=w(t,r);await M(t,i);let n=`${i}.lock`;return C(n,()=>j(n,r,a,e))}async function j(t,r,a,e){let i=e.timeoutMs??1e4,n=e.staleAfterMs??3e4,f=Date.now(),o;for(;!o;)try{o=await open(t,"wx"),await o.writeFile(`${JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})}
1
+ import {b}from'./chunk-IKUFNK46.js';import {d}from'./chunk-25AWHAB5.js';import {w as w$1,x}from'./chunk-VQZ5PI5J.js';import l from'path';import {randomUUID}from'crypto';import {open,link,copyFile}from'fs/promises';import s from'fs-extra';function I(t,r){let a=l.resolve(t),e=r.trim();if(!e||l.isAbsolute(e))throw new Error(`Workspace artifact path must be non-empty and relative: ${r}`);let i=l.resolve(a,e),n=l.relative(a,i);if(n===".."||n.startsWith(`..${l.sep}`)||l.isAbsolute(n))throw new Error(`Workspace artifact path escapes workspace root: ${r}`);return i}function w(t,r){return I(t,w$1(r))}function F(t,r){return I(t,x(r))}async function M(t,r){let a=l.resolve(t);await s.ensureDir(a);let e=l.dirname(r);await s.ensureDir(e);let[i,n]=await Promise.all([s.realpath(a),s.realpath(e)]),f=l.relative(i,n);if(f===".."||f.startsWith(`..${l.sep}`)||l.isAbsolute(f))throw new Error(`Workspace artifact parent resolves outside workspace root: ${e}`)}async function $(t,r){let a=l.resolve(t),[e,i]=await Promise.all([s.realpath(a),s.realpath(r)]),n=l.relative(e,i);if(n===".."||n.startsWith(`..${l.sep}`)||l.isAbsolute(n))throw new Error(`Workspace artifact resolves outside workspace root: ${r}`)}function L(t){let r=t?.code;return process.platform==="win32"&&(r==="EPERM"||r==="EINVAL"||r==="ENOSYS")}function R(t,r=process.platform){if(r!=="win32")return false;let a=t?.code;return a==="EPERM"||a==="EACCES"||a==="EBUSY"}async function h(t){let r=process.platform==="win32"?6:1,a;for(let e=0;e<r;e+=1)try{await s.remove(t);return}catch(i){if(a=i,!R(i)||e===r-1)throw i;await new Promise(n=>setTimeout(n,10*2**e));}throw a}var g=new Map;async function C(t,r){let a=g.get(t)??Promise.resolve(),e,i=new Promise(f=>{e=f;}),n=a.catch(()=>{}).then(()=>i);g.set(t,n),await a.catch(()=>{});try{return await r()}finally{e(),g.get(t)===n&&g.delete(t);}}async function N(t){try{await t.sync();}catch(r){if(!L(r))throw r}}async function y(t,r,a){await M(t,r);let e=l.dirname(r),i=`${l.basename(r)}.`,n=Date.now();for(let o of await s.readdir(e)){if(!o.startsWith(i)||!o.endsWith(".tmp"))continue;let p=l.join(e,o),u=await s.stat(p).catch(()=>null);u&&n-u.mtimeMs>3e4&&await s.remove(p).catch(()=>{});}let f=`${r}.${process.pid}.${randomUUID()}.tmp`;try{await a(f);let o=await open(f,"r");try{await N(o);}finally{await o.close();}let p=Number(process.env.WORKSPAI_TEST_ATOMIC_WRITE_DELAY_MS??0);Number.isFinite(p)&&p>0&&await new Promise(u=>setTimeout(u,Math.min(p,3e4)));try{await s.rename(f,r);}catch(u){let c=u.code;if(c!=="EEXIST"&&c!=="EPERM")throw u;await s.move(f,r,{overwrite:true});}}finally{await s.remove(f).catch(()=>{});}}async function O(t,r,a,e={}){let i=w(t,r);await M(t,i);let n=`${i}.lock`;return C(n,()=>j(n,r,a,e))}async function j(t,r,a,e){let i=e.timeoutMs??1e4,n=e.staleAfterMs??3e4,f=Date.now(),o;for(;!o;)try{o=await open(t,"wx"),await o.writeFile(`${JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})}
2
2
  `),await N(o);}catch(p){if(!(p.code==="EEXIST"||R(p)))throw o&&(await o.close().catch(()=>{}),o=void 0,await h(t).catch(()=>{})),p;o&&(await o.close().catch(()=>{}),o=void 0,await h(t).catch(()=>{}));let[d,_]=await Promise.all([s.stat(t).catch(()=>null),s.readJson(t).catch(()=>null)]),P=Number(_?.pid),A=Number.isInteger(P)&&P>0,E=false;if(A)try{process.kill(P,0),E=true;}catch(v){E=v.code==="EPERM";}let J=!A&&!!(d&&Date.now()-d.mtimeMs>n);if(A&&!E||J){await h(t).catch(()=>{});continue}if(Date.now()-f>=i)throw new Error(`Timed out waiting for workspace artifact lock: ${r}`);await new Promise(v=>setTimeout(v,20));}try{return await a()}finally{await o.close().catch(()=>{}),await h(t);}}async function Q(t,r){let a=[w(t,r),F(t,r)];for(let e of a)if(await s.pathExists(e))return await $(t,e),e;return null}async function Z(t,r,a){b(r,a);let e=w(t,r);return await y(t,e,i=>s.writeJson(i,a,{spaces:2})),d({workspacePath:t,relativePath:r}),e}async function tt(t,r,a){return U(t,r,a.map(e=>({rootPath:t,...e})))}async function U(t,r,a){if(a.length===0)return [];let e=a.map(n=>({...n,rootPath:l.resolve(n.rootPath),path:w(n.rootPath,n.relativePath)})),i=e.find((n,f)=>e.findIndex(o=>o.path===n.path)!==f);if(i)throw new Error(`Duplicate workspace artifact transaction target: ${i.relativePath}`);for(let n of e)b(n.relativePath,n.payload);return O(t,r,async()=>{let n=randomUUID(),f=[];try{for(let o of e){let p=await s.pathExists(o.path),u={path:o.path,rootPath:o.rootPath,exists:p,backupPath:null};if(f.push(u),p){let c=`${o.path}.${process.pid}.${n}.rollback`;await $(o.rootPath,o.path);try{try{await link(o.path,c);}catch{await copyFile(o.path,c);}u.backupPath=c;}catch(d){throw await s.remove(c).catch(()=>{}),d}}}for(let o=0;o<e.length;o+=1){let p=e[o];await y(p.rootPath,p.path,c=>s.writeJson(c,p.payload,{spaces:2}));let u=Number(process.env.WORKSPAI_TEST_FAIL_ARTIFACT_SET_AFTER??0);if(Number.isInteger(u)&&u===o+1)throw new Error(`Injected artifact-set failure after ${u} write(s).`)}for(let o of e)d({workspacePath:o.rootPath,relativePath:o.relativePath});return e.map(o=>o.path)}catch(o){let u=(await Promise.allSettled(f.map(async c=>{if(!c.exists){await s.remove(c.path);return}c.backupPath&&await y(c.rootPath,c.path,d=>copyFile(c.backupPath,d));}))).filter(c=>c.status==="rejected");throw u.length>0?new AggregateError([o,...u.map(c=>c.reason)],"Workspace artifact transaction failed and rollback was incomplete."):o}finally{await Promise.all(f.map(o=>o.backupPath?s.remove(o.backupPath).catch(()=>{}):Promise.resolve()));}})}async function rt(t,r,a){let e=w(t,r);return await y(t,e,i=>s.writeFile(i,a,"utf-8")),d({workspacePath:t,relativePath:r}),e}export{w as a,F as b,O as c,Q as d,Z as e,tt as f,U as g,rt as h};
@@ -1,2 +1,2 @@
1
- import {b as b$1}from'./chunk-3OGPTLI2.js';import {b}from'./chunk-PSYQ6IJA.js';import {q,f as f$1,g}from'./chunk-TP7VKEUF.js';import {d}from'./chunk-EHCKITR4.js';import {e as e$1,d as d$1}from'./chunk-XDPTAV2T.js';import {f,e}from'./chunk-ZGHJIQXL.js';import E from'path';import A from'fs-extra';var re=f.agentContext,se=e.agentContext;function ne(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="gemini"||t==="qwen"||t==="kimi"||t==="grok"||t==="copilot"||t==="windsurf"||t==="amazon-q"||t==="orca"?t:"generic"}function G(e){return `npx --yes --package workspai workspai ${e}`.trim()}function x(e){return `npx workspai ${e}`.trim()}async function C(e,t,i){let s=E.join(e,t);if(!await A.pathExists(s))return null;try{let n=await A.readJson(s);return typeof n!="object"||n===null||!("schemaVersion"in n)||n.schemaVersion!==i?null:n}catch{return null}}function m(e$1){return {id:e$1.id,scope:e$1.scope,display:x(e$1.args),execute:G(e$1.args),description:e$1.description,...e$1.project?{project:e$1.project}:{},freshness:f$1({id:`command.${e$1.id}`,label:`${e$1.id} command`,scope:"command",value:{display:x(e$1.args),execute:G(e$1.args)},...e$1.project?{project:e$1.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e$1.generatedAt,now:e$1.now,sourceArtifact:e.model,sourcePath:`safeCommands.${e$1.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function L(e,t){return `workspace run ${t} --scope project:${e.name}`}function ae(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function ie(e,t,i){let s={generatedAt:e.generatedAt,now:i},n=[m({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),m({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),m({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),m({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),m({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),m({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),m({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),m({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=t?[t]:e.projects;for(let a of c)a.commands.fleetStages.includes("test")&&n.push(m({id:`project.${a.name}.test`,scope:"project",project:a.name,args:L(a,"test"),description:`Run tests for ${a.name} through workspace orchestration.`,...s})),a.commands.fleetStages.includes("build")&&n.push(m({id:`project.${a.name}.build`,scope:"project",project:a.name,args:L(a,"build"),description:`Build ${a.name} through workspace orchestration.`,...s}));return n}function ce(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function pe(e,t){if(!t?.startsWith("project:"))return;let i=ae(t);if(i)return e.projects.find(s=>oe(s).includes(i))}function de(e,t,i){let s=[...e.validation?.issues??[]];t?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let n=s.filter(a=>a.severity==="error").length,c=s.filter(a=>a.severity==="warning").length;return {status:n>0?"failed":c>0?"warning":"passed",errors:n,warnings:c,issues:s}}async function me(e,t){let i=[],s=[];for(let[n,c]of Object.entries(e.evidence))c&&await d$1(t,c.path)!==null?i.push(`${n}: ${c.path}`):s.push(n);return {available:i.sort(),missing:s.sort()}}function le(e){let t=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${i}, and ${s}.`}function ge(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),((e.summary.extendedProjects??0)>0||e.summary.observedProjects>0)&&t.push("Some projects use extended or observed support tiers; command coverage may be partial."),t}async function We(e$1){let t=e$1.model??await q({workspacePath:e$1.workspacePath,includeEvidence:e$1.includeEvidence===true,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),i=ne(e$1.agent),s=pe(t,e$1.scope),n=de(t,e$1.scope,s);if(e$1.strict===true&&n.status!=="passed"){let r=n.issues.map(g=>`${g.severity}:${g.code}:${g.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${r}`)}let c=e$1.now??new Date,a=t.facts??[],K=new Set((s?[s]:t.projects).map(r=>r.name)),R=a.filter(r=>r.project?K.has(r.project):true),H=(s?[s]:t.projects).map(r=>{let g=R.filter(p=>p.project===r.name);return {name:r.name,path:r.path,kind:r.kind,category:r.category,runtime:r.runtime,framework:r.frameworkDisplayName,...r.generator?{generator:r.generator}:{},createCapability:r.createCapability,supportTier:r.supportTier,...r.governance?{governance:r.governance}:{},safeCommands:ce(r),importantFiles:r.importantFiles,facts:g}}),S=await me(t,e$1.workspacePath),F=E.join(e$1.workspacePath,e.knowledgeGraph),u=await A.pathExists(F)?await A.readJson(F).catch(()=>null):null,N=false;if(u?.schemaVersion===f.knowledgeGraph)try{b(u,t),N=true;}catch{}let $=le(t),M=ie(t,s,c),b$2=await C(e$1.workspacePath,e.impact,f.impact),l=await C(e$1.workspacePath,e.doctor,f.doctor),v=await C(e$1.workspacePath,e.analyze,f.analyze),k=await C(e$1.workspacePath,e.readiness,f.readiness),h=await C(e$1.workspacePath,e.verify,f.verify),w=await C(e$1.workspacePath,e.explain,f.explain),f$2=await C(e$1.workspacePath,e.diff,f.diff),B=b$2?.summary?{changed:b$2.summary.changed,risk:b$2.summary.risk,affectedProjects:b$2.summary.affectedProjects,blastRadius:b$2.summary.blastRadius,recommendedCommands:b$2.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let r=Array.isArray(l.projects)?l.projects:[],g=[];for(let p of r.slice(0,6)){let te=Array.isArray(p.probes)?p.probes:[];for(let y of te.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&g.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return g.slice(0,8)})()}:void 0,J=v?.summary?{score:v.summary.score,verdict:v.summary.verdict,findingCounts:v.summary.findings,topFindings:(Array.isArray(v.findings)?v.findings:[]).filter(p=>p?.severity==="fail"||p?.severity==="warn").slice(0,8).map(p=>({severity:p.severity,title:p.title,target:p.target,remediation:p.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(r=>({gate:r.gate,status:r.status,summary:r.summary})):void 0}:void 0,Q=h?.summary?{verdict:h.summary.verdict,exitCode:h.summary.exitCode,stepsFailed:h.summary.stepsFailed,stepsMissing:h.summary.stepsMissing,blockingReasons:h.blockingReasons,missingEvidence:h.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(r=>({id:r.id,title:r.title,body:r.body})):void 0}:void 0,Z=f$2?.summary?{changed:f$2.summary.changed,addedProjects:f$2.summary.addedProjects,removedProjects:f$2.summary.removedProjects,changedProjects:f$2.summary.changedProjects,workspaceChanges:f$2.summary.workspaceChanges,validationChanges:f$2.summary.validationChanges,gitChangedFiles:f$2.summary.gitChangedFiles}:void 0,ee=M.map(r=>f$1({id:`context.command.${r.id}`,label:`${r.id} safe command`,scope:"command",value:{display:r.display,execute:r.execute,scope:r.scope},...r.project?{project:r.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:c,sourceArtifact:e.agentContext,sourcePath:`safeCommands.${r.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),I=[...R,...ee],W=g({facts:I,generatedAt:c.toISOString(),now:c}),j=b$1();return {schemaVersion:re,generatedAt:c.toISOString(),agent:i,workspaceSummary:$,modelRef:e.model,knowledgeGraph:{artifact:e.knowledgeGraph,schemaVersion:f.knowledgeGraph,available:N,...typeof u?.quality?.entityCount=="number"?{entityCount:u.quality.entityCount}:{},...typeof u?.quality?.relationCount=="number"?{relationCount:u.quality.relationCount}:{},...typeof u?.quality?.proofCount=="number"?{proofCount:u.quality.proofCount}:{},queryCommands:[x("workspace graph search <query> --limit 12 --json"),x("workspace graph entities [kind] --json"),x("workspace graph evidence <entity-or-relation> --json"),x("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:j.schemaVersion,contractPath:j.contractPath,currentStep:"context",canonicalReadOrder:[...j.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:`workspace:${t.workspace.name}`,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e$1.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:M,facts:I,factFreshness:W,evidence:S,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:n,agentInstructions:[`Read \`${e.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${e.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ge(t),...W.verifyBeforeUseFacts>0?[`${W.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[$,`Evidence available: ${S.available.length}. Missing evidence groups: ${S.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
1
+ import {b as b$1}from'./chunk-3OGPTLI2.js';import {b}from'./chunk-LEOFD3W5.js';import {q,f as f$1,g}from'./chunk-2KX6KHEC.js';import {d}from'./chunk-TCLKGPXF.js';import {e as e$1,d as d$1}from'./chunk-C2VTO5WT.js';import {f,e}from'./chunk-ZGHJIQXL.js';import E from'path';import A from'fs-extra';var re=f.agentContext,se=e.agentContext;function ne(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="gemini"||t==="qwen"||t==="kimi"||t==="grok"||t==="copilot"||t==="windsurf"||t==="amazon-q"||t==="orca"?t:"generic"}function G(e){return `npx --yes --package workspai workspai ${e}`.trim()}function x(e){return `npx workspai ${e}`.trim()}async function C(e,t,i){let s=E.join(e,t);if(!await A.pathExists(s))return null;try{let n=await A.readJson(s);return typeof n!="object"||n===null||!("schemaVersion"in n)||n.schemaVersion!==i?null:n}catch{return null}}function m(e$1){return {id:e$1.id,scope:e$1.scope,display:x(e$1.args),execute:G(e$1.args),description:e$1.description,...e$1.project?{project:e$1.project}:{},freshness:f$1({id:`command.${e$1.id}`,label:`${e$1.id} command`,scope:"command",value:{display:x(e$1.args),execute:G(e$1.args)},...e$1.project?{project:e$1.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e$1.generatedAt,now:e$1.now,sourceArtifact:e.model,sourcePath:`safeCommands.${e$1.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function L(e,t){return `workspace run ${t} --scope project:${e.name}`}function ae(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function ie(e,t,i){let s={generatedAt:e.generatedAt,now:i},n=[m({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),m({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),m({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),m({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),m({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),m({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),m({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),m({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=t?[t]:e.projects;for(let a of c)a.commands.fleetStages.includes("test")&&n.push(m({id:`project.${a.name}.test`,scope:"project",project:a.name,args:L(a,"test"),description:`Run tests for ${a.name} through workspace orchestration.`,...s})),a.commands.fleetStages.includes("build")&&n.push(m({id:`project.${a.name}.build`,scope:"project",project:a.name,args:L(a,"build"),description:`Build ${a.name} through workspace orchestration.`,...s}));return n}function ce(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function pe(e,t){if(!t?.startsWith("project:"))return;let i=ae(t);if(i)return e.projects.find(s=>oe(s).includes(i))}function de(e,t,i){let s=[...e.validation?.issues??[]];t?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let n=s.filter(a=>a.severity==="error").length,c=s.filter(a=>a.severity==="warning").length;return {status:n>0?"failed":c>0?"warning":"passed",errors:n,warnings:c,issues:s}}async function me(e,t){let i=[],s=[];for(let[n,c]of Object.entries(e.evidence))c&&await d$1(t,c.path)!==null?i.push(`${n}: ${c.path}`):s.push(n);return {available:i.sort(),missing:s.sort()}}function le(e){let t=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${i}, and ${s}.`}function ge(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),((e.summary.extendedProjects??0)>0||e.summary.observedProjects>0)&&t.push("Some projects use extended or observed support tiers; command coverage may be partial."),t}async function We(e$1){let t=e$1.model??await q({workspacePath:e$1.workspacePath,includeEvidence:e$1.includeEvidence===true,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),i=ne(e$1.agent),s=pe(t,e$1.scope),n=de(t,e$1.scope,s);if(e$1.strict===true&&n.status!=="passed"){let r=n.issues.map(g=>`${g.severity}:${g.code}:${g.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${r}`)}let c=e$1.now??new Date,a=t.facts??[],K=new Set((s?[s]:t.projects).map(r=>r.name)),R=a.filter(r=>r.project?K.has(r.project):true),H=(s?[s]:t.projects).map(r=>{let g=R.filter(p=>p.project===r.name);return {name:r.name,path:r.path,kind:r.kind,category:r.category,runtime:r.runtime,framework:r.frameworkDisplayName,...r.generator?{generator:r.generator}:{},createCapability:r.createCapability,supportTier:r.supportTier,...r.governance?{governance:r.governance}:{},safeCommands:ce(r),importantFiles:r.importantFiles,facts:g}}),S=await me(t,e$1.workspacePath),F=E.join(e$1.workspacePath,e.knowledgeGraph),u=await A.pathExists(F)?await A.readJson(F).catch(()=>null):null,N=false;if(u?.schemaVersion===f.knowledgeGraph)try{b(u,t),N=true;}catch{}let $=le(t),M=ie(t,s,c),b$2=await C(e$1.workspacePath,e.impact,f.impact),l=await C(e$1.workspacePath,e.doctor,f.doctor),v=await C(e$1.workspacePath,e.analyze,f.analyze),k=await C(e$1.workspacePath,e.readiness,f.readiness),h=await C(e$1.workspacePath,e.verify,f.verify),w=await C(e$1.workspacePath,e.explain,f.explain),f$2=await C(e$1.workspacePath,e.diff,f.diff),B=b$2?.summary?{changed:b$2.summary.changed,risk:b$2.summary.risk,affectedProjects:b$2.summary.affectedProjects,blastRadius:b$2.summary.blastRadius,recommendedCommands:b$2.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let r=Array.isArray(l.projects)?l.projects:[],g=[];for(let p of r.slice(0,6)){let te=Array.isArray(p.probes)?p.probes:[];for(let y of te.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&g.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return g.slice(0,8)})()}:void 0,J=v?.summary?{score:v.summary.score,verdict:v.summary.verdict,findingCounts:v.summary.findings,topFindings:(Array.isArray(v.findings)?v.findings:[]).filter(p=>p?.severity==="fail"||p?.severity==="warn").slice(0,8).map(p=>({severity:p.severity,title:p.title,target:p.target,remediation:p.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(r=>({gate:r.gate,status:r.status,summary:r.summary})):void 0}:void 0,Q=h?.summary?{verdict:h.summary.verdict,exitCode:h.summary.exitCode,stepsFailed:h.summary.stepsFailed,stepsMissing:h.summary.stepsMissing,blockingReasons:h.blockingReasons,missingEvidence:h.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(r=>({id:r.id,title:r.title,body:r.body})):void 0}:void 0,Z=f$2?.summary?{changed:f$2.summary.changed,addedProjects:f$2.summary.addedProjects,removedProjects:f$2.summary.removedProjects,changedProjects:f$2.summary.changedProjects,workspaceChanges:f$2.summary.workspaceChanges,validationChanges:f$2.summary.validationChanges,gitChangedFiles:f$2.summary.gitChangedFiles}:void 0,ee=M.map(r=>f$1({id:`context.command.${r.id}`,label:`${r.id} safe command`,scope:"command",value:{display:r.display,execute:r.execute,scope:r.scope},...r.project?{project:r.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:c,sourceArtifact:e.agentContext,sourcePath:`safeCommands.${r.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),I=[...R,...ee],W=g({facts:I,generatedAt:c.toISOString(),now:c}),j=b$1();return {schemaVersion:re,generatedAt:c.toISOString(),agent:i,workspaceSummary:$,modelRef:e.model,knowledgeGraph:{artifact:e.knowledgeGraph,schemaVersion:f.knowledgeGraph,available:N,...typeof u?.quality?.entityCount=="number"?{entityCount:u.quality.entityCount}:{},...typeof u?.quality?.relationCount=="number"?{relationCount:u.quality.relationCount}:{},...typeof u?.quality?.proofCount=="number"?{proofCount:u.quality.proofCount}:{},queryCommands:[x("workspace graph search <query> --limit 12 --json"),x("workspace graph entities [kind] --json"),x("workspace graph evidence <entity-or-relation> --json"),x("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:j.schemaVersion,contractPath:j.contractPath,currentStep:"context",canonicalReadOrder:[...j.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:`workspace:${t.workspace.name}`,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e$1.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:M,facts:I,factFreshness:W,evidence:S,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:n,agentInstructions:[`Read \`${e.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${e.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ge(t),...W.verifyBeforeUseFacts>0?[`${W.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[$,`Evidence available: ${S.available.length}. Missing evidence groups: ${S.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
2
2
  `),impactSummary:B,doctorSummary:U,analyzeSummary:J,readinessSummary:X,verifySummary:Q,explainSummary:Y,diffSummary:Z}}async function je(e,t){return e$1(t,se,d(e))}export{re as a,se as b,We as c,je as d};
@@ -1,2 +1,2 @@
1
- import {e,b as b$1}from'./chunk-5TY74LLW.js';import b from'crypto';import {constants}from'fs';import a from'fs/promises';import n from'path';var O="workspai.lifecycle-transaction",k=1,v="manifest.json",N="lifecycle-transaction-";async function h(r){try{return await a.lstat(r)}catch(e){if(e.code==="ENOENT")return null;throw e}}function D(r){let e=r?.code;return process.platform==="win32"&&(e==="EPERM"||e==="EINVAL"||e==="ENOSYS")}async function E(r){try{await r.sync();}catch(e){if(!D(e))throw e}}function T(r){if(typeof r!="string"||!n.isAbsolute(r))throw new Error("Lifecycle transaction journal contains a non-absolute target path.")}function F(r){if(typeof r!="string"||r.length===0||n.basename(r)!==r||r==="."||r==="..")throw new Error("Lifecycle transaction journal contains an unsafe backup reference.")}function J(r){if(!r||typeof r!="object")throw new Error("Lifecycle transaction journal is not an object.");let e=r;if(e.kind!==O||e.version!==k)throw new Error("Lifecycle transaction journal has an unsupported format.");if(!Number.isInteger(e.ownerPid)||e.ownerPid<=0)throw new Error("Lifecycle transaction journal has an invalid owner process.");if(!["active","committed","rolling-back"].includes(e.phase))throw new Error("Lifecycle transaction journal has an invalid phase.");if(!Array.isArray(e.operations))throw new Error("Lifecycle transaction journal has invalid operations.");for(let t of e.operations){if(!t||typeof t!="object")throw new Error("Lifecycle transaction journal contains an invalid operation.");let i=t;if(T(i.path),i.type!=="tree"){if(i.type!=="file"||!["absent","regular"].includes(i.state))throw new Error("Lifecycle transaction journal contains an invalid operation.");if(i.state==="regular"){if(!Number.isInteger(i.mode)||i.mode<0||i.mode>4095)throw new Error("Lifecycle transaction journal contains an invalid file mode.");F(i.backup);}}}return e}async function L(r){let e;try{e=await a.open(r,constants.O_RDONLY);}catch(t){if(D(t))return;throw t}try{await E(e);}finally{await e.close();}}async function P(r,e){let t=n.join(n.dirname(r),`.${n.basename(r)}.${process.pid}.${b.randomUUID()}.tmp`);try{let i=await a.open(t,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL,384);try{await i.writeFile(e),await E(i);}finally{await i.close();}await a.rename(t,r),await L(n.dirname(r));}catch(i){throw await a.rm(t,{force:true}).catch(()=>{}),i}}async function S(r,e){await P(n.join(r,v),Buffer.from(`${JSON.stringify(e,null,2)}
1
+ import {e,b as b$1}from'./chunk-25AWHAB5.js';import b from'crypto';import {constants}from'fs';import a from'fs/promises';import n from'path';var O="workspai.lifecycle-transaction",k=1,v="manifest.json",N="lifecycle-transaction-";async function h(r){try{return await a.lstat(r)}catch(e){if(e.code==="ENOENT")return null;throw e}}function D(r){let e=r?.code;return process.platform==="win32"&&(e==="EPERM"||e==="EINVAL"||e==="ENOSYS")}async function E(r){try{await r.sync();}catch(e){if(!D(e))throw e}}function T(r){if(typeof r!="string"||!n.isAbsolute(r))throw new Error("Lifecycle transaction journal contains a non-absolute target path.")}function F(r){if(typeof r!="string"||r.length===0||n.basename(r)!==r||r==="."||r==="..")throw new Error("Lifecycle transaction journal contains an unsafe backup reference.")}function J(r){if(!r||typeof r!="object")throw new Error("Lifecycle transaction journal is not an object.");let e=r;if(e.kind!==O||e.version!==k)throw new Error("Lifecycle transaction journal has an unsupported format.");if(!Number.isInteger(e.ownerPid)||e.ownerPid<=0)throw new Error("Lifecycle transaction journal has an invalid owner process.");if(!["active","committed","rolling-back"].includes(e.phase))throw new Error("Lifecycle transaction journal has an invalid phase.");if(!Array.isArray(e.operations))throw new Error("Lifecycle transaction journal has invalid operations.");for(let t of e.operations){if(!t||typeof t!="object")throw new Error("Lifecycle transaction journal contains an invalid operation.");let i=t;if(T(i.path),i.type!=="tree"){if(i.type!=="file"||!["absent","regular"].includes(i.state))throw new Error("Lifecycle transaction journal contains an invalid operation.");if(i.state==="regular"){if(!Number.isInteger(i.mode)||i.mode<0||i.mode>4095)throw new Error("Lifecycle transaction journal contains an invalid file mode.");F(i.backup);}}}return e}async function L(r){let e;try{e=await a.open(r,constants.O_RDONLY);}catch(t){if(D(t))return;throw t}try{await E(e);}finally{await e.close();}}async function P(r,e){let t=n.join(n.dirname(r),`.${n.basename(r)}.${process.pid}.${b.randomUUID()}.tmp`);try{let i=await a.open(t,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL,384);try{await i.writeFile(e),await E(i);}finally{await i.close();}await a.rename(t,r),await L(n.dirname(r));}catch(i){throw await a.rm(t,{force:true}).catch(()=>{}),i}}async function S(r,e){await P(n.join(r,v),Buffer.from(`${JSON.stringify(e,null,2)}
2
2
  `));}async function A(r,e){let t=await h(r.path);if(t?.isSymbolicLink()||t&&!t.isFile())throw new Error(`Refusing to restore over a non-regular file: ${r.path}`);if(r.state==="absent"){t&&await a.unlink(r.path);return}if(!e)throw new Error(`Missing durable backup for: ${r.path}`);if(!await h(n.dirname(r.path)))return;let i=n.join(e,r.backup),o=await a.lstat(i).catch(s=>{if(s.code==="ENOENT"&&t?.isFile())return t;throw s});if(o===t)return;if(!o.isFile()||o.isSymbolicLink())throw new Error(`Lifecycle transaction backup is not a regular file: ${i}`);let c=await a.readFile(i),u=n.join(n.dirname(r.path),`.${n.basename(r.path)}.${process.pid}.${b.randomUUID()}.rollback`),l=await a.open(u,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL,r.mode);try{await l.writeFile(c),await l.chmod(r.mode),await E(l);}finally{await l.close();}try{await a.rename(u,r.path),await L(n.dirname(r.path));}catch(s){throw await a.rm(u,{force:true}).catch(()=>{}),s}}async function R(r){let e=await h(r.path);if(e){if(e.isSymbolicLink()||!e.isDirectory())throw new Error(`Refusing to remove a non-directory owned tree: ${r.path}`);await a.rm(r.path,{recursive:true});}}async function $(r,e){let t=[];for(let i of [...r].reverse())try{i.type==="file"?await A(i,e):await R(i);}catch(o){t.push(o);}if(t.length>0)throw new AggregateError(t,"Lifecycle transaction rollback failed.")}var g=class r{constructor(e){this.transactionDirectory=e;this.journalPath=e?n.join(e,v):void 0;}transactionDirectory;journalPath;actions=[];durableOperations=[];phase="active";finished=false;static async create(e={}){if(!e.journalDirectory)return new r;let t=n.resolve(e.journalDirectory);await a.mkdir(t,{recursive:true});let i=await a.mkdtemp(n.join(t,N));await L(t);let o=new r(i);return await o.persist(),o}assertActive(){if(this.finished||this.phase!=="active")throw new Error("Lifecycle transaction is no longer active.")}async persist(e=this.durableOperations){this.transactionDirectory&&await S(this.transactionDirectory,{kind:O,version:k,ownerPid:process.pid,phase:this.phase,operations:e});}async addDurableOperation(e){let t=[...this.durableOperations,e];await this.persist(t),this.durableOperations.push(e),this.actions.push(e);}async captureFile(e$1){this.assertActive();let t=n.resolve(e$1),i=await h(t);if(!i){await this.addDurableOperation({type:"file",path:t,state:"absent"}),e({targetPath:t,operation:"capture-preimage",status:"planned"});return}if(i.isSymbolicLink()||!i.isFile())throw new Error(`Lifecycle transaction can only capture regular files: ${t}`);let o;try{o=await a.open(t,constants.O_RDONLY|(constants.O_NOFOLLOW??0));}catch(c){throw c.code==="ENOENT"?new Error(`File changed while being captured: ${t}`,{cause:c}):c}try{let c=await o.stat();if(!c.isFile())throw new Error(`Lifecycle transaction can only capture regular files: ${t}`);let u=await o.readFile(),l=c.mode&4095;if(this.transactionDirectory){let s=`file-${this.durableOperations.length}-${b.randomUUID()}.bin`;await P(n.join(this.transactionDirectory,s),u),await this.addDurableOperation({type:"file",path:t,state:"regular",mode:l,backup:s});}else {let s=`memory-${this.durableOperations.length}`,d={type:"file",path:t,state:"regular",mode:l,backup:s};this.durableOperations.push(d),this.actions.push({type:"compensation",run:async()=>{let p=await h(t);if(p?.isSymbolicLink()||p&&!p.isFile())throw new Error(`Refusing to restore over a non-regular file: ${t}`);let w=n.join(n.dirname(t),`.${n.basename(t)}.${process.pid}.${b.randomUUID()}.rollback`);await a.writeFile(w,u,{flag:"wx",mode:l}),await a.chmod(w,l);try{await a.rename(w,t);}catch(j){throw await a.rm(w,{force:true}).catch(()=>{}),j}}});}e({targetPath:t,operation:"capture-preimage",status:"planned"});}finally{await o.close();}}async captureOwnedTree(e$1){this.assertActive();let t=n.resolve(e$1),i=await h(t);if(!i)return await this.addDurableOperation({type:"tree",path:t}),e({targetPath:t,operation:"create-tree",status:"planned"}),true;if(i.isSymbolicLink()||!i.isDirectory())throw new Error(`Lifecycle transaction tree must be absent or a directory: ${t}`);return false}registerCompensation(e){this.assertActive(),this.actions.push({type:"compensation",run:async()=>e()});}async commit(){if(!this.finished){this.assertActive(),this.phase="committed";try{await this.persist(),this.finished=true,this.actions.length=0,this.transactionDirectory&&await a.rm(this.transactionDirectory,{recursive:true}).catch(()=>{}),b$1({kind:"operation.completed",status:"succeeded",component:"lifecycle-transaction",message:"Lifecycle transaction committed.",attributes:{capturedTargets:this.durableOperations.length}});}catch(e){throw this.phase="active",e}}}async rollback(){if(this.finished||this.phase==="committed")return;this.assertActive(),this.phase="rolling-back",b$1({kind:"operation.started",status:"running",component:"lifecycle-transaction",message:"Lifecycle transaction rollback started.",attributes:{capturedTargets:this.durableOperations.length}});try{await this.persist();}catch(t){throw this.phase="active",t}let e=[];for(let t of [...this.actions].reverse())try{t.type==="compensation"?await t.run():t.type==="file"?await A(t,this.transactionDirectory):await R(t);}catch(i){e.push(i);}if(e.length>0)throw b$1({kind:"operation.failed",status:"failed",component:"lifecycle-transaction",message:"Lifecycle transaction rollback failed.",attributes:{failures:e.length}}),new AggregateError(e,"Lifecycle transaction rollback failed.");this.finished=true,this.transactionDirectory&&await a.rm(this.transactionDirectory,{recursive:true}),b$1({kind:"operation.completed",status:"rolled-back",component:"lifecycle-transaction",message:"Lifecycle transaction rolled back.",attributes:{restoredTargets:this.durableOperations.length}});}};async function Y(r={}){return g.create(r)}async function V(r){let e=n.resolve(r),t=await a.readdir(e,{withFileTypes:true}).catch(c=>{if(c.code==="ENOENT")return [];throw c}),i=[],o=[];for(let c of t){if(!c.isDirectory()||!c.name.startsWith(N))continue;let u=n.join(e,c.name);try{let l;try{l=await a.readFile(n.join(u,v),"utf8");}catch(p){if(p.code==="ENOENT")continue;throw p}let s=J(JSON.parse(l));if(s.phase==="committed"){await a.rm(u,{recursive:true});continue}let d=false;try{process.kill(s.ownerPid,0),d=true;}catch(p){d=p.code==="EPERM";}if(d)continue;s.phase==="active"&&(s.phase="rolling-back",await S(u,s)),await $(s.operations,u),await a.rm(u,{recursive:true}),i.push(u);}catch(l){o.push(l);}}if(o.length>0)throw new AggregateError(o,"Lifecycle transaction recovery failed.");return i}export{Y as a,V as b};
@@ -1,4 +1,4 @@
1
- import {a as a$1}from'./chunk-QMQBX3RV.js';import {a}from'./chunk-NS53IPAC.js';import {e}from'./chunk-XDPTAV2T.js';import {h as h$1,b,a as a$2,d,c}from'./chunk-ZGHJIQXL.js';import pe from'path';import h from'chalk';import {createHash}from'crypto';var F="workspai.doctor-adapter.v1",D=["runtime","dependency","security","configuration","test","quality"];function A(e){return e.trim().toLowerCase().replace(/[^a-z0-9+.#-]+/g,"-")}function ae(e){if(e.contractVersion!==F)throw new Error(`Unsupported Doctor adapter contract: ${e.contractVersion}`);if(!e.id.trim())throw new Error("Doctor adapter id must not be empty.");if(e.runtimeFamilies.length===0)throw new Error(`Doctor adapter ${e.id} must own at least one runtime family.`);if(e.platforms.length===0)throw new Error(`Doctor adapter ${e.id} must declare supported platforms.`);let i=e.domains.map(t=>t.domain);if(i.length!==D.length||new Set(i).size!==D.length||D.some(t=>!i.includes(t)))throw new Error(`Doctor adapter ${e.id} must declare every canonical diagnostic domain exactly once.`);for(let t of e.domains)if(t.level==="unsupported"&&t.limitations.length===0)throw new Error(`Doctor adapter ${e.id} must explain unsupported ${t.domain} coverage.`)}var $=class{#e=new Map;#i=new Map;#t=new Map;register(i){ae(i);let t=A(i.id);if(this.#e.has(t))throw new Error(`Doctor adapter id is already registered: ${i.id}`);let s=[...i.runtimeFamilies,...i.aliases].map(A);for(let c of s){let a=this.#i.get(c);if(a)throw new Error(`Doctor runtime ${c} is already owned by adapter ${a}.`)}for(let c of i.frameworks.map(A)){let a=this.#t.get(c);if(a)throw new Error(`Doctor framework ${c} is already owned by adapter ${a}.`)}let r=structuredClone(i);this.#e.set(t,r);for(let c of s)this.#i.set(c,t);for(let c of i.frameworks.map(A))this.#t.set(c,t);return this}resolveWithDiagnostics(i){let t=i.runtimeFamily?this.#i.get(A(i.runtimeFamily)):void 0,s=i.framework?this.#t.get(A(i.framework)):void 0;if(t&&s&&t!==s)return {status:"conflict",descriptor:null,runtimeOwner:t,frameworkOwner:s};let r=t??s;return {status:r?"matched":"unresolved",descriptor:r?structuredClone(this.#e.get(r)??null):null,...t?{runtimeOwner:t}:{},...s?{frameworkOwner:s}:{}}}resolve(i){return this.resolveWithDiagnostics(i).descriptor}list(){return [...this.#e.values()].map(i=>structuredClone(i)).sort((i,t)=>i.id.localeCompare(t.id))}};var Y=[...D],W=["linux","darwin","win32"],re=[{id:"node",aliases:["nodejs","javascript","typescript"],frameworks:["NestJS","Next.js","Remix","Nuxt","React","Vue","Angular","SvelteKit","Svelte","Vite","Astro","Solid","Express","Fastify","Koa","Electron","VS Code Extension"],tier:"first-class",native:Y},{id:"python",aliases:["py"],frameworks:["FastAPI","Django","Flask","Python"],tier:"first-class",native:Y},{id:"go",aliases:["golang"],frameworks:["Go","Go/Fiber","Go/Gin","Echo"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"java",aliases:["jvm"],frameworks:["Java","Spring Boot"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"dotnet",aliases:[".net","csharp","c#"],frameworks:["ASP.NET"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"rust",aliases:["cargo"],frameworks:["Rust","Axum"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"php",aliases:["composer"],frameworks:["PHP","Laravel"],tier:"first-class",native:["runtime","dependency","security"],portable:["configuration","test","quality"]},{id:"ruby",aliases:["bundler"],frameworks:["Ruby","Ruby on Rails"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"elixir",aliases:["beam"],frameworks:["Elixir","Phoenix"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"clojure",frameworks:["Clojure"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"deno",frameworks:["Deno"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"bun",frameworks:["Bun"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"scala",frameworks:["Scala"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"kotlin",frameworks:["Kotlin"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"c",aliases:["c-lang"],frameworks:["C"],tier:"extended",portable:["runtime","dependency","test","quality"],observable:["configuration"],limitations:["Security diagnosis requires a declared native scanner or workspace adapter."]},{id:"cpp",aliases:["c++","cplusplus"],frameworks:["C++"],tier:"extended",portable:["runtime","dependency","test","quality"],observable:["configuration"],limitations:["Security diagnosis requires a declared native scanner or workspace adapter."]}];function oe(e,i){let t={runtime:["project markers","entrypoints","toolchain evidence"],dependency:["dependency manifests","lockfiles","installed-tree evidence"],security:["runtime-native audit","advisory evidence"],configuration:["environment contracts","deployment/container markers"],test:["test scripts","test configuration","coverage evidence"],quality:["lint/format/static-analysis contracts"]};return [`${e} adapter`,...t[i]]}function ce(e,i){return e.native?.includes(i)?"native":e.portable?.includes(i)?"portable":e.observable?.includes(i)?"observable":"unsupported"}function le(e){let i=D.map(t=>{let s=ce(e,t);return {domain:t,level:s,evidenceSources:s==="unsupported"?[]:oe(e.id,t),limitations:s==="unsupported"?[`${e.id} has no built-in ${t} provider; declare a workspace adapter.`]:s==="observable"?[`${t} evidence is observable but not runtime-native for ${e.id}.`]:[]}});return {contractVersion:F,id:`builtin.${e.id}`,runtimeFamilies:[e.id],aliases:e.aliases??[],frameworks:e.frameworks,projectKinds:["backend","frontend","desktop","extension","fullstack","generic"],tier:e.tier,platforms:[...W],domains:i,repairModes:["typed-operation","structured-invocation","manual-guidance"],source:"builtin",limitations:e.limitations??[]}}function de(){return {contractVersion:F,id:"builtin.unknown",runtimeFamilies:["unknown"],aliases:["generic","unrecognized"],frameworks:["Unknown"],projectKinds:["backend","frontend","desktop","extension","fullstack","generic"],tier:"fallback",platforms:[...W],domains:D.map(e=>({domain:e,level:e==="security"?"unsupported":"observable",evidenceSources:e==="security"?[]:["portable workspace markers","declared custom checks"],limitations:[e==="security"?"No safe security claim is possible without a runtime-native audit provider.":`Only portable ${e} evidence is available until a runtime adapter is registered.`]})),repairModes:["manual-guidance"],source:"builtin",limitations:["Unknown runtimes are fail-closed: missing domain evidence is reported as unknown, never healthy.","Automatic repair is unavailable until a typed adapter owns the runtime."]}}function P(){let e=new $;for(let i of re)e.register(le(i));return e.register(de()),e}function J(e,i=P()){let t=i.resolveWithDiagnostics(e),s=t.descriptor??i.resolve({runtimeFamily:"unknown"});if(!s)throw new Error("Doctor fallback adapter is not registered.");let r=c=>s.domains.filter(a=>a.level===c).map(a=>a.domain);return {registryVersion:b,adapterId:s.id,runtimeFamily:s.runtimeFamilies[0]??"unknown",tier:s.tier,confidence:s.tier==="first-class"?"high":s.tier==="extended"?"medium":"low",nativeDomains:r("native"),portableDomains:r("portable"),observableDomains:r("observable"),unsupportedDomains:r("unsupported"),limitations:[...t.status==="conflict"?[`Runtime/framework ownership conflict (${t.runtimeOwner} vs ${t.frameworkOwner}); Doctor failed closed instead of selecting an ambiguous adapter.`]:[],...s.limitations,...s.domains.flatMap(c=>c.limitations)]}}function K(e={}){let i=P(),t=i.list(),s=i.resolveWithDiagnostics({runtimeFamily:e.runtime,framework:e.framework}),r=e.runtime||e.framework?[s.descriptor]:t;if((e.runtime||e.framework)&&!r[0]){let a=i.resolve({runtimeFamily:"unknown"});a&&(s.status==="conflict"&&a.limitations.unshift(`Runtime/framework ownership conflict (${s.runtimeOwner} vs ${s.frameworkOwner}); Doctor failed closed instead of selecting an ambiguous adapter.`),r[0]=a);}let c=r.filter(a=>!!a);return {schemaVersion:a$2,registryVersion:b,generatedBy:"workspai",policy:{unknownIsHealthy:false,unsupportedIsHealthy:false,repairRequiresTypedOperation:true,canonicalDomains:[...D]},summary:{adapterCount:c.length,firstClassRuntimes:c.filter(a=>a.tier==="first-class").length,extendedRuntimes:c.filter(a=>a.tier==="extended").length,fallbackRuntimes:c.filter(a=>a.tier==="fallback").length,frameworkCount:new Set(c.flatMap(a=>a.frameworks)).size,platformCount:new Set(c.flatMap(a=>a.platforms)).size},adapters:c}}var me=["runtime","dependency","security","configuration","test","quality"];function I(e){return createHash("sha256").update(e).digest("hex").slice(0,12)}function S(e){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Q(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function ge(e,i){let t=Q(e);return t?i.some(s=>[s.reason,s.recommendation??""].map(Q).filter(Boolean).some(c=>c===t||c.includes(t)||t.includes(c))):true}function fe(e){return e.status==="fail"?"blocking":e.status==="warn"?"advisory":"informational"}function X(e){return e.issueClass==="dependency"?"dependency":e.issueClass==="security"?"security":e.issueClass==="environment"||e.issueClass==="configuration"||e.issueClass==="container"||e.issueClass==="deployment"||e.issueClass==="workspace-contract"?"configuration":e.issueClass==="test"?"test":e.issueClass==="quality"||e.issueClass==="custom"?"quality":e.issueClass==="runtime"||e.issueClass==="framework"||e.issueClass==="source-tree"?"runtime":null}function ye(e,i){return me.map(t=>{let s=e.filter(o=>X(o)===t),r=e.filter(o=>o.applicability!=="not-applicable"&&X(o)===t),c=i.unsupportedDomains.includes(t);if(r.length===0){let o=s.some(d=>d.applicability==="not-applicable");return {id:t,status:o?"not-applicable":"not-run",observationCount:0,blockingFindings:0,advisoryFindings:0,reason:o?`${t} checks ran and found no declared intent requiring this domain.`:c?`${t} is unsupported by Doctor adapter ${i.adapterId}; no healthy claim is allowed.`:`No ${t} diagnostic observation was produced.`}}let a=r.some(o=>o.freshness?.status==="stale"||o.freshness?.status==="unknown"),p=r.filter(o=>o.status==="fail").length,m=r.filter(o=>o.status==="warn").length,C=p>0||m>0;return {id:t,status:a?"stale":C?"findings":c?"not-run":"clean",observationCount:r.length,blockingFindings:p,advisoryFindings:m,reason:a?`${t} evidence is stale or has unknown freshness.`:C?`${t} diagnostics produced findings.`:c?`${t} observations cannot establish complete health because adapter ${i.adapterId} declares the domain unsupported.`:`${t} diagnostics completed without findings.`}})}function De(e){if(e.status==="pass")return "not-needed";let i=e.repairCapability;return i?i.status==="manual"||i.requiresReview?"manual":i.status!=="available"||!i.canAutoFix?"unavailable":i.requiresApproval?"approval-required":"automatic":"unavailable"}function be(e){if(e.freshness?.status==="stale"||e.freshness?.status==="unknown")return {label:"low",score:.35,state:"unknown"};let i=!!(e.issueClass&&e.issueClass!=="unknown"),t=!!(e.repairCapability?.operation?.type||e.repairCapability?.invocation?.executable);return i&&t&&e.repairIntent?.confidence==="high"?{label:"high",score:.95,state:"confirmed"}:i&&(e.status==="fail"||e.status==="warn")?{label:"medium",score:t?.82:.68,state:"candidate"}:e.status==="pass"?{label:"high",score:.98,state:"confirmed"}:{label:"low",score:.3,state:"unknown"}}function ve(e,i){let t=[{kind:"probe",role:"observation",ref:`probe:${e.id}`,claim:e.reason}];for(let r of e.repairCapability?.files??[])t.push({kind:"file",role:"repair-target",ref:r.split(pe.sep).join("/"),claim:"Structured repair capability declared this path as an affected target."});if(e.repairCapability?.invocation?.executable){let r=e.repairCapability.invocation;t.push({kind:"command",role:"verification",ref:[r.executable,...r.args??[]].join(" "),claim:"Structured command invocation is available for this diagnostic path."});}if(e.issueClass==="security"&&/(?:dependency|audit|vulnerab|security-hygiene)/i.test(`${e.id} ${e.label}`))for(let r of i??[])t.push({kind:"dependency",role:"subject",ref:r.version?`${r.name}@${r.version}`:r.name,claim:r.advisoryIds&&r.advisoryIds.length>0?`Dependency is referenced by ${r.advisoryIds.join(", ")}.`:"Dependency is present in security audit evidence."});return t}function we(e,i){let t=i.issueClass?.trim()||"unknown",s=be(i);return {id:`${S(i.id)}:${I(`${e.projectPath}\0${i.id}`)}`,causalKey:[S(e.projectName),I(e.projectPath),S(t),S(i.id)].join(":"),projectName:e.projectName,projectPath:e.projectPath,probeId:i.id,label:i.label,status:fe(i),severity:i.severity,issueClass:t,operationalImpact:i.operationalImpact?.trim()||"developer-friction",applicability:i.applicability??"applicable",confidence:s.label,confidenceScore:s.score,diagnosisState:s.state,symptom:i.reason,...i.recommendation?{recommendation:i.recommendation}:{},proofs:ve(i,e.dependencySubjects),repair:{disposition:De(i),...i.repairCapability?.id?{capabilityId:i.repairCapability.id}:{},...i.repairCapability?.operation?.type?{operationType:i.repairCapability.operation.type}:{},...i.repairCapability?.verifyCommand?{verifyCommand:i.repairCapability.verifyCommand}:{},requiresFreshEvidence:i.repairIntent?.requiresFreshEvidence===true||i.freshness?.verifyBeforeUse===true}}}function he(e,i,t){let s=`legacy-runtime-issue-${t+1}`;return {id:`${s}:${I(`${e.projectPath}\0${i}`)}`,causalKey:[S(e.projectName),I(e.projectPath),"unknown",I(i)].join(":"),projectName:e.projectName,projectPath:e.projectPath,probeId:s,label:"Runtime diagnostic issue",status:"blocking",severity:"error",issueClass:"unknown",operationalImpact:"runtime-risk",applicability:"applicable",confidence:"low",confidenceScore:.25,diagnosisState:"unknown",symptom:i,proofs:[{kind:"unknown",role:"observation",ref:`legacy-issue:${t+1}`,claim:i}],repair:{disposition:"unavailable",requiresFreshEvidence:true}}}function Z(e){let i=[...e.probes],t=[...new Set((e.runtimeFamilies&&e.runtimeFamilies.length>0?e.runtimeFamilies:[e.runtimeFamily??"unknown"]).filter(Boolean))],s=e.runtimeFamily??t[0]??"unknown",r=t.filter(n=>n!==s&&n!=="unknown"),c=J({runtimeFamily:e.runtimeFamily,framework:e.framework},e.adapterRegistry),a$1=ye(i,c),p=(e.legacyIssues??[]).filter(n=>!ge(n,i)),m=new Map;for(let n of i){let l=m.get(n.id)??new Set;l.add(n.status),m.set(n.id,l);}let C=[...m.entries()].filter(([,n])=>n.size>1).map(([n,l])=>({probeId:n,statuses:[...l].sort(),reason:"The same diagnostic probe produced contradictory states in one project scan."})),o=[...i.filter(n=>n.applicability!=="not-applicable"&&n.status!=="pass").map(n=>we(e,n)),...p.map((n,l)=>he(e,n,l))],d={blocking:4,unknown:3,advisory:2,informational:1},O=new Map;for(let n of o){let l=O.get(n.causalKey)??[];l.push(n),O.set(n.causalKey,l);}let g=[...O.values()].map(n=>{let u=[...n].sort((f,j)=>d[j.status]-d[f.status]||j.confidenceScore-f.confidenceScore||f.id.localeCompare(j.id)).at(0);if(!u)throw new Error("Doctor diagnosis causal group cannot be empty.");let G=structuredClone(u);return G.proofs=[...new Map(n.flatMap(f=>f.proofs).map(f=>[`${f.kind}:${f.role}:${f.ref}:${f.claim}`,f])).values()],G}).sort((n,l)=>n.causalKey.localeCompare(l.causalKey)||n.id.localeCompare(l.id)),k=new Map;for(let n of g){let l=k.get(n.causalKey)??[];l.push(n),k.set(n.causalKey,l);}let b=[...k.entries()].map(([n,l])=>({causalKey:n,issueClass:l[0]?.issueClass??"unknown",status:l.some(u=>u.status==="blocking")?"blocking":l.some(u=>u.status==="advisory")?"advisory":l.some(u=>u.status==="unknown")?"unknown":"informational",findingIds:l.map(u=>u.id),projectPaths:[...new Set(l.map(u=>u.projectPath))],repairable:l.some(u=>u.repair.disposition==="automatic"||u.repair.disposition==="approval-required")})),v=[...g.filter(n=>n.diagnosisState==="unknown"||n.issueClass==="unknown"||n.applicability==="unknown").map(n=>({id:`unknown:${n.id}`,probeId:n.probeId,reason:n.issueClass==="unknown"?"The observation is real, but Doctor cannot yet bind it to a typed issue class.":"Evidence is insufficient or stale for a confirmed diagnosis."})),...a$1.filter(n=>n.status==="not-run"||n.status==="stale").map(n=>({id:`unknown:domain:${n.id}:${I(e.projectPath)}`,reason:n.reason})),...r.map(n=>({id:`unknown:runtime:${S(n)}:${I(e.projectPath)}`,reason:e.projectArchetype==="platform"?`${n} is part of this cross-language platform, but only portable evidence and the primary ${s} runtime adapter were evaluated. Add a typed ${n} adapter before making runtime-specific health claims.`:`${n} was detected inside this composite project boundary, but the ${s} adapter is the only runtime-specific adapter evaluated for this scan. Declare a nested project boundary or a typed Doctor adapter before treating ${n} as healthy.`}))],y=g.filter(n=>n.diagnosisState!=="unknown").length,x=g.length===0?100:y/g.length*100,ie=a$1.filter(n=>n.status!=="not-run"&&n.status!=="stale").length/a$1.length*100,U=t.filter(n=>n!=="unknown").length,te=s!=="unknown"&&t.includes(s)?1:0,ne=U===0?0:te/U*100,se=Math.round(Math.min(x,ie,ne)*100)/100;return {schemaVersion:a,engineVersion:"universal-diagnosis-v1",project:{name:e.projectName,path:e.projectPath,runtimeFamily:e.runtimeFamily??"unknown",runtimeFamilies:t,framework:e.framework??"Unknown",projectKind:e.projectKind??"generic"},capability:c,domains:a$1,coverage:{totalObservations:i.length+p.length,evaluatedObservations:i.filter(n=>n.applicability!=="not-applicable").length,passingObservations:i.filter(n=>n.applicability!=="not-applicable"&&n.status==="pass").length,blockingFindings:g.filter(n=>n.status==="blocking").length,advisoryFindings:g.filter(n=>n.status==="advisory").length,unknownFindings:v.length,repairableFindings:g.filter(n=>n.repair.disposition==="automatic"||n.repair.disposition==="approval-required").length,manualFindings:g.filter(n=>n.repair.disposition==="manual").length,unsupportedFindings:g.filter(n=>n.repair.disposition==="unavailable").length,contradictionCount:C.length,diagnosisCompleteness:se},findings:g,causalGroups:b,unknowns:v,contradictions:C}}function w(e){let i=e.severity??"error",t=e.repair??"unavailable";return {id:e.id,label:e.label,status:i==="error"?"fail":"warn",severity:i,reason:`${e.label} detected by the validation corpus.`,issueClass:e.issueClass,operationalImpact:i==="error"?"release-risk":"ci-risk",repairIntent:{confidence:e.confidence??"medium",requiresFreshEvidence:true},...t==="unavailable"?{}:{repairCapability:{id:`repair.${e.id}`,status:t==="manual"?"manual":"available",canAutoFix:t==="automatic"||t==="approval-required",requiresApproval:t==="approval-required",requiresReview:t==="manual",operation:{type:"validation-operation"},verifyCommand:"npx workspai doctor project --json"}}}}var Ce=[{id:"runtime-missing",diseaseClass:"runtime",description:"Required runtime is absent.",probe:w({id:"runtime-missing",label:"Runtime missing",issueClass:"runtime"}),expected:{finding:true,domain:"runtime",status:"blocking",diagnosisState:"candidate",repairDisposition:"unavailable"}},{id:"dependencies-missing",diseaseClass:"dependency",description:"Installed dependency tree is absent.",probe:w({id:"dependencies-missing",label:"Dependencies missing",issueClass:"dependency",repair:"automatic",confidence:"high"}),expected:{finding:true,domain:"dependency",status:"blocking",diagnosisState:"confirmed",repairDisposition:"automatic"}},{id:"security-advisory",diseaseClass:"security",description:"A runtime-native audit reports a blocking advisory.",probe:w({id:"security-advisory",label:"Security advisory",issueClass:"security",repair:"approval-required",confidence:"high"}),expected:{finding:true,domain:"security",status:"blocking",diagnosisState:"confirmed",repairDisposition:"approval-required"}},{id:"environment-contract",diseaseClass:"configuration",description:"Environment/configuration contract is incomplete.",probe:w({id:"environment-contract",label:"Environment contract incomplete",issueClass:"environment",severity:"warn",repair:"manual"}),expected:{finding:true,domain:"configuration",status:"advisory",diagnosisState:"candidate",repairDisposition:"manual"}},{id:"container-contract",diseaseClass:"configuration",description:"Container delivery contract is incomplete.",probe:w({id:"container-contract",label:"Container contract incomplete",issueClass:"container",severity:"warn"}),expected:{finding:true,domain:"configuration",status:"advisory",diagnosisState:"candidate",repairDisposition:"unavailable"}},{id:"tests-missing",diseaseClass:"test",description:"No deterministic test surface is declared.",probe:w({id:"tests-missing",label:"Tests missing",issueClass:"test",severity:"warn",repair:"manual"}),expected:{finding:true,domain:"test",status:"advisory",diagnosisState:"candidate",repairDisposition:"manual"}},{id:"quality-missing",diseaseClass:"quality",description:"No lint/format/static-analysis surface is declared.",probe:w({id:"quality-missing",label:"Quality tooling missing",issueClass:"quality",severity:"warn"}),expected:{finding:true,domain:"quality",status:"advisory",diagnosisState:"candidate",repairDisposition:"unavailable"}},{id:"stale-evidence",diseaseClass:"freshness",description:"Evidence is stale and must not be treated as confirmed.",probe:{...w({id:"stale-evidence",label:"Stale evidence",issueClass:"security"}),freshness:{status:"stale",verifyBeforeUse:true}},expected:{finding:true,domain:"security",status:"blocking",diagnosisState:"unknown",repairDisposition:"unavailable"}},{id:"unknown-disease",diseaseClass:"unknown",description:"A real symptom cannot be bound to a typed disease class.",probe:w({id:"unknown-disease",label:"Unknown disease",issueClass:"unknown"}),expected:{finding:true,status:"blocking",diagnosisState:"unknown",repairDisposition:"unavailable"}},{id:"healthy-runtime",diseaseClass:"healthy-control",description:"Healthy evidence must not become a finding.",probe:{id:"healthy-runtime",label:"Healthy runtime",status:"pass",severity:"info",reason:"Runtime evidence is healthy.",issueClass:"runtime",operationalImpact:"none"},expected:{finding:false,domain:"runtime"}}];function _(e){return Math.round(e*1e4)/1e4}function ee(){let i=P().list(),t=i.flatMap(o=>Ce.map(d=>{let O=o.runtimeFamilies[0]??"unknown",g=o.frameworks[0]??"Unknown",k=Z({projectName:`validation-${o.id}-${d.id}`,projectPath:`/virtual/doctor-validation/${o.id}/${d.id}`,runtimeFamily:O,framework:g,projectKind:"generic",probes:[d.probe]}),b=k.findings.find(x=>x.probeId===d.probe.id),N=k.domains.find(x=>x.observationCount>0)?.id,v={finding:!!b,...N?{domain:N}:{},...b?.status?{status:b.status}:{},...b?.diagnosisState?{diagnosisState:b.diagnosisState}:{},...b?.repair.disposition?{repairDisposition:b.repair.disposition}:{}},y=[];return v.finding!==d.expected.finding&&y.push("finding-presence"),d.expected.domain&&v.domain!==d.expected.domain&&y.push("domain"),d.expected.status&&v.status!==d.expected.status&&y.push("status"),d.expected.diagnosisState&&v.diagnosisState!==d.expected.diagnosisState&&y.push("diagnosis-state"),d.expected.repairDisposition&&v.repairDisposition!==d.expected.repairDisposition&&y.push("repair-disposition"),k.capability.adapterId!==o.id&&y.push("adapter-binding"),{id:`${o.id}:${d.id}`,passed:y.length===0,expected:d.expected,actual:v,failures:y}})),s=t.filter(o=>o.expected.finding),r=t.filter(o=>!o.expected.finding),c$1=s.filter(o=>o.actual.finding).length,a=s.length-c$1,p=r.filter(o=>!o.actual.finding).length,m=r.length-p,C=new Set(t.map(o=>o.actual.domain).filter(o=>!!o));return {schemaVersion:c,corpusVersion:d,capabilityRegistryVersion:b,scope:"synthetic-contract-corpus",summary:{totalCases:t.length,passedCases:t.filter(o=>o.passed).length,failedCases:t.filter(o=>!o.passed).length,truePositives:c$1,trueNegatives:p,falsePositives:m,falseNegatives:a,precision:_(c$1/Math.max(1,c$1+m)),recall:_(c$1/Math.max(1,c$1+a)),domainCoverage:_(C.size/D.length),runtimeAdapterCoverage:_(new Set(t.map(o=>o.id.split(":",1)[0])).size/Math.max(1,i.length)),runtimeAdaptersExercised:i.length,declaredPlatforms:new Set(i.flatMap(o=>o.platforms)).size},cases:t,limitations:["Precision and recall describe the versioned synthetic contract corpus, not every public repository.","Every registered runtime adapter is exercised against the same disease corpus; this proves contract behavior, not tool availability on a host.","Runtime-native fixture and real Linux, macOS, and Windows acceptance gates remain separate evidence surfaces."]}}async function Qe(e$1={}){let i=K({runtime:e$1.runtime,framework:e$1.framework}),t=e$1.validate?ee():void 0,s,r;if(e$1.write){let a=e$1.workspace?pe.resolve(e$1.workspace):a$1(process.cwd());if(!a)return e$1.json?console.log(JSON.stringify({schemaVersion:i.schemaVersion,status:"error",error:{code:"doctor.capabilities.workspace-not-found",message:"--write requires a Workspai workspace or --workspace <path>."}},null,2)):console.log(h.red("Doctor capabilities could not be written: no workspace found.")),1;let p=K();s=await e(a,h$1.doctorCapabilities.artifactPath,p),t&&(r=await e(a,h$1.doctorValidation.artifactPath,t));}let c={...i,...t?{validation:t}:{},...s?{artifactPath:s}:{},...r?{validationArtifactPath:r}:{}};if(e$1.json)e$1.quiet||console.log(JSON.stringify(c,null,2));else if(!e$1.quiet){console.log(h.bold.cyan(`
1
+ import {a as a$1}from'./chunk-QMQBX3RV.js';import {a}from'./chunk-NS53IPAC.js';import {e}from'./chunk-C2VTO5WT.js';import {h as h$1,b,a as a$2,d,c}from'./chunk-ZGHJIQXL.js';import pe from'path';import h from'chalk';import {createHash}from'crypto';var F="workspai.doctor-adapter.v1",D=["runtime","dependency","security","configuration","test","quality"];function A(e){return e.trim().toLowerCase().replace(/[^a-z0-9+.#-]+/g,"-")}function ae(e){if(e.contractVersion!==F)throw new Error(`Unsupported Doctor adapter contract: ${e.contractVersion}`);if(!e.id.trim())throw new Error("Doctor adapter id must not be empty.");if(e.runtimeFamilies.length===0)throw new Error(`Doctor adapter ${e.id} must own at least one runtime family.`);if(e.platforms.length===0)throw new Error(`Doctor adapter ${e.id} must declare supported platforms.`);let i=e.domains.map(t=>t.domain);if(i.length!==D.length||new Set(i).size!==D.length||D.some(t=>!i.includes(t)))throw new Error(`Doctor adapter ${e.id} must declare every canonical diagnostic domain exactly once.`);for(let t of e.domains)if(t.level==="unsupported"&&t.limitations.length===0)throw new Error(`Doctor adapter ${e.id} must explain unsupported ${t.domain} coverage.`)}var $=class{#e=new Map;#i=new Map;#t=new Map;register(i){ae(i);let t=A(i.id);if(this.#e.has(t))throw new Error(`Doctor adapter id is already registered: ${i.id}`);let s=[...i.runtimeFamilies,...i.aliases].map(A);for(let c of s){let a=this.#i.get(c);if(a)throw new Error(`Doctor runtime ${c} is already owned by adapter ${a}.`)}for(let c of i.frameworks.map(A)){let a=this.#t.get(c);if(a)throw new Error(`Doctor framework ${c} is already owned by adapter ${a}.`)}let r=structuredClone(i);this.#e.set(t,r);for(let c of s)this.#i.set(c,t);for(let c of i.frameworks.map(A))this.#t.set(c,t);return this}resolveWithDiagnostics(i){let t=i.runtimeFamily?this.#i.get(A(i.runtimeFamily)):void 0,s=i.framework?this.#t.get(A(i.framework)):void 0;if(t&&s&&t!==s)return {status:"conflict",descriptor:null,runtimeOwner:t,frameworkOwner:s};let r=t??s;return {status:r?"matched":"unresolved",descriptor:r?structuredClone(this.#e.get(r)??null):null,...t?{runtimeOwner:t}:{},...s?{frameworkOwner:s}:{}}}resolve(i){return this.resolveWithDiagnostics(i).descriptor}list(){return [...this.#e.values()].map(i=>structuredClone(i)).sort((i,t)=>i.id.localeCompare(t.id))}};var Y=[...D],W=["linux","darwin","win32"],re=[{id:"node",aliases:["nodejs","javascript","typescript"],frameworks:["NestJS","Next.js","Remix","Nuxt","React","Vue","Angular","SvelteKit","Svelte","Vite","Astro","Solid","Express","Fastify","Koa","Electron","VS Code Extension"],tier:"first-class",native:Y},{id:"python",aliases:["py"],frameworks:["FastAPI","Django","Flask","Python"],tier:"first-class",native:Y},{id:"go",aliases:["golang"],frameworks:["Go","Go/Fiber","Go/Gin","Echo"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"java",aliases:["jvm"],frameworks:["Java","Spring Boot"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"dotnet",aliases:[".net","csharp","c#"],frameworks:["ASP.NET"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"rust",aliases:["cargo"],frameworks:["Rust","Axum"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"php",aliases:["composer"],frameworks:["PHP","Laravel"],tier:"first-class",native:["runtime","dependency","security"],portable:["configuration","test","quality"]},{id:"ruby",aliases:["bundler"],frameworks:["Ruby","Ruby on Rails"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"elixir",aliases:["beam"],frameworks:["Elixir","Phoenix"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"clojure",frameworks:["Clojure"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"deno",frameworks:["Deno"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"bun",frameworks:["Bun"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"scala",frameworks:["Scala"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"kotlin",frameworks:["Kotlin"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"c",aliases:["c-lang"],frameworks:["C"],tier:"extended",portable:["runtime","dependency","test","quality"],observable:["configuration"],limitations:["Security diagnosis requires a declared native scanner or workspace adapter."]},{id:"cpp",aliases:["c++","cplusplus"],frameworks:["C++"],tier:"extended",portable:["runtime","dependency","test","quality"],observable:["configuration"],limitations:["Security diagnosis requires a declared native scanner or workspace adapter."]}];function oe(e,i){let t={runtime:["project markers","entrypoints","toolchain evidence"],dependency:["dependency manifests","lockfiles","installed-tree evidence"],security:["runtime-native audit","advisory evidence"],configuration:["environment contracts","deployment/container markers"],test:["test scripts","test configuration","coverage evidence"],quality:["lint/format/static-analysis contracts"]};return [`${e} adapter`,...t[i]]}function ce(e,i){return e.native?.includes(i)?"native":e.portable?.includes(i)?"portable":e.observable?.includes(i)?"observable":"unsupported"}function le(e){let i=D.map(t=>{let s=ce(e,t);return {domain:t,level:s,evidenceSources:s==="unsupported"?[]:oe(e.id,t),limitations:s==="unsupported"?[`${e.id} has no built-in ${t} provider; declare a workspace adapter.`]:s==="observable"?[`${t} evidence is observable but not runtime-native for ${e.id}.`]:[]}});return {contractVersion:F,id:`builtin.${e.id}`,runtimeFamilies:[e.id],aliases:e.aliases??[],frameworks:e.frameworks,projectKinds:["backend","frontend","desktop","extension","fullstack","generic"],tier:e.tier,platforms:[...W],domains:i,repairModes:["typed-operation","structured-invocation","manual-guidance"],source:"builtin",limitations:e.limitations??[]}}function de(){return {contractVersion:F,id:"builtin.unknown",runtimeFamilies:["unknown"],aliases:["generic","unrecognized"],frameworks:["Unknown"],projectKinds:["backend","frontend","desktop","extension","fullstack","generic"],tier:"fallback",platforms:[...W],domains:D.map(e=>({domain:e,level:e==="security"?"unsupported":"observable",evidenceSources:e==="security"?[]:["portable workspace markers","declared custom checks"],limitations:[e==="security"?"No safe security claim is possible without a runtime-native audit provider.":`Only portable ${e} evidence is available until a runtime adapter is registered.`]})),repairModes:["manual-guidance"],source:"builtin",limitations:["Unknown runtimes are fail-closed: missing domain evidence is reported as unknown, never healthy.","Automatic repair is unavailable until a typed adapter owns the runtime."]}}function P(){let e=new $;for(let i of re)e.register(le(i));return e.register(de()),e}function J(e,i=P()){let t=i.resolveWithDiagnostics(e),s=t.descriptor??i.resolve({runtimeFamily:"unknown"});if(!s)throw new Error("Doctor fallback adapter is not registered.");let r=c=>s.domains.filter(a=>a.level===c).map(a=>a.domain);return {registryVersion:b,adapterId:s.id,runtimeFamily:s.runtimeFamilies[0]??"unknown",tier:s.tier,confidence:s.tier==="first-class"?"high":s.tier==="extended"?"medium":"low",nativeDomains:r("native"),portableDomains:r("portable"),observableDomains:r("observable"),unsupportedDomains:r("unsupported"),limitations:[...t.status==="conflict"?[`Runtime/framework ownership conflict (${t.runtimeOwner} vs ${t.frameworkOwner}); Doctor failed closed instead of selecting an ambiguous adapter.`]:[],...s.limitations,...s.domains.flatMap(c=>c.limitations)]}}function K(e={}){let i=P(),t=i.list(),s=i.resolveWithDiagnostics({runtimeFamily:e.runtime,framework:e.framework}),r=e.runtime||e.framework?[s.descriptor]:t;if((e.runtime||e.framework)&&!r[0]){let a=i.resolve({runtimeFamily:"unknown"});a&&(s.status==="conflict"&&a.limitations.unshift(`Runtime/framework ownership conflict (${s.runtimeOwner} vs ${s.frameworkOwner}); Doctor failed closed instead of selecting an ambiguous adapter.`),r[0]=a);}let c=r.filter(a=>!!a);return {schemaVersion:a$2,registryVersion:b,generatedBy:"workspai",policy:{unknownIsHealthy:false,unsupportedIsHealthy:false,repairRequiresTypedOperation:true,canonicalDomains:[...D]},summary:{adapterCount:c.length,firstClassRuntimes:c.filter(a=>a.tier==="first-class").length,extendedRuntimes:c.filter(a=>a.tier==="extended").length,fallbackRuntimes:c.filter(a=>a.tier==="fallback").length,frameworkCount:new Set(c.flatMap(a=>a.frameworks)).size,platformCount:new Set(c.flatMap(a=>a.platforms)).size},adapters:c}}var me=["runtime","dependency","security","configuration","test","quality"];function I(e){return createHash("sha256").update(e).digest("hex").slice(0,12)}function S(e){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Q(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function ge(e,i){let t=Q(e);return t?i.some(s=>[s.reason,s.recommendation??""].map(Q).filter(Boolean).some(c=>c===t||c.includes(t)||t.includes(c))):true}function fe(e){return e.status==="fail"?"blocking":e.status==="warn"?"advisory":"informational"}function X(e){return e.issueClass==="dependency"?"dependency":e.issueClass==="security"?"security":e.issueClass==="environment"||e.issueClass==="configuration"||e.issueClass==="container"||e.issueClass==="deployment"||e.issueClass==="workspace-contract"?"configuration":e.issueClass==="test"?"test":e.issueClass==="quality"||e.issueClass==="custom"?"quality":e.issueClass==="runtime"||e.issueClass==="framework"||e.issueClass==="source-tree"?"runtime":null}function ye(e,i){return me.map(t=>{let s=e.filter(o=>X(o)===t),r=e.filter(o=>o.applicability!=="not-applicable"&&X(o)===t),c=i.unsupportedDomains.includes(t);if(r.length===0){let o=s.some(d=>d.applicability==="not-applicable");return {id:t,status:o?"not-applicable":"not-run",observationCount:0,blockingFindings:0,advisoryFindings:0,reason:o?`${t} checks ran and found no declared intent requiring this domain.`:c?`${t} is unsupported by Doctor adapter ${i.adapterId}; no healthy claim is allowed.`:`No ${t} diagnostic observation was produced.`}}let a=r.some(o=>o.freshness?.status==="stale"||o.freshness?.status==="unknown"),p=r.filter(o=>o.status==="fail").length,m=r.filter(o=>o.status==="warn").length,C=p>0||m>0;return {id:t,status:a?"stale":C?"findings":c?"not-run":"clean",observationCount:r.length,blockingFindings:p,advisoryFindings:m,reason:a?`${t} evidence is stale or has unknown freshness.`:C?`${t} diagnostics produced findings.`:c?`${t} observations cannot establish complete health because adapter ${i.adapterId} declares the domain unsupported.`:`${t} diagnostics completed without findings.`}})}function De(e){if(e.status==="pass")return "not-needed";let i=e.repairCapability;return i?i.status==="manual"||i.requiresReview?"manual":i.status!=="available"||!i.canAutoFix?"unavailable":i.requiresApproval?"approval-required":"automatic":"unavailable"}function be(e){if(e.freshness?.status==="stale"||e.freshness?.status==="unknown")return {label:"low",score:.35,state:"unknown"};let i=!!(e.issueClass&&e.issueClass!=="unknown"),t=!!(e.repairCapability?.operation?.type||e.repairCapability?.invocation?.executable);return i&&t&&e.repairIntent?.confidence==="high"?{label:"high",score:.95,state:"confirmed"}:i&&(e.status==="fail"||e.status==="warn")?{label:"medium",score:t?.82:.68,state:"candidate"}:e.status==="pass"?{label:"high",score:.98,state:"confirmed"}:{label:"low",score:.3,state:"unknown"}}function ve(e,i){let t=[{kind:"probe",role:"observation",ref:`probe:${e.id}`,claim:e.reason}];for(let r of e.repairCapability?.files??[])t.push({kind:"file",role:"repair-target",ref:r.split(pe.sep).join("/"),claim:"Structured repair capability declared this path as an affected target."});if(e.repairCapability?.invocation?.executable){let r=e.repairCapability.invocation;t.push({kind:"command",role:"verification",ref:[r.executable,...r.args??[]].join(" "),claim:"Structured command invocation is available for this diagnostic path."});}if(e.issueClass==="security"&&/(?:dependency|audit|vulnerab|security-hygiene)/i.test(`${e.id} ${e.label}`))for(let r of i??[])t.push({kind:"dependency",role:"subject",ref:r.version?`${r.name}@${r.version}`:r.name,claim:r.advisoryIds&&r.advisoryIds.length>0?`Dependency is referenced by ${r.advisoryIds.join(", ")}.`:"Dependency is present in security audit evidence."});return t}function we(e,i){let t=i.issueClass?.trim()||"unknown",s=be(i);return {id:`${S(i.id)}:${I(`${e.projectPath}\0${i.id}`)}`,causalKey:[S(e.projectName),I(e.projectPath),S(t),S(i.id)].join(":"),projectName:e.projectName,projectPath:e.projectPath,probeId:i.id,label:i.label,status:fe(i),severity:i.severity,issueClass:t,operationalImpact:i.operationalImpact?.trim()||"developer-friction",applicability:i.applicability??"applicable",confidence:s.label,confidenceScore:s.score,diagnosisState:s.state,symptom:i.reason,...i.recommendation?{recommendation:i.recommendation}:{},proofs:ve(i,e.dependencySubjects),repair:{disposition:De(i),...i.repairCapability?.id?{capabilityId:i.repairCapability.id}:{},...i.repairCapability?.operation?.type?{operationType:i.repairCapability.operation.type}:{},...i.repairCapability?.verifyCommand?{verifyCommand:i.repairCapability.verifyCommand}:{},requiresFreshEvidence:i.repairIntent?.requiresFreshEvidence===true||i.freshness?.verifyBeforeUse===true}}}function he(e,i,t){let s=`legacy-runtime-issue-${t+1}`;return {id:`${s}:${I(`${e.projectPath}\0${i}`)}`,causalKey:[S(e.projectName),I(e.projectPath),"unknown",I(i)].join(":"),projectName:e.projectName,projectPath:e.projectPath,probeId:s,label:"Runtime diagnostic issue",status:"blocking",severity:"error",issueClass:"unknown",operationalImpact:"runtime-risk",applicability:"applicable",confidence:"low",confidenceScore:.25,diagnosisState:"unknown",symptom:i,proofs:[{kind:"unknown",role:"observation",ref:`legacy-issue:${t+1}`,claim:i}],repair:{disposition:"unavailable",requiresFreshEvidence:true}}}function Z(e){let i=[...e.probes],t=[...new Set((e.runtimeFamilies&&e.runtimeFamilies.length>0?e.runtimeFamilies:[e.runtimeFamily??"unknown"]).filter(Boolean))],s=e.runtimeFamily??t[0]??"unknown",r=t.filter(n=>n!==s&&n!=="unknown"),c=J({runtimeFamily:e.runtimeFamily,framework:e.framework},e.adapterRegistry),a$1=ye(i,c),p=(e.legacyIssues??[]).filter(n=>!ge(n,i)),m=new Map;for(let n of i){let l=m.get(n.id)??new Set;l.add(n.status),m.set(n.id,l);}let C=[...m.entries()].filter(([,n])=>n.size>1).map(([n,l])=>({probeId:n,statuses:[...l].sort(),reason:"The same diagnostic probe produced contradictory states in one project scan."})),o=[...i.filter(n=>n.applicability!=="not-applicable"&&n.status!=="pass").map(n=>we(e,n)),...p.map((n,l)=>he(e,n,l))],d={blocking:4,unknown:3,advisory:2,informational:1},O=new Map;for(let n of o){let l=O.get(n.causalKey)??[];l.push(n),O.set(n.causalKey,l);}let g=[...O.values()].map(n=>{let u=[...n].sort((f,j)=>d[j.status]-d[f.status]||j.confidenceScore-f.confidenceScore||f.id.localeCompare(j.id)).at(0);if(!u)throw new Error("Doctor diagnosis causal group cannot be empty.");let G=structuredClone(u);return G.proofs=[...new Map(n.flatMap(f=>f.proofs).map(f=>[`${f.kind}:${f.role}:${f.ref}:${f.claim}`,f])).values()],G}).sort((n,l)=>n.causalKey.localeCompare(l.causalKey)||n.id.localeCompare(l.id)),k=new Map;for(let n of g){let l=k.get(n.causalKey)??[];l.push(n),k.set(n.causalKey,l);}let b=[...k.entries()].map(([n,l])=>({causalKey:n,issueClass:l[0]?.issueClass??"unknown",status:l.some(u=>u.status==="blocking")?"blocking":l.some(u=>u.status==="advisory")?"advisory":l.some(u=>u.status==="unknown")?"unknown":"informational",findingIds:l.map(u=>u.id),projectPaths:[...new Set(l.map(u=>u.projectPath))],repairable:l.some(u=>u.repair.disposition==="automatic"||u.repair.disposition==="approval-required")})),v=[...g.filter(n=>n.diagnosisState==="unknown"||n.issueClass==="unknown"||n.applicability==="unknown").map(n=>({id:`unknown:${n.id}`,probeId:n.probeId,reason:n.issueClass==="unknown"?"The observation is real, but Doctor cannot yet bind it to a typed issue class.":"Evidence is insufficient or stale for a confirmed diagnosis."})),...a$1.filter(n=>n.status==="not-run"||n.status==="stale").map(n=>({id:`unknown:domain:${n.id}:${I(e.projectPath)}`,reason:n.reason})),...r.map(n=>({id:`unknown:runtime:${S(n)}:${I(e.projectPath)}`,reason:e.projectArchetype==="platform"?`${n} is part of this cross-language platform, but only portable evidence and the primary ${s} runtime adapter were evaluated. Add a typed ${n} adapter before making runtime-specific health claims.`:`${n} was detected inside this composite project boundary, but the ${s} adapter is the only runtime-specific adapter evaluated for this scan. Declare a nested project boundary or a typed Doctor adapter before treating ${n} as healthy.`}))],y=g.filter(n=>n.diagnosisState!=="unknown").length,x=g.length===0?100:y/g.length*100,ie=a$1.filter(n=>n.status!=="not-run"&&n.status!=="stale").length/a$1.length*100,U=t.filter(n=>n!=="unknown").length,te=s!=="unknown"&&t.includes(s)?1:0,ne=U===0?0:te/U*100,se=Math.round(Math.min(x,ie,ne)*100)/100;return {schemaVersion:a,engineVersion:"universal-diagnosis-v1",project:{name:e.projectName,path:e.projectPath,runtimeFamily:e.runtimeFamily??"unknown",runtimeFamilies:t,framework:e.framework??"Unknown",projectKind:e.projectKind??"generic"},capability:c,domains:a$1,coverage:{totalObservations:i.length+p.length,evaluatedObservations:i.filter(n=>n.applicability!=="not-applicable").length,passingObservations:i.filter(n=>n.applicability!=="not-applicable"&&n.status==="pass").length,blockingFindings:g.filter(n=>n.status==="blocking").length,advisoryFindings:g.filter(n=>n.status==="advisory").length,unknownFindings:v.length,repairableFindings:g.filter(n=>n.repair.disposition==="automatic"||n.repair.disposition==="approval-required").length,manualFindings:g.filter(n=>n.repair.disposition==="manual").length,unsupportedFindings:g.filter(n=>n.repair.disposition==="unavailable").length,contradictionCount:C.length,diagnosisCompleteness:se},findings:g,causalGroups:b,unknowns:v,contradictions:C}}function w(e){let i=e.severity??"error",t=e.repair??"unavailable";return {id:e.id,label:e.label,status:i==="error"?"fail":"warn",severity:i,reason:`${e.label} detected by the validation corpus.`,issueClass:e.issueClass,operationalImpact:i==="error"?"release-risk":"ci-risk",repairIntent:{confidence:e.confidence??"medium",requiresFreshEvidence:true},...t==="unavailable"?{}:{repairCapability:{id:`repair.${e.id}`,status:t==="manual"?"manual":"available",canAutoFix:t==="automatic"||t==="approval-required",requiresApproval:t==="approval-required",requiresReview:t==="manual",operation:{type:"validation-operation"},verifyCommand:"npx workspai doctor project --json"}}}}var Ce=[{id:"runtime-missing",diseaseClass:"runtime",description:"Required runtime is absent.",probe:w({id:"runtime-missing",label:"Runtime missing",issueClass:"runtime"}),expected:{finding:true,domain:"runtime",status:"blocking",diagnosisState:"candidate",repairDisposition:"unavailable"}},{id:"dependencies-missing",diseaseClass:"dependency",description:"Installed dependency tree is absent.",probe:w({id:"dependencies-missing",label:"Dependencies missing",issueClass:"dependency",repair:"automatic",confidence:"high"}),expected:{finding:true,domain:"dependency",status:"blocking",diagnosisState:"confirmed",repairDisposition:"automatic"}},{id:"security-advisory",diseaseClass:"security",description:"A runtime-native audit reports a blocking advisory.",probe:w({id:"security-advisory",label:"Security advisory",issueClass:"security",repair:"approval-required",confidence:"high"}),expected:{finding:true,domain:"security",status:"blocking",diagnosisState:"confirmed",repairDisposition:"approval-required"}},{id:"environment-contract",diseaseClass:"configuration",description:"Environment/configuration contract is incomplete.",probe:w({id:"environment-contract",label:"Environment contract incomplete",issueClass:"environment",severity:"warn",repair:"manual"}),expected:{finding:true,domain:"configuration",status:"advisory",diagnosisState:"candidate",repairDisposition:"manual"}},{id:"container-contract",diseaseClass:"configuration",description:"Container delivery contract is incomplete.",probe:w({id:"container-contract",label:"Container contract incomplete",issueClass:"container",severity:"warn"}),expected:{finding:true,domain:"configuration",status:"advisory",diagnosisState:"candidate",repairDisposition:"unavailable"}},{id:"tests-missing",diseaseClass:"test",description:"No deterministic test surface is declared.",probe:w({id:"tests-missing",label:"Tests missing",issueClass:"test",severity:"warn",repair:"manual"}),expected:{finding:true,domain:"test",status:"advisory",diagnosisState:"candidate",repairDisposition:"manual"}},{id:"quality-missing",diseaseClass:"quality",description:"No lint/format/static-analysis surface is declared.",probe:w({id:"quality-missing",label:"Quality tooling missing",issueClass:"quality",severity:"warn"}),expected:{finding:true,domain:"quality",status:"advisory",diagnosisState:"candidate",repairDisposition:"unavailable"}},{id:"stale-evidence",diseaseClass:"freshness",description:"Evidence is stale and must not be treated as confirmed.",probe:{...w({id:"stale-evidence",label:"Stale evidence",issueClass:"security"}),freshness:{status:"stale",verifyBeforeUse:true}},expected:{finding:true,domain:"security",status:"blocking",diagnosisState:"unknown",repairDisposition:"unavailable"}},{id:"unknown-disease",diseaseClass:"unknown",description:"A real symptom cannot be bound to a typed disease class.",probe:w({id:"unknown-disease",label:"Unknown disease",issueClass:"unknown"}),expected:{finding:true,status:"blocking",diagnosisState:"unknown",repairDisposition:"unavailable"}},{id:"healthy-runtime",diseaseClass:"healthy-control",description:"Healthy evidence must not become a finding.",probe:{id:"healthy-runtime",label:"Healthy runtime",status:"pass",severity:"info",reason:"Runtime evidence is healthy.",issueClass:"runtime",operationalImpact:"none"},expected:{finding:false,domain:"runtime"}}];function _(e){return Math.round(e*1e4)/1e4}function ee(){let i=P().list(),t=i.flatMap(o=>Ce.map(d=>{let O=o.runtimeFamilies[0]??"unknown",g=o.frameworks[0]??"Unknown",k=Z({projectName:`validation-${o.id}-${d.id}`,projectPath:`/virtual/doctor-validation/${o.id}/${d.id}`,runtimeFamily:O,framework:g,projectKind:"generic",probes:[d.probe]}),b=k.findings.find(x=>x.probeId===d.probe.id),N=k.domains.find(x=>x.observationCount>0)?.id,v={finding:!!b,...N?{domain:N}:{},...b?.status?{status:b.status}:{},...b?.diagnosisState?{diagnosisState:b.diagnosisState}:{},...b?.repair.disposition?{repairDisposition:b.repair.disposition}:{}},y=[];return v.finding!==d.expected.finding&&y.push("finding-presence"),d.expected.domain&&v.domain!==d.expected.domain&&y.push("domain"),d.expected.status&&v.status!==d.expected.status&&y.push("status"),d.expected.diagnosisState&&v.diagnosisState!==d.expected.diagnosisState&&y.push("diagnosis-state"),d.expected.repairDisposition&&v.repairDisposition!==d.expected.repairDisposition&&y.push("repair-disposition"),k.capability.adapterId!==o.id&&y.push("adapter-binding"),{id:`${o.id}:${d.id}`,passed:y.length===0,expected:d.expected,actual:v,failures:y}})),s=t.filter(o=>o.expected.finding),r=t.filter(o=>!o.expected.finding),c$1=s.filter(o=>o.actual.finding).length,a=s.length-c$1,p=r.filter(o=>!o.actual.finding).length,m=r.length-p,C=new Set(t.map(o=>o.actual.domain).filter(o=>!!o));return {schemaVersion:c,corpusVersion:d,capabilityRegistryVersion:b,scope:"synthetic-contract-corpus",summary:{totalCases:t.length,passedCases:t.filter(o=>o.passed).length,failedCases:t.filter(o=>!o.passed).length,truePositives:c$1,trueNegatives:p,falsePositives:m,falseNegatives:a,precision:_(c$1/Math.max(1,c$1+m)),recall:_(c$1/Math.max(1,c$1+a)),domainCoverage:_(C.size/D.length),runtimeAdapterCoverage:_(new Set(t.map(o=>o.id.split(":",1)[0])).size/Math.max(1,i.length)),runtimeAdaptersExercised:i.length,declaredPlatforms:new Set(i.flatMap(o=>o.platforms)).size},cases:t,limitations:["Precision and recall describe the versioned synthetic contract corpus, not every public repository.","Every registered runtime adapter is exercised against the same disease corpus; this proves contract behavior, not tool availability on a host.","Runtime-native fixture and real Linux, macOS, and Windows acceptance gates remain separate evidence surfaces."]}}async function Qe(e$1={}){let i=K({runtime:e$1.runtime,framework:e$1.framework}),t=e$1.validate?ee():void 0,s,r;if(e$1.write){let a=e$1.workspace?pe.resolve(e$1.workspace):a$1(process.cwd());if(!a)return e$1.json?console.log(JSON.stringify({schemaVersion:i.schemaVersion,status:"error",error:{code:"doctor.capabilities.workspace-not-found",message:"--write requires a Workspai workspace or --workspace <path>."}},null,2)):console.log(h.red("Doctor capabilities could not be written: no workspace found.")),1;let p=K();s=await e(a,h$1.doctorCapabilities.artifactPath,p),t&&(r=await e(a,h$1.doctorValidation.artifactPath,t));}let c={...i,...t?{validation:t}:{},...s?{artifactPath:s}:{},...r?{validationArtifactPath:r}:{}};if(e$1.json)e$1.quiet||console.log(JSON.stringify(c,null,2));else if(!e$1.quiet){console.log(h.bold.cyan(`
2
2
  \u{1FA7A} Workspai Doctor capabilities
3
3
  `)),console.log(`${i.summary.adapterCount} adapter(s) \xB7 ${i.summary.frameworkCount} framework mapping(s) \xB7 ${i.summary.platformCount} platform(s)`);for(let a of i.adapters){let p=a.domains.map(m=>`${m.domain}:${m.level}`).join(" \xB7 ");console.log(h.bold(`
4
4
  ${a.runtimeFamilies.join(", ")} \xB7 ${a.tier}`)),console.log(h.gray(p));for(let m of a.limitations)console.log(h.yellow(` ! ${m}`));}if(t){let a=t.summary,p=a.failedCases===0?h.green:h.red;console.log(p(`
@@ -1 +1 @@
1
- import {c,e}from'./chunk-XDPTAV2T.js';import {i,h as h$1}from'./chunk-ZGHJIQXL.js';import {t}from'./chunk-VQZ5PI5J.js';import u from'fs';import A from'path';var a=h$1.workspaceRunLast.schemaVersion,W="workspace-run-last.json",o=i.workspaceRunLast;var P=new Set(["init","test","build","start"]);function _(e){return P.has(e)}async function d(e){try{return await u.promises.access(e,u.constants.F_OK),true}catch{return false}}async function w(e){try{let r=await u.promises.readFile(e,"utf-8");return JSON.parse(r)}catch{return null}}function m(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function h(e){let r=e.stage;return typeof r!="string"||r.trim().length===0||!Array.isArray(e.projects)?false:_(r)||/^[a-z][a-z0-9_-]*$/i.test(r)}function T(e){let r=m(e);return !r||r.schemaVersion===a?false:h(r)}function C(e){let r=m(e);return r?r.schemaVersion===a&&r.stages!=null:false}function p(e){if(C(e))return e;if(T(e)){let r=e.stage;return {schemaVersion:a,generatedAt:e.generatedAt,workspacePath:e.workspacePath,latestStage:r,stages:{[r]:e},enterpriseControls:e.enterpriseControls??{jsonReady:true,evidencePath:o}}}return null}function U(e,r){let n=p(e);if(!n)return null;let t=r??n.latestStage;return n.stages[t]??null}async function V(e){let r=(await Promise.all(t(A.resolve(e),"reports",W).map(async t=>await d(t)?t:null))).find(t=>typeof t=="string");if(!r)return null;let n=await w(r);return p(n)}async function j(e$1,r){let n=A.resolve(e$1);return c(n,o,async()=>{let t$1=(await Promise.all(t(n,"reports",W).map(async s=>await d(s)?s:null))).find(s=>typeof s=="string"),R=t$1?await w(t$1):null,i=p(R);if(t$1&&!i)throw new Error(`Workspace run evidence is unreadable or invalid; refusing to overwrite: ${t$1}`);let l=i?{...i.stages}:{};l[r.stage]=r;let g={schemaVersion:a,generatedAt:r.generatedAt,workspacePath:r.workspacePath,latestStage:r.stage,stages:l,enterpriseControls:{jsonReady:true,evidencePath:o}};return await e(n,o,g),g})}export{W as a,o as b,U as c,V as d,j as e};
1
+ import {c,e}from'./chunk-C2VTO5WT.js';import {i,h as h$1}from'./chunk-ZGHJIQXL.js';import {t}from'./chunk-VQZ5PI5J.js';import u from'fs';import A from'path';var a=h$1.workspaceRunLast.schemaVersion,W="workspace-run-last.json",o=i.workspaceRunLast;var P=new Set(["init","test","build","start"]);function _(e){return P.has(e)}async function d(e){try{return await u.promises.access(e,u.constants.F_OK),true}catch{return false}}async function w(e){try{let r=await u.promises.readFile(e,"utf-8");return JSON.parse(r)}catch{return null}}function m(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function h(e){let r=e.stage;return typeof r!="string"||r.trim().length===0||!Array.isArray(e.projects)?false:_(r)||/^[a-z][a-z0-9_-]*$/i.test(r)}function T(e){let r=m(e);return !r||r.schemaVersion===a?false:h(r)}function C(e){let r=m(e);return r?r.schemaVersion===a&&r.stages!=null:false}function p(e){if(C(e))return e;if(T(e)){let r=e.stage;return {schemaVersion:a,generatedAt:e.generatedAt,workspacePath:e.workspacePath,latestStage:r,stages:{[r]:e},enterpriseControls:e.enterpriseControls??{jsonReady:true,evidencePath:o}}}return null}function U(e,r){let n=p(e);if(!n)return null;let t=r??n.latestStage;return n.stages[t]??null}async function V(e){let r=(await Promise.all(t(A.resolve(e),"reports",W).map(async t=>await d(t)?t:null))).find(t=>typeof t=="string");if(!r)return null;let n=await w(r);return p(n)}async function j(e$1,r){let n=A.resolve(e$1);return c(n,o,async()=>{let t$1=(await Promise.all(t(n,"reports",W).map(async s=>await d(s)?s:null))).find(s=>typeof s=="string"),R=t$1?await w(t$1):null,i=p(R);if(t$1&&!i)throw new Error(`Workspace run evidence is unreadable or invalid; refusing to overwrite: ${t$1}`);let l=i?{...i.stages}:{};l[r.stage]=r;let g={schemaVersion:a,generatedAt:r.generatedAt,workspacePath:r.workspacePath,latestStage:r.stage,stages:l,enterpriseControls:{jsonReady:true,evidencePath:o}};return await e(n,o,g),g})}export{W as a,o as b,U as c,V as d,j as e};