workspai 0.58.0 → 0.59.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 (140) hide show
  1. package/README.md +80 -32
  2. package/contracts/agent-customization-pack.v1.json +52 -4
  3. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +90 -0
  4. package/contracts/extension-cli-compatibility.v1.json +3 -1
  5. package/contracts/project-workspace-resolution.v1.json +15 -2
  6. package/contracts/published-contract-catalog.v1.json +10 -0
  7. package/contracts/runtime-command-surface.v1.json +54 -0
  8. package/contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json +247 -0
  9. package/contracts/workspace-intelligence/agent-customization-pack-report.v1.json +16 -1
  10. package/contracts/workspace-intelligence/goal-index.v1.json +7 -1
  11. package/contracts/workspace-intelligence/goal-pack.v1.json +2 -1
  12. package/contracts/workspace-intelligence/project-agent-entry.v1.json +204 -0
  13. package/contracts/workspace-intelligence/project-context-agent.v1.json +43 -26
  14. package/contracts/workspace-intelligence/workspace-context.v1.json +14 -1
  15. package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +15 -2
  16. package/contracts/workspace-repair-capabilities.v1.json +5 -0
  17. package/dist/analyze-52TEGLDR.js +1 -0
  18. package/dist/{artifact-remediation-plan-JRX4XZ7C.js → artifact-remediation-plan-HPNQTNJ2.js} +1 -1
  19. package/dist/autopilot-release-KQGDM2AA.js +1 -0
  20. package/dist/capabilities-command-VBLZXP2T.js +1 -0
  21. package/dist/chunk-4PUJVYRM.js +1 -0
  22. package/dist/{chunk-4NN5QWOB.js → chunk-5NIZNXRS.js} +1 -1
  23. package/dist/{chunk-HYY5PQCV.js → chunk-5PSKBJKJ.js} +1 -1
  24. package/dist/{chunk-AA4PNQKR.js → chunk-5SFCBZOH.js} +1 -1
  25. package/dist/{chunk-MFJ6ZP7S.js → chunk-6FBNSTUS.js} +1 -1
  26. package/dist/{chunk-FY6OHOXR.js → chunk-7DSYI7YN.js} +1 -1
  27. package/dist/chunk-7SFXADXO.js +2 -0
  28. package/dist/{chunk-GRGUPSNP.js → chunk-CCDGHPEJ.js} +1 -1
  29. package/dist/{chunk-T63WRURN.js → chunk-D65FCQIO.js} +1 -1
  30. package/dist/{chunk-YYCPRYP7.js → chunk-DGGTTRYE.js} +1 -1
  31. package/dist/{chunk-SM55RK3C.js → chunk-ENKGGWRX.js} +1 -1
  32. package/dist/{chunk-RMDVRNU7.js → chunk-GPOZILMY.js} +1 -1
  33. package/dist/{chunk-C4NYG57I.js → chunk-HCFWT42C.js} +1 -1
  34. package/dist/chunk-HOUQIT7U.js +1 -0
  35. package/dist/{chunk-RJDGC6AQ.js → chunk-HS3DJMU5.js} +1 -1
  36. package/dist/{chunk-HI7ONEFI.js → chunk-J3X56S7L.js} +1 -1
  37. package/dist/{chunk-N3DFX4BY.js → chunk-KBR4Y4RW.js} +1 -1
  38. package/dist/{chunk-H545P6LN.js → chunk-KTN2ARZJ.js} +1 -1
  39. package/dist/chunk-LPCWROQ3.js +1 -0
  40. package/dist/{chunk-6TNSCVR4.js → chunk-M3IKRWXA.js} +1 -1
  41. package/dist/{chunk-CFBAGPB4.js → chunk-M4UOXP5T.js} +1 -1
  42. package/dist/{chunk-LGJAAPNR.js → chunk-N4QQADXX.js} +1 -1
  43. package/dist/{chunk-FXIE2WVG.js → chunk-NOZ4JCH7.js} +1 -1
  44. package/dist/chunk-NZ3WZYD5.js +1 -0
  45. package/dist/{chunk-VAWV3UKV.js → chunk-OFWSZYUX.js} +1 -1
  46. package/dist/{chunk-XC26FNRL.js → chunk-OLC7EYUA.js} +3 -3
  47. package/dist/chunk-PVXSIYLP.js +1 -0
  48. package/dist/{chunk-7KXRA5ST.js → chunk-PXWKMPPI.js} +1 -1
  49. package/dist/{chunk-II4ROT6X.js → chunk-QCKWQFCD.js} +1 -1
  50. package/dist/{chunk-4YICCES6.js → chunk-QFBVQUKV.js} +1 -1
  51. package/dist/{chunk-G4VMNWSU.js → chunk-QJCCZLOF.js} +1 -1
  52. package/dist/{chunk-A3JCETSF.js → chunk-QMPFNXI7.js} +1 -1
  53. package/dist/{chunk-YMY6EFX4.js → chunk-RBBBXFEU.js} +1 -1
  54. package/dist/{chunk-TTLVG5AR.js → chunk-RHK53ZK7.js} +1 -1
  55. package/dist/chunk-S45YGN2I.js +142 -0
  56. package/dist/chunk-S4CWUZ4K.js +1 -0
  57. package/dist/{chunk-EEMRRCGR.js → chunk-SP5EHSWG.js} +1 -1
  58. package/dist/chunk-TCURN5VD.js +2 -0
  59. package/dist/{chunk-CHMCKYJJ.js → chunk-UVBPEX3E.js} +1 -1
  60. package/dist/chunk-V3ABABV5.js +39 -0
  61. package/dist/{chunk-WSDVFLHT.js → chunk-W6FHVXNL.js} +1 -1
  62. package/dist/{chunk-M2BK3XTP.js → chunk-WQX3JYEP.js} +1 -1
  63. package/dist/{chunk-AUCHMXUZ.js → chunk-WSRUPDZN.js} +1 -1
  64. package/dist/{chunk-GVS5OFUB.js → chunk-YEEAWZWI.js} +1 -1
  65. package/dist/{chunk-I5PDN2P2.js → chunk-ZJCM37KX.js} +1 -1
  66. package/dist/{create-QIN56Y4M.js → create-6QWIJTGU.js} +1 -1
  67. package/dist/{doctor-RP4Q2CKJ.js → doctor-NAZEKMGU.js} +1 -1
  68. package/dist/goal-lifecycle-ECIRCHN5.js +1 -0
  69. package/dist/goal-pack-HBOPVZFO.js +1 -0
  70. package/dist/index.d.ts +8 -1
  71. package/dist/index.js +134 -132
  72. package/dist/{pipeline-77NUVYQD.js → pipeline-5LLFP5ZH.js} +1 -1
  73. package/dist/project-agent-entry-AFKDDRDL.js +1 -0
  74. package/dist/{project-intelligence-lens-AM2B2PXU.js → project-intelligence-lens-U2V3VNZG.js} +1 -1
  75. package/dist/{project-test-coverage-MUSS7Z7V.js → project-test-coverage-HP37HUV2.js} +1 -1
  76. package/dist/{verified-goal-ZSIZYNVO.js → verified-goal-HUYJ6LBI.js} +1 -1
  77. package/dist/{workspace-LFESVKE7.js → workspace-CQ43AWUF.js} +1 -1
  78. package/dist/{workspace-agent-sync-JMRX6J2Y.js → workspace-agent-sync-YMXYUGYY.js} +1 -1
  79. package/dist/{workspace-archive-MFHCFCDO.js → workspace-archive-ZBCKJHXS.js} +1 -1
  80. package/dist/{workspace-context-TBKRMVMT.js → workspace-context-RAO62QVU.js} +1 -1
  81. package/dist/{workspace-contract-KKVC2DUQ.js → workspace-contract-ACSIHJIO.js} +1 -1
  82. package/dist/workspace-explain-RH27OQB4.js +1 -0
  83. package/dist/workspace-explain-contract-ZL4NMLZI.js +1 -0
  84. package/dist/{workspace-feedback-O6J3RQML.js → workspace-feedback-RQ4TGJW6.js} +1 -1
  85. package/dist/{workspace-foundation-JQWT7YGC.js → workspace-foundation-JH2GFSAZ.js} +1 -1
  86. package/dist/{workspace-graph-stream-V5WOXP4B.js → workspace-graph-stream-ZZZEQQTE.js} +1 -1
  87. package/dist/workspace-graph-token-efficiency-D7CUT6NX.js +1 -0
  88. package/dist/{workspace-history-TOCRMJUJ.js → workspace-history-SYCDK7FO.js} +1 -1
  89. package/dist/{workspace-intelligence-SDBIRKMK.js → workspace-intelligence-3YERTBA3.js} +1 -1
  90. package/dist/{workspace-intelligence-evaluation-E4UMWDAZ.js → workspace-intelligence-evaluation-CQDKOYZZ.js} +1 -1
  91. package/dist/{workspace-intelligence-runner-DIMNL6CJ.js → workspace-intelligence-runner-YXMOT6GK.js} +1 -1
  92. package/dist/{workspace-intelligence-runtime-registry-YGWB2RRS.js → workspace-intelligence-runtime-registry-IW6J53LO.js} +1 -1
  93. package/dist/{workspace-knowledge-graph-MUW6UAGI.js → workspace-knowledge-graph-HZZP6ZRB.js} +1 -1
  94. package/dist/{workspace-knowledge-graph-query-6DAOXGGT.js → workspace-knowledge-graph-query-ON45H6Y7.js} +1 -1
  95. package/dist/workspace-knowledge-graph-snapshot-7DWHMEM2.js +1 -0
  96. package/dist/{workspace-mcp-serve-2SWLIH4I.js → workspace-mcp-serve-5TTAN243.js} +1 -1
  97. package/dist/{workspace-model-VPFCKTYQ.js → workspace-model-EIQSKDX7.js} +1 -1
  98. package/dist/{workspace-onboarding-GHI6UTQJ.js → workspace-onboarding-SHHW4R4G.js} +1 -1
  99. package/dist/{workspace-readme-RASXBZRQ.js → workspace-readme-56YZ4EAZ.js} +1 -1
  100. package/dist/{workspace-registry-summary-7QT7YMIU.js → workspace-registry-summary-OV5KX3WC.js} +1 -1
  101. package/dist/workspace-repair-engine-BNXZHW35.js +3 -0
  102. package/dist/workspace-run-7EJEBHAH.js +1 -0
  103. package/dist/{workspace-verify-RYCQZYYB.js → workspace-verify-W4P6LBIH.js} +1 -1
  104. package/dist/{workspace-watch-U3YGN3GG.js → workspace-watch-EZ4D4VCF.js} +1 -1
  105. package/docs/GLOSSARY.md +13 -10
  106. package/docs/README.md +24 -19
  107. package/docs/README_CONTENT_CONTRACT.md +12 -8
  108. package/docs/agent-entry.md +194 -0
  109. package/docs/ci-workflows.md +1 -1
  110. package/docs/commands-reference.md +26 -2
  111. package/docs/contracts/ARTIFACT_CATALOG.md +9 -3
  112. package/docs/contracts/COMMAND_OWNERSHIP_MATRIX.md +3 -0
  113. package/docs/contracts/README.md +7 -0
  114. package/docs/goal-packs.md +70 -9
  115. package/docs/workspace-operations.md +16 -8
  116. package/docs/workspace-repair-engine.md +36 -5
  117. package/package.json +3 -2
  118. package/scripts/enterprise-package-smoke.mjs +4 -0
  119. package/dist/analyze-MAU36FTX.js +0 -1
  120. package/dist/autopilot-release-TA2L7SCB.js +0 -1
  121. package/dist/capabilities-command-HE2FICLG.js +0 -1
  122. package/dist/chunk-42Q5E2YV.js +0 -1
  123. package/dist/chunk-7IRGSM25.js +0 -1
  124. package/dist/chunk-CNWUIXF3.js +0 -1
  125. package/dist/chunk-FPJNWPKU.js +0 -1
  126. package/dist/chunk-HH54C3XJ.js +0 -1
  127. package/dist/chunk-NQ5H4R2I.js +0 -83
  128. package/dist/chunk-PCXBPQO6.js +0 -1
  129. package/dist/chunk-QXW3SLEX.js +0 -1
  130. package/dist/chunk-TMOKXYAQ.js +0 -2
  131. package/dist/chunk-VIFTO53Y.js +0 -1
  132. package/dist/chunk-ZDYGO3T7.js +0 -36
  133. package/dist/goal-lifecycle-YTBU3ICP.js +0 -1
  134. package/dist/goal-pack-MYYH7K43.js +0 -1
  135. package/dist/workspace-explain-RGGZL5IW.js +0 -1
  136. package/dist/workspace-explain-contract-4ZZ6CJ44.js +0 -1
  137. package/dist/workspace-graph-token-efficiency-TF23UYEF.js +0 -1
  138. package/dist/workspace-knowledge-graph-snapshot-7IU2QAXI.js +0 -1
  139. package/dist/workspace-repair-engine-AZTJIFCY.js +0 -3
  140. package/dist/workspace-run-VMZY6LIF.js +0 -1
@@ -1 +1 @@
1
- import {e,p,i,f as f$1,g}from'./chunk-HH54C3XJ.js';var l="workspai-workspace-intelligence-chain-v1",u="contracts/workspace-intelligence-chain.v1.json";function f(){let e$1=e,t=p,n=[{id:"model",ordinal:1,phase:"understand",label:"Model",command:[...t.model.command],consumes:["workspace markers","project metadata","registry","contract","policies"],inputRefs:["projects-repositories","runtime-dependencies","workspace-rules","existing-evidence"],consumesArtifacts:[],produces:[...t.model.produces],dependsOn:[],exitPolicy:"stop-on-error",purpose:"Build the canonical current model and its structurally bound, derived Knowledge Graph."},{id:"diff",ordinal:2,phase:"change",label:"Diff",command:[...t.diff.command],consumes:[e$1.model,e$1.snapshot],inputRefs:["changes","model-baseline"],consumesArtifacts:[e$1.model,e$1.snapshot],produces:[...t.diff.produces],dependsOn:["model"],exitPolicy:"stop-on-error",purpose:"Describe structural change against the selected baseline."},{id:"impact",ordinal:3,phase:"change",label:"Impact",command:[...t.impact.command],consumes:[e$1.model,e$1.diff],inputRefs:[],consumesArtifacts:[e$1.model,e$1.diff],produces:[...t.impact.produces],dependsOn:["diff"],exitPolicy:"stop-on-error",purpose:"Calculate transitive blast radius over the workspace graph."},{id:"doctor-evidence",ordinal:4,phase:"evidence",label:"Doctor Evidence",command:[...t["doctor-evidence"].command],consumes:["workspace runtime and project health signals"],inputRefs:["projects-repositories","runtime-dependencies","existing-evidence"],consumesArtifacts:[],produces:[...t["doctor-evidence"].produces],dependsOn:["impact"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh health evidence after the impact artifact exists."},{id:"contract-evidence",ordinal:5,phase:"evidence",label:"Contract Evidence",command:[...t["contract-evidence"].command],consumes:[i.workspaceContract],inputRefs:["workspace-rules"],consumesArtifacts:[],produces:[...t["contract-evidence"].produces],dependsOn:["impact"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh structural contract evidence without hiding failed verdicts."},{id:"analyze-evidence",ordinal:6,phase:"evidence",label:"Analyze Evidence",command:[...t["analyze-evidence"].command],consumes:[e$1.model,"workspace runtime and dependency signals"],inputRefs:["projects-repositories","runtime-dependencies","workspace-rules"],consumesArtifacts:[e$1.model],produces:[...t["analyze-evidence"].produces],dependsOn:["impact"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh analysis evidence required by the release-readiness gate."},{id:"readiness-evidence",ordinal:7,phase:"evidence",label:"Readiness Evidence",command:[...t["readiness-evidence"].command],consumes:["doctor, analysis, runtime, and release signals"],inputRefs:["runtime-dependencies","existing-evidence"],consumesArtifacts:[e$1.doctor,e$1.contractVerify,e$1.analyze],produces:[...t["readiness-evidence"].produces],dependsOn:["doctor-evidence","contract-evidence","analyze-evidence"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh release-readiness evidence before the definitive gate."},{id:"verify",ordinal:8,phase:"gate",label:"Verify",command:[...t.verify.command],consumes:[e$1.impact,e$1.doctor,e$1.contractVerify,e$1.readiness],inputRefs:[],consumesArtifacts:[e$1.impact,e$1.doctor,e$1.contractVerify,e$1.readiness],produces:[...t.verify.produces],dependsOn:["impact","doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence"],exitPolicy:"continue-on-structured-verdict",purpose:"Emit the definitive evidence-backed workspace gate."},{id:"context",ordinal:9,phase:"ground",label:"Agent Context",command:[...t.context.command],consumes:[e$1.model,e$1.impact,e$1.verify],inputRefs:[],consumesArtifacts:[e$1.model,e$1.impact,e$1.verify],produces:[...t.context.produces],dependsOn:["verify"],exitPolicy:"stop-on-error",purpose:"Build compact agent context from the same verified evidence."},{id:"agent-sync",ordinal:10,phase:"distribute",label:"Agent Grounding",command:[...t["agent-sync"].command],consumerArgs:{vscode:["--target","vscode"]},consumes:[e$1.agentContext],inputRefs:[],consumesArtifacts:[e$1.agentContext],produces:[...t["agent-sync"].produces],dependsOn:["context"],exitPolicy:"stop-on-error",purpose:"Distribute one context into portable agent and IDE surfaces."},{id:"explain",ordinal:11,phase:"explain",label:"Explain",command:[...t.explain.command],consumes:[e$1.verify,e$1.impact],inputRefs:[],consumesArtifacts:[e$1.verify,e$1.impact],produces:[...t.explain.produces],dependsOn:["verify"],exitPolicy:"continue-on-structured-verdict",purpose:"Translate evidence and blockers into a human and agent-readable narrative."}];return {schemaVersion:l,name:"Workspace Intelligence Chain",contractPath:u,invariant:"Every consumer must preserve step identity, dependencies, artifact flow, and verdict semantics; presentation may change, chain meaning may not.",invariants:["Missing or unreadable input is unknown or unavailable; it must not be presented as verified absence.","Freshness and provenance travel with evidence and must not be discarded by projections.","The current graph is an evidence-backed workspace knowledge graph with bounded source intelligence, not a complete cross-language symbol or call graph.","Simple and standard presentations summarize the contract; their contractRefs must preserve complete traceability.","Conditional provider outputs must be resolved through their dedicated inventory contract.","Auxiliary capabilities expose or refresh intelligence but are not mandatory execution-chain steps.","Canonical step commands are stage-pure: they must not implicitly execute a downstream chain step or regenerate an upstream artifact.","Canonical JSON artifacts must satisfy their registered schema both when produced and when consumed across CLI, MCP, IDE, and CI trust boundaries.","Schema validity is necessary but not sufficient: hashes, embedded models, summaries, counts, graph statistics, and artifact references must remain semantically coherent.","Persisted impact evidence must be rejected as stale when the current workspace model or Git observation no longer matches its embedded diff.","Canonical artifact replacement must be atomic and workspace-contained; an interrupted or denied write must preserve the last valid artifact.","Concurrent history updates must be serialized without silently dropping entries, and invalid history must never be overwritten as if it were absent.","The canonical global registry is ~/.workspai/workspaces.json; ~/.rapidkit/workspaces.json is a non-authoritative compatibility mirror for legacy consumers and must not diverge after a CLI registry mutation."],semantics:{workspace:"The governed operating boundary that relates one or more projects and repositories to shared metadata, policies, contracts, evidence, and consumers.",repository:"A source-control boundary that may contain one or more projects and may live inside or outside the workspace root.",project:"A discoverable build or runtime unit with its own path, metadata or observable manifests, command capabilities, and evidence.",evidence:"A sourced observation or generated verification result with provenance and freshness; evidence may be consumed by a later run.",artifact:"A durable generated file that another command or consumer can read without parsing terminal prose.",gate:"A structured verdict with reasons and exit semantics derived from current evidence."},workspaceLifecycle:{ingestionRoutes:[{id:"create",label:"Create",commands:["create workspace","create project"],result:"Create a workspace or supported project and write canonical Workspai metadata."},{id:"adopt",label:"Adopt",commands:["adopt"],result:"Register an existing project in place without requiring source relocation."},{id:"import",label:"Import",commands:["import","workspace import"],result:"Attach an existing project or repository path to the workspace inventory."}],durableState:[{id:"workspace-identity",paths:[".workspai-workspace",".workspai/workspace.json"],purpose:"Identify the workspace boundary, profile, and canonical root."},{id:"project-inventory",paths:[".workspai/project.json",".workspai/context.json",".workspai/adopt.json","~/.workspai/workspaces.json","~/.rapidkit/workspaces.json (legacy compatibility mirror)"],purpose:"Record native, adopted, imported, and globally registered project locations while preserving a non-authoritative mirror for legacy extension discovery."},{id:"governance",paths:[".workspai/policies.yml",i.workspaceContract],purpose:"Define workspace policy and explicit structural relationships."},{id:"graph-overrides",paths:[".workspai/workspace-graph.overrides.json"],purpose:"Provide explicit dependency edges that override inferred relationships."}],rule:"Create, adopt, and import are ingestion routes, not intelligence facts. Their durable state becomes observable input to Model."},runtimeRegistry:{authority:"contracts/workspace-intelligence-runtime-registry.ts",artifacts:Object.entries(e).map(([r,s])=>({id:r,path:s,schemaVersion:f$1[r],schemaContract:g[r]}))},executionEnvelope:{rule:"Sync and baseline resolution are deterministic execution prerequisites, not canonical intelligence stages; every run reports them separately and preserves the exact canonical stage sequence.",operations:[{id:"sync",executionPoint:"before:model",artifacts:[i.workspaceContract,i.workspaceRegistry],failurePolicy:"stop-and-report",purpose:"Reconcile portable workspace inventory and contract inputs before modeling."},{id:"baseline",executionPoint:"after:model-before:diff",artifacts:[e$1.snapshot],failurePolicy:"stop-and-report",purpose:"Create an initial structural baseline when absent or reuse the existing baseline before Diff."}],report:{artifact:e$1.intelligenceRun,schemaVersion:f$1.intelligenceRun,invariant:"The report must preserve exact preflight and stage order, registry-owned artifacts, failure propagation, and aggregate status/exit semantics."}},boundaries:{inputs:[{id:"projects-repositories",label:"Projects and repositories",sources:["projects","repositories","services","modules","imported paths"],entersAt:"model"},{id:"runtime-dependencies",label:"Runtime and dependencies",sources:["runtime manifests","lockfiles","scripts","framework markers","package dependencies","bounded multi-language source observations for supported file extensions"],entersAt:"model"},{id:"workspace-rules",label:"Workspace rules",sources:["workspace markers","registry","project metadata","contracts","policies","ownership","graph overrides"],entersAt:"model"},{id:"changes",label:"Changes",sources:["repository state","git state","model baseline","workspace diff"],entersAt:"diff"},{id:"model-baseline",label:"Explicit model baseline",sources:[e$1.snapshot],entersAt:"diff"},{id:"existing-evidence",label:"Existing evidence",sources:["doctor reports","analysis reports","contract verification","release readiness","pipeline results","tests and runtime evidence","previous intelligence artifacts"],entersAt:"doctor-evidence"}],outputs:[{id:"understanding",label:"System understanding",artifacts:[e$1.model,e$1.knowledgeGraph,e$1.diff,e$1.impact],producedBy:["model","diff","impact"],inventory:"complete-for-chain"},{id:"governance-evidence",label:"Governance evidence",artifacts:[e$1.doctor,e$1.contractVerify,e$1.analyze,e$1.readiness,e$1.verify,e$1.history],producedBy:["doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence","verify"],inventory:"complete-for-chain"},{id:"agent-grounding",label:"Agent grounding",artifacts:[e$1.agentContext,e$1.agentIndex,e$1.agentCustomizationPack,e$1.skillsIndex,e$1.agents],producedBy:["context","agent-sync"],inventory:"canonical-minimum",inventoryContract:"contracts/agent-customization-pack.v1.json"},{id:"explanations",label:"Explainable decisions",artifacts:[e$1.explain],producedBy:["explain"],inventory:"complete-for-chain"}],consumers:[{id:"developers",label:"Developers",channels:["CLI","reports","AGENTS.md"]},{id:"ci",label:"CI",channels:["JSON artifacts","exit codes","release gates"]},{id:"ides",label:"IDEs",channels:["synced contracts","extension","agent context"]},{id:"ai-agents",label:"AI agents",channels:["INDEX.json","context","skills","MCP"]}]},deliveryChannels:[{id:"artifacts",carries:["reports","models","context","grounding","skills"],authority:"canonical"},{id:"json-stdout",carries:["structured command results"],authority:"projection"},{id:"human-cli",carries:["summaries","diagnostics","next actions"],authority:"projection"},{id:"exit-codes",carries:["gate and command status"],authority:"projection"},{id:"watch-events",carries:["incremental workspace change events"],authority:"projection"},{id:"mcp",carries:["read-mostly access to current workspace artifacts"],authority:"projection"}],feedback:{from:["developers","ci","ides","ai-agents"],signals:["source commits","dependency updates","policy and contract edits","repairs","test and runtime results","agent action outcomes"],reentersThrough:["projects-repositories","runtime-dependencies","workspace-rules","changes","existing-evidence"],rule:"Consumer actions are not silently treated as truth. They re-enter as observable changes or evidence and must be modeled and verified again."},auxiliaryCapabilities:[{id:"graph",commands:["workspace graph emit","workspace graph explain","workspace graph entities","workspace graph evidence","workspace graph path","workspace graph search","workspace graph benchmark","workspace graph overlay","workspace graph dot","workspace graph mermaid","workspace graph jsonld","workspace graph graphml","workspace graph gexf"],reads:[e$1.model,e$1.knowledgeGraph],role:"Query the proof-backed graph derived from the canonical workspace model.",chainStep:false},{id:"evaluation",commands:["workspace eval init","workspace eval record","workspace eval status","workspace eval report","workspace eval compare"],reads:[e$1.evaluationLive,e$1.evaluationLastRun],produces:[e$1.evaluationLive,e$1.evaluationLastRun],role:"Measure model usage, activity, cost provenance, and verified outcomes without storing prompt or response bodies.",chainStep:false},{id:"watch",commands:["workspace watch"],reads:["workspace inputs",e$1.model],role:"Refresh the model incrementally and emit deterministic change events.",chainStep:false},{id:"mcp",commands:["workspace mcp serve"],reads:["workspace evidence artifacts"],role:"Expose read-mostly workspace evidence to compatible clients.",chainStep:false}],presentations:{simple:{layers:["inputs","intelligence","outputs","consumers"],nodes:[{id:"input-layer",kind:"inputs",label:"Input Layer",summary:"Projects \xB7 Repositories \xB7 Dependencies \xB7 Changes",contractRefs:["projects-repositories","runtime-dependencies","workspace-rules","changes","model-baseline","existing-evidence"]},{id:"workspace-intelligence",kind:"intelligence",label:"Workspace Intelligence",summary:"Model \xB7 Graph \xB7 Impact \xB7 Verify",contractRefs:n.map(r=>r.id)},{id:"agent-grounding",kind:"outputs",label:"Agent Grounding",summary:"AGENTS.md \xB7 Skills \xB7 Context",contractRefs:["agent-grounding"]},{id:"evidence-and-decisions",kind:"outputs",label:"Evidence Contracts",summary:"Reports \xB7 Artifacts \xB7 Gates",contractRefs:["understanding","governance-evidence","explanations"]},{id:"shared-consumers",kind:"consumers",label:"Shared Consumers",summary:"Developers \xB7 CI \xB7 IDEs \xB7 AI agents",contractRefs:["developers","ci","ides","ai-agents"]}],rule:"Use concrete user-facing language for first-contact explanations. Every input, output, consumer, and chain step must remain traceable through contractRefs even when details are summarized."},standard:{phases:["understand","change","evidence","gate","ground","distribute","explain"],nodes:[{id:"understand",label:"Understand",question:"What exists in the current workspace?",stepRefs:["model"]},{id:"change",label:"Change",question:"What changed, and what can it affect?",stepRefs:["diff","impact"]},{id:"evidence",label:"Evidence",question:"What health, contract, and readiness facts were observed?",stepRefs:["doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence"]},{id:"gate",label:"Gate",question:"Is the current state acceptable and trustworthy?",stepRefs:["verify"]},{id:"ground",label:"Ground",question:"What should an agent know before acting?",stepRefs:["context"]},{id:"distribute",label:"Distribute",question:"Which durable agent and IDE surfaces receive that context?",stepRefs:["agent-sync"]},{id:"explain",label:"Explain",question:"Why did the system reach this result or verdict?",stepRefs:["explain"]}],rule:"Use for architecture education and product surfaces. Every phase must appear once and in order."},advanced:{steps:n.map(r=>r.id),requiredFields:["command","inputRefs","consumesArtifacts","produces","dependsOn","exitPolicy","purpose"],rule:"Use for implementers, adapters, IDEs, and CI. Preserve every step and its artifact and verdict semantics."}},steps:n,diagram:{direction:"TB",nodes:n.map(({id:r,label:s,phase:p})=>({id:r,label:s,phase:p})),edges:n.flatMap(r=>r.dependsOn.map(s=>({from:s,to:r.id,meaning:"required before"})))},consumers:{agents:{canonicalReadOrder:[e$1.agentIndex,e$1.agentContext,e$1.verify,e$1.impact,e$1.explain,e$1.model,e$1.knowledgeGraph,e$1.agentCustomizationPack,e$1.skillsIndex],entrypoints:[e$1.agents,".workspai/AGENT-GROUNDING.md"],rule:"Agents must cite current artifacts, preserve verified versus inferred status, and re-run the producing step when evidence is missing or stale."},ideAndCi:{requiredArtifacts:[e$1.model,e$1.knowledgeGraph,e$1.impact,e$1.verify],rule:"IDEs and CI must consume structured artifacts and verdict exit semantics rather than parse human help or terminal prose."},docsAndDiagrams:{rule:"Documentation and diagrams must derive labels, ordering, and edges from this contract and must not invent implemented steps."}}}}export{l as a,f as b};
1
+ import {e,p,i,f as f$1,g}from'./chunk-NZ3WZYD5.js';var l="workspai-workspace-intelligence-chain-v1",u="contracts/workspace-intelligence-chain.v1.json";function f(){let e$1=e,t=p,n=[{id:"model",ordinal:1,phase:"understand",label:"Model",command:[...t.model.command],consumes:["workspace markers","project metadata","registry","contract","policies"],inputRefs:["projects-repositories","runtime-dependencies","workspace-rules","existing-evidence"],consumesArtifacts:[],produces:[...t.model.produces],dependsOn:[],exitPolicy:"stop-on-error",purpose:"Build the canonical current model and its structurally bound, derived Knowledge Graph."},{id:"diff",ordinal:2,phase:"change",label:"Diff",command:[...t.diff.command],consumes:[e$1.model,e$1.snapshot],inputRefs:["changes","model-baseline"],consumesArtifacts:[e$1.model,e$1.snapshot],produces:[...t.diff.produces],dependsOn:["model"],exitPolicy:"stop-on-error",purpose:"Describe structural change against the selected baseline."},{id:"impact",ordinal:3,phase:"change",label:"Impact",command:[...t.impact.command],consumes:[e$1.model,e$1.diff],inputRefs:[],consumesArtifacts:[e$1.model,e$1.diff],produces:[...t.impact.produces],dependsOn:["diff"],exitPolicy:"stop-on-error",purpose:"Calculate transitive blast radius over the workspace graph."},{id:"doctor-evidence",ordinal:4,phase:"evidence",label:"Doctor Evidence",command:[...t["doctor-evidence"].command],consumes:["workspace runtime and project health signals"],inputRefs:["projects-repositories","runtime-dependencies","existing-evidence"],consumesArtifacts:[],produces:[...t["doctor-evidence"].produces],dependsOn:["impact"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh health evidence after the impact artifact exists."},{id:"contract-evidence",ordinal:5,phase:"evidence",label:"Contract Evidence",command:[...t["contract-evidence"].command],consumes:[i.workspaceContract],inputRefs:["workspace-rules"],consumesArtifacts:[],produces:[...t["contract-evidence"].produces],dependsOn:["impact"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh structural contract evidence without hiding failed verdicts."},{id:"analyze-evidence",ordinal:6,phase:"evidence",label:"Analyze Evidence",command:[...t["analyze-evidence"].command],consumes:[e$1.model,"workspace runtime and dependency signals"],inputRefs:["projects-repositories","runtime-dependencies","workspace-rules"],consumesArtifacts:[e$1.model],produces:[...t["analyze-evidence"].produces],dependsOn:["impact"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh analysis evidence required by the release-readiness gate."},{id:"readiness-evidence",ordinal:7,phase:"evidence",label:"Readiness Evidence",command:[...t["readiness-evidence"].command],consumes:["doctor, analysis, runtime, and release signals"],inputRefs:["runtime-dependencies","existing-evidence"],consumesArtifacts:[e$1.doctor,e$1.contractVerify,e$1.analyze],produces:[...t["readiness-evidence"].produces],dependsOn:["doctor-evidence","contract-evidence","analyze-evidence"],exitPolicy:"continue-on-structured-verdict",purpose:"Refresh release-readiness evidence before the definitive gate."},{id:"verify",ordinal:8,phase:"gate",label:"Verify",command:[...t.verify.command],consumes:[e$1.impact,e$1.doctor,e$1.contractVerify,e$1.readiness],inputRefs:[],consumesArtifacts:[e$1.impact,e$1.doctor,e$1.contractVerify,e$1.readiness],produces:[...t.verify.produces],dependsOn:["impact","doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence"],exitPolicy:"continue-on-structured-verdict",purpose:"Emit the definitive evidence-backed workspace gate."},{id:"context",ordinal:9,phase:"ground",label:"Agent Context",command:[...t.context.command],consumes:[e$1.model,e$1.impact,e$1.verify],inputRefs:[],consumesArtifacts:[e$1.model,e$1.impact,e$1.verify],produces:[...t.context.produces],dependsOn:["verify"],exitPolicy:"stop-on-error",purpose:"Build compact agent context from the same verified evidence."},{id:"agent-sync",ordinal:10,phase:"distribute",label:"Agent Grounding",command:[...t["agent-sync"].command],consumerArgs:{vscode:["--target","vscode"]},consumes:[e$1.agentContext],inputRefs:[],consumesArtifacts:[e$1.agentContext],produces:[...t["agent-sync"].produces],dependsOn:["context"],exitPolicy:"stop-on-error",purpose:"Distribute one context into portable agent and IDE surfaces."},{id:"explain",ordinal:11,phase:"explain",label:"Explain",command:[...t.explain.command],consumes:[e$1.verify,e$1.impact],inputRefs:[],consumesArtifacts:[e$1.verify,e$1.impact],produces:[...t.explain.produces],dependsOn:["verify"],exitPolicy:"continue-on-structured-verdict",purpose:"Translate evidence and blockers into a human and agent-readable narrative."}];return {schemaVersion:l,name:"Workspace Intelligence Chain",contractPath:u,invariant:"Every consumer must preserve step identity, dependencies, artifact flow, and verdict semantics; presentation may change, chain meaning may not.",invariants:["Missing or unreadable input is unknown or unavailable; it must not be presented as verified absence.","Freshness and provenance travel with evidence and must not be discarded by projections.","The current graph is an evidence-backed workspace knowledge graph with bounded source intelligence, not a complete cross-language symbol or call graph.","Simple and standard presentations summarize the contract; their contractRefs must preserve complete traceability.","Conditional provider outputs must be resolved through their dedicated inventory contract.","Auxiliary capabilities expose or refresh intelligence but are not mandatory execution-chain steps.","Canonical step commands are stage-pure: they must not implicitly execute a downstream chain step or regenerate an upstream artifact.","Canonical JSON artifacts must satisfy their registered schema both when produced and when consumed across CLI, MCP, IDE, and CI trust boundaries.","Schema validity is necessary but not sufficient: hashes, embedded models, summaries, counts, graph statistics, and artifact references must remain semantically coherent.","Persisted impact evidence must be rejected as stale when the current workspace model or Git observation no longer matches its embedded diff.","Canonical artifact replacement must be atomic and workspace-contained; an interrupted or denied write must preserve the last valid artifact.","Concurrent history updates must be serialized without silently dropping entries, and invalid history must never be overwritten as if it were absent.","The canonical global registry is ~/.workspai/workspaces.json; ~/.rapidkit/workspaces.json is a non-authoritative compatibility mirror for legacy consumers and must not diverge after a CLI registry mutation."],semantics:{workspace:"The governed operating boundary that relates one or more projects and repositories to shared metadata, policies, contracts, evidence, and consumers.",repository:"A source-control boundary that may contain one or more projects and may live inside or outside the workspace root.",project:"A discoverable build or runtime unit with its own path, metadata or observable manifests, command capabilities, and evidence.",evidence:"A sourced observation or generated verification result with provenance and freshness; evidence may be consumed by a later run.",artifact:"A durable generated file that another command or consumer can read without parsing terminal prose.",gate:"A structured verdict with reasons and exit semantics derived from current evidence."},workspaceLifecycle:{ingestionRoutes:[{id:"create",label:"Create",commands:["create workspace","create project"],result:"Create a workspace or supported project and write canonical Workspai metadata."},{id:"adopt",label:"Adopt",commands:["adopt"],result:"Register an existing project in place without requiring source relocation."},{id:"import",label:"Import",commands:["import","workspace import"],result:"Attach an existing project or repository path to the workspace inventory."}],durableState:[{id:"workspace-identity",paths:[".workspai-workspace",".workspai/workspace.json"],purpose:"Identify the workspace boundary, profile, and canonical root."},{id:"project-inventory",paths:[".workspai/project.json",".workspai/context.json",".workspai/adopt.json","~/.workspai/workspaces.json","~/.rapidkit/workspaces.json (legacy compatibility mirror)"],purpose:"Record native, adopted, imported, and globally registered project locations while preserving a non-authoritative mirror for legacy extension discovery."},{id:"governance",paths:[".workspai/policies.yml",i.workspaceContract],purpose:"Define workspace policy and explicit structural relationships."},{id:"graph-overrides",paths:[".workspai/workspace-graph.overrides.json"],purpose:"Provide explicit dependency edges that override inferred relationships."}],rule:"Create, adopt, and import are ingestion routes, not intelligence facts. Their durable state becomes observable input to Model."},runtimeRegistry:{authority:"contracts/workspace-intelligence-runtime-registry.ts",artifacts:Object.entries(e).map(([r,s])=>({id:r,path:s,schemaVersion:f$1[r],schemaContract:g[r]}))},executionEnvelope:{rule:"Sync and baseline resolution are deterministic execution prerequisites, not canonical intelligence stages; every run reports them separately and preserves the exact canonical stage sequence.",operations:[{id:"sync",executionPoint:"before:model",artifacts:[i.workspaceContract,i.workspaceRegistry],failurePolicy:"stop-and-report",purpose:"Reconcile portable workspace inventory and contract inputs before modeling."},{id:"baseline",executionPoint:"after:model-before:diff",artifacts:[e$1.snapshot],failurePolicy:"stop-and-report",purpose:"Create an initial structural baseline when absent or reuse the existing baseline before Diff."}],report:{artifact:e$1.intelligenceRun,schemaVersion:f$1.intelligenceRun,invariant:"The report must preserve exact preflight and stage order, registry-owned artifacts, failure propagation, and aggregate status/exit semantics."}},boundaries:{inputs:[{id:"projects-repositories",label:"Projects and repositories",sources:["projects","repositories","services","modules","imported paths"],entersAt:"model"},{id:"runtime-dependencies",label:"Runtime and dependencies",sources:["runtime manifests","lockfiles","scripts","framework markers","package dependencies","bounded multi-language source observations for supported file extensions"],entersAt:"model"},{id:"workspace-rules",label:"Workspace rules",sources:["workspace markers","registry","project metadata","contracts","policies","ownership","graph overrides"],entersAt:"model"},{id:"changes",label:"Changes",sources:["repository state","git state","model baseline","workspace diff"],entersAt:"diff"},{id:"model-baseline",label:"Explicit model baseline",sources:[e$1.snapshot],entersAt:"diff"},{id:"existing-evidence",label:"Existing evidence",sources:["doctor reports","analysis reports","contract verification","release readiness","pipeline results","tests and runtime evidence","previous intelligence artifacts"],entersAt:"doctor-evidence"}],outputs:[{id:"understanding",label:"System understanding",artifacts:[e$1.model,e$1.knowledgeGraph,e$1.diff,e$1.impact],producedBy:["model","diff","impact"],inventory:"complete-for-chain"},{id:"governance-evidence",label:"Governance evidence",artifacts:[e$1.doctor,e$1.contractVerify,e$1.analyze,e$1.readiness,e$1.verify,e$1.history],producedBy:["doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence","verify"],inventory:"complete-for-chain"},{id:"agent-grounding",label:"Agent grounding",artifacts:[e$1.agentContext,e$1.agentIndex,e$1.agentCustomizationPack,e$1.skillsIndex,e$1.agents],producedBy:["context","agent-sync"],inventory:"canonical-minimum",inventoryContract:"contracts/agent-customization-pack.v1.json"},{id:"explanations",label:"Explainable decisions",artifacts:[e$1.explain],producedBy:["explain"],inventory:"complete-for-chain"}],consumers:[{id:"developers",label:"Developers",channels:["CLI","reports","AGENTS.md"]},{id:"ci",label:"CI",channels:["JSON artifacts","exit codes","release gates"]},{id:"ides",label:"IDEs",channels:["synced contracts","extension","agent context"]},{id:"ai-agents",label:"AI agents",channels:["INDEX.json","context","skills","MCP"]}]},deliveryChannels:[{id:"artifacts",carries:["reports","models","context","grounding","skills"],authority:"canonical"},{id:"json-stdout",carries:["structured command results"],authority:"projection"},{id:"human-cli",carries:["summaries","diagnostics","next actions"],authority:"projection"},{id:"exit-codes",carries:["gate and command status"],authority:"projection"},{id:"watch-events",carries:["incremental workspace change events"],authority:"projection"},{id:"mcp",carries:["read-mostly access to current workspace artifacts"],authority:"projection"}],feedback:{from:["developers","ci","ides","ai-agents"],signals:["source commits","dependency updates","policy and contract edits","repairs","test and runtime results","agent action outcomes"],reentersThrough:["projects-repositories","runtime-dependencies","workspace-rules","changes","existing-evidence"],rule:"Consumer actions are not silently treated as truth. They re-enter as observable changes or evidence and must be modeled and verified again."},auxiliaryCapabilities:[{id:"graph",commands:["workspace graph emit","workspace graph explain","workspace graph entities","workspace graph evidence","workspace graph path","workspace graph search","workspace graph benchmark","workspace graph overlay","workspace graph dot","workspace graph mermaid","workspace graph jsonld","workspace graph graphml","workspace graph gexf"],reads:[e$1.model,e$1.knowledgeGraph],role:"Query the proof-backed graph derived from the canonical workspace model.",chainStep:false},{id:"evaluation",commands:["workspace eval init","workspace eval record","workspace eval status","workspace eval report","workspace eval compare"],reads:[e$1.evaluationLive,e$1.evaluationLastRun],produces:[e$1.evaluationLive,e$1.evaluationLastRun],role:"Measure model usage, activity, cost provenance, and verified outcomes without storing prompt or response bodies.",chainStep:false},{id:"watch",commands:["workspace watch"],reads:["workspace inputs",e$1.model],role:"Refresh the model incrementally and emit deterministic change events.",chainStep:false},{id:"mcp",commands:["workspace mcp serve"],reads:["workspace evidence artifacts"],role:"Expose read-mostly workspace evidence to compatible clients.",chainStep:false}],presentations:{simple:{layers:["inputs","intelligence","outputs","consumers"],nodes:[{id:"input-layer",kind:"inputs",label:"Input Layer",summary:"Projects \xB7 Repositories \xB7 Dependencies \xB7 Changes",contractRefs:["projects-repositories","runtime-dependencies","workspace-rules","changes","model-baseline","existing-evidence"]},{id:"workspace-intelligence",kind:"intelligence",label:"Workspace Intelligence",summary:"Model \xB7 Graph \xB7 Impact \xB7 Verify",contractRefs:n.map(r=>r.id)},{id:"agent-grounding",kind:"outputs",label:"Agent Grounding",summary:"AGENTS.md \xB7 Skills \xB7 Context",contractRefs:["agent-grounding"]},{id:"evidence-and-decisions",kind:"outputs",label:"Evidence Contracts",summary:"Reports \xB7 Artifacts \xB7 Gates",contractRefs:["understanding","governance-evidence","explanations"]},{id:"shared-consumers",kind:"consumers",label:"Shared Consumers",summary:"Developers \xB7 CI \xB7 IDEs \xB7 AI agents",contractRefs:["developers","ci","ides","ai-agents"]}],rule:"Use concrete user-facing language for first-contact explanations. Every input, output, consumer, and chain step must remain traceable through contractRefs even when details are summarized."},standard:{phases:["understand","change","evidence","gate","ground","distribute","explain"],nodes:[{id:"understand",label:"Understand",question:"What exists in the current workspace?",stepRefs:["model"]},{id:"change",label:"Change",question:"What changed, and what can it affect?",stepRefs:["diff","impact"]},{id:"evidence",label:"Evidence",question:"What health, contract, and readiness facts were observed?",stepRefs:["doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence"]},{id:"gate",label:"Gate",question:"Is the current state acceptable and trustworthy?",stepRefs:["verify"]},{id:"ground",label:"Ground",question:"What should an agent know before acting?",stepRefs:["context"]},{id:"distribute",label:"Distribute",question:"Which durable agent and IDE surfaces receive that context?",stepRefs:["agent-sync"]},{id:"explain",label:"Explain",question:"Why did the system reach this result or verdict?",stepRefs:["explain"]}],rule:"Use for architecture education and product surfaces. Every phase must appear once and in order."},advanced:{steps:n.map(r=>r.id),requiredFields:["command","inputRefs","consumesArtifacts","produces","dependsOn","exitPolicy","purpose"],rule:"Use for implementers, adapters, IDEs, and CI. Preserve every step and its artifact and verdict semantics."}},steps:n,diagram:{direction:"TB",nodes:n.map(({id:r,label:s,phase:p})=>({id:r,label:s,phase:p})),edges:n.flatMap(r=>r.dependsOn.map(s=>({from:s,to:r.id,meaning:"required before"})))},consumers:{agents:{canonicalReadOrder:[e$1.agentIndex,e$1.agentContext,e$1.verify,e$1.impact,e$1.explain,e$1.model,e$1.knowledgeGraph,e$1.agentCustomizationPack,e$1.skillsIndex],entrypoints:[e$1.agents,".workspai/AGENT-GROUNDING.md"],rule:"Agents must cite current artifacts, preserve verified versus inferred status, and re-run the producing step when evidence is missing or stale."},ideAndCi:{requiredArtifacts:[e$1.model,e$1.knowledgeGraph,e$1.impact,e$1.verify],rule:"IDEs and CI must consume structured artifacts and verdict exit semantics rather than parse human help or terminal prose."},docsAndDiagrams:{rule:"Documentation and diagrams must derive labels, ordering, and edges from this contract and must not invent implemented steps."}}}}export{l as a,f as b};
@@ -1 +1 @@
1
- import {a as a$6}from'./chunk-HTYMXMQM.js';import {i,o}from'./chunk-WJVB6SSD.js';import {a as a$2}from'./chunk-27UR373Z.js';import {a}from'./chunk-Y5YAP4F3.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {m,a as a$3,d as d$2,c as c$2,b as b$2}from'./chunk-EEMRRCGR.js';import {a as a$1}from'./chunk-T5YRFRJV.js';import {c,b as b$1,i as i$2,w,f as f$3}from'./chunk-WP3CXMVA.js';import {j as j$1,i as i$3,h}from'./chunk-ZCPT6KC3.js';import {a as a$4}from'./chunk-GR6442P7.js';import {f as f$2,d as d$1,a as a$5,e as e$1}from'./chunk-GRGUPSNP.js';import {f,e,i as i$1,h as h$1}from'./chunk-HH54C3XJ.js';import {t,s}from'./chunk-MOSXTVPU.js';import f$1 from'path';import W from'fs-extra';import Dt from'crypto';import {createRequire}from'module';var At=new Set(["backend","desktop","extension","service","frontend","worker","library","infra","docs","test-suite","unknown"]);async function rt(e){try{if(!await W.pathExists(e))return null;let t=await W.readJSON(e);return t&&typeof t=="object"?t:null}catch{return null}}async function Rt(e){for(let t of e){let r=await rt(t);if(r)return r}return null}function tt(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return At.has(t)?t==="service"?"backend":t:null}function nt(e){switch(e){case "backend":case "service":case "worker":return "backend";case "frontend":case "desktop":case "extension":case "library":return e;case "infra":return "infrastructure";case "docs":return "documentation";case "test-suite":return "quality";default:return "unknown"}}async function ot(e,t$1){let r=t$1??await Rt(t(e,"project.json")),o=tt(r?.kind)??tt(r?.type);if(o)return o;let s=typeof r?.kit_name=="string"?r.kit_name:r?.kit,n=typeof r?.framework=="string"?r.framework:null,i=typeof r?.runtime=="string"?r.runtime:null,a=`${typeof s=="string"?s:""} ${n??""} ${i??""}`.trim().toLowerCase();if(/\b(tauri|electron|wails|desktop)\b/.test(a))return "desktop";if(/\b(vscode-extension|visual studio code extension|jetbrains-plugin|browser-extension)\b/.test(a))return "extension";if(/\b(frontend|nextjs|next\.js|react|vue|svelte|vite|angular|astro|remix|nuxt)\b/.test(a))return "frontend";if(/\b(fastapi|nestjs|springboot|spring boot|gofiber|gogin|dotnet|webapi|django|flask|express|fastify|python|node|java|go|rust|php|ruby|elixir)\b/.test(a))return "backend";let c=await rt(f$1.join(e,"package.json"));if(c){let d={...c.dependencies??{},...c.devDependencies??{}},u=c.scripts??{},p=Object.values(u).filter(v=>typeof v=="string").join(" ").toLowerCase(),l=c.engines??{},m=Array.isArray(c.categories)?c.categories.filter(v=>typeof v=="string"):[];if(d["@tauri-apps/api"]||d["@tauri-apps/cli"]||await W.pathExists(f$1.join(e,"src-tauri","tauri.conf.json"))||await W.pathExists(f$1.join(e,"src-tauri","tauri.conf.json5"))||d.electron||d["@electron-forge/cli"]||p.includes("electron-forge")||p.includes("electron "))return "desktop";if(typeof l.vscode=="string"||m.some(v=>v.toLowerCase()==="extension packs")||c.publisher&&(c.activationEvents||c.contributes))return "extension";if(d.next||d.react||d.vue||d.svelte||d.vite||d["@angular/core"]||p.includes("next ")||p.includes("vite "))return "frontend";if(c.private===true&&!d.express&&!d["@nestjs/core"])return "library"}return await W.pathExists(f$1.join(e,"Dockerfile"))||await W.pathExists(f$1.join(e,"docker-compose.yml"))||await W.pathExists(f$1.join(e,"terraform.tf"))?"infra":"backend"}var Mt=new Set(c().map(e=>e.id)),It=[...i().map(e=>({id:e.kitId,aliases:[...e.aliases],ecosystem:e.framework,status:"available",canExecuteCreate:true,versionPolicy:e.versionPolicy,officialCommands:[e.commandDisplay("<name>",{skipGit:false,skipInstall:false})],adoptAfterCreate:true,...e.minNodeVersion?{runtimeRequirements:{node:`>=${e.minNodeVersion}`}}:e.minNodeMajor?{runtimeRequirements:{node:`>=${e.minNodeMajor}`}}:{}})),...o().map(e=>({id:e.kitId,aliases:[...e.aliases],ecosystem:e.framework,status:"available",canExecuteCreate:true,versionPolicy:e.versionPolicy,officialCommands:[e.commandDisplay("<name>",{skipGit:false,skipInstall:false})],adoptAfterCreate:true,...e.nodeSupport?{runtimeRequirements:{node:e.nodeSupport.requirement}}:{}})),{id:"wordpress-site",aliases:["wordpress","wordpress-site","wp","wp-site"],ecosystem:"wordpress",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["wp core download","wp config create","wp db create","wp core install"],adoptAfterCreate:true},{id:"wordpress-block",aliases:["wordpress-block","wp-block","gutenberg-block"],ecosystem:"wordpress",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["npx @wordpress/create-block@latest <slug>"],adoptAfterCreate:true},{id:"symfony",aliases:["symfony","php-symfony"],ecosystem:"php",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["composer create-project symfony/skeleton <name>"],adoptAfterCreate:true},{id:"rails",aliases:["rails","ruby-on-rails","ruby-rails"],ecosystem:"ruby",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["rails new <name>"],adoptAfterCreate:true}],z=new Map;for(let e of It){z.set(e.id,e);for(let t of e.aliases)z.set(t,e);}var Ft=new Set(["php","ruby","rust","elixir","clojure","scala","kotlin","unknown"]);function $(e){return e?.trim().toLowerCase()||void 0}function st(e){let t=$(e.kitId)??$(e.framework)??$(e.runtime)??"unknown";if(e.projectExists)return {lane:"existing",status:"available",canExecuteCreate:false,requested:t,reason:"Existing projects enter Workspace Intelligence through adopt/import."};let r=e.kitId?b$1(e.kitId):void 0;if(r&&Mt.has(r))return {lane:"native",status:"available",canExecuteCreate:true,requested:t,resolved:r,reason:"Workspai owns the create contract, project marker, registry, doctor, and workspace model path."};let o=z.get(t)??z.get($(e.framework)??"")??z.get($(e.runtime)??"");if(o)return {lane:"official",status:o.status,canExecuteCreate:o.canExecuteCreate,requested:t,resolved:o.id,officialCommands:o.officialCommands,fallbackLane:o.canExecuteCreate?void 0:"existing",reason:o.status==="available"?"Workspai runs the official ecosystem generator, then registers the project in Workspace Intelligence.":"Official generator support is planned but not enabled; use adopt/import until Workspai owns the post-create contract."};let s=$(e.runtime);return s&&Ft.has(s)?{lane:"existing",status:"available",canExecuteCreate:false,requested:t,resolved:s,reason:"Runtime can be governed through Workspace Intelligence, but native create is not supported."}:{lane:"existing",status:"available",canExecuteCreate:false,requested:t,reason:"No native create contract is available; use adopt/import to enter Workspace Intelligence."}}function Gr(e){return !e.canExecuteCreate&&(e.lane==="official"||e.lane==="existing"&&e.resolved!==void 0)}var $r="rapidkit-freshness-metadata-v1";function ke(e){if(Array.isArray(e))return e.map(t=>ke(t));if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=ke(e[r]);return t}return e}function Ot(e){return JSON.stringify(ke(e))}function V(e){return Dt.createHash("sha256").update(Ot(e)).digest("hex")}var at=".workspai/workspace-graph.overrides.json",Gt=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),_t=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","node_modules","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),ct=600,dt=5,Tt=256*1024,it={inferred:1,contract:2,manual:3};function Nt(e){return e.split(f$1.sep).join("/")}function ne(e,t){return Nt(f$1.relative(e,t)||".")}function pt(e){let t=new Map;for(let r of e.projects)t.has(r.name)||t.set(r.name,{id:r.name,path:r.path,...r.runtime?{runtime:r.runtime}:{},...r.framework?{framework:r.framework}:{},...r.kind?{kind:r.kind}:{}});return [...t.values()].sort((r,o)=>r.id.localeCompare(o.id))}function lt(e,t){let r=new Map,o=new Map;for(let n of t.projects){if(r.has(n.name))continue;let i=n.absolutePath?f$1.resolve(n.absolutePath):f$1.resolve(e,n.path);r.set(n.name,i),o.has(i)||o.set(i,n.name);}let s=[...o.entries()].map(([n,i])=>({dir:n,id:i})).sort((n,i)=>i.dir.length-n.dir.length||n.dir.localeCompare(i.dir));return {idToDir:r,dirToId:o,sortedDirs:s}}function oe(e,t){let r=f$1.resolve(t);for(let{dir:o,id:s}of e.sortedDirs)if(r===o||r.startsWith(`${o}${f$1.sep}`))return s;return null}async function ve(e){try{if(!await W.pathExists(e))return null;let t=await W.readJSON(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async function je(e){try{return await W.pathExists(e)?await W.readFile(e,"utf8"):null}catch{return null}}async function ut(e,t){let r=[],o=new Map;for(let[s,n]of t.idToDir.entries()){let i=await ve(f$1.join(n,"package.json")),a=typeof i?.name=="string"?i.name.trim():"";a&&!o.has(a)&&o.set(a,s);}for(let[s,n]of t.idToDir.entries()){let i=await ve(f$1.join(n,"package.json"));if(i){let a=["dependencies","devDependencies","peerDependencies","optionalDependencies"],c=new Set;for(let d of a){let u=i[d];if(!(!u||typeof u!="object"||Array.isArray(u)))for(let p of Object.keys(u)){let l=o.get(p);!l||l===s||c.has(l)||(c.add(l),r.push({from:s,to:l,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ne(e,f$1.join(n,"package.json")),detail:`declares dependency ${p}`}]}));}}}r.push(...await $t(e,t,s,n)),r.push(...await Vt(e,t,s,n));}return r}async function $t(e,t,r,o){let s=await je(f$1.join(o,"pyproject.toml"));if(!s)return [];let n=[],i=new Set,a=/path\s*=\s*["']([^"']+)["']/g,c;for(;(c=a.exec(s))!==null;){let d=oe(t,f$1.resolve(o,c[1]));!d||d===r||i.has(d)||(i.add(d),n.push({from:r,to:d,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ne(e,f$1.join(o,"pyproject.toml")),detail:`path dependency ${c[1]}`}]}));}return n}async function Vt(e,t,r,o){let s=await je(f$1.join(o,"go.mod"));if(!s)return [];let n=[],i=new Set,a=/replace\s+\S+\s+=>\s+(\.[^\s]+)/g,c;for(;(c=a.exec(s))!==null;){let d=oe(t,f$1.resolve(o,c[1]));!d||d===r||i.has(d)||(i.add(d),n.push({from:r,to:d,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ne(e,f$1.join(o,"go.mod")),detail:`go.mod replace ${c[1]}`}]}));}return n}async function Kt(e,t){let r=[],o=[e];for(;o.length>0&&r.length<t;){let s=o.shift();if(!s)continue;let n=[];try{n=await W.readdir(s,{withFileTypes:true});}catch{continue}let i=[],a=[];for(let c of n)if(c.isDirectory()){if(_t.has(c.name)||a$4(c.name)||c.name.startsWith("."))continue;i.push(f$1.join(s,c.name));}else c.isFile()&&Gt.has(f$1.extname(c.name))&&a.push(f$1.join(s,c.name));a.sort((c,d)=>c.localeCompare(d)),i.sort((c,d)=>c.localeCompare(d));for(let c of a){if(r.length>=t)break;r.push(c);}o.push(...i);}return r}var Ht=[/\bfrom\s+["']([^"']+)["']/g,/\bimport\s+["']([^"']+)["']/g,/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g,/\brequire\s*\(\s*["']([^"']+)["']\s*\)/g];function Bt(e){let t=new Set;for(let r of Ht){r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){let s=o[1];s.startsWith(".")&&t.add(s);}}return [...t]}async function be(e,t,r,o){let s=new Map;for(let[n,i]of t.idToDir.entries()){if(o&&!o.has(n))continue;let a=await Kt(i,r);for(let c of a){let d=await W.stat(c).catch(()=>null);if(!d||d.size>Tt)continue;let u=await je(c);if(u)for(let p of Bt(u)){let l=f$1.resolve(f$1.dirname(c),p),m=oe(t,l);if(!m||m===n)continue;let v=`${n}\0${m}`,h=s.get(v);h||(h={from:n,to:m,evidence:[]},s.set(v,h)),h.evidence.length<dt&&h.evidence.push({file:ne(e,c),detail:`imports ${p}`});}}}return [...s.values()].map(n=>({from:n.from,to:n.to,kind:"code-import",source:"inferred",confidence:"medium",evidence:n.evidence}))}function Lt(e,t,r){let o=new Map;for(let s of r.projects){let n=zt(e,t,s);n&&o.set(s.slug,n);}return o}function zt(e,t,r){let o=[r.relativePath,r.externalPath].filter(s=>typeof s=="string"&&s.length>0);for(let s of o){let n=f$1.resolve(e,s),i=t.dirToId.get(n)??oe(t,n);if(i)return i}return t.idToDir.has(r.slug)?r.slug:null}function ft(e,t,r){let o=[],s=Lt(e,t,r),n=d$2,i=new Map,a=new Map;for(let c of r.projects){let d=s.get(c.slug);if(!d)continue;let u=c.contracts??{publishes:[],consumes:[],dependsOn:[]};for(let p of u.dependsOn??[]){let l=s.get(p);!l||l===d||o.push({from:d,to:l,kind:"service-dependsOn",source:"contract",confidence:"high",evidence:[{file:n,detail:`dependsOn ${p}`}]});}for(let p of u.publishes??[])i.has(p)||i.set(p,new Set),i.get(p)?.add(d);for(let p of u.consumes??[])a.has(p)||a.set(p,new Set),a.get(p)?.add(d);}for(let[c,d]of i.entries()){let u=a.get(c);if(u)for(let p of u)for(let l of d)p!==l&&o.push({from:p,to:l,kind:"event-pub-sub",source:"contract",confidence:"high",evidence:[{file:n,detail:`consumes event ${c}`}]});}return o.push(...Ut(r,s)),o}function ye(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function Ut(e,t){let r=[],o=e.projects.map(s=>({project:s,id:t.get(s.slug)})).filter(s=>!!s.id).filter(s=>ye(s.project.slug).length>=3);for(let s of e.projects){let n=t.get(s.slug);if(!n)continue;let i=s.contracts?.env??[];if(i.length===0)continue;let a=new Set;for(let c of i){let d=ye(c);for(let u of o)u.id===n||a.has(u.id)||!(d.includes(ye(u.project.slug))&&(u.project.ports?.length??0)>0)||(a.add(u.id),r.push({from:n,to:u.id,kind:"shared-resource",source:"inferred",confidence:"low",evidence:[{file:d$2,detail:`env ${c} references ${u.project.slug}`}]}));}}return r}async function mt(e,t){let r=await ve(f$1.join(e,at)),o=Array.isArray(r?.edges)?r?.edges:[],s=[],n=new Set(c$2);for(let i of o){if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i,c=typeof a.from=="string"?a.from:"",d=typeof a.to=="string"?a.to:"",u=typeof a.kind=="string"?a.kind:"";if(!t.has(c)||!t.has(d)||c===d||!n.has(u))continue;let p=Array.isArray(a.evidence)?a.evidence.map(l=>l&&typeof l=="object"&&typeof l.file=="string"?{file:l.file,...typeof l.detail=="string"?{detail:l.detail}:{}}:null).filter(l=>!!l):[];s.push({from:c,to:d,kind:u,source:"manual",confidence:"high",evidence:p.length>0?p:[{file:at,detail:"manual edge"}]});}return s}function qt(e){return `${e.from}\0${e.to}\0${e.kind}`}function Jt(e){let t=new Set,r=[];for(let o of e){let s=`${o.file}\0${o.detail??""}`;t.has(s)||(t.add(s),r.push(o));}return r.sort((o,s)=>o.file.localeCompare(s.file)||(o.detail??"").localeCompare(s.detail??"")).slice(0,dt)}function Xt(e){let t=new Map;for(let r of e){let o=qt(r),s=t.get(o);if(!s){t.set(o,{...r,evidence:[...r.evidence]});continue}let n=it[s.source],i=it[r.source];i>n?t.set(o,{...r,evidence:[...r.evidence,...s.evidence]}):i===n&&s.evidence.push(...r.evidence);}return [...t.values()].map(r=>({from:r.from,to:r.to,kind:r.kind,source:r.source,confidence:r.confidence,evidence:Jt(r.evidence)})).sort((r,o)=>r.from.localeCompare(o.from)||r.to.localeCompare(o.to)||r.kind.localeCompare(o.kind)||r.source.localeCompare(o.source))}function we(e){return Math.round(e*1e3)/1e3}function Yt(e){return Math.max(0,Math.min(100,Math.round(e)))}function Qt(e){return e>=75?"critical":e>=50?"high":e>=20?"medium":"low"}function Zt(e){return e==="critical"||e==="high"?"strict":e==="medium"?"elevated":"normal"}function er(e,t){let r=a$6({nodes:e,edges:t}),o=new Map;for(let s of e){let n=r.byId.get(s.id)??{fanIn:0,fanOut:0,reach:0,betweenness:0,isHotspot:false},i=t.filter(m=>m.from===s.id||m.to===s.id),a=i.filter(m=>m.source==="contract"||m.source==="manual").length,c=i.filter(m=>m.confidence==="low").length,d=[],u=n.reach*20+n.fanIn*14+n.fanOut*8+Math.min(20,n.betweenness*4)+a*8;n.isHotspot&&(u+=24,d.push("Critical-path hotspot in dependency graph")),n.reach>0&&d.push(`Change reaches ${n.reach} dependent project(s)`),n.fanIn>0&&d.push(`${n.fanIn} direct dependent project(s)`),n.fanOut>0&&d.push(`${n.fanOut} direct dependency project(s)`),a>0&&d.push(`${a} contract/manual edge(s)`),c>0&&d.push(`${c} low-confidence inferred edge(s) need review`),i.length===0&&d.push("No dependency evidence connected to this project yet");let p=Yt(u),l=Qt(p);o.set(s.id,{weight:l,score:p,verificationPriority:Zt(l),reasons:d.slice(0,5),centrality:{fanIn:n.fanIn,fanOut:n.fanOut,reach:n.reach,betweenness:n.betweenness,isHotspot:n.isHotspot}});}return o}function tr(e,t){let r=er(e,t);return e.map(o=>({...o,operationalProfile:r.get(o.id)}))}function rr(e,t){let r=new Set;for(let c of t)r.add(c.from),r.add(c.to);let o=e.length,s=t.length,n=e.filter(c=>r.has(c.id)).length,i=Math.max(0,o-n),a=a$6({nodes:e,edges:t});return {nodeCount:o,edgeCount:s,inferredEdges:t.filter(c=>c.source==="inferred").length,contractEdges:t.filter(c=>c.source==="contract").length,manualEdges:t.filter(c=>c.source==="manual").length,authoritativeEdges:t.filter(c=>c.source==="contract"||c.source==="manual").length,lowConfidenceEdges:t.filter(c=>c.confidence==="low").length,orphanCount:i,connectedNodeCount:n,density:we(o>1?s/(o*(o-1)):0),edgeCoverageRatio:we(o>0?n/o:1),evidenceCoverageRatio:we(s>0?t.filter(c=>c.evidence.length>0).length/s:1),hotspotCount:a.hotspots.length,hasCycle:or(e,t)}}function nr(e,t,r){let o=[],s=e.filter(n=>!t.some(i=>i.from===n.id||i.to===n.id)).map(n=>n.id).sort((n,i)=>n.localeCompare(i));return r.nodeCount===0&&o.push({code:"graph.empty",severity:"info",message:"Workspace model has no projects, so dependency reasoning is unavailable.",recommendation:"Import, scaffold, or register projects before relying on graph-aware impact."}),r.nodeCount>1&&r.edgeCount===0?o.push({code:"graph.edges.missing",severity:"warning",message:"Projects were detected, but no inter-project dependency edges were found.",recommendation:"Run graph explain, add workspace contract relationships, or define manual graph overrides for operational dependencies that code imports cannot reveal.",nodeIds:s}):r.orphanCount>0&&o.push({code:"graph.orphans.detected",severity:"warning",message:`${r.orphanCount} project(s) have no dependency evidence connected to the graph.`,recommendation:"Review isolated projects and add package, contract, or manual edges when they participate in release-critical flows.",nodeIds:s.slice(0,12)}),r.lowConfidenceEdges>0&&o.push({code:"graph.low_confidence_edges",severity:"info",message:`${r.lowConfidenceEdges} inferred edge(s) are low confidence.`,recommendation:"Promote important low-confidence relationships to workspace contract or manual overrides."}),r.edgeCount>0&&r.evidenceCoverageRatio<1&&o.push({code:"graph.evidence.partial",severity:"warning",message:"Some dependency edges do not include file-level evidence.",recommendation:"Attach evidence to manual overrides so agents can audit why a relationship exists."}),r.hasCycle&&o.push({code:"graph.cycle.detected",severity:"error",message:"The dependency graph contains at least one directed cycle.",recommendation:"Break the cycle or document the relationship explicitly before using graph-aware release gates."}),o.sort((n,i)=>{let a={error:0,warning:1,info:2};return a[n.severity]-a[i.severity]||n.code.localeCompare(i.code)})}function or(e,t){let r=new Map;for(let c of e)r.set(c.id,[]);for(let c of t)r.has(c.from)||r.set(c.from,[]),r.get(c.from)?.push(c.to);let o=0,s=1,n=2,i=new Map;for(let c of r.keys())i.set(c,o);let a=c=>{let d=[{id:c,index:0}];for(i.set(c,s);d.length>0;){let u=d[d.length-1],p=r.get(u.id)??[];if(u.index>=p.length){i.set(u.id,n),d.pop();continue}let l=p[u.index];u.index+=1;let m=i.get(l)??o;if(m===s)return true;m===o&&(i.set(l,s),d.push({id:l,index:0}));}return false};for(let c of [...r.keys()].sort())if(i.get(c)===o&&a(c))return true;return false}function gt(e,t,r,o){let s=Xt(r.filter(c=>t.has(c.from)&&t.has(c.to))),n=tr(e,s),i=rr(e,s),a=nr(e,s,i);return {schemaVersion:b$2,generatedAt:(o??new Date).toISOString(),nodes:n,edges:s,stats:i,...a.length>0?{diagnostics:a}:{}}}async function ht(e){let t=f$1.resolve(e.workspacePath),r=e.maxImportFilesPerProject??ct,o=pt(e.model),s=new Set(o.map(a=>a.id)),n=lt(t,e.model),i=[];return i.push(...await ut(t,n)),i.push(...await be(t,n,r)),e.contract&&i.push(...ft(t,n,e.contract)),i.push(...await mt(t,s)),gt(o,s,i,e.now)}async function kt(e){let t=f$1.resolve(e.workspacePath),r=e.maxImportFilesPerProject??ct,o=pt(e.model),s=new Set(o.map(a=>a.id)),n=lt(t,e.model),i=[];if(i.push(...await ut(t,n)),e.structuralChange)i.push(...await be(t,n,r));else {i.push(...await be(t,n,r,e.changedProjectIds));for(let a of e.previousGraph.edges)a.kind==="code-import"&&a.source==="inferred"&&!e.changedProjectIds.has(a.from)&&s.has(a.from)&&s.has(a.to)&&i.push({from:a.from,to:a.to,kind:"code-import",source:"inferred",confidence:a.confidence,evidence:a.evidence});}return e.contract&&i.push(...ft(t,n,e.contract)),i.push(...await mt(t,s)),gt(o,s,i,e.now)}var Ce=h$1.workspaceModelCache.schemaVersion,Pe=i$1.workspaceModelCache,yt=["package.json","pyproject.toml","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","workspai.project.json",".workspai/project.json",".workspai/context.json","rapidkit.project.json",".rapidkit/project.json",".rapidkit/context.json"],wt=[i$1.workspaceContract,".workspai/workspace.json","workspai.workspace.json",".workspai/policies.yml",".workspai/policies.yaml",".rapidkit/workspace.contract.json",".rapidkit/workspace.json","rapidkit.workspace.json",".rapidkit/policies.yml",".rapidkit/policies.yaml"],ir=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),cr=new Set([".git",".workspai",".rapidkit","node_modules","dist","build","out","target","coverage",".next",".turbo",".cache",".venv"]),dr=1500,U=null;function Se(){if(U)return U;try{U=createRequire(import.meta.url)("../package.json")?.version??"0.0.0";}catch{U="0.0.0";}return U}async function se(e){try{let t=await W.readFile(e);return Dt.createHash("sha256").update(t).digest("hex")}catch{return null}}async function pr(e){let t={};for(let s of yt){let n=await se(f$1.join(e,s));n&&(t[s]=n);}let r=[],o=[e];for(;o.length>0&&r.length<dr;){let s=o.shift();if(!s)continue;let n=[];try{n=await W.readdir(s,{withFileTypes:true});}catch{continue}let i=[];for(let a of n)if(a.isDirectory()){if(cr.has(a.name)||a$4(a.name)||a.name.startsWith("."))continue;i.push(f$1.join(s,a.name));}else if(a.isFile()&&ir.has(f$1.extname(a.name))){let c=f$1.join(s,a.name),d=await W.stat(c).catch(()=>null);if(d){let u=f$1.relative(e,c).split(f$1.sep).join("/");r.push(`${u}:${d.size}:${Math.round(d.mtimeMs)}`);}}i.sort((a,c)=>a.localeCompare(c)),o.push(...i);}return r.sort((s,n)=>s.localeCompare(n)),V({manifests:t,source:r})}async function ae(e,t){let r=f$1.resolve(e),o={},s=[...new Set(t.map(n=>f$1.relative(r,f$1.resolve(n)).split(f$1.sep).join("/")))].sort((n,i)=>n.localeCompare(i));for(let n of s)o[n]=await pr(f$1.join(r,n));return o}async function ie(e){let t=f$1.resolve(e),r={};for(let o of wt){let s=await se(f$1.join(t,o));s&&(r[o]=s);}return r}async function ce(e){let t=f$1.resolve(e.workspacePath),r=[...new Set(e.projectPaths.map(n=>f$1.relative(t,f$1.resolve(n)).split(f$1.sep).join("/")))].sort((n,i)=>n.localeCompare(i)),o=[];for(let n of r){let i={};for(let a of yt){let c=await se(f$1.join(t,n,a));c&&(i[a]=c);}o.push({project:n,manifests:i});}let s={};for(let n of wt){let i=await se(f$1.join(t,n));i&&(s[n]=i);}return V({cacheSchema:Ce,cliVersion:e.cliVersion,flags:e.flags,workspaceJson:e.workspaceJson??null,marker:e.marker??null,projects:o,workspaceFiles:s})}async function Ee(e){let t=await d$1(e,Pe)??a$5(e,Pe);try{if(!await W.pathExists(t))return null;let r=await W.readJson(t);return !r||r.schemaVersion!==Ce||typeof r.inputsHash!="string"||typeof r.cliVersion!="string"||!r.model?null:r}catch{return null}}async function de(e,t){let r={schemaVersion:Ce,...t};return e$1(e,Pe,r)}var vt="rapidkit-fact-freshness-v1",J={durable:720*60*60,derived:10080*60,evidenceBacked:1440*60,live:300,verifyBeforeUse:1440*60};function lr(e){switch(e){case "durable":return J.durable;case "derived":return J.derived;case "evidence-backed":return J.evidenceBacked;case "live":return J.live;case "verify-before-use":return J.verifyBeforeUse}}function ur(e){if(e.status)return e.status;if(e.ttlSeconds===null)return "unknown";let t=Date.parse(e.generatedAt);if(!Number.isFinite(t))return "unknown";let r=t+e.ttlSeconds*1e3;return e.now.getTime()>r?"stale":"fresh"}function fr(e){let t=e.now??new Date,r=e.generatedAt??t.toISOString(),o=Date.parse(r),s=Number.isFinite(o),n=s?r:t.toISOString(),i=e.ttlSeconds===void 0?lr(e.kind):e.ttlSeconds,a=ur({generatedAt:n,ttlSeconds:i,status:e.status??(s?void 0:"unknown"),now:t}),c=Date.parse(n),d=i===null||!Number.isFinite(c)?void 0:new Date(c+i*1e3),u=e.verifyBeforeUse??(e.kind==="live"||e.kind==="verify-before-use"||e.category!=="structure"||a!=="fresh");return {schemaVersion:vt,kind:e.kind,category:e.category,generatedAt:n,ttlSeconds:i,...d?{expiresAt:d.toISOString()}:{},status:a,verifyBeforeUse:u,...e.sourceArtifact?{sourceArtifact:e.sourceArtifact}:{},...e.sourcePath?{sourcePath:e.sourcePath}:{},inputsHash:e.inputsHash??V(e.value??null),reason:e.reason}}function b(e){return {id:e.id,label:e.label,scope:e.scope,value:e.value,...e.project?{project:e.project}:{},freshness:fr({...e.freshness,value:e.value})}}function bt(e){let t=e.generatedAt??(e.now??new Date).toISOString(),r={durable:0,derived:0,"evidence-backed":0,live:0,"verify-before-use":0},o={structure:0,verification:0,state:0},s=0,n=0,i=0,a=0;for(let c of e.facts)r[c.freshness.kind]+=1,o[c.freshness.category]+=1,c.freshness.status==="stale"&&(s+=1),c.freshness.status==="unknown"&&(n+=1),c.freshness.kind==="live"&&(i+=1),c.freshness.verifyBeforeUse&&(a+=1);return {schemaVersion:vt,generatedAt:t,status:s>0?"stale":n>0?"unknown":"fresh",totalFacts:e.facts.length,staleFacts:s,unknownFacts:n,liveFacts:i,verifyBeforeUseFacts:a,byKind:r,byCategory:o}}var mr=f.model,pe=e.model;function We(e){return e.projectTopology??e.graph}function Pt(e){return !!(e.projectTopology&&e.graph&&c$1(e.projectTopology)===c$1(e.graph))}function Fn(e){let t=e.engineStatus==="hit"||e.engineStatus==="unchanged"?"reused":e.engineStatus==="incremental"?"partially-reused":"rebuilt";return {schemaVersion:"workspace-model-build.v1",mode:e.mode,outcome:t,engineStatus:e.engineStatus}}var gr=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","bun.lock","bun.lockb","deps.edn","project.clj","build.sbt","docker-compose.yml","docker-compose.yaml","terraform.tf"],hr=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next",".turbo"]);function Ct(e,t){return (f$1.relative(e,t)||".").split(f$1.sep).join("/")}async function St(e){try{if(!await W.pathExists(e))return null;let t=await W.readJSON(e);return t&&typeof t=="object"?t:null}catch{return null}}async function kr(e,t){for(let r of t)if(await W.pathExists(f$1.join(e,r)))return true;return false}function xe(e){let t=Number.parseInt(process.env.RAPIDKIT_WORKSPACE_MODEL_SCAN_DEPTH??"",10),r=typeof e=="number"&&Number.isFinite(e)?e:Number.isFinite(t)?t:4;return Math.min(12,Math.max(1,Math.trunc(r)))}async function Ae(e,t){let r=f$1.resolve(e),o=[{dirPath:r,depth:0}],s=new Set,n=new Set;for(;o.length>0;){let i=o.shift();if(!i)continue;let a=f$1.resolve(i.dirPath);if(n.has(a))continue;if(n.add(a),a!==r&&await kr(a,gr)){s.add(a);continue}if(i.depth>=t)continue;let c=[];try{c=await W.readdir(a,{withFileTypes:true});}catch{continue}for(let d of c)!d.isDirectory()||hr.has(d.name)||a$4(d.name)||d.name.startsWith(".")&&d.name!==".config"||o.push({dirPath:f$1.join(a,d.name),depth:i.depth+1});}return Array.from(s).sort((i,a)=>i.localeCompare(a))}function Re(e){let t=new Set,r=[];for(let o of e){let s=f$1.resolve(o);t.has(s)||(t.add(s),r.push(s));}return r.sort((o,s)=>o.localeCompare(s))}function jt(e,t){let r=e?.[t];return typeof r=="string"&&r.trim()?r.trim():void 0}function yr(e,t){return e?.[t]===true}function wr(e,t,r){let o=e?.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,s=jt(o,"generator"),n=jt(o,"command_display"),i=typeof t=="string"&&t.startsWith("frontend.");if(!(!s&&!i))return {...s?{id:s}:{},...t?{kit:t}:{},displayName:r,source:yr(o,"official_generator")?"official-generator":"metadata",...n?{commandDisplay:n}:{}}}async function vr(e){let t=[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json","package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","CMakeLists.txt","meson.build","Makefile","WORKSPACE","WORKSPACE.bazel","MODULE.bazel","BUILD","BUILD.bazel",".bazelrc","composer.json","Gemfile","mix.exs","deno.json","setup.py","setup.cfg","Dockerfile","docker-compose.yml","README.md"],r=[];for(let o of t)await W.pathExists(f$1.join(e,o))&&r.push(o);return r}async function E(e,t,r,o=t){let s=await d$1(e,t),n=s!==null,i={path:o.split(f$1.sep).join("/"),exists:n};if(s&&r){let a=await St(s);typeof a?.generatedAt=="string"&&(i.generatedAt=a.generatedAt);let c=a?.status??a?.result??a?.verdict;typeof c=="string"&&(i.status=c);}return i}async function br(e,t,r){let o=Ct(e,t),s=".workspai/reports",n=c=>E(t,`${s}/${c}`,r,`${o}/${s}/${c}`),i=await n("doctor-project-last-run.json");return {doctor:i?.exists===true?i:await n("doctor-last-run.json"),remediationPlan:await n("doctor-remediation-plan-last-run.json"),fixResult:await n("doctor-fix-result-last-run.json"),analyze:await n("analyze-last-run.json"),readiness:await n("release-readiness-last-run.json")}}async function jr(e,t,r){let o=i$2(t),s=j$1(t,o),n=w(t),i=f$3(s.runtime),a=await ot(t,o),c=r.contractProject?.slug?r.contractProject.slug:typeof o?.name=="string"&&o.name.trim()?o.name.trim():f$1.basename(t),d=typeof o?.kit_name=="string"?o.kit_name:typeof o?.kit=="string"?o.kit:r.contractProject?.kit,u=typeof o?.engine=="string"?o.engine:n.engine!=="unknown"?n.engine:void 0,p=wr(o,d,s.displayName),l=st({kitId:d,framework:s.key,runtime:s.runtime}),m=f$1.relative(e,t),h$1=m===".."||m.startsWith(`..${f$1.sep}`)?i$3(t):h(t),x=[s.runtime,...h$1.filter(A=>A!==s.runtime)];return {name:c,path:Ct(e,t),...r.includeAbsolutePaths?{absolutePath:t}:{},kind:a,category:nt(a),runtime:s.runtime,runtimeCandidates:x,framework:s.key,frameworkDisplayName:s.displayName,confidence:s.confidence,detectionSource:s.source,supportTier:s.supportTier,runtimeSupportTier:i.tier,runtimeDoctorSupport:i.doctorSupport,moduleSupport:n.moduleSupport,...d?{kit:d}:{},...u?{engine:u}:{},...p?{generator:p}:{},createCapability:l,commands:{supported:n.supportedCommands,unsupported:n.unsupportedCommands,global:n.globalCommands,fleetStages:n.fleetStages,localOnly:n.localOnlyCommands,map:n.commandMap},importantFiles:await vr(t),evidence:await br(e,t,r.includeEvidence),provenance:{path:r.contractProject?"workspace contract declaration reconciled with filesystem discovery":"filesystem discovery",runtime:s.source,framework:s.source,commands:"project command capability matrix",createCapability:"create planner capability contract",evidence:"project .workspai/reports"}}}async function Me(e){for(let t of s(e,"workspace.json")){let r=await St(t);if(r)return r}return null}function Pr(e){if(e.length===0)return "empty-workspace";let t=new Set(e.map(r=>r.category));return t.size>1?"polyglot-product-workspace":t.has("frontend")&&e.length>1?"full-stack-workspace":t.has("frontend")?"frontend-workspace":t.has("desktop")?"desktop-application-workspace":t.has("extension")?"extension-workspace":t.has("library")?"library-workspace":e.length>1?"backend-platform":"backend-workspace"}function Cr(e){let t=new Set;for(let r of e){let o=`${r.name} ${r.path}`.toLowerCase();for(let s of ["auth","billing","payment","notification","order","admin","report","search","analytics"])o.includes(s)&&t.add(s);}return Array.from(t).sort()}function P(e,t,r,o){return {severity:e,code:t,message:r,target:o}}function Et(e){let t=[];e.workspace.name.trim()||t.push(P("error","workspace.name.missing","Workspace name could not be resolved.","workspace")),e.workspace.type==="observed-workspace"&&t.push(P("warning","workspace.marker.missing","Workspace marker is missing; model is based on filesystem observation.","workspace.marker")),e.summary.projectCount===0&&t.push(P("warning","workspace.projects.empty","No project roots were detected in this workspace.","projects")),e.contracts.exists||t.push(P("warning","workspace.contract.missing","Workspace contract is missing; dependency and API edges may be incomplete.",e.contracts.workspaceContractPath));let r=new Map;for(let n of e.projects){let i=n.name.toLowerCase(),a=r.get(i)??[];a.push(n),r.set(i,a),n.importantFiles.length||t.push(P("warning","project.markers.missing",`Project ${n.name} has no important manifest files recorded.`,n.path));let c=f$1.isAbsolute(n.path)?n.path:f$1.resolve(e.workspace.root,n.path);W.existsSync(c)||t.push(P("warning","project.path.missing",`Registered project ${n.name} is not available at its declared path.`,n.path)),n.runtime==="unknown"&&t.push(P("warning","project.runtime.unknown",`Project ${n.name} runtime could not be confidently detected.`,n.path));let d=["test","build"];for(let l of d)n.commands.supported.includes(l)&&n.commands.unsupported.includes(l)&&t.push(P("error","project.commands.conflict",`Project ${n.name} marks ${l} as both supported and unsupported.`,n.path));let u=new Set(n.commands.fleetStages),p=new Set(n.commands.localOnly);for(let l of n.commands.fleetStages){p.has(l)&&t.push(P("error","project.commands.scope-conflict",`Project ${n.name} marks ${l} as both fleet and local-only.`,n.path));let m=n.commands.map[l];(!m||m.status!=="supported"||m.fleetEligible!==true||m.executionScope!=="fleet")&&t.push(P("error","project.commands.fleet-stage-invalid",`Project ${n.name} advertises ${l} as a fleet stage without a supported fleet capability.`,n.path));}for(let l of n.commands.localOnly){let m=n.commands.map[l];(!m||m.status!=="supported"||m.executionScope!=="local-only"||m.fleetEligible===true)&&t.push(P("error","project.commands.local-only-invalid",`Project ${n.name} advertises ${l} as local-only without a matching local-only capability.`,n.path));}for(let l of Object.values(n.commands.map))l.status==="supported"&&(l.fleetEligible===true&&!u.has(l.command)&&t.push(P("error","project.commands.fleet-stage-missing",`Project ${n.name} capability ${l.command} is fleet-eligible but missing from fleetStages.`,n.path)),l.executionScope==="local-only"&&l.fleetEligible!==true&&!p.has(l.command)&&t.push(P("error","project.commands.local-only-missing",`Project ${n.name} capability ${l.command} is local-only but missing from localOnly commands.`,n.path)));}for(let[n,i]of r.entries())i.length>1&&t.push(P("error","project.name.duplicate",`Project name "${n}" is ambiguous across ${i.length} project roots.`,i.map(a=>a.path).join(", ")));e.projectTopology&&e.graph&&c$1({...e.projectTopology,generatedAt:"<ignored>"})!==c$1({...e.graph,generatedAt:"<ignored>"})&&t.push(P("error","workspace.project-topology.alias-mismatch","Deprecated model.graph must remain structurally identical to canonical model.projectTopology during the v1 migration window.","projectTopology"));let o=t.filter(n=>n.severity==="error").length,s=t.filter(n=>n.severity==="warning").length;return {status:o>0?"failed":s>0?"warning":"passed",errors:o,warnings:s,issues:t}}function Dn(e){return Et(e)}function j(e){return e.join(".")}function Sr(e,t){let r=pe,o=e.generatedAt,s=[b({id:"workspace.name",label:"Workspace name",scope:"workspace",value:e.workspace.name,freshness:{kind:"durable",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["workspace","name"]),reason:"Workspace identity is structural metadata and changes through workspace setup."}}),b({id:"workspace.type",label:"Workspace type",scope:"workspace",value:e.identity.workspaceType,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["identity","workspaceType"]),reason:"Workspace type is derived from the current project inventory."}}),b({id:"workspace.projectCount",label:"Project count",scope:"workspace",value:e.summary.projectCount,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["summary","projectCount"]),reason:"Project count is derived from workspace discovery and should be refreshed after structural changes."}}),b({id:"workspace.runtimeFamilies",label:"Runtime families",scope:"workspace",value:e.identity.runtimeFamilies,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["identity","runtimeFamilies"]),reason:"Runtime coverage is inferred from project surfaces."}}),b({id:"workspace.policyMode",label:"Workspace policy mode",scope:"policy",value:e.policies.mode,freshness:{kind:"durable",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["policies","mode"]),reason:"Policy mode is configuration, not runtime state."}}),b({id:"workspace.contract.exists",label:"Workspace contract presence",scope:"contract",value:e.contracts.exists,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["contracts","exists"]),reason:"Contract presence is derived from workspace files and should be refreshed before release gating."}})],n=We(e);n&&s.push(b({id:"graph.edgeCount",label:"Dependency graph edge count",scope:"graph",value:n.stats.edgeCount,freshness:{kind:"derived",category:"structure",generatedAt:n.generatedAt??o,now:t,sourceArtifact:r,sourcePath:j(["projectTopology","stats","edgeCount"]),reason:"Graph topology is derived from manifests, imports, and workspace contracts."}}),b({id:"graph.evidenceCoverageRatio",label:"Dependency graph evidence coverage",scope:"graph",value:n.stats.evidenceCoverageRatio,freshness:{kind:"derived",category:"structure",generatedAt:n.generatedAt??o,now:t,sourceArtifact:r,sourcePath:j(["projectTopology","stats","evidenceCoverageRatio"]),reason:"Graph evidence coverage changes when dependency evidence or contract edges change."}}));for(let[i,a]of e.projects.entries()){let c=`projects[${i}]`,d={kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,reason:"Project facts are derived from workspace discovery, project metadata, and framework probes."};s.push(b({id:`project.${a.name}.kind`,label:`${a.name} kind`,scope:"project",project:a.name,value:a.kind,freshness:{...d,sourcePath:j([c,"kind"])}}),b({id:`project.${a.name}.category`,label:`${a.name} category`,scope:"project",project:a.name,value:a.category,freshness:{...d,sourcePath:j([c,"category"])}}),b({id:`project.${a.name}.runtime`,label:`${a.name} runtime`,scope:"project",project:a.name,value:a.runtime,freshness:{...d,sourcePath:j([c,"runtime"])}}),b({id:`project.${a.name}.framework`,label:`${a.name} framework`,scope:"project",project:a.name,value:a.frameworkDisplayName,freshness:{...d,sourcePath:j([c,"frameworkDisplayName"])}}),b({id:`project.${a.name}.supportTier`,label:`${a.name} support tier`,scope:"project",project:a.name,value:a.supportTier,freshness:{...d,sourcePath:j([c,"supportTier"])}}),b({id:`project.${a.name}.safeFleetStages`,label:`${a.name} safe fleet stages`,scope:"command",project:a.name,value:a.commands.fleetStages,freshness:{...d,sourcePath:j([c,"commands","fleetStages"]),reason:"Safe command availability is derived from package and project command surfaces."}}));for(let[u,p]of Object.entries(a.evidence))s.push(b({id:`project.${a.name}.evidence.${u}`,label:`${a.name} ${u} evidence`,scope:"evidence",project:a.name,value:p?{path:p.path,exists:p.exists,status:p.status??null}:{exists:false},freshness:{kind:p?.exists?"evidence-backed":"verify-before-use",category:"verification",generatedAt:p?.generatedAt??o,now:t,status:p?.exists?void 0:"unknown",sourceArtifact:p?.path??r,sourcePath:j([c,"evidence",u]),verifyBeforeUse:true,reason:p?.exists?"Evidence reports can expire or become stale after source changes.":"Missing evidence must be generated before this fact is used for verification."}}));}for(let[i,a]of Object.entries(e.evidence))s.push(b({id:`workspace.evidence.${i}`,label:`Workspace ${i} evidence`,scope:"evidence",value:a?{path:a.path,exists:a.exists,status:a.status??null}:null,freshness:{kind:a?.exists?"evidence-backed":"verify-before-use",category:"verification",generatedAt:a?.generatedAt??o,now:t,status:a?.exists?void 0:"unknown",sourceArtifact:a?.path??r,sourcePath:j(["evidence",i]),verifyBeforeUse:true,reason:a?.exists?"Workspace evidence can expire or become stale after project, dependency, or policy changes.":"Missing workspace evidence must be generated before release or repair decisions."}}));return s}async function le(e$1){let t=f$1.resolve(e$1.workspacePath),r=e$1.includeAbsolutePaths===true,o=e$1.includeEvidence===true,s$1=xe(e$1.observableScanDepth),n=e$1.now??new Date,[i,a$3,c,d,u,p]=await Promise.all([a(t),Me(t),Ie(t),a$1(t),a$2(t,{descendIntoMatchedProjects:false}),Ae(t,s$1)]),l=new Map;for(let g of c?.projects??[]){let fe=g.externalPath?f$1.resolve(g.externalPath):f$1.resolve(t,g.relativePath);l.set(fe,g);}let m=Re([...u,...p,...l.keys(),...d.map(g=>f$1.isAbsolute(g.path)?g.path:f$1.join(t,g.path))]),v=e$1.reuseProjectModels,h=await Promise.all(m.map(g=>{if(v){let fe=f$1.relative(t,f$1.resolve(g)).split(f$1.sep).join("/"),Fe=v.get(fe);if(Fe)return Promise.resolve(Fe)}return jr(t,g,{includeAbsolutePaths:r,includeEvidence:o,contractProject:l.get(f$1.resolve(g))})})),x=typeof a$3?.workspace_name=="string"?a$3.workspace_name:typeof a$3?.name=="string"?a$3.name:i?.name||c?.workspace.name||f$1.basename(t),A=typeof a$3?.profile=="string"?a$3.profile:typeof a$3?.mode=="string"?a$3.mode:c?.workspace.profile,H=Array.from(new Set(h.map(g=>g.kind))).sort(),ue=Array.from(new Set(h.map(g=>g.category))).sort(),B=Array.from(new Set(h.flatMap(g=>g.runtimeCandidates.length>0?g.runtimeCandidates:[g.runtime]))).sort(),X=Array.from(new Set(h.map(g=>g.framework))).sort(),F=[".workspai/policies.yml",".workspai/policies.yaml",".rapidkit/policies.yml",".rapidkit/policies.yaml"].find(g=>W.existsSync(f$1.join(t,g))),Y=s(t,"workspace.contract.json").map(g=>f$1.relative(t,g).split(f$1.sep).join("/")).find(g=>W.existsSync(f$1.join(t,g)))??i$1.workspaceContract,R=await W.pathExists(f$1.join(t,Y)),Q={schemaVersion:mr,generatedAt:n.toISOString(),workspace:{name:x,root:t,...A?{profile:A}:{},type:i?"rapidkit-workspace":"observed-workspace",...i?{marker:{createdBy:i.createdBy,version:i.version,createdAt:i.createdAt}}:{}},identity:{workspaceType:Pr(h),surfaces:H,categories:ue,runtimeFamilies:B,businessCapabilities:Cr(h)},discovery:{observableScanDepth:s$1},projects:h,policies:{mode:typeof a$3?.policy_mode=="string"?a$3.policy_mode:typeof a$3?.policyMode=="string"?a$3.policyMode:"warn",source:F??null,exists:!!F},contracts:{workspaceContractPath:Y,exists:R,status:R?"known":"missing"},evidence:{doctor:await E(t,e.doctor,o),projectDoctor:await E(t,i$1.doctorProject,o),doctorRemediationPlan:await E(t,i$1.doctorRemediationPlan,o),artifactRemediationPlan:await E(t,i$1.artifactRemediationPlan,o),doctorFixResult:await E(t,i$1.doctorFixResult,o),analyze:await E(t,e.analyze,o),readiness:await E(t,e.readiness,o),pipeline:await E(t,i$1.pipelineLastRun,o)},summary:{projectCount:h.length,runtimes:B,frameworks:X,firstClassProjects:h.filter(g=>g.supportTier==="first-class").length,observedProjects:h.filter(g=>g.supportTier==="observed").length}},w=await Wt(t,Q,{contractExists:R,now:n,incrementalGraph:e$1.incrementalGraph}),C={...Q,projectTopology:w,graph:w},M=Et(C),D=Sr({...C},n),xt=bt({facts:D,generatedAt:n.toISOString(),now:n});return {...C,facts:D,factFreshness:xt,validation:M}}async function On(e){if(e.cache!==true)return {model:await le(e),cache:"disabled"};let t=f$1.resolve(e.workspacePath),r=xe(e.observableScanDepth),o=Se(),[s,n,i,a$3,c]=await Promise.all([a(t),Me(t),a$1(t),a$2(t,{descendIntoMatchedProjects:false}),Ae(t,r)]),d=Re([...a$3,...c,...i.map(h=>f$1.isAbsolute(h.path)?h.path:f$1.join(t,h.path))]),u=await ce({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:d,workspaceJson:n,marker:s}),p=await Ee(t);if(p&&p.cliVersion===o&&p.inputsHash===u&&Pt(p.model))return {model:p.model,cache:"hit"};let l=await le({...e}),[m,v]=await Promise.all([ae(t,d),ie(t)]);return await de(t,{cliVersion:o,inputsHash:u,generatedAt:(e.now??new Date).toISOString(),model:l,projectSignatures:m,workspaceFileSignatures:v}),{model:l,cache:"miss"}}function Er(e,t){let r=new Set,o=new Set,s=new Set;for(let[n,i]of Object.entries(t))n in e?e[n]!==i&&r.add(n):o.add(n);for(let n of Object.keys(e))n in t||s.add(n);return {changed:r,added:o,removed:s}}function Wr(e={},t={}){let r=new Set([...Object.keys(e),...Object.keys(t)]);for(let o of r)if(e[o]!==t[o])return false;return true}async function Gn(e){let t=f$1.resolve(e.workspacePath),r=xe(e.observableScanDepth),o=Se(),s=e.now??new Date,[n,i,a$3,c,d]=await Promise.all([a(t),Me(t),a$1(t),a$2(t,{descendIntoMatchedProjects:false}),Ae(t,r)]),u=Re([...c,...d,...a$3.map(w=>f$1.isAbsolute(w.path)?w.path:f$1.join(t,w.path))]),p=await Ee(t),l=async()=>{let w=await le({...e}),C=await ce({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:u,workspaceJson:i,marker:n}),[M,D]=await Promise.all([ae(t,u),ie(t)]);return await de(t,{cliVersion:o,inputsHash:C,generatedAt:s.toISOString(),model:w,projectSignatures:M,workspaceFileSignatures:D}),{model:w,mode:"full"}},m=p?We(p.model):void 0;if(!p||p.cliVersion!==o||!p.projectSignatures||!m||!Pt(p.model))return l();let v=await ie(t);if(!Wr(p.workspaceFileSignatures,v))return l();let h=await ae(t,u),{changed:x,added:A,removed:H}=Er(p.projectSignatures,h);if(x.size===0&&A.size===0&&H.size===0)return {model:p.model,mode:"unchanged"};let ue=new Set([...x,...A]),B=new Map;for(let w of p.model.projects){let C=w.path.split(f$1.sep).join("/");!ue.has(C)&&!H.has(C)&&B.set(C,w);}let X=new Set,F=false;for(let w of p.model.projects){let C=w.path.split(f$1.sep).join("/");x.has(C)&&X.add(w.name);}let Y=A.size>0||H.size>0,R=await le({...e,reuseProjectModels:B,incrementalGraph:{previousGraph:m,changedProjectIds:X,structuralChange:Y||F}});for(let w of p.model.projects){let C=w.path.split(f$1.sep).join("/");if(!x.has(C))continue;let M=R.projects.find(D=>D.path.split(f$1.sep).join("/")===C);if(M&&M.name!==w.name){F=true;break}}if(F)return l();let Q=await ce({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:u,workspaceJson:i,marker:n});return await de(t,{cliVersion:o,inputsHash:Q,generatedAt:s.toISOString(),model:R,projectSignatures:h,workspaceFileSignatures:v}),{model:R,mode:"incremental"}}async function Ie(e){try{let{contract:t}=await m({workspacePath:e});return t&&typeof t=="object"?t:null}catch{return null}}async function Wt(e,t,r){let o=r.contractExists?await Ie(e):null;try{return r.incrementalGraph?await kt({workspacePath:e,model:t,contract:o,now:r.now,previousGraph:r.incrementalGraph.previousGraph,changedProjectIds:r.incrementalGraph.changedProjectIds,structuralChange:r.incrementalGraph.structuralChange}):await ht({workspacePath:e,model:t,contract:o,now:r.now})}catch{let s=t.projects.map(n=>({id:n.name,path:n.path}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:r.now.toISOString(),nodes:s,edges:[],stats:{nodeCount:s.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:s.length,connectedNodeCount:0,density:0,edgeCoverageRatio:s.length>0?0:1,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:s.length>1?[{code:"graph.inference.failed",severity:"warning",message:"Dependency graph inference failed; model contains projects but no dependency edges.",recommendation:"Run workspace model again after fixing graph inputs, or add workspace contract/manual graph overrides.",nodeIds:s.map(n=>n.id).sort((n,i)=>n.localeCompare(i))}]:void 0}}}async function _n(e$1,t){let r=e$1.contracts.exists?await Ie(t):null,{buildWorkspaceKnowledgeGraph:o}=await import('./workspace-knowledge-graph-MUW6UAGI.js'),s=a$3(e$1),n=await o({workspacePath:t,workspace:{name:e$1.workspace.name,...e$1.workspace.profile?{profile:e$1.workspace.profile}:{}},projects:e$1.projects.map(a=>({id:a.name,path:a.path,...a.absolutePath?{absolutePath:a.absolutePath}:{},runtime:a.runtime,runtimeCandidates:a.runtimeCandidates,framework:a.framework,kind:a.kind,category:a.category,...a.kit?{kit:a.kit}:{}})),projectTopology:We(e$1)??await Wt(t,e$1,{contractExists:e$1.contracts.exists,now:new Date(e$1.generatedAt)}),contract:r,now:new Date(e$1.generatedAt),source:{kind:"workspace-model",artifact:pe,hashAlgorithm:"sha256",hash:d(s)}}),[,i]=await f$2(t,pe,[{relativePath:e.knowledgeGraph,payload:n},{relativePath:pe,payload:s}]);return i}export{nt as a,ot as b,st as c,Gr as d,$r as e,V as f,vt as g,b as h,bt as i,mr as j,pe as k,We as l,Fn as m,Dn as n,Sr as o,le as p,On as q,Gn as r,_n as s};
1
+ import {i,o}from'./chunk-WJVB6SSD.js';import {a as a$2}from'./chunk-27UR373Z.js';import {a as a$6}from'./chunk-HTYMXMQM.js';import {a}from'./chunk-Y5YAP4F3.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {m,a as a$3,d as d$2,c as c$2,b as b$2}from'./chunk-SP5EHSWG.js';import {c,b as b$1,i as i$2,w,f as f$3}from'./chunk-WP3CXMVA.js';import {a as a$1}from'./chunk-T5YRFRJV.js';import {j as j$1,i as i$3,h}from'./chunk-ZCPT6KC3.js';import {a as a$4}from'./chunk-GR6442P7.js';import {f as f$2,d as d$1,a as a$5,e as e$1}from'./chunk-CCDGHPEJ.js';import {f,e,i as i$1,h as h$1}from'./chunk-NZ3WZYD5.js';import {t,s}from'./chunk-MOSXTVPU.js';import f$1 from'path';import W from'fs-extra';import Dt from'crypto';import {createRequire}from'module';var At=new Set(["backend","desktop","extension","service","frontend","worker","library","infra","docs","test-suite","unknown"]);async function rt(e){try{if(!await W.pathExists(e))return null;let t=await W.readJSON(e);return t&&typeof t=="object"?t:null}catch{return null}}async function Rt(e){for(let t of e){let r=await rt(t);if(r)return r}return null}function tt(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return At.has(t)?t==="service"?"backend":t:null}function nt(e){switch(e){case "backend":case "service":case "worker":return "backend";case "frontend":case "desktop":case "extension":case "library":return e;case "infra":return "infrastructure";case "docs":return "documentation";case "test-suite":return "quality";default:return "unknown"}}async function ot(e,t$1){let r=t$1??await Rt(t(e,"project.json")),o=tt(r?.kind)??tt(r?.type);if(o)return o;let s=typeof r?.kit_name=="string"?r.kit_name:r?.kit,n=typeof r?.framework=="string"?r.framework:null,i=typeof r?.runtime=="string"?r.runtime:null,a=`${typeof s=="string"?s:""} ${n??""} ${i??""}`.trim().toLowerCase();if(/\b(tauri|electron|wails|desktop)\b/.test(a))return "desktop";if(/\b(vscode-extension|visual studio code extension|jetbrains-plugin|browser-extension)\b/.test(a))return "extension";if(/\b(frontend|nextjs|next\.js|react|vue|svelte|vite|angular|astro|remix|nuxt)\b/.test(a))return "frontend";if(/\b(fastapi|nestjs|springboot|spring boot|gofiber|gogin|dotnet|webapi|django|flask|express|fastify|python|node|java|go|rust|php|ruby|elixir)\b/.test(a))return "backend";let c=await rt(f$1.join(e,"package.json"));if(c){let d={...c.dependencies??{},...c.devDependencies??{}},u=c.scripts??{},p=Object.values(u).filter(v=>typeof v=="string").join(" ").toLowerCase(),l=c.engines??{},m=Array.isArray(c.categories)?c.categories.filter(v=>typeof v=="string"):[];if(d["@tauri-apps/api"]||d["@tauri-apps/cli"]||await W.pathExists(f$1.join(e,"src-tauri","tauri.conf.json"))||await W.pathExists(f$1.join(e,"src-tauri","tauri.conf.json5"))||d.electron||d["@electron-forge/cli"]||p.includes("electron-forge")||p.includes("electron "))return "desktop";if(typeof l.vscode=="string"||m.some(v=>v.toLowerCase()==="extension packs")||c.publisher&&(c.activationEvents||c.contributes))return "extension";if(d.next||d.react||d.vue||d.svelte||d.vite||d["@angular/core"]||p.includes("next ")||p.includes("vite "))return "frontend";if(c.private===true&&!d.express&&!d["@nestjs/core"])return "library"}return await W.pathExists(f$1.join(e,"Dockerfile"))||await W.pathExists(f$1.join(e,"docker-compose.yml"))||await W.pathExists(f$1.join(e,"terraform.tf"))?"infra":"backend"}var Mt=new Set(c().map(e=>e.id)),It=[...i().map(e=>({id:e.kitId,aliases:[...e.aliases],ecosystem:e.framework,status:"available",canExecuteCreate:true,versionPolicy:e.versionPolicy,officialCommands:[e.commandDisplay("<name>",{skipGit:false,skipInstall:false})],adoptAfterCreate:true,...e.minNodeVersion?{runtimeRequirements:{node:`>=${e.minNodeVersion}`}}:e.minNodeMajor?{runtimeRequirements:{node:`>=${e.minNodeMajor}`}}:{}})),...o().map(e=>({id:e.kitId,aliases:[...e.aliases],ecosystem:e.framework,status:"available",canExecuteCreate:true,versionPolicy:e.versionPolicy,officialCommands:[e.commandDisplay("<name>",{skipGit:false,skipInstall:false})],adoptAfterCreate:true,...e.nodeSupport?{runtimeRequirements:{node:e.nodeSupport.requirement}}:{}})),{id:"wordpress-site",aliases:["wordpress","wordpress-site","wp","wp-site"],ecosystem:"wordpress",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["wp core download","wp config create","wp db create","wp core install"],adoptAfterCreate:true},{id:"wordpress-block",aliases:["wordpress-block","wp-block","gutenberg-block"],ecosystem:"wordpress",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["npx @wordpress/create-block@latest <slug>"],adoptAfterCreate:true},{id:"symfony",aliases:["symfony","php-symfony"],ecosystem:"php",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["composer create-project symfony/skeleton <name>"],adoptAfterCreate:true},{id:"rails",aliases:["rails","ruby-on-rails","ruby-rails"],ecosystem:"ruby",status:"planned",canExecuteCreate:false,versionPolicy:"planned",officialCommands:["rails new <name>"],adoptAfterCreate:true}],z=new Map;for(let e of It){z.set(e.id,e);for(let t of e.aliases)z.set(t,e);}var Ft=new Set(["php","ruby","rust","elixir","clojure","scala","kotlin","unknown"]);function $(e){return e?.trim().toLowerCase()||void 0}function st(e){let t=$(e.kitId)??$(e.framework)??$(e.runtime)??"unknown";if(e.projectExists)return {lane:"existing",status:"available",canExecuteCreate:false,requested:t,reason:"Existing projects enter Workspace Intelligence through adopt/import."};let r=e.kitId?b$1(e.kitId):void 0;if(r&&Mt.has(r))return {lane:"native",status:"available",canExecuteCreate:true,requested:t,resolved:r,reason:"Workspai owns the create contract, project marker, registry, doctor, and workspace model path."};let o=z.get(t)??z.get($(e.framework)??"")??z.get($(e.runtime)??"");if(o)return {lane:"official",status:o.status,canExecuteCreate:o.canExecuteCreate,requested:t,resolved:o.id,officialCommands:o.officialCommands,fallbackLane:o.canExecuteCreate?void 0:"existing",reason:o.status==="available"?"Workspai runs the official ecosystem generator, then registers the project in Workspace Intelligence.":"Official generator support is planned but not enabled; use adopt/import until Workspai owns the post-create contract."};let s=$(e.runtime);return s&&Ft.has(s)?{lane:"existing",status:"available",canExecuteCreate:false,requested:t,resolved:s,reason:"Runtime can be governed through Workspace Intelligence, but native create is not supported."}:{lane:"existing",status:"available",canExecuteCreate:false,requested:t,reason:"No native create contract is available; use adopt/import to enter Workspace Intelligence."}}function Gr(e){return !e.canExecuteCreate&&(e.lane==="official"||e.lane==="existing"&&e.resolved!==void 0)}var $r="rapidkit-freshness-metadata-v1";function ke(e){if(Array.isArray(e))return e.map(t=>ke(t));if(e&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=ke(e[r]);return t}return e}function Ot(e){return JSON.stringify(ke(e))}function V(e){return Dt.createHash("sha256").update(Ot(e)).digest("hex")}var at=".workspai/workspace-graph.overrides.json",Gt=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),_t=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","node_modules","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),ct=600,dt=5,Tt=256*1024,it={inferred:1,contract:2,manual:3};function Nt(e){return e.split(f$1.sep).join("/")}function ne(e,t){return Nt(f$1.relative(e,t)||".")}function pt(e){let t=new Map;for(let r of e.projects)t.has(r.name)||t.set(r.name,{id:r.name,path:r.path,...r.runtime?{runtime:r.runtime}:{},...r.framework?{framework:r.framework}:{},...r.kind?{kind:r.kind}:{}});return [...t.values()].sort((r,o)=>r.id.localeCompare(o.id))}function lt(e,t){let r=new Map,o=new Map;for(let n of t.projects){if(r.has(n.name))continue;let i=n.absolutePath?f$1.resolve(n.absolutePath):f$1.resolve(e,n.path);r.set(n.name,i),o.has(i)||o.set(i,n.name);}let s=[...o.entries()].map(([n,i])=>({dir:n,id:i})).sort((n,i)=>i.dir.length-n.dir.length||n.dir.localeCompare(i.dir));return {idToDir:r,dirToId:o,sortedDirs:s}}function oe(e,t){let r=f$1.resolve(t);for(let{dir:o,id:s}of e.sortedDirs)if(r===o||r.startsWith(`${o}${f$1.sep}`))return s;return null}async function ve(e){try{if(!await W.pathExists(e))return null;let t=await W.readJSON(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async function je(e){try{return await W.pathExists(e)?await W.readFile(e,"utf8"):null}catch{return null}}async function ut(e,t){let r=[],o=new Map;for(let[s,n]of t.idToDir.entries()){let i=await ve(f$1.join(n,"package.json")),a=typeof i?.name=="string"?i.name.trim():"";a&&!o.has(a)&&o.set(a,s);}for(let[s,n]of t.idToDir.entries()){let i=await ve(f$1.join(n,"package.json"));if(i){let a=["dependencies","devDependencies","peerDependencies","optionalDependencies"],c=new Set;for(let d of a){let u=i[d];if(!(!u||typeof u!="object"||Array.isArray(u)))for(let p of Object.keys(u)){let l=o.get(p);!l||l===s||c.has(l)||(c.add(l),r.push({from:s,to:l,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ne(e,f$1.join(n,"package.json")),detail:`declares dependency ${p}`}]}));}}}r.push(...await $t(e,t,s,n)),r.push(...await Vt(e,t,s,n));}return r}async function $t(e,t,r,o){let s=await je(f$1.join(o,"pyproject.toml"));if(!s)return [];let n=[],i=new Set,a=/path\s*=\s*["']([^"']+)["']/g,c;for(;(c=a.exec(s))!==null;){let d=oe(t,f$1.resolve(o,c[1]));!d||d===r||i.has(d)||(i.add(d),n.push({from:r,to:d,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ne(e,f$1.join(o,"pyproject.toml")),detail:`path dependency ${c[1]}`}]}));}return n}async function Vt(e,t,r,o){let s=await je(f$1.join(o,"go.mod"));if(!s)return [];let n=[],i=new Set,a=/replace\s+\S+\s+=>\s+(\.[^\s]+)/g,c;for(;(c=a.exec(s))!==null;){let d=oe(t,f$1.resolve(o,c[1]));!d||d===r||i.has(d)||(i.add(d),n.push({from:r,to:d,kind:"package-dep",source:"inferred",confidence:"high",evidence:[{file:ne(e,f$1.join(o,"go.mod")),detail:`go.mod replace ${c[1]}`}]}));}return n}async function Kt(e,t){let r=[],o=[e];for(;o.length>0&&r.length<t;){let s=o.shift();if(!s)continue;let n=[];try{n=await W.readdir(s,{withFileTypes:true});}catch{continue}let i=[],a=[];for(let c of n)if(c.isDirectory()){if(_t.has(c.name)||a$4(c.name)||c.name.startsWith("."))continue;i.push(f$1.join(s,c.name));}else c.isFile()&&Gt.has(f$1.extname(c.name))&&a.push(f$1.join(s,c.name));a.sort((c,d)=>c.localeCompare(d)),i.sort((c,d)=>c.localeCompare(d));for(let c of a){if(r.length>=t)break;r.push(c);}o.push(...i);}return r}var Ht=[/\bfrom\s+["']([^"']+)["']/g,/\bimport\s+["']([^"']+)["']/g,/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g,/\brequire\s*\(\s*["']([^"']+)["']\s*\)/g];function Bt(e){let t=new Set;for(let r of Ht){r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){let s=o[1];s.startsWith(".")&&t.add(s);}}return [...t]}async function be(e,t,r,o){let s=new Map;for(let[n,i]of t.idToDir.entries()){if(o&&!o.has(n))continue;let a=await Kt(i,r);for(let c of a){let d=await W.stat(c).catch(()=>null);if(!d||d.size>Tt)continue;let u=await je(c);if(u)for(let p of Bt(u)){let l=f$1.resolve(f$1.dirname(c),p),m=oe(t,l);if(!m||m===n)continue;let v=`${n}\0${m}`,h=s.get(v);h||(h={from:n,to:m,evidence:[]},s.set(v,h)),h.evidence.length<dt&&h.evidence.push({file:ne(e,c),detail:`imports ${p}`});}}}return [...s.values()].map(n=>({from:n.from,to:n.to,kind:"code-import",source:"inferred",confidence:"medium",evidence:n.evidence}))}function Lt(e,t,r){let o=new Map;for(let s of r.projects){let n=zt(e,t,s);n&&o.set(s.slug,n);}return o}function zt(e,t,r){let o=[r.relativePath,r.externalPath].filter(s=>typeof s=="string"&&s.length>0);for(let s of o){let n=f$1.resolve(e,s),i=t.dirToId.get(n)??oe(t,n);if(i)return i}return t.idToDir.has(r.slug)?r.slug:null}function ft(e,t,r){let o=[],s=Lt(e,t,r),n=d$2,i=new Map,a=new Map;for(let c of r.projects){let d=s.get(c.slug);if(!d)continue;let u=c.contracts??{publishes:[],consumes:[],dependsOn:[]};for(let p of u.dependsOn??[]){let l=s.get(p);!l||l===d||o.push({from:d,to:l,kind:"service-dependsOn",source:"contract",confidence:"high",evidence:[{file:n,detail:`dependsOn ${p}`}]});}for(let p of u.publishes??[])i.has(p)||i.set(p,new Set),i.get(p)?.add(d);for(let p of u.consumes??[])a.has(p)||a.set(p,new Set),a.get(p)?.add(d);}for(let[c,d]of i.entries()){let u=a.get(c);if(u)for(let p of u)for(let l of d)p!==l&&o.push({from:p,to:l,kind:"event-pub-sub",source:"contract",confidence:"high",evidence:[{file:n,detail:`consumes event ${c}`}]});}return o.push(...Ut(r,s)),o}function ye(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function Ut(e,t){let r=[],o=e.projects.map(s=>({project:s,id:t.get(s.slug)})).filter(s=>!!s.id).filter(s=>ye(s.project.slug).length>=3);for(let s of e.projects){let n=t.get(s.slug);if(!n)continue;let i=s.contracts?.env??[];if(i.length===0)continue;let a=new Set;for(let c of i){let d=ye(c);for(let u of o)u.id===n||a.has(u.id)||!(d.includes(ye(u.project.slug))&&(u.project.ports?.length??0)>0)||(a.add(u.id),r.push({from:n,to:u.id,kind:"shared-resource",source:"inferred",confidence:"low",evidence:[{file:d$2,detail:`env ${c} references ${u.project.slug}`}]}));}}return r}async function mt(e,t){let r=await ve(f$1.join(e,at)),o=Array.isArray(r?.edges)?r?.edges:[],s=[],n=new Set(c$2);for(let i of o){if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i,c=typeof a.from=="string"?a.from:"",d=typeof a.to=="string"?a.to:"",u=typeof a.kind=="string"?a.kind:"";if(!t.has(c)||!t.has(d)||c===d||!n.has(u))continue;let p=Array.isArray(a.evidence)?a.evidence.map(l=>l&&typeof l=="object"&&typeof l.file=="string"?{file:l.file,...typeof l.detail=="string"?{detail:l.detail}:{}}:null).filter(l=>!!l):[];s.push({from:c,to:d,kind:u,source:"manual",confidence:"high",evidence:p.length>0?p:[{file:at,detail:"manual edge"}]});}return s}function qt(e){return `${e.from}\0${e.to}\0${e.kind}`}function Jt(e){let t=new Set,r=[];for(let o of e){let s=`${o.file}\0${o.detail??""}`;t.has(s)||(t.add(s),r.push(o));}return r.sort((o,s)=>o.file.localeCompare(s.file)||(o.detail??"").localeCompare(s.detail??"")).slice(0,dt)}function Xt(e){let t=new Map;for(let r of e){let o=qt(r),s=t.get(o);if(!s){t.set(o,{...r,evidence:[...r.evidence]});continue}let n=it[s.source],i=it[r.source];i>n?t.set(o,{...r,evidence:[...r.evidence,...s.evidence]}):i===n&&s.evidence.push(...r.evidence);}return [...t.values()].map(r=>({from:r.from,to:r.to,kind:r.kind,source:r.source,confidence:r.confidence,evidence:Jt(r.evidence)})).sort((r,o)=>r.from.localeCompare(o.from)||r.to.localeCompare(o.to)||r.kind.localeCompare(o.kind)||r.source.localeCompare(o.source))}function we(e){return Math.round(e*1e3)/1e3}function Yt(e){return Math.max(0,Math.min(100,Math.round(e)))}function Qt(e){return e>=75?"critical":e>=50?"high":e>=20?"medium":"low"}function Zt(e){return e==="critical"||e==="high"?"strict":e==="medium"?"elevated":"normal"}function er(e,t){let r=a$6({nodes:e,edges:t}),o=new Map;for(let s of e){let n=r.byId.get(s.id)??{fanIn:0,fanOut:0,reach:0,betweenness:0,isHotspot:false},i=t.filter(m=>m.from===s.id||m.to===s.id),a=i.filter(m=>m.source==="contract"||m.source==="manual").length,c=i.filter(m=>m.confidence==="low").length,d=[],u=n.reach*20+n.fanIn*14+n.fanOut*8+Math.min(20,n.betweenness*4)+a*8;n.isHotspot&&(u+=24,d.push("Critical-path hotspot in dependency graph")),n.reach>0&&d.push(`Change reaches ${n.reach} dependent project(s)`),n.fanIn>0&&d.push(`${n.fanIn} direct dependent project(s)`),n.fanOut>0&&d.push(`${n.fanOut} direct dependency project(s)`),a>0&&d.push(`${a} contract/manual edge(s)`),c>0&&d.push(`${c} low-confidence inferred edge(s) need review`),i.length===0&&d.push("No dependency evidence connected to this project yet");let p=Yt(u),l=Qt(p);o.set(s.id,{weight:l,score:p,verificationPriority:Zt(l),reasons:d.slice(0,5),centrality:{fanIn:n.fanIn,fanOut:n.fanOut,reach:n.reach,betweenness:n.betweenness,isHotspot:n.isHotspot}});}return o}function tr(e,t){let r=er(e,t);return e.map(o=>({...o,operationalProfile:r.get(o.id)}))}function rr(e,t){let r=new Set;for(let c of t)r.add(c.from),r.add(c.to);let o=e.length,s=t.length,n=e.filter(c=>r.has(c.id)).length,i=Math.max(0,o-n),a=a$6({nodes:e,edges:t});return {nodeCount:o,edgeCount:s,inferredEdges:t.filter(c=>c.source==="inferred").length,contractEdges:t.filter(c=>c.source==="contract").length,manualEdges:t.filter(c=>c.source==="manual").length,authoritativeEdges:t.filter(c=>c.source==="contract"||c.source==="manual").length,lowConfidenceEdges:t.filter(c=>c.confidence==="low").length,orphanCount:i,connectedNodeCount:n,density:we(o>1?s/(o*(o-1)):0),edgeCoverageRatio:we(o>0?n/o:1),evidenceCoverageRatio:we(s>0?t.filter(c=>c.evidence.length>0).length/s:1),hotspotCount:a.hotspots.length,hasCycle:or(e,t)}}function nr(e,t,r){let o=[],s=e.filter(n=>!t.some(i=>i.from===n.id||i.to===n.id)).map(n=>n.id).sort((n,i)=>n.localeCompare(i));return r.nodeCount===0&&o.push({code:"graph.empty",severity:"info",message:"Workspace model has no projects, so dependency reasoning is unavailable.",recommendation:"Import, scaffold, or register projects before relying on graph-aware impact."}),r.nodeCount>1&&r.edgeCount===0?o.push({code:"graph.edges.missing",severity:"warning",message:"Projects were detected, but no inter-project dependency edges were found.",recommendation:"Run graph explain, add workspace contract relationships, or define manual graph overrides for operational dependencies that code imports cannot reveal.",nodeIds:s}):r.orphanCount>0&&o.push({code:"graph.orphans.detected",severity:"warning",message:`${r.orphanCount} project(s) have no dependency evidence connected to the graph.`,recommendation:"Review isolated projects and add package, contract, or manual edges when they participate in release-critical flows.",nodeIds:s.slice(0,12)}),r.lowConfidenceEdges>0&&o.push({code:"graph.low_confidence_edges",severity:"info",message:`${r.lowConfidenceEdges} inferred edge(s) are low confidence.`,recommendation:"Promote important low-confidence relationships to workspace contract or manual overrides."}),r.edgeCount>0&&r.evidenceCoverageRatio<1&&o.push({code:"graph.evidence.partial",severity:"warning",message:"Some dependency edges do not include file-level evidence.",recommendation:"Attach evidence to manual overrides so agents can audit why a relationship exists."}),r.hasCycle&&o.push({code:"graph.cycle.detected",severity:"error",message:"The dependency graph contains at least one directed cycle.",recommendation:"Break the cycle or document the relationship explicitly before using graph-aware release gates."}),o.sort((n,i)=>{let a={error:0,warning:1,info:2};return a[n.severity]-a[i.severity]||n.code.localeCompare(i.code)})}function or(e,t){let r=new Map;for(let c of e)r.set(c.id,[]);for(let c of t)r.has(c.from)||r.set(c.from,[]),r.get(c.from)?.push(c.to);let o=0,s=1,n=2,i=new Map;for(let c of r.keys())i.set(c,o);let a=c=>{let d=[{id:c,index:0}];for(i.set(c,s);d.length>0;){let u=d[d.length-1],p=r.get(u.id)??[];if(u.index>=p.length){i.set(u.id,n),d.pop();continue}let l=p[u.index];u.index+=1;let m=i.get(l)??o;if(m===s)return true;m===o&&(i.set(l,s),d.push({id:l,index:0}));}return false};for(let c of [...r.keys()].sort())if(i.get(c)===o&&a(c))return true;return false}function gt(e,t,r,o){let s=Xt(r.filter(c=>t.has(c.from)&&t.has(c.to))),n=tr(e,s),i=rr(e,s),a=nr(e,s,i);return {schemaVersion:b$2,generatedAt:(o??new Date).toISOString(),nodes:n,edges:s,stats:i,...a.length>0?{diagnostics:a}:{}}}async function ht(e){let t=f$1.resolve(e.workspacePath),r=e.maxImportFilesPerProject??ct,o=pt(e.model),s=new Set(o.map(a=>a.id)),n=lt(t,e.model),i=[];return i.push(...await ut(t,n)),i.push(...await be(t,n,r)),e.contract&&i.push(...ft(t,n,e.contract)),i.push(...await mt(t,s)),gt(o,s,i,e.now)}async function kt(e){let t=f$1.resolve(e.workspacePath),r=e.maxImportFilesPerProject??ct,o=pt(e.model),s=new Set(o.map(a=>a.id)),n=lt(t,e.model),i=[];if(i.push(...await ut(t,n)),e.structuralChange)i.push(...await be(t,n,r));else {i.push(...await be(t,n,r,e.changedProjectIds));for(let a of e.previousGraph.edges)a.kind==="code-import"&&a.source==="inferred"&&!e.changedProjectIds.has(a.from)&&s.has(a.from)&&s.has(a.to)&&i.push({from:a.from,to:a.to,kind:"code-import",source:"inferred",confidence:a.confidence,evidence:a.evidence});}return e.contract&&i.push(...ft(t,n,e.contract)),i.push(...await mt(t,s)),gt(o,s,i,e.now)}var Ce=h$1.workspaceModelCache.schemaVersion,Pe=i$1.workspaceModelCache,yt=["package.json","pyproject.toml","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","workspai.project.json",".workspai/project.json",".workspai/context.json","rapidkit.project.json",".rapidkit/project.json",".rapidkit/context.json"],wt=[i$1.workspaceContract,".workspai/workspace.json","workspai.workspace.json",".workspai/policies.yml",".workspai/policies.yaml",".rapidkit/workspace.contract.json",".rapidkit/workspace.json","rapidkit.workspace.json",".rapidkit/policies.yml",".rapidkit/policies.yaml"],ir=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]),cr=new Set([".git",".workspai",".rapidkit","node_modules","dist","build","out","target","coverage",".next",".turbo",".cache",".venv"]),dr=1500,U=null;function Se(){if(U)return U;try{U=createRequire(import.meta.url)("../package.json")?.version??"0.0.0";}catch{U="0.0.0";}return U}async function se(e){try{let t=await W.readFile(e);return Dt.createHash("sha256").update(t).digest("hex")}catch{return null}}async function pr(e){let t={};for(let s of yt){let n=await se(f$1.join(e,s));n&&(t[s]=n);}let r=[],o=[e];for(;o.length>0&&r.length<dr;){let s=o.shift();if(!s)continue;let n=[];try{n=await W.readdir(s,{withFileTypes:true});}catch{continue}let i=[];for(let a of n)if(a.isDirectory()){if(cr.has(a.name)||a$4(a.name)||a.name.startsWith("."))continue;i.push(f$1.join(s,a.name));}else if(a.isFile()&&ir.has(f$1.extname(a.name))){let c=f$1.join(s,a.name),d=await W.stat(c).catch(()=>null);if(d){let u=f$1.relative(e,c).split(f$1.sep).join("/");r.push(`${u}:${d.size}:${Math.round(d.mtimeMs)}`);}}i.sort((a,c)=>a.localeCompare(c)),o.push(...i);}return r.sort((s,n)=>s.localeCompare(n)),V({manifests:t,source:r})}async function ae(e,t){let r=f$1.resolve(e),o={},s=[...new Set(t.map(n=>f$1.relative(r,f$1.resolve(n)).split(f$1.sep).join("/")))].sort((n,i)=>n.localeCompare(i));for(let n of s)o[n]=await pr(f$1.join(r,n));return o}async function ie(e){let t=f$1.resolve(e),r={};for(let o of wt){let s=await se(f$1.join(t,o));s&&(r[o]=s);}return r}async function ce(e){let t=f$1.resolve(e.workspacePath),r=[...new Set(e.projectPaths.map(n=>f$1.relative(t,f$1.resolve(n)).split(f$1.sep).join("/")))].sort((n,i)=>n.localeCompare(i)),o=[];for(let n of r){let i={};for(let a of yt){let c=await se(f$1.join(t,n,a));c&&(i[a]=c);}o.push({project:n,manifests:i});}let s={};for(let n of wt){let i=await se(f$1.join(t,n));i&&(s[n]=i);}return V({cacheSchema:Ce,cliVersion:e.cliVersion,flags:e.flags,workspaceJson:e.workspaceJson??null,marker:e.marker??null,projects:o,workspaceFiles:s})}async function Ee(e){let t=await d$1(e,Pe)??a$5(e,Pe);try{if(!await W.pathExists(t))return null;let r=await W.readJson(t);return !r||r.schemaVersion!==Ce||typeof r.inputsHash!="string"||typeof r.cliVersion!="string"||!r.model?null:r}catch{return null}}async function de(e,t){let r={schemaVersion:Ce,...t};return e$1(e,Pe,r)}var vt="rapidkit-fact-freshness-v1",J={durable:720*60*60,derived:10080*60,evidenceBacked:1440*60,live:300,verifyBeforeUse:1440*60};function lr(e){switch(e){case "durable":return J.durable;case "derived":return J.derived;case "evidence-backed":return J.evidenceBacked;case "live":return J.live;case "verify-before-use":return J.verifyBeforeUse}}function ur(e){if(e.status)return e.status;if(e.ttlSeconds===null)return "unknown";let t=Date.parse(e.generatedAt);if(!Number.isFinite(t))return "unknown";let r=t+e.ttlSeconds*1e3;return e.now.getTime()>r?"stale":"fresh"}function fr(e){let t=e.now??new Date,r=e.generatedAt??t.toISOString(),o=Date.parse(r),s=Number.isFinite(o),n=s?r:t.toISOString(),i=e.ttlSeconds===void 0?lr(e.kind):e.ttlSeconds,a=ur({generatedAt:n,ttlSeconds:i,status:e.status??(s?void 0:"unknown"),now:t}),c=Date.parse(n),d=i===null||!Number.isFinite(c)?void 0:new Date(c+i*1e3),u=e.verifyBeforeUse??(e.kind==="live"||e.kind==="verify-before-use"||e.category!=="structure"||a!=="fresh");return {schemaVersion:vt,kind:e.kind,category:e.category,generatedAt:n,ttlSeconds:i,...d?{expiresAt:d.toISOString()}:{},status:a,verifyBeforeUse:u,...e.sourceArtifact?{sourceArtifact:e.sourceArtifact}:{},...e.sourcePath?{sourcePath:e.sourcePath}:{},inputsHash:e.inputsHash??V(e.value??null),reason:e.reason}}function b(e){return {id:e.id,label:e.label,scope:e.scope,value:e.value,...e.project?{project:e.project}:{},freshness:fr({...e.freshness,value:e.value})}}function bt(e){let t=e.generatedAt??(e.now??new Date).toISOString(),r={durable:0,derived:0,"evidence-backed":0,live:0,"verify-before-use":0},o={structure:0,verification:0,state:0},s=0,n=0,i=0,a=0;for(let c of e.facts)r[c.freshness.kind]+=1,o[c.freshness.category]+=1,c.freshness.status==="stale"&&(s+=1),c.freshness.status==="unknown"&&(n+=1),c.freshness.kind==="live"&&(i+=1),c.freshness.verifyBeforeUse&&(a+=1);return {schemaVersion:vt,generatedAt:t,status:s>0?"stale":n>0?"unknown":"fresh",totalFacts:e.facts.length,staleFacts:s,unknownFacts:n,liveFacts:i,verifyBeforeUseFacts:a,byKind:r,byCategory:o}}var mr=f.model,pe=e.model;function We(e){return e.projectTopology??e.graph}function Pt(e){return !!(e.projectTopology&&e.graph&&c$1(e.projectTopology)===c$1(e.graph))}function Fn(e){let t=e.engineStatus==="hit"||e.engineStatus==="unchanged"?"reused":e.engineStatus==="incremental"?"partially-reused":"rebuilt";return {schemaVersion:"workspace-model-build.v1",mode:e.mode,outcome:t,engineStatus:e.engineStatus}}var gr=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","bun.lock","bun.lockb","deps.edn","project.clj","build.sbt","docker-compose.yml","docker-compose.yaml","terraform.tf"],hr=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next",".turbo"]);function Ct(e,t){return (f$1.relative(e,t)||".").split(f$1.sep).join("/")}async function St(e){try{if(!await W.pathExists(e))return null;let t=await W.readJSON(e);return t&&typeof t=="object"?t:null}catch{return null}}async function kr(e,t){for(let r of t)if(await W.pathExists(f$1.join(e,r)))return true;return false}function xe(e){let t=Number.parseInt(process.env.RAPIDKIT_WORKSPACE_MODEL_SCAN_DEPTH??"",10),r=typeof e=="number"&&Number.isFinite(e)?e:Number.isFinite(t)?t:4;return Math.min(12,Math.max(1,Math.trunc(r)))}async function Ae(e,t){let r=f$1.resolve(e),o=[{dirPath:r,depth:0}],s=new Set,n=new Set;for(;o.length>0;){let i=o.shift();if(!i)continue;let a=f$1.resolve(i.dirPath);if(n.has(a))continue;if(n.add(a),a!==r&&await kr(a,gr)){s.add(a);continue}if(i.depth>=t)continue;let c=[];try{c=await W.readdir(a,{withFileTypes:true});}catch{continue}for(let d of c)!d.isDirectory()||hr.has(d.name)||a$4(d.name)||d.name.startsWith(".")&&d.name!==".config"||o.push({dirPath:f$1.join(a,d.name),depth:i.depth+1});}return Array.from(s).sort((i,a)=>i.localeCompare(a))}function Re(e){let t=new Set,r=[];for(let o of e){let s=f$1.resolve(o);t.has(s)||(t.add(s),r.push(s));}return r.sort((o,s)=>o.localeCompare(s))}function jt(e,t){let r=e?.[t];return typeof r=="string"&&r.trim()?r.trim():void 0}function yr(e,t){return e?.[t]===true}function wr(e,t,r){let o=e?.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,s=jt(o,"generator"),n=jt(o,"command_display"),i=typeof t=="string"&&t.startsWith("frontend.");if(!(!s&&!i))return {...s?{id:s}:{},...t?{kit:t}:{},displayName:r,source:yr(o,"official_generator")?"official-generator":"metadata",...n?{commandDisplay:n}:{}}}async function vr(e){let t=[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json","package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","CMakeLists.txt","meson.build","Makefile","WORKSPACE","WORKSPACE.bazel","MODULE.bazel","BUILD","BUILD.bazel",".bazelrc","composer.json","Gemfile","mix.exs","deno.json","setup.py","setup.cfg","Dockerfile","docker-compose.yml","README.md"],r=[];for(let o of t)await W.pathExists(f$1.join(e,o))&&r.push(o);return r}async function E(e,t,r,o=t){let s=await d$1(e,t),n=s!==null,i={path:o.split(f$1.sep).join("/"),exists:n};if(s&&r){let a=await St(s);typeof a?.generatedAt=="string"&&(i.generatedAt=a.generatedAt);let c=a?.status??a?.result??a?.verdict;typeof c=="string"&&(i.status=c);}return i}async function br(e,t,r){let o=Ct(e,t),s=".workspai/reports",n=c=>E(t,`${s}/${c}`,r,`${o}/${s}/${c}`),i=await n("doctor-project-last-run.json");return {doctor:i?.exists===true?i:await n("doctor-last-run.json"),remediationPlan:await n("doctor-remediation-plan-last-run.json"),fixResult:await n("doctor-fix-result-last-run.json"),analyze:await n("analyze-last-run.json"),readiness:await n("release-readiness-last-run.json")}}async function jr(e,t,r){let o=i$2(t),s=j$1(t,o),n=w(t),i=f$3(s.runtime),a=await ot(t,o),c=r.contractProject?.slug?r.contractProject.slug:typeof o?.name=="string"&&o.name.trim()?o.name.trim():f$1.basename(t),d=typeof o?.kit_name=="string"?o.kit_name:typeof o?.kit=="string"?o.kit:r.contractProject?.kit,u=typeof o?.engine=="string"?o.engine:n.engine!=="unknown"?n.engine:void 0,p=wr(o,d,s.displayName),l=st({kitId:d,framework:s.key,runtime:s.runtime}),m=f$1.relative(e,t),h$1=m===".."||m.startsWith(`..${f$1.sep}`)?i$3(t):h(t),x=[s.runtime,...h$1.filter(A=>A!==s.runtime)];return {name:c,path:Ct(e,t),...r.includeAbsolutePaths?{absolutePath:t}:{},kind:a,category:nt(a),runtime:s.runtime,runtimeCandidates:x,framework:s.key,frameworkDisplayName:s.displayName,confidence:s.confidence,detectionSource:s.source,supportTier:s.supportTier,runtimeSupportTier:i.tier,runtimeDoctorSupport:i.doctorSupport,moduleSupport:n.moduleSupport,...d?{kit:d}:{},...u?{engine:u}:{},...p?{generator:p}:{},createCapability:l,commands:{supported:n.supportedCommands,unsupported:n.unsupportedCommands,global:n.globalCommands,fleetStages:n.fleetStages,localOnly:n.localOnlyCommands,map:n.commandMap},importantFiles:await vr(t),evidence:await br(e,t,r.includeEvidence),provenance:{path:r.contractProject?"workspace contract declaration reconciled with filesystem discovery":"filesystem discovery",runtime:s.source,framework:s.source,commands:"project command capability matrix",createCapability:"create planner capability contract",evidence:"project .workspai/reports"}}}async function Me(e){for(let t of s(e,"workspace.json")){let r=await St(t);if(r)return r}return null}function Pr(e){if(e.length===0)return "empty-workspace";let t=new Set(e.map(r=>r.category));return t.size>1?"polyglot-product-workspace":t.has("frontend")&&e.length>1?"full-stack-workspace":t.has("frontend")?"frontend-workspace":t.has("desktop")?"desktop-application-workspace":t.has("extension")?"extension-workspace":t.has("library")?"library-workspace":e.length>1?"backend-platform":"backend-workspace"}function Cr(e){let t=new Set;for(let r of e){let o=`${r.name} ${r.path}`.toLowerCase();for(let s of ["auth","billing","payment","notification","order","admin","report","search","analytics"])o.includes(s)&&t.add(s);}return Array.from(t).sort()}function P(e,t,r,o){return {severity:e,code:t,message:r,target:o}}function Et(e){let t=[];e.workspace.name.trim()||t.push(P("error","workspace.name.missing","Workspace name could not be resolved.","workspace")),e.workspace.type==="observed-workspace"&&t.push(P("warning","workspace.marker.missing","Workspace marker is missing; model is based on filesystem observation.","workspace.marker")),e.summary.projectCount===0&&t.push(P("warning","workspace.projects.empty","No project roots were detected in this workspace.","projects")),e.contracts.exists||t.push(P("warning","workspace.contract.missing","Workspace contract is missing; dependency and API edges may be incomplete.",e.contracts.workspaceContractPath));let r=new Map;for(let n of e.projects){let i=n.name.toLowerCase(),a=r.get(i)??[];a.push(n),r.set(i,a),n.importantFiles.length||t.push(P("warning","project.markers.missing",`Project ${n.name} has no important manifest files recorded.`,n.path));let c=f$1.isAbsolute(n.path)?n.path:f$1.resolve(e.workspace.root,n.path);W.existsSync(c)||t.push(P("warning","project.path.missing",`Registered project ${n.name} is not available at its declared path.`,n.path)),n.runtime==="unknown"&&t.push(P("warning","project.runtime.unknown",`Project ${n.name} runtime could not be confidently detected.`,n.path));let d=["test","build"];for(let l of d)n.commands.supported.includes(l)&&n.commands.unsupported.includes(l)&&t.push(P("error","project.commands.conflict",`Project ${n.name} marks ${l} as both supported and unsupported.`,n.path));let u=new Set(n.commands.fleetStages),p=new Set(n.commands.localOnly);for(let l of n.commands.fleetStages){p.has(l)&&t.push(P("error","project.commands.scope-conflict",`Project ${n.name} marks ${l} as both fleet and local-only.`,n.path));let m=n.commands.map[l];(!m||m.status!=="supported"||m.fleetEligible!==true||m.executionScope!=="fleet")&&t.push(P("error","project.commands.fleet-stage-invalid",`Project ${n.name} advertises ${l} as a fleet stage without a supported fleet capability.`,n.path));}for(let l of n.commands.localOnly){let m=n.commands.map[l];(!m||m.status!=="supported"||m.executionScope!=="local-only"||m.fleetEligible===true)&&t.push(P("error","project.commands.local-only-invalid",`Project ${n.name} advertises ${l} as local-only without a matching local-only capability.`,n.path));}for(let l of Object.values(n.commands.map))l.status==="supported"&&(l.fleetEligible===true&&!u.has(l.command)&&t.push(P("error","project.commands.fleet-stage-missing",`Project ${n.name} capability ${l.command} is fleet-eligible but missing from fleetStages.`,n.path)),l.executionScope==="local-only"&&l.fleetEligible!==true&&!p.has(l.command)&&t.push(P("error","project.commands.local-only-missing",`Project ${n.name} capability ${l.command} is local-only but missing from localOnly commands.`,n.path)));}for(let[n,i]of r.entries())i.length>1&&t.push(P("error","project.name.duplicate",`Project name "${n}" is ambiguous across ${i.length} project roots.`,i.map(a=>a.path).join(", ")));e.projectTopology&&e.graph&&c$1({...e.projectTopology,generatedAt:"<ignored>"})!==c$1({...e.graph,generatedAt:"<ignored>"})&&t.push(P("error","workspace.project-topology.alias-mismatch","Deprecated model.graph must remain structurally identical to canonical model.projectTopology during the v1 migration window.","projectTopology"));let o=t.filter(n=>n.severity==="error").length,s=t.filter(n=>n.severity==="warning").length;return {status:o>0?"failed":s>0?"warning":"passed",errors:o,warnings:s,issues:t}}function Dn(e){return Et(e)}function j(e){return e.join(".")}function Sr(e,t){let r=pe,o=e.generatedAt,s=[b({id:"workspace.name",label:"Workspace name",scope:"workspace",value:e.workspace.name,freshness:{kind:"durable",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["workspace","name"]),reason:"Workspace identity is structural metadata and changes through workspace setup."}}),b({id:"workspace.type",label:"Workspace type",scope:"workspace",value:e.identity.workspaceType,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["identity","workspaceType"]),reason:"Workspace type is derived from the current project inventory."}}),b({id:"workspace.projectCount",label:"Project count",scope:"workspace",value:e.summary.projectCount,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["summary","projectCount"]),reason:"Project count is derived from workspace discovery and should be refreshed after structural changes."}}),b({id:"workspace.runtimeFamilies",label:"Runtime families",scope:"workspace",value:e.identity.runtimeFamilies,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["identity","runtimeFamilies"]),reason:"Runtime coverage is inferred from project surfaces."}}),b({id:"workspace.policyMode",label:"Workspace policy mode",scope:"policy",value:e.policies.mode,freshness:{kind:"durable",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["policies","mode"]),reason:"Policy mode is configuration, not runtime state."}}),b({id:"workspace.contract.exists",label:"Workspace contract presence",scope:"contract",value:e.contracts.exists,freshness:{kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,sourcePath:j(["contracts","exists"]),reason:"Contract presence is derived from workspace files and should be refreshed before release gating."}})],n=We(e);n&&s.push(b({id:"graph.edgeCount",label:"Dependency graph edge count",scope:"graph",value:n.stats.edgeCount,freshness:{kind:"derived",category:"structure",generatedAt:n.generatedAt??o,now:t,sourceArtifact:r,sourcePath:j(["projectTopology","stats","edgeCount"]),reason:"Graph topology is derived from manifests, imports, and workspace contracts."}}),b({id:"graph.evidenceCoverageRatio",label:"Dependency graph evidence coverage",scope:"graph",value:n.stats.evidenceCoverageRatio,freshness:{kind:"derived",category:"structure",generatedAt:n.generatedAt??o,now:t,sourceArtifact:r,sourcePath:j(["projectTopology","stats","evidenceCoverageRatio"]),reason:"Graph evidence coverage changes when dependency evidence or contract edges change."}}));for(let[i,a]of e.projects.entries()){let c=`projects[${i}]`,d={kind:"derived",category:"structure",generatedAt:o,now:t,sourceArtifact:r,reason:"Project facts are derived from workspace discovery, project metadata, and framework probes."};s.push(b({id:`project.${a.name}.kind`,label:`${a.name} kind`,scope:"project",project:a.name,value:a.kind,freshness:{...d,sourcePath:j([c,"kind"])}}),b({id:`project.${a.name}.category`,label:`${a.name} category`,scope:"project",project:a.name,value:a.category,freshness:{...d,sourcePath:j([c,"category"])}}),b({id:`project.${a.name}.runtime`,label:`${a.name} runtime`,scope:"project",project:a.name,value:a.runtime,freshness:{...d,sourcePath:j([c,"runtime"])}}),b({id:`project.${a.name}.framework`,label:`${a.name} framework`,scope:"project",project:a.name,value:a.frameworkDisplayName,freshness:{...d,sourcePath:j([c,"frameworkDisplayName"])}}),b({id:`project.${a.name}.supportTier`,label:`${a.name} support tier`,scope:"project",project:a.name,value:a.supportTier,freshness:{...d,sourcePath:j([c,"supportTier"])}}),b({id:`project.${a.name}.safeFleetStages`,label:`${a.name} safe fleet stages`,scope:"command",project:a.name,value:a.commands.fleetStages,freshness:{...d,sourcePath:j([c,"commands","fleetStages"]),reason:"Safe command availability is derived from package and project command surfaces."}}));for(let[u,p]of Object.entries(a.evidence))s.push(b({id:`project.${a.name}.evidence.${u}`,label:`${a.name} ${u} evidence`,scope:"evidence",project:a.name,value:p?{path:p.path,exists:p.exists,status:p.status??null}:{exists:false},freshness:{kind:p?.exists?"evidence-backed":"verify-before-use",category:"verification",generatedAt:p?.generatedAt??o,now:t,status:p?.exists?void 0:"unknown",sourceArtifact:p?.path??r,sourcePath:j([c,"evidence",u]),verifyBeforeUse:true,reason:p?.exists?"Evidence reports can expire or become stale after source changes.":"Missing evidence must be generated before this fact is used for verification."}}));}for(let[i,a]of Object.entries(e.evidence))s.push(b({id:`workspace.evidence.${i}`,label:`Workspace ${i} evidence`,scope:"evidence",value:a?{path:a.path,exists:a.exists,status:a.status??null}:null,freshness:{kind:a?.exists?"evidence-backed":"verify-before-use",category:"verification",generatedAt:a?.generatedAt??o,now:t,status:a?.exists?void 0:"unknown",sourceArtifact:a?.path??r,sourcePath:j(["evidence",i]),verifyBeforeUse:true,reason:a?.exists?"Workspace evidence can expire or become stale after project, dependency, or policy changes.":"Missing workspace evidence must be generated before release or repair decisions."}}));return s}async function le(e$1){let t=f$1.resolve(e$1.workspacePath),r=e$1.includeAbsolutePaths===true,o=e$1.includeEvidence===true,s$1=xe(e$1.observableScanDepth),n=e$1.now??new Date,[i,a$3,c,d,u,p]=await Promise.all([a(t),Me(t),Ie(t),a$1(t),a$2(t,{descendIntoMatchedProjects:false}),Ae(t,s$1)]),l=new Map;for(let g of c?.projects??[]){let fe=g.externalPath?f$1.resolve(g.externalPath):f$1.resolve(t,g.relativePath);l.set(fe,g);}let m=Re([...u,...p,...l.keys(),...d.map(g=>f$1.isAbsolute(g.path)?g.path:f$1.join(t,g.path))]),v=e$1.reuseProjectModels,h=await Promise.all(m.map(g=>{if(v){let fe=f$1.relative(t,f$1.resolve(g)).split(f$1.sep).join("/"),Fe=v.get(fe);if(Fe)return Promise.resolve(Fe)}return jr(t,g,{includeAbsolutePaths:r,includeEvidence:o,contractProject:l.get(f$1.resolve(g))})})),x=typeof a$3?.workspace_name=="string"?a$3.workspace_name:typeof a$3?.name=="string"?a$3.name:i?.name||c?.workspace.name||f$1.basename(t),A=typeof a$3?.profile=="string"?a$3.profile:typeof a$3?.mode=="string"?a$3.mode:c?.workspace.profile,H=Array.from(new Set(h.map(g=>g.kind))).sort(),ue=Array.from(new Set(h.map(g=>g.category))).sort(),B=Array.from(new Set(h.flatMap(g=>g.runtimeCandidates.length>0?g.runtimeCandidates:[g.runtime]))).sort(),X=Array.from(new Set(h.map(g=>g.framework))).sort(),F=[".workspai/policies.yml",".workspai/policies.yaml",".rapidkit/policies.yml",".rapidkit/policies.yaml"].find(g=>W.existsSync(f$1.join(t,g))),Y=s(t,"workspace.contract.json").map(g=>f$1.relative(t,g).split(f$1.sep).join("/")).find(g=>W.existsSync(f$1.join(t,g)))??i$1.workspaceContract,R=await W.pathExists(f$1.join(t,Y)),Q={schemaVersion:mr,generatedAt:n.toISOString(),workspace:{name:x,root:t,...A?{profile:A}:{},type:i?"rapidkit-workspace":"observed-workspace",...i?{marker:{createdBy:i.createdBy,version:i.version,createdAt:i.createdAt}}:{}},identity:{workspaceType:Pr(h),surfaces:H,categories:ue,runtimeFamilies:B,businessCapabilities:Cr(h)},discovery:{observableScanDepth:s$1},projects:h,policies:{mode:typeof a$3?.policy_mode=="string"?a$3.policy_mode:typeof a$3?.policyMode=="string"?a$3.policyMode:"warn",source:F??null,exists:!!F},contracts:{workspaceContractPath:Y,exists:R,status:R?"known":"missing"},evidence:{doctor:await E(t,e.doctor,o),projectDoctor:await E(t,i$1.doctorProject,o),doctorRemediationPlan:await E(t,i$1.doctorRemediationPlan,o),artifactRemediationPlan:await E(t,i$1.artifactRemediationPlan,o),doctorFixResult:await E(t,i$1.doctorFixResult,o),analyze:await E(t,e.analyze,o),readiness:await E(t,e.readiness,o),pipeline:await E(t,i$1.pipelineLastRun,o)},summary:{projectCount:h.length,runtimes:B,frameworks:X,firstClassProjects:h.filter(g=>g.supportTier==="first-class").length,observedProjects:h.filter(g=>g.supportTier==="observed").length}},w=await Wt(t,Q,{contractExists:R,now:n,incrementalGraph:e$1.incrementalGraph}),C={...Q,projectTopology:w,graph:w},M=Et(C),D=Sr({...C},n),xt=bt({facts:D,generatedAt:n.toISOString(),now:n});return {...C,facts:D,factFreshness:xt,validation:M}}async function On(e){if(e.cache!==true)return {model:await le(e),cache:"disabled"};let t=f$1.resolve(e.workspacePath),r=xe(e.observableScanDepth),o=Se(),[s,n,i,a$3,c]=await Promise.all([a(t),Me(t),a$1(t),a$2(t,{descendIntoMatchedProjects:false}),Ae(t,r)]),d=Re([...a$3,...c,...i.map(h=>f$1.isAbsolute(h.path)?h.path:f$1.join(t,h.path))]),u=await ce({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:d,workspaceJson:n,marker:s}),p=await Ee(t);if(p&&p.cliVersion===o&&p.inputsHash===u&&Pt(p.model))return {model:p.model,cache:"hit"};let l=await le({...e}),[m,v]=await Promise.all([ae(t,d),ie(t)]);return await de(t,{cliVersion:o,inputsHash:u,generatedAt:(e.now??new Date).toISOString(),model:l,projectSignatures:m,workspaceFileSignatures:v}),{model:l,cache:"miss"}}function Er(e,t){let r=new Set,o=new Set,s=new Set;for(let[n,i]of Object.entries(t))n in e?e[n]!==i&&r.add(n):o.add(n);for(let n of Object.keys(e))n in t||s.add(n);return {changed:r,added:o,removed:s}}function Wr(e={},t={}){let r=new Set([...Object.keys(e),...Object.keys(t)]);for(let o of r)if(e[o]!==t[o])return false;return true}async function Gn(e){let t=f$1.resolve(e.workspacePath),r=xe(e.observableScanDepth),o=Se(),s=e.now??new Date,[n,i,a$3,c,d]=await Promise.all([a(t),Me(t),a$1(t),a$2(t,{descendIntoMatchedProjects:false}),Ae(t,r)]),u=Re([...c,...d,...a$3.map(w=>f$1.isAbsolute(w.path)?w.path:f$1.join(t,w.path))]),p=await Ee(t),l=async()=>{let w=await le({...e}),C=await ce({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:u,workspaceJson:i,marker:n}),[M,D]=await Promise.all([ae(t,u),ie(t)]);return await de(t,{cliVersion:o,inputsHash:C,generatedAt:s.toISOString(),model:w,projectSignatures:M,workspaceFileSignatures:D}),{model:w,mode:"full"}},m=p?We(p.model):void 0;if(!p||p.cliVersion!==o||!p.projectSignatures||!m||!Pt(p.model))return l();let v=await ie(t);if(!Wr(p.workspaceFileSignatures,v))return l();let h=await ae(t,u),{changed:x,added:A,removed:H}=Er(p.projectSignatures,h);if(x.size===0&&A.size===0&&H.size===0)return {model:p.model,mode:"unchanged"};let ue=new Set([...x,...A]),B=new Map;for(let w of p.model.projects){let C=w.path.split(f$1.sep).join("/");!ue.has(C)&&!H.has(C)&&B.set(C,w);}let X=new Set,F=false;for(let w of p.model.projects){let C=w.path.split(f$1.sep).join("/");x.has(C)&&X.add(w.name);}let Y=A.size>0||H.size>0,R=await le({...e,reuseProjectModels:B,incrementalGraph:{previousGraph:m,changedProjectIds:X,structuralChange:Y||F}});for(let w of p.model.projects){let C=w.path.split(f$1.sep).join("/");if(!x.has(C))continue;let M=R.projects.find(D=>D.path.split(f$1.sep).join("/")===C);if(M&&M.name!==w.name){F=true;break}}if(F)return l();let Q=await ce({workspacePath:t,cliVersion:o,flags:{includeAbsolutePaths:e.includeAbsolutePaths===true,includeEvidence:e.includeEvidence===true,observableScanDepth:r},projectPaths:u,workspaceJson:i,marker:n});return await de(t,{cliVersion:o,inputsHash:Q,generatedAt:s.toISOString(),model:R,projectSignatures:h,workspaceFileSignatures:v}),{model:R,mode:"incremental"}}async function Ie(e){try{let{contract:t}=await m({workspacePath:e});return t&&typeof t=="object"?t:null}catch{return null}}async function Wt(e,t,r){let o=r.contractExists?await Ie(e):null;try{return r.incrementalGraph?await kt({workspacePath:e,model:t,contract:o,now:r.now,previousGraph:r.incrementalGraph.previousGraph,changedProjectIds:r.incrementalGraph.changedProjectIds,structuralChange:r.incrementalGraph.structuralChange}):await ht({workspacePath:e,model:t,contract:o,now:r.now})}catch{let s=t.projects.map(n=>({id:n.name,path:n.path}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:r.now.toISOString(),nodes:s,edges:[],stats:{nodeCount:s.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:s.length,connectedNodeCount:0,density:0,edgeCoverageRatio:s.length>0?0:1,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:s.length>1?[{code:"graph.inference.failed",severity:"warning",message:"Dependency graph inference failed; model contains projects but no dependency edges.",recommendation:"Run workspace model again after fixing graph inputs, or add workspace contract/manual graph overrides.",nodeIds:s.map(n=>n.id).sort((n,i)=>n.localeCompare(i))}]:void 0}}}async function _n(e$1,t){let r=e$1.contracts.exists?await Ie(t):null,{buildWorkspaceKnowledgeGraph:o}=await import('./workspace-knowledge-graph-HZZP6ZRB.js'),s=a$3(e$1),n=await o({workspacePath:t,workspace:{name:e$1.workspace.name,...e$1.workspace.profile?{profile:e$1.workspace.profile}:{}},projects:e$1.projects.map(a=>({id:a.name,path:a.path,...a.absolutePath?{absolutePath:a.absolutePath}:{},runtime:a.runtime,runtimeCandidates:a.runtimeCandidates,framework:a.framework,kind:a.kind,category:a.category,...a.kit?{kit:a.kit}:{}})),projectTopology:We(e$1)??await Wt(t,e$1,{contractExists:e$1.contracts.exists,now:new Date(e$1.generatedAt)}),contract:r,now:new Date(e$1.generatedAt),source:{kind:"workspace-model",artifact:pe,hashAlgorithm:"sha256",hash:d(s)}}),[,i]=await f$2(t,pe,[{relativePath:e.knowledgeGraph,payload:n},{relativePath:pe,payload:s}]);return i}export{nt as a,ot as b,st as c,Gr as d,$r as e,V as f,vt as g,b as h,bt as i,mr as j,pe as k,We as l,Fn as m,Dn as n,Sr as o,le as p,On as q,Gn as r,_n as s};
@@ -1 +1 @@
1
- import {b,c,d as d$1}from'./chunk-A3JCETSF.js';import {a as a$1,b as b$1}from'./chunk-PYCJWW4B.js';import {c as c$2}from'./chunk-WSDVFLHT.js';import {c as c$1,d as d$4}from'./chunk-C4NYG57I.js';import {p as p$1,a,o,g,d as d$3,f as f$1}from'./chunk-VAWV3UKV.js';import {a as a$4}from'./chunk-X7FYEKLI.js';import {p,l,f as f$2}from'./chunk-AUCHMXUZ.js';import {d}from'./chunk-EWZZUQBR.js';import {a as a$2}from'./chunk-EEMRRCGR.js';import {d as d$2,e as e$1}from'./chunk-GRGUPSNP.js';import {a as a$3}from'./chunk-AFIFZTOY.js';import {f,e,i,g as g$1,h}from'./chunk-HH54C3XJ.js';import m from'path';import v from'fs-extra';var fe="rapidkit-blocker-resolution-v1";function pe(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return f$2({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function we(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function me(e){let t=we(e.reason),r=pe({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",...e.sourceCommand?{}:{studioActionId:"run-analyze"}}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:fe,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?e.sourceCommand?`Run the source command once: ${e.sourceCommand}, then verify.`:"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function Re(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function Ce(e){return e.length===0||e.every(t=>Re(t))}function ge(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&Ce(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function tt(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var ye=f.verify,G=e.verify;function Ae(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ke(e){let t=await v.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f$1)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$3(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$3(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let o=s.transitiveImpact.reduce((u,d)=>Math.max(u,d.distance??0),0);s.summary.blastRadius.maxDistance!==o&&i.push("blastRadius.maxDistance does not match transitive impact distances");let k=l(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==k&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function Ee(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Se(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function We(e$1,t){if(e$1.id==="workspace.doctor")return m.join(t,e.doctor);if(e$1.id==="workspace.contract.verify")return m.join(t,e.contractVerify);if(e$1.id==="workspace.readiness")return m.join(t,e.readiness);if(e$1.id==="workspace.analyze")return m.join(t,".workspai","reports","analyze-last-run.json");if(e$1.id==="workspace.pipeline")return m.join(t,".workspai","reports","pipeline-last-run.json");if(e$1.id==="workspace.doctor-fix")return m.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e$1.id.startsWith("project.")&&e$1.id.includes("."))return m.join(t,".workspai","reports","workspace-run-last.json")}function C(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function je(e){if(!c$1(e,"workspace"))return {status:"fail",message:"Doctor evidence contract is missing or unsupported."};try{d$4(e);}catch(s){return {status:"fail",message:`Doctor evidence semantic validation failed: ${s instanceof Error?s.message:String(s)}`}}let t=a$4(e);return t.hasSystemErrors||t.blockingFindings>0?{status:"fail",message:`Doctor evidence reports ${t.blockingFindings} canonical blocking finding(s).`}:t.advisoryFindings+t.unknownFindings+t.contradictionCount+t.missingDiagnosisProjects>0||t.staleEvidence||t.unknownFreshness||t.minimumDiagnosisCompleteness<100?{status:"warn",message:`Doctor evidence needs attention (${t.advisoryFindings} advisory, ${t.unknownFindings} unknown, ${t.contradictionCount} contradictory; ${t.minimumDiagnosisCompleteness}% complete).`}:{status:"pass",message:"Canonical Doctor evidence is complete, fresh, and healthy."}}function xe(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function Pe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Ie(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function Ve(e){let t=e.schemaVersion===h.doctorFixResult.schemaVersion?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s.length>0)return {status:"fail",message:`Doctor fix result reports ${s.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function Fe(e,t){let r=await d$2(e,i.doctorRemediationPlan);if(!r)return false;try{let s=C(await v.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let o=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!o||!t)return true;let k=Date.parse(o),u=Date.parse(t);return !Number.isFinite(k)||!Number.isFinite(u)?true:k>=u}catch{return false}}function $e(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Oe(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function De(e,t,r){let s=$e(t),i=c$2(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let o=i.stage;if(s&&o!==s)return {status:"missing",message:`Workspace run evidence is for stage "${o}", expected "${s}".`};let k=Array.isArray(i.projects)?i.projects:[],u=t.project?.toLowerCase();if(!u)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=k.find(g=>{let c=C(g);if(!c)return false;let n=typeof c.projectName=="string"?c.projectName.toLowerCase():"",a=["projectPath","relativePath","path"].map(f=>c[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return n===u||a.some(f=>f.endsWith(`/${u}`)||f===u)});if(d){let g=R(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(g)return {status:"fail",message:g};let c=C(d),n=typeof c?.status=="string"?c.status:"unknown";return n==="failed"?{status:"fail",message:`Workspace run evidence failed for ${t.project}.`}:n==="passed"?{status:"pass",message:`Workspace run evidence passed for ${t.project}.`}:n==="skipped"?{status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}:{status:"warn",message:`Workspace run evidence status is ${n} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function R(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function Be(e){if(e.id==="workspace.doctor")return g$1.doctor;if(e.id==="workspace.readiness")return g$1.readiness;if(e.id==="workspace.contract.verify")return g$1.contractVerify;if(e.id==="workspace.analyze")return g$1.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function _e(e,t,r,s){let i=We(e,t),o=i?m.relative(t,i).split(m.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let k=i?await d$2(t,o??""):null;if(!i||!k)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:o,message:o?`Missing evidence report: ${o}`:"No evidence mapping exists for this command."};let u;try{u=await v.readJson(k);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=C(u);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:"Evidence report is not a JSON object."};let g=Be(e);if(g)try{a$3(d,g,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=R(d.generatedAt,s,"Doctor evidence");n?c={status:"fail",message:n}:c=je(d);}else if(e.id==="workspace.readiness"){let n=R(d.generatedAt,s,"Release readiness evidence");n?c={status:"fail",message:n}:c=xe(d);}else if(e.id==="workspace.contract.verify"){let n=R(d.generatedAt,s,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=Pe(d);}else if(e.id==="workspace.analyze"){let n=R(d.generatedAt,s,"Analyze evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.pipeline"){let n=R(d.generatedAt,s,"Pipeline evidence");n?c={status:"fail",message:n}:c=Oe(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion===h.doctorFixResult.schemaVersion?d:d.fixResult,a=C(n),f=typeof a?.generatedAt=="string"?a.generatedAt:void 0,y=R(f,s,"Doctor fix result");y?c={status:"fail",message:y}:await Fe(t,f)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=Ve(d);}else if(e.id.startsWith("project."))c=De(d,e,s);else {let n=R(d.generatedAt,s,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:o,message:c.message}}function Ne(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,o=e.filter(n=>n.status==="missing").length,k=e.filter(n=>n.status==="skipped").length,u=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,g="ready",c=0;return u.length>0||t.blockingReasons.length>0?(g="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(g="needs-attention",c=1),{verdict:g,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:o,stepsSkipped:k}}function He(e,t){let r=x(e.affectedProjects.map(a=>a.project?.name).filter(a=>typeof a=="string")),s=new Set(r.map(a=>a.toLowerCase())),i=x(e.transitiveImpact.map(a=>a.project?.name).filter(a=>typeof a=="string").filter(a=>!s.has(a.toLowerCase()))),o=new Map;for(let a of t){if(a.scope!=="project"||!a.project)continue;let f=a.project.toLowerCase(),y=o.get(f)??[];y.push(a),o.set(f,y);}let k=[],u=[],d=[],g=[],c=false,n=(a,f)=>{let y=o.get(a.toLowerCase())??[];if(y.length===0){d.push(a);return}let P=y.filter(p=>p.status==="fail"),b=P.filter(p=>p.required),I=y.filter(p=>p.status==="missing"),E=I.filter(p=>p.required),V=y.some(p=>p.status==="pass"||p.status==="warn");if(b.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has failed verification evidence (${b.map(p=>p.id).join(", ")}).`);return}if(P.length>0){u.push(a),c=true;return}if(E.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has missing required verification evidence (${E.map(p=>p.id).join(", ")}).`);return}if(I.length>0){u.push(a),c=true;return}if(V){k.push(a);return}d.push(a);};for(let a of r)n(a,"directly-changed");for(let a of i)n(a,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:x(k),uncovered:x(u),unverifiable:x(d)},blockingReasons:g,needsAttention:c}}function x(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function Me(e$1){let t=m.resolve(e$1.workspacePath);if(e$1.fromImpactPath){let o=Ae(t,e$1.fromImpactPath);return {impact:await ke(o),fromImpactRef:m.relative(t,o).split(m.sep).join("/"),impactFromDisk:true}}let r=m.join(t,g);if(await v.pathExists(r))return {impact:await ke(r),fromImpactRef:g,impactFromDisk:true};let s=m.join(t,d$3);if(await v.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$3,scope:e$1.scope,includeAbsolutePaths:e$1.includeAbsolutePaths,includeEvidence:e$1.includeEvidence,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),fromImpactRef:d$3,impactFromDisk:false};let i=await p({workspacePath:t,includeAbsolutePaths:e$1.includeAbsolutePaths,includeEvidence:e$1.includeEvidence,observableScanDepth:e$1.observableScanDepth,now:e$1.now});return {impact:{schemaVersion:f$1,generatedAt:(e$1.now??new Date).toISOString(),fromRef:"baseline",diffRef:e.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:l(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:f.diff,generatedAt:(e$1.now??new Date).toISOString(),fromRef:"baseline",toRef:e.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function Te(e,t){if(t)return e.generatedAt}async function bt(e){let t=m.resolve(e.workspacePath),{impact:r,fromImpactRef:s,impactFromDisk:i}=await Me(e),o$1=r.diff.currentModel,k=i?await p({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):o$1,u=[];if(i){let l=await p$1({workspacePath:t,fromPath:r.diff.fromRef,diff:r.diff,scope:e.scope,now:e.now}),W=[r.affectedProjects,r.transitiveImpact,r.verificationPlan],A=[l.affectedProjects,l.transitiveImpact,l.verificationPlan];JSON.stringify(W)!==JSON.stringify(A)&&u.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(k)!==r.diff.toHash&&u.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r.diff.git;if(i&&d$2?.available){let l=a(t,{ref:d$2.ref}),W=r.diff.changes.filter(h=>h.type.startsWith("git.")).map(h=>`${h.type}:${h.target.replace(/^git:/,"")}`).sort(),A=[...l.changedFiles.map(h=>`git.file.changed:${h}`),...l.untrackedFiles.map(h=>`git.untracked:${h}`),...l.deletedFiles.map(h=>`git.deleted:${h}`)].sort();(!l.available||l.commit!==d$2.commit||JSON.stringify(A)!==JSON.stringify(W))&&u.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let g=Te(r,i),c$1=Ee([...o(),...r.verificationPlan]).filter(l=>Se(e.scope,l)),n=[];for(let l of c$1)n.push(await _e(l,t,o$1.contracts.exists===true,g));let a$2=He(r,n),f=a$1(l(o$1)??{nodes:[],edges:[]}),y=b(o$1),P=await Ke(t),b$2=c(y,P?.freshness?.projectHashes),I={verdict:b$2.verdict,baseline:b$2.baseline,changed:b$2.changed,added:b$2.added,removed:b$2.removed,projectHashes:d$1(y)},E=b$1(f),V=o$1.policies?.mode??"warn",p$2=await Le(o$1,t),B=qe(V,p$2),S=Ne(n,{blockingReasons:[...a$2.blockingReasons,...E,...B.blockingReasons,...u],needsAttention:a$2.needsAttention||B.needsAttention}),he=n.filter(l=>l.status==="missing"&&l.evidencePath).map(l=>l.evidencePath),_=[...n.filter(l=>l.required&&(l.status==="fail"||l.status==="missing")).map(l=>`${l.id}: ${l.message}`),...a$2.blockingReasons,...E,...B.blockingReasons,...u],ve=p$2.filter(l=>l.severity==="error").length,be=o$1.summary?.projectCount??o$1.projects.length,U=ge({projectCount:be,verdict:S.verdict,exitCode:S.exitCode,blockingReasons:_,policyErrorCount:ve});S.verdict=U.verdict,S.exitCode=U.exitCode;let Y=Array.from(new Set(_.map(l=>l.trim()).filter(Boolean))).slice(0,12).map((l,W)=>{let A=n.find(h=>l.startsWith(`${h.id}:`));return me({reason:l,blockerId:`blocker-${W+1}`,sourceCommand:A?.command.display,sourceArtifact:A?.evidencePath,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:G})});return {schemaVersion:ye,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r.summary.changed,risk:r.summary.risk,affectedProjects:r.summary.affectedProjects,recommendedCommands:r.summary.recommendedCommands},summary:S,steps:n,missingEvidence:he,blockingReasons:_,...Y.length>0?{resolutionHints:Y}:{},verificationPlan:c$1,affectedSubgraph:a$2.subgraph,graphIntegrity:f,freshness:I,policyMode:V,policyViolations:p$2}}async function Le(e$1,t){let r=[];for(let i of e$1.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await d$2(t,e.contractVerify);try{if(s&&await v.pathExists(s)){let i=await v.readJson(s);if(Array.isArray(i.violations))for(let o of i.violations)typeof o=="string"&&o.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:o});}}catch{}return r.sort((i,o)=>i.source!==o.source?i.source.localeCompare(o.source):i.code!==o.code?i.code.localeCompare(o.code):i.message.localeCompare(o.message))}function qe(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function Ke(e){let t=m.join(e,G);try{if(!await v.pathExists(t))return null;let r=await v.readJson(t);return r&&r.schemaVersion===ye?r:null}catch{return null}}async function wt(e,t){return e$1(t,G,a$2(e))}function ze(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function Rt(e,t){return ze(e,t).exitCode}export{fe as a,tt as b,ye as c,G as d,He as e,bt as f,wt as g,ze as h,Rt as i};
1
+ import {b,c,d as d$1}from'./chunk-QMPFNXI7.js';import {c as c$2}from'./chunk-W6FHVXNL.js';import {a as a$4}from'./chunk-X7FYEKLI.js';import {c as c$1,d as d$4}from'./chunk-HCFWT42C.js';import {a as a$1,b as b$1}from'./chunk-PYCJWW4B.js';import {p as p$1,a,o,g,d as d$3,f as f$1}from'./chunk-OFWSZYUX.js';import {p,l,f as f$2}from'./chunk-WSRUPDZN.js';import {d}from'./chunk-EWZZUQBR.js';import {a as a$2}from'./chunk-SP5EHSWG.js';import {d as d$2,e as e$1}from'./chunk-CCDGHPEJ.js';import {a as a$3}from'./chunk-AFIFZTOY.js';import {f,e,i,g as g$1,h}from'./chunk-NZ3WZYD5.js';import m from'path';import v from'fs-extra';var fe="rapidkit-blocker-resolution-v1";function pe(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return f$2({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function we(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function me(e){let t=we(e.reason),r=pe({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",...e.sourceCommand?{}:{studioActionId:"run-analyze"}}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:fe,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?e.sourceCommand?`Run the source command once: ${e.sourceCommand}, then verify.`:"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function Re(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function Ce(e){return e.length===0||e.every(t=>Re(t))}function ge(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&Ce(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function tt(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var ye=f.verify,G=e.verify;function Ae(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ke(e){let t=await v.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f$1)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$3(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$3(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let o=s.transitiveImpact.reduce((u,d)=>Math.max(u,d.distance??0),0);s.summary.blastRadius.maxDistance!==o&&i.push("blastRadius.maxDistance does not match transitive impact distances");let k=l(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==k&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function Ee(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Se(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function We(e$1,t){if(e$1.id==="workspace.doctor")return m.join(t,e.doctor);if(e$1.id==="workspace.contract.verify")return m.join(t,e.contractVerify);if(e$1.id==="workspace.readiness")return m.join(t,e.readiness);if(e$1.id==="workspace.analyze")return m.join(t,".workspai","reports","analyze-last-run.json");if(e$1.id==="workspace.pipeline")return m.join(t,".workspai","reports","pipeline-last-run.json");if(e$1.id==="workspace.doctor-fix")return m.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e$1.id.startsWith("project.")&&e$1.id.includes("."))return m.join(t,".workspai","reports","workspace-run-last.json")}function C(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function je(e){if(!c$1(e,"workspace"))return {status:"fail",message:"Doctor evidence contract is missing or unsupported."};try{d$4(e);}catch(s){return {status:"fail",message:`Doctor evidence semantic validation failed: ${s instanceof Error?s.message:String(s)}`}}let t=a$4(e);return t.hasSystemErrors||t.blockingFindings>0?{status:"fail",message:`Doctor evidence reports ${t.blockingFindings} canonical blocking finding(s).`}:t.advisoryFindings+t.unknownFindings+t.contradictionCount+t.missingDiagnosisProjects>0||t.staleEvidence||t.unknownFreshness||t.minimumDiagnosisCompleteness<100?{status:"warn",message:`Doctor evidence needs attention (${t.advisoryFindings} advisory, ${t.unknownFindings} unknown, ${t.contradictionCount} contradictory; ${t.minimumDiagnosisCompleteness}% complete).`}:{status:"pass",message:"Canonical Doctor evidence is complete, fresh, and healthy."}}function xe(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function Pe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Ie(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function Ve(e){let t=e.schemaVersion===h.doctorFixResult.schemaVersion?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s.length>0)return {status:"fail",message:`Doctor fix result reports ${s.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function Fe(e,t){let r=await d$2(e,i.doctorRemediationPlan);if(!r)return false;try{let s=C(await v.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let o=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!o||!t)return true;let k=Date.parse(o),u=Date.parse(t);return !Number.isFinite(k)||!Number.isFinite(u)?true:k>=u}catch{return false}}function $e(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Oe(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function De(e,t,r){let s=$e(t),i=c$2(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let o=i.stage;if(s&&o!==s)return {status:"missing",message:`Workspace run evidence is for stage "${o}", expected "${s}".`};let k=Array.isArray(i.projects)?i.projects:[],u=t.project?.toLowerCase();if(!u)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=k.find(g=>{let c=C(g);if(!c)return false;let n=typeof c.projectName=="string"?c.projectName.toLowerCase():"",a=["projectPath","relativePath","path"].map(f=>c[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return n===u||a.some(f=>f.endsWith(`/${u}`)||f===u)});if(d){let g=R(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(g)return {status:"fail",message:g};let c=C(d),n=typeof c?.status=="string"?c.status:"unknown";return n==="failed"?{status:"fail",message:`Workspace run evidence failed for ${t.project}.`}:n==="passed"?{status:"pass",message:`Workspace run evidence passed for ${t.project}.`}:n==="skipped"?{status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}:{status:"warn",message:`Workspace run evidence status is ${n} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function R(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function Be(e){if(e.id==="workspace.doctor")return g$1.doctor;if(e.id==="workspace.readiness")return g$1.readiness;if(e.id==="workspace.contract.verify")return g$1.contractVerify;if(e.id==="workspace.analyze")return g$1.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function _e(e,t,r,s){let i=We(e,t),o=i?m.relative(t,i).split(m.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let k=i?await d$2(t,o??""):null;if(!i||!k)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:o,message:o?`Missing evidence report: ${o}`:"No evidence mapping exists for this command."};let u;try{u=await v.readJson(k);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=C(u);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:"Evidence report is not a JSON object."};let g=Be(e);if(g)try{a$3(d,g,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=R(d.generatedAt,s,"Doctor evidence");n?c={status:"fail",message:n}:c=je(d);}else if(e.id==="workspace.readiness"){let n=R(d.generatedAt,s,"Release readiness evidence");n?c={status:"fail",message:n}:c=xe(d);}else if(e.id==="workspace.contract.verify"){let n=R(d.generatedAt,s,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=Pe(d);}else if(e.id==="workspace.analyze"){let n=R(d.generatedAt,s,"Analyze evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.pipeline"){let n=R(d.generatedAt,s,"Pipeline evidence");n?c={status:"fail",message:n}:c=Oe(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion===h.doctorFixResult.schemaVersion?d:d.fixResult,a=C(n),f=typeof a?.generatedAt=="string"?a.generatedAt:void 0,y=R(f,s,"Doctor fix result");y?c={status:"fail",message:y}:await Fe(t,f)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=Ve(d);}else if(e.id.startsWith("project."))c=De(d,e,s);else {let n=R(d.generatedAt,s,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:o,message:c.message}}function Ne(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,o=e.filter(n=>n.status==="missing").length,k=e.filter(n=>n.status==="skipped").length,u=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,g="ready",c=0;return u.length>0||t.blockingReasons.length>0?(g="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(g="needs-attention",c=1),{verdict:g,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:o,stepsSkipped:k}}function He(e,t){let r=x(e.affectedProjects.map(a=>a.project?.name).filter(a=>typeof a=="string")),s=new Set(r.map(a=>a.toLowerCase())),i=x(e.transitiveImpact.map(a=>a.project?.name).filter(a=>typeof a=="string").filter(a=>!s.has(a.toLowerCase()))),o=new Map;for(let a of t){if(a.scope!=="project"||!a.project)continue;let f=a.project.toLowerCase(),y=o.get(f)??[];y.push(a),o.set(f,y);}let k=[],u=[],d=[],g=[],c=false,n=(a,f)=>{let y=o.get(a.toLowerCase())??[];if(y.length===0){d.push(a);return}let P=y.filter(p=>p.status==="fail"),b=P.filter(p=>p.required),I=y.filter(p=>p.status==="missing"),E=I.filter(p=>p.required),V=y.some(p=>p.status==="pass"||p.status==="warn");if(b.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has failed verification evidence (${b.map(p=>p.id).join(", ")}).`);return}if(P.length>0){u.push(a),c=true;return}if(E.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has missing required verification evidence (${E.map(p=>p.id).join(", ")}).`);return}if(I.length>0){u.push(a),c=true;return}if(V){k.push(a);return}d.push(a);};for(let a of r)n(a,"directly-changed");for(let a of i)n(a,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:x(k),uncovered:x(u),unverifiable:x(d)},blockingReasons:g,needsAttention:c}}function x(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function Me(e$1){let t=m.resolve(e$1.workspacePath);if(e$1.fromImpactPath){let o=Ae(t,e$1.fromImpactPath);return {impact:await ke(o),fromImpactRef:m.relative(t,o).split(m.sep).join("/"),impactFromDisk:true}}let r=m.join(t,g);if(await v.pathExists(r))return {impact:await ke(r),fromImpactRef:g,impactFromDisk:true};let s=m.join(t,d$3);if(await v.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$3,scope:e$1.scope,includeAbsolutePaths:e$1.includeAbsolutePaths,includeEvidence:e$1.includeEvidence,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),fromImpactRef:d$3,impactFromDisk:false};let i=await p({workspacePath:t,includeAbsolutePaths:e$1.includeAbsolutePaths,includeEvidence:e$1.includeEvidence,observableScanDepth:e$1.observableScanDepth,now:e$1.now});return {impact:{schemaVersion:f$1,generatedAt:(e$1.now??new Date).toISOString(),fromRef:"baseline",diffRef:e.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:l(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:f.diff,generatedAt:(e$1.now??new Date).toISOString(),fromRef:"baseline",toRef:e.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function Te(e,t){if(t)return e.generatedAt}async function bt(e){let t=m.resolve(e.workspacePath),{impact:r,fromImpactRef:s,impactFromDisk:i}=await Me(e),o$1=r.diff.currentModel,k=i?await p({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):o$1,u=[];if(i){let l=await p$1({workspacePath:t,fromPath:r.diff.fromRef,diff:r.diff,scope:e.scope,now:e.now}),W=[r.affectedProjects,r.transitiveImpact,r.verificationPlan],A=[l.affectedProjects,l.transitiveImpact,l.verificationPlan];JSON.stringify(W)!==JSON.stringify(A)&&u.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(k)!==r.diff.toHash&&u.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r.diff.git;if(i&&d$2?.available){let l=a(t,{ref:d$2.ref}),W=r.diff.changes.filter(h=>h.type.startsWith("git.")).map(h=>`${h.type}:${h.target.replace(/^git:/,"")}`).sort(),A=[...l.changedFiles.map(h=>`git.file.changed:${h}`),...l.untrackedFiles.map(h=>`git.untracked:${h}`),...l.deletedFiles.map(h=>`git.deleted:${h}`)].sort();(!l.available||l.commit!==d$2.commit||JSON.stringify(A)!==JSON.stringify(W))&&u.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let g=Te(r,i),c$1=Ee([...o(),...r.verificationPlan]).filter(l=>Se(e.scope,l)),n=[];for(let l of c$1)n.push(await _e(l,t,o$1.contracts.exists===true,g));let a$2=He(r,n),f=a$1(l(o$1)??{nodes:[],edges:[]}),y=b(o$1),P=await Ke(t),b$2=c(y,P?.freshness?.projectHashes),I={verdict:b$2.verdict,baseline:b$2.baseline,changed:b$2.changed,added:b$2.added,removed:b$2.removed,projectHashes:d$1(y)},E=b$1(f),V=o$1.policies?.mode??"warn",p$2=await Le(o$1,t),B=qe(V,p$2),S=Ne(n,{blockingReasons:[...a$2.blockingReasons,...E,...B.blockingReasons,...u],needsAttention:a$2.needsAttention||B.needsAttention}),he=n.filter(l=>l.status==="missing"&&l.evidencePath).map(l=>l.evidencePath),_=[...n.filter(l=>l.required&&(l.status==="fail"||l.status==="missing")).map(l=>`${l.id}: ${l.message}`),...a$2.blockingReasons,...E,...B.blockingReasons,...u],ve=p$2.filter(l=>l.severity==="error").length,be=o$1.summary?.projectCount??o$1.projects.length,U=ge({projectCount:be,verdict:S.verdict,exitCode:S.exitCode,blockingReasons:_,policyErrorCount:ve});S.verdict=U.verdict,S.exitCode=U.exitCode;let Y=Array.from(new Set(_.map(l=>l.trim()).filter(Boolean))).slice(0,12).map((l,W)=>{let A=n.find(h=>l.startsWith(`${h.id}:`));return me({reason:l,blockerId:`blocker-${W+1}`,sourceCommand:A?.command.display,sourceArtifact:A?.evidencePath,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:G})});return {schemaVersion:ye,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r.summary.changed,risk:r.summary.risk,affectedProjects:r.summary.affectedProjects,recommendedCommands:r.summary.recommendedCommands},summary:S,steps:n,missingEvidence:he,blockingReasons:_,...Y.length>0?{resolutionHints:Y}:{},verificationPlan:c$1,affectedSubgraph:a$2.subgraph,graphIntegrity:f,freshness:I,policyMode:V,policyViolations:p$2}}async function Le(e$1,t){let r=[];for(let i of e$1.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await d$2(t,e.contractVerify);try{if(s&&await v.pathExists(s)){let i=await v.readJson(s);if(Array.isArray(i.violations))for(let o of i.violations)typeof o=="string"&&o.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:o});}}catch{}return r.sort((i,o)=>i.source!==o.source?i.source.localeCompare(o.source):i.code!==o.code?i.code.localeCompare(o.code):i.message.localeCompare(o.message))}function qe(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function Ke(e){let t=m.join(e,G);try{if(!await v.pathExists(t))return null;let r=await v.readJson(t);return r&&r.schemaVersion===ye?r:null}catch{return null}}async function wt(e,t){return e$1(t,G,a$2(e))}function ze(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function Rt(e,t){return ze(e,t).exitCode}export{fe as a,tt as b,ye as c,G as d,He as e,bt as f,wt as g,ze as h,Rt as i};
@@ -1,4 +1,4 @@
1
- import {a as a$1}from'./chunk-JEI6BTZI.js';import {a}from'./chunk-7KXRA5ST.js';import {c,e,d}from'./chunk-N3DFX4BY.js';import {d as d$1,b}from'./chunk-GVS5OFUB.js';import {g}from'./chunk-VAWV3UKV.js';import {p as p$1,l}from'./chunk-AUCHMXUZ.js';import {m,a as a$2}from'./chunk-EEMRRCGR.js';import {e as e$1}from'./chunk-GRGUPSNP.js';import {b as b$2}from'./chunk-T63WRURN.js';import {a as a$3}from'./chunk-AFIFZTOY.js';import v from'path';import b$1 from'fs-extra';function J(e$1){switch(e$1){case "why":return d;case "trace":return e;default:return c}}async function P(e,o,n){try{if(!await b$1.pathExists(e))return null;let r=await b$1.readJson(e);return o?b$2(o,r,e):n&&a$3(r,n,e),r}catch(r){if((o||n)&&await b$1.pathExists(e))throw r;return null}}function G(e,o){if(!e)return null;let n=o.trim().toLowerCase();return e.projects.find(r=>r.slug.toLowerCase()===n||r.relativePath.toLowerCase()===n)??null}function X(e,o,n){let r=n.trim().toLowerCase(),t=(l(e)?.nodes.map(a=>a.id)??e.projects.map(a=>a.name)).find(a=>a.toLowerCase()===r);if(t)return t;let d=e.projects.find(a=>[a.name,a.path,v.basename(a.path)].filter(u=>u.trim().length>0).some(u=>u.toLowerCase()===r));if(d)return d.name;let c=G(o,n);if(c){let a=e.projects.find(u=>u.path===c.relativePath||u.path.endsWith(`/${c.relativePath}`));if(a)return a.name}return n}function Y(e,o){if(!e)return [];let n=o.trim().toLowerCase(),r=new Set;for(let l of e.projects){l.contracts.dependsOn?.some(t=>t.toLowerCase()===n)&&r.add(l.slug);for(let t of l.contracts.consumes??[])for(let d of e.projects)d.contracts.publishes?.includes(t)&&d.slug===n&&r.add(l.slug);}return [...r].sort()}function q(e,o){if(!e)return [];let n=o.trim().toLowerCase();return e.steps.filter(r=>r.scope==="project"&&r.project?.toLowerCase()===n&&r.command?.display).map(r=>r.command.display).slice(0,8)}function p(e,o,n){return {id:e,title:o,body:n.trim()}}async function fe(e){let o=v.resolve(e.workspacePath),n=(e.now??new Date).toISOString(),r=e.model??await p$1({workspacePath:o,includeEvidence:true}),l$1=e.contract;if(l$1===void 0)try{l$1=(await m({workspacePath:o})).contract;}catch{l$1=null;}let t=e.verify;t===void 0&&(t=await P(v.join(o,d$1),d$1));let d=e.impact;if(d===void 0&&(d=await P(v.join(o,g),g)),e.target.kind==="release-blocked"){let s=t?.blockingReasons??[],i=(r.summary?.projectCount??r.projects.length)===0,g=[p("verdict",i?"Workspace scaffold posture":"Release verdict",t?i?`Scaffold posture: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Freshness: **${t.freshness.verdict}**. No registered projects yet \u2014 release gates apply after the first project is added.`:`Verdict: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Risk: **${t.impact.risk}**. Freshness: **${t.freshness.verdict}**.`:"No workspace verify report found. Run `npx workspai workspace verify --json --write` first."),p("blockers",i?"Pre-project signals":"Blocking reasons",s.length?s.map(h=>`- ${h}`).join(`
1
+ import {a as a$1}from'./chunk-JEI6BTZI.js';import {a}from'./chunk-PXWKMPPI.js';import {c,e,d}from'./chunk-KBR4Y4RW.js';import {d as d$1,b}from'./chunk-YEEAWZWI.js';import {g}from'./chunk-OFWSZYUX.js';import {p as p$1,l}from'./chunk-WSRUPDZN.js';import {m,a as a$2}from'./chunk-SP5EHSWG.js';import {e as e$1}from'./chunk-CCDGHPEJ.js';import {b as b$2}from'./chunk-D65FCQIO.js';import {a as a$3}from'./chunk-AFIFZTOY.js';import v from'path';import b$1 from'fs-extra';function J(e$1){switch(e$1){case "why":return d;case "trace":return e;default:return c}}async function P(e,o,n){try{if(!await b$1.pathExists(e))return null;let r=await b$1.readJson(e);return o?b$2(o,r,e):n&&a$3(r,n,e),r}catch(r){if((o||n)&&await b$1.pathExists(e))throw r;return null}}function G(e,o){if(!e)return null;let n=o.trim().toLowerCase();return e.projects.find(r=>r.slug.toLowerCase()===n||r.relativePath.toLowerCase()===n)??null}function X(e,o,n){let r=n.trim().toLowerCase(),t=(l(e)?.nodes.map(a=>a.id)??e.projects.map(a=>a.name)).find(a=>a.toLowerCase()===r);if(t)return t;let d=e.projects.find(a=>[a.name,a.path,v.basename(a.path)].filter(u=>u.trim().length>0).some(u=>u.toLowerCase()===r));if(d)return d.name;let c=G(o,n);if(c){let a=e.projects.find(u=>u.path===c.relativePath||u.path.endsWith(`/${c.relativePath}`));if(a)return a.name}return n}function Y(e,o){if(!e)return [];let n=o.trim().toLowerCase(),r=new Set;for(let l of e.projects){l.contracts.dependsOn?.some(t=>t.toLowerCase()===n)&&r.add(l.slug);for(let t of l.contracts.consumes??[])for(let d of e.projects)d.contracts.publishes?.includes(t)&&d.slug===n&&r.add(l.slug);}return [...r].sort()}function q(e,o){if(!e)return [];let n=o.trim().toLowerCase();return e.steps.filter(r=>r.scope==="project"&&r.project?.toLowerCase()===n&&r.command?.display).map(r=>r.command.display).slice(0,8)}function p(e,o,n){return {id:e,title:o,body:n.trim()}}async function fe(e){let o=v.resolve(e.workspacePath),n=(e.now??new Date).toISOString(),r=e.model??await p$1({workspacePath:o,includeEvidence:true}),l$1=e.contract;if(l$1===void 0)try{l$1=(await m({workspacePath:o})).contract;}catch{l$1=null;}let t=e.verify;t===void 0&&(t=await P(v.join(o,d$1),d$1));let d=e.impact;if(d===void 0&&(d=await P(v.join(o,g),g)),e.target.kind==="release-blocked"){let s=t?.blockingReasons??[],i=(r.summary?.projectCount??r.projects.length)===0,g=[p("verdict",i?"Workspace scaffold posture":"Release verdict",t?i?`Scaffold posture: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Freshness: **${t.freshness.verdict}**. No registered projects yet \u2014 release gates apply after the first project is added.`:`Verdict: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Risk: **${t.impact.risk}**. Freshness: **${t.freshness.verdict}**.`:"No workspace verify report found. Run `npx workspai workspace verify --json --write` first."),p("blockers",i?"Pre-project signals":"Blocking reasons",s.length?s.map(h=>`- ${h}`).join(`
2
2
  `):i?"No pre-project signals in the latest verify report.":"No blocking reasons in the latest verify report.")];return t?.resolutionHints?.length&&g.push(p("resolution","Resolution hints",t.resolutionHints.map(h=>`- **${h.blockerId}** (${h.resolutionClass}): ${h.commandRetryHint??h.fixHints[0]?.detail??"See fix hints"}`).join(`
3
3
  `))),{schemaVersion:a,generatedAt:n,workspacePath:o,target:e.target,summary:t?i?b(s.length,t.summary.verdict):s.length>0||t.summary.verdict==="blocked"?`Release blocked: ${t.summary.verdict} with ${s.length} blocking reason(s).`:t.summary.verdict==="needs-attention"?"Release needs attention: advisory or incomplete verification evidence remains; no blocking reason was reported.":`Release posture: ${t.summary.verdict}; no blocking reason was reported.`:"Release posture unknown \u2014 verify report missing.",sections:g,releaseVerdict:t?.summary.verdict,evidenceFreshness:t?.freshness.verdict,blocking:!!(t&&(t.summary.verdict==="blocked"||s.length>0)),releaseRisk:t?.impact.risk,blockingReasons:s,resolutionHints:t?.resolutionHints}}if(e.target.kind==="blocker"){let s=e.target,m=t?.resolutionHints?.find(g=>g.blockerId===s.blockerId),i=t?.blockingReasons.find(g=>g.includes(s.blockerId))??t?.blockingReasons[0];return {schemaVersion:a,generatedAt:n,workspacePath:o,target:s,summary:m?`Blocker ${s.blockerId}: ${m.resolutionClass}`:`Blocker ${s.blockerId} (no structured hint)`,sections:[p("reason","Blocking signal",i??"No matching blocking reason in verify."),p("hint","Resolution class",m?`${m.resolutionClass}
4
4
 
@@ -1 +1 @@
1
- export{c as PYTHON_FREE_WORKSPACE_PROFILES,a as buildWorkspaceManifest,f as createProject,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,b as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-CFBAGPB4.js';
1
+ export{c as PYTHON_FREE_WORKSPACE_PROFILES,a as buildWorkspaceManifest,f as createProject,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,b as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-M4UOXP5T.js';
@@ -1 +1 @@
1
- export{a as DOCTOR_WORKSPACE_REPORT_PATH,n as applyEnvKeyAddFix,j as applyFileAppendFix,k as applyFileCopyFix,i as applyFileCreateFix,m as applyJsonEditFix,o as applyMakefileTargetFix,h as applyPackageScriptFix,f as assertOperationPathInsideProject,g as assertOperationPathInsideProjectResolved,e as buildRepairOperationIdentity,q as computeDoctorFixAwareExitCode,p as computeDoctorGateExitCode,l as decodeJsonPointerSegment,d as parseInternalRepairCommand,c as parsePackageScriptFix,b as resolveDoctorPolicyProfile,r as runDoctor}from'./chunk-SM55RK3C.js';
1
+ export{a as DOCTOR_WORKSPACE_REPORT_PATH,n as applyEnvKeyAddFix,j as applyFileAppendFix,k as applyFileCopyFix,i as applyFileCreateFix,m as applyJsonEditFix,o as applyMakefileTargetFix,h as applyPackageScriptFix,f as assertOperationPathInsideProject,g as assertOperationPathInsideProjectResolved,e as buildRepairOperationIdentity,q as computeDoctorFixAwareExitCode,p as computeDoctorGateExitCode,l as decodeJsonPointerSegment,d as parseInternalRepairCommand,c as parsePackageScriptFix,b as resolveDoctorPolicyProfile,r as runDoctor}from'./chunk-ENKGGWRX.js';
@@ -0,0 +1 @@
1
+ export{f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,j as buildGoalLifecycleResult,k as inspectGoalLifecycle,o as linkGoalRepairTransaction,m as prepareGoalVerification,l as transitionGoalLifecycle,n as verifyGoalLifecycle}from'./chunk-HOUQIT7U.js';
@@ -0,0 +1 @@
1
+ import {c as c$5}from'./chunk-5PSKBJKJ.js';import {c}from'./chunk-RBBBXFEU.js';import {i,h as h$1,d as d$1,f as f$2,c as c$3,e as e$1}from'./chunk-HOUQIT7U.js';export{b as GOAL_AGENT_HANDOFF_SCHEMA_VERSION,f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,g as GOAL_LIFECYCLE_RESULT_SCHEMA_VERSION,d as GOAL_PACK_LAST_RUN_PATH,a as GOAL_PACK_SCHEMA_VERSION,c as GOAL_PLAN_RESULT_SCHEMA_VERSION}from'./chunk-HOUQIT7U.js';import {f as f$3}from'./chunk-4PUJVYRM.js';import {b}from'./chunk-GPOZILMY.js';import {a as a$1}from'./chunk-5NIZNXRS.js';import {c as c$4}from'./chunk-QFBVQUKV.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {c as c$2,f as f$1}from'./chunk-CCDGHPEJ.js';import {a}from'./chunk-AFIFZTOY.js';import {f,e}from'./chunk-NZ3WZYD5.js';import h from'path';import G from'fs-extra';var ce=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/,ie=/(?:^|\s)(?:\/(?:home|Users|private|var|tmp|mnt|opt|srv|root|workspace|workspaces|data|Volumes|etc|usr|run|dev|proc|sys)\/[^\s]+|[A-Za-z]:[\\/][^\s]+|\\\\[^\\\s]+\\[^\s]+)/,le=/(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:github_pat_|gh[pousr]_|glpat-|npm_|xox[baprs]-|sk-(?:proj-)?)[A-Za-z0-9_-]{12,}|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[A-Za-z0-9_-]{20,}|\bBearer\s+[A-Za-z0-9._~+/-]{16,}|[a-z][a-z0-9+.-]*:\/\/[^\s:/]+:[^\s@/]+@|\b(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^\s]{6,})/i,pe=[{category:"test-coverage",patterns:[/\b(?:test\s+)?coverage\b/i,/\bcoverage\s+(?:to|above|at least)\b/i]},{category:"dependency-security",patterns:[/\b(?:dependency|dependencies|package|packages)\b.*\b(?:security|vulnerab|audit)\b/i,/\b(?:security|vulnerab|audit)\b.*\b(?:dependency|dependencies|package|packages)\b/i]},{category:"release-readiness",patterns:[/\brelease[ -]readiness\b/i,/\bready (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare\b[^\n]{0,80}\bfor release\b/i]},{category:"defect-repair",patterns:[/\b(?:fix|repair|resolve|debug)\b.*\b(?:bug|error|failure|issue|regression)\b/i]},{category:"performance",patterns:[/\b(?:performance|latency|throughput|memory|cpu|optimi[sz]e|faster|slower)\b/i]},{category:"refactor",patterns:[/\b(?:refactor|restructure|decouple|extract|simplify|cleanup|clean up)\b/i]},{category:"documentation",patterns:[/\b(?:document|documentation|readme|guide|tutorial|docs)\b/i]},{category:"feature-change",patterns:[/\b(?:add|build|create|implement|introduce|support)\b/i]},{category:"system-understanding",patterns:[/\b(?:understand|explain|map|find|where|how|architecture|analy[sz]e|search)\b/i]}];function de(e){if(typeof e!="string")throw new Error("Goal intent must be text.");let t=e.trim().replace(/\s+/g," ");if(!t)throw new Error("Goal intent cannot be empty.");if(t.length>2e3)throw new Error("Goal intent exceeds the 2000 character safety limit.");if(ce.test(t))throw new Error("Goal intent contains unsupported control characters.");if(ie.test(t))throw new Error("Goal intent contains a machine-local absolute path. Use a workspace-relative path or project scope.");if(le.test(t))throw new Error("Goal intent appears to contain secret material and was not persisted.");return t}function ue(e){let t=e.match(/\b(?:coverage\D{0,24})?(100|\d{1,2})(?:\.\d+)?\s*%/i);if(!t||!/coverage/i.test(e))return null;let o=Number(t[1]);return Number.isFinite(o)&&o>=0&&o<=100?o:null}function Z(e){let t=de(e),o=pe.filter(c=>c.patterns.some(m=>m.test(t))).map(c=>c.category),r=o[0]??"feature-change",i=ue(t),l=[];return o.length>1&&o[0]!=="test-coverage"&&l.push(`The intent also contains signals for: ${o.slice(1).join(", ")}.`),r==="test-coverage"&&i===null&&l.push("A numeric test coverage target is required for machine verification."),{original:t,normalized:t.toLocaleLowerCase("en-US"),statement:t.replace(/[.!?]+$/,""),category:r,confidence:o.length===1?"high":o.length>1?"medium":"low",ambiguities:l,...i===null?{}:{requestedTarget:{metric:"test-coverage-percent",operator:"at-least",value:i}}}}function X(e){let t={"test-coverage":["test suite coverage configuration instrumentation","CI tests LCOV Cobertura JaCoCo LLVM coverage"],"dependency-security":["dependency manifest lockfile security audit vulnerability"],"release-readiness":["release pipeline readiness gates build test deploy"],"defect-repair":["failure error test implementation call path"],"feature-change":["API implementation module dependency tests"],refactor:["module dependency ownership implementation tests"],performance:["performance benchmark latency throughput runtime"],documentation:["documentation README guide architecture decision"],"system-understanding":["architecture service API dependency ownership"]};return [...new Set([e.statement,...t[e.category]])].slice(0,3)}var Q="contracts/workspace-intelligence/goal-pack.v1.json",Y="contracts/workspace-intelligence/goal-agent-handoff.v1.json",me="contracts/workspace-intelligence/goal-plan-result.v1.json",te="contracts/workspace-intelligence/goal-index.v1.json";function ee(e){return e.split(h.sep).join("/")}function q(e,t){return h.resolve(t.absolutePath??h.join(e,t.path))}function ge(e){let t=e.requested.trim().replace(/^project:/,"");if(!t)throw new Error("Project goal scope must name a project.");let o=h.isAbsolute(t)?h.resolve(t):null,r=e.model.projects.filter(i=>i.name===t||ee(i.path)===ee(t)||o!==null&&q(e.workspacePath,i)===o);if(r.length!==1)throw new Error(r.length===0?`Project goal scope was not found in the canonical model: ${t}`:`Project goal scope is ambiguous in the canonical model: ${t}`);return r[0]}async function fe(e){let t=await a$1(e);if(t.status==="miss")throw new Error(`Canonical model and live graph evidence are required (${t.reason}). Run \`workspai workspace intelligence run --for-agent generic --strict --json\` or retry with --refresh.`);let{model:o,graph:r}=t;return a(o,"contracts/workspace-intelligence/workspace-model.v1.json","Goal source model"),a(r,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Goal source graph"),c$4(r,o),{model:o,graph:r}}function he(e){if(e.explicitScope?.trim()==="workspace")return {kind:"workspace",projects:e.model.projects.map(t=>t.name).sort(),selectionSource:"explicit"};if(e.explicitScope?.trim())return {kind:"project",projects:[ge({workspacePath:e.workspacePath,model:e.model,requested:e.explicitScope}).name],selectionSource:"explicit"};if(e.invocationProjectPath){let t=h.resolve(e.invocationProjectPath),o=e.model.projects.filter(r=>q(e.workspacePath,r)===t);if(o.length!==1)throw new Error("The invocation project is not represented uniquely in the canonical workspace model. Refresh intelligence or pass --scope explicitly.");return {kind:"project",projects:[o[0].name],selectionSource:"invocation-project"}}return {kind:"workspace",projects:e.model.projects.map(t=>t.name).sort(),selectionSource:"workspace"}}function ke(e,t){if(t.kind==="workspace")return {entities:e.quality.entityCount,relationships:e.quality.relationCount,proofs:e.quality.proofCount,unresolved:e.quality.unknownCount,proofCoveragePercent:Number((e.quality.relationProofCoverageRatio*100).toFixed(2))};let o=new Set(t.projects),r=e.entities.filter(p=>p.projectId!==void 0&&o.has(p.projectId)),i=new Set(r.map(p=>p.id)),l=e.relations.filter(p=>i.has(p.from)||i.has(p.to)),c=new Set([...r.flatMap(p=>p.proofIds),...l.flatMap(p=>p.proofIds)]),m=l.filter(p=>p.proofIds.length>0).length;return {entities:r.length,relationships:l.length,proofs:c.size,unresolved:l.length-m,proofCoveragePercent:l.length===0?100:Number((m/l.length*100).toFixed(2))}}async function we(e$1){let t=new Set(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp","unknown"]),o=h.join(e$1.workspacePath,e.intelligenceRun),r=await G.readJson(o).catch(()=>null),l=(Array.isArray(r?.stages)?r.stages:[]).filter(a=>a.status==="blocked"||a.status==="failed").map(a=>String(a.id??"unknown")).sort(),c=r?.status,m={status:c==="passed"?"passed":c==="blocked"||c==="failed"?"blocked":"unknown",artifact:e.intelligenceRun,blockedStages:l},p={status:"not-applicable",runtime:null,runner:null,existingEvidence:[],prerequisites:[]};if(e$1.intent.category==="test-coverage"){let a=await Promise.all(e$1.projects.map(async n=>({project:n,capability:await c$5(q(e$1.workspacePath,n),t.has(n.runtime)?n.runtime:"unknown")}))),u=a.map(n=>n.capability.status);p={status:u.includes("unsupported")?"unsupported":u.includes("requires-setup")?"requires-setup":"available",runtime:a.length===1?a[0].capability.runtime:[...new Set(a.map(n=>n.capability.runtime))].join(","),runner:a.length===1?a[0].capability.runner:[...new Set(a.flatMap(n=>n.capability.runner?[n.capability.runner]:[]))].join(",")||null,existingEvidence:a.flatMap(n=>n.capability.existingEvidence.map(d=>({project:n.project.name,...d}))).filter((n,d,f)=>f.findIndex(w=>w.project===n.project&&w.path===n.path&&w.sha256===n.sha256)===d).sort((n,d)=>n.project.localeCompare(d.project)||n.path.localeCompare(d.path)),prerequisites:[...new Set(a.flatMap(n=>n.capability.prerequisites))].sort()};}let x=X(e$1.intent),P=x.map(a=>{let u=e$1.projects.map(f=>f$3(e$1.graph,{query:a,projectId:f.name,limit:20,relationsPerEntity:0,minimumTermMatches:2}).entities),n=[],d=new Set;for(let f=0;u.some(w=>f<w.length);f+=1)for(let w of u){let N=w[f];!N||d.has(N.id)||(d.add(N.id),n.push(N));}return n}),E={"test-coverage":["test-suite"],"dependency-security":["package","module"],"release-readiness":["pipeline","deployment","lifecycle-stage"],"defect-repair":["test-suite","lifecycle-stage"],"feature-change":["project","runtime-unit","api","package","module","test-suite"],refactor:["package","module","api","test-suite"],performance:["lifecycle-stage","test-suite","pipeline"],documentation:["document","decision"],"system-understanding":["project","service","api","package","protocol"]},R=new Set(e$1.projects.map(a=>a.name)),S=e$1.graph.entities.filter(a=>a.proofIds.length>0&&(!a.projectId||R.has(a.projectId))&&E[e$1.intent.category].includes(a.kind)).sort((a,u)=>E[e$1.intent.category].indexOf(a.kind)-E[e$1.intent.category].indexOf(u.kind)||a.label.localeCompare(u.label)),s=[],b=new Set,k=a=>{!a||s.length>=20||b.has(a.id)||(b.add(a.id),s.push(a));},A=(e$1.intent.statement.match(/[A-Za-z][A-Za-z0-9+#.-]{1,}/g)??[]).length>=2,T=A?P[0]??[]:[];for(let a of T.slice(0,12))k(a);if(!A)for(let a of S)k(a);for(let a=0;s.length<20&&P.slice(1).some(u=>a<u.length);a+=1)for(let u of P.slice(1))k(u[a]);if(A)for(let a of S)k(a);for(let a of T.slice(12))k(a);let C=s.map(a=>({entityId:a.id,kind:a.kind,label:a.label,proofIds:a.proofIds.slice(0,12)})),g=P[0]?.length??0;return {workspaceIntelligence:m,measurement:p,retrieval:{status:A&&g>=3?"grounded":C.length>0?"partial":"empty",strategy:"deterministic-category-v1",queries:x,anchors:C}}}async function ye(e){let t=h.join(e,f$2);if(!await G.pathExists(t))return {schemaVersion:e$1,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let o=await G.readJson(t);return a(o,te,"Goal index"),h$1(o),o}function Pe(e,t,o){let r=e.goals.find(c=>c.id===t.id),i=t.state==="ready-to-plan",l={id:t.id,fingerprint:t.fingerprint,objective:t.intent.statement,category:t.intent.category,state:t.state,lifecycle:r?.lifecycle==="cancelled"?"cancelled":i?"active":"planned",scope:t.scope,createdAt:r?.createdAt??t.generatedAt,updatedAt:o,goalPack:t.artifacts.goalPack,agentHandoff:t.artifacts.agentHandoff,...r?.verifiedGoalId?{verifiedGoalId:r.verifiedGoalId}:{},...r?.repairTransactionId?{repairTransactionId:r.repairTransactionId}:{},...r?.repairTransactionIds?{repairTransactionIds:r.repairTransactionIds}:{}};return {schemaVersion:e$1,generatedAt:o,activeGoalId:l.lifecycle==="active"?t.id:e.activeGoalId,goals:[...e.goals.filter(c=>c.id!==t.id).map(c=>l.lifecycle==="active"&&c.lifecycle==="active"?{...c,lifecycle:"planned",updatedAt:o}:c),l].sort((c,m)=>c.id.localeCompare(m.id))}}async function Me(e$1){let t=b({startPath:h.resolve(e$1.startPath),explicitWorkspacePath:e$1.workspacePath,strict:true,requireProjectMembership:true});if(!t)throw new Error("No canonical Workspai workspace could be resolved.");let o=h.resolve(t.workspacePath);e$1.refresh&&await c({workspacePath:o,strict:false,agent:"generic"});let{model:r,graph:i$1}=await fe(o),l=he({workspacePath:o,invocationProjectPath:t.projectPath,model:r,explicitScope:e$1.scope}),c$4=r.projects.filter(g=>l.projects.includes(g.name));if(c$4.length===0)throw new Error("A Goal Pack requires at least one registered project in its selected scope.");let m=e$1.maxAttempts??5;if(!Number.isInteger(m)||m<1||m>25)throw new Error("--max-attempts must be an integer from 1 to 25.");let p=new Date().toISOString(),x=d(r),P=Z(e$1.intent),E=await we({workspacePath:o,projects:c$4,graph:i$1,intent:P}),R={generatedAt:p,intent:P,workspaceName:r.workspace.name,scope:l,sourceBinding:{model:{artifact:e.model,schemaVersion:f.model,hashAlgorithm:"sha256",hashSemantics:"workspace-model-structural-v1",hash:x,generatedAt:r.generatedAt},graph:{artifact:e.knowledgeGraph,schemaVersion:f.knowledgeGraph,hashAlgorithm:"sha256",hashSemantics:"canonical-json-v1",hash:c$1(i$1),generatedAt:i$1.generatedAt,modelHash:i$1.source.hash,...i$1.source.inputs?.hash?{inputHash:i$1.source.inputs.hash}:{}}},preflight:E,baseline:{projectCount:c$4.length,runtimes:[...new Set(c$4.flatMap(g=>g.runtimeCandidates))].sort(),frameworks:[...new Set(c$4.map(g=>g.framework))].sort(),graph:ke(i$1,l)},maxAttempts:m,consumer:e$1.consumer??"generic"},S={digestCanonical:c$1},{goalPack:s,handoff:b$1}=i(R,S);a(s,Q,"Goal Pack"),a(b$1,Y,"Goal agent handoff");let k=false,A=async()=>{let g=h.join(o,s.artifacts.goalPack),a$1=h.join(o,s.artifacts.agentHandoff),[u,n]=await Promise.all([G.pathExists(g),G.pathExists(a$1)]);if(u!==n)throw new Error(`Goal Pack instance is incomplete and cannot be resumed: ${s.id}`);if(!u)return;let[d,f]=await Promise.all([G.readJson(g),G.readJson(a$1)]);a(d,Q,"Persisted Goal Pack"),a(f,Y,"Persisted goal agent handoff");let w=i({...R,generatedAt:d.generatedAt,sourceBinding:d.sourceBinding},S);if(d.id!==s.id||f.goalId!==s.id||c$1(d)!==c$1(w.goalPack)||c$1(f)!==c$1(w.handoff))throw new Error(`Goal Pack instance failed immutable integrity validation: ${s.id}`);s=d,b$1=f,k=true;};if(e$1.dryRun)await A();else {let g=`.workspai/goals/${s.id}/publication`;await c$2(o,g,async()=>{await A();let a$1=Pe(await ye(o),s,new Date().toISOString());a(a$1,te,"Goal index"),h$1(a$1),await f$1(o,d$1,k?[{relativePath:d$1,payload:s},{relativePath:f$2,payload:a$1}]:[{relativePath:s.artifacts.goalPack,payload:s},{relativePath:s.artifacts.agentHandoff,payload:b$1},{relativePath:d$1,payload:s},{relativePath:f$2,payload:a$1}]);});}let T=[s.artifacts.goalPack,s.artifacts.agentHandoff,d$1,f$2],C={schemaVersion:c$3,result:s.state==="needs-confirmation"?"needs-confirmation":s.state==="blocked"?"blocked":s.state==="needs-evidence"?"needs-evidence":"planned",resolution:{source:t.source,invocationScope:t.projectPath?"project":"workspace"},goalPack:s,agentHandoff:b$1,writtenArtifacts:e$1.dryRun?[]:k?[d$1,f$2]:T,dryRun:e$1.dryRun===true,resumed:k};return a(C,me,"Goal plan result"),C}export{Me as planGoalPack};