workspai 0.63.0 → 0.65.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 (138) hide show
  1. package/README.md +37 -44
  2. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +4 -0
  3. package/contracts/create-planner-capabilities.v1.json +251 -8
  4. package/contracts/runtime-command-surface.v1.json +12 -1
  5. package/contracts/workspace-contract.v1.json +51 -6
  6. package/contracts/workspace-intelligence/project-context-agent.v1.json +29 -0
  7. package/contracts/workspace-intelligence/workspace-knowledge-graph.v1.json +11 -1
  8. package/contracts/workspace-intelligence/workspace-model.v1.json +28 -1
  9. package/contracts/workspace-model-cache.v1.json +4 -0
  10. package/contracts/workspace-repair-capabilities.v1.json +66 -0
  11. package/dist/analyze-5PDVWECJ.js +1 -0
  12. package/dist/autopilot-release-JVIJCTKX.js +1 -0
  13. package/dist/capabilities-command-LHM3XIS6.js +1 -0
  14. package/dist/chunk-2C5ZBVBI.js +2 -0
  15. package/dist/{chunk-QQU536KA.js → chunk-2RL6RRT2.js} +3 -3
  16. package/dist/{chunk-QB3BLYUR.js → chunk-6JWNDWOA.js} +1 -1
  17. package/dist/{chunk-HS3DJMU5.js → chunk-6TBTMWNA.js} +1 -1
  18. package/dist/chunk-D5YJOQYK.js +1 -0
  19. package/dist/chunk-DFG33SBR.js +2 -0
  20. package/dist/chunk-FY4IIAIF.js +1 -0
  21. package/dist/chunk-GQSRNUCU.js +105 -0
  22. package/dist/{chunk-2LLMKTMO.js → chunk-HDNATYW7.js} +1 -1
  23. package/dist/chunk-HEZZ72V4.js +94 -0
  24. package/dist/chunk-HN7P4T3B.js +681 -0
  25. package/dist/chunk-J7QYANXK.js +8 -0
  26. package/dist/{chunk-Z5L2IK54.js → chunk-JD3A5QM6.js} +1 -1
  27. package/dist/{chunk-DIJGQUEV.js → chunk-JQLJBK5N.js} +1 -1
  28. package/dist/chunk-KLSSPJTV.js +1 -0
  29. package/dist/{chunk-GPOZILMY.js → chunk-L22EABIC.js} +1 -1
  30. package/dist/{chunk-J5OMC4RZ.js → chunk-MDTI3UEB.js} +1 -1
  31. package/dist/chunk-MYJQGGIU.js +5 -0
  32. package/dist/chunk-NOV6723U.js +1 -0
  33. package/dist/chunk-NYEAMMUL.js +1 -0
  34. package/dist/chunk-O5B2L3R2.js +1 -0
  35. package/dist/chunk-OWB5KWSS.js +13 -0
  36. package/dist/chunk-P5PSZQPB.js +2 -0
  37. package/dist/chunk-QI3HG6IG.js +144 -0
  38. package/dist/chunk-RGNCL5OB.js +1 -0
  39. package/dist/chunk-SWGSFLTC.js +1 -0
  40. package/dist/chunk-U5FCQTVL.js +4 -0
  41. package/dist/{chunk-W3HXTCSY.js → chunk-UXEO5QCF.js} +1 -1
  42. package/dist/{chunk-QJCCZLOF.js → chunk-VRGEPPUB.js} +1 -1
  43. package/dist/chunk-VVJK5NFY.js +2 -0
  44. package/dist/chunk-VXKWWX7S.js +8 -0
  45. package/dist/chunk-W322YDHS.js +49 -0
  46. package/dist/chunk-WCJU3CFG.js +1 -0
  47. package/dist/chunk-WPRLXKWC.js +8 -0
  48. package/dist/{chunk-E4LJ3PQD.js → chunk-XGE2FDI4.js} +1 -1
  49. package/dist/{chunk-5SFCBZOH.js → chunk-YN5X2FTP.js} +1 -1
  50. package/dist/chunk-YOCN7GF4.js +1 -0
  51. package/dist/chunk-YYQEWAES.js +1 -0
  52. package/dist/chunk-ZEEV5J4I.js +1 -0
  53. package/dist/create-ALT2ME6H.js +1 -0
  54. package/dist/{doctor-LDZ7BIU3.js → doctor-RW4R3O5C.js} +1 -1
  55. package/dist/{goal-lifecycle-HAWBRYDF.js → goal-lifecycle-VYOKS6E6.js} +1 -1
  56. package/dist/goal-pack-YWPI43QL.js +1 -0
  57. package/dist/index.d.ts +2 -1
  58. package/dist/index.js +199 -195
  59. package/dist/{pipeline-TWHWU6GP.js → pipeline-U4N2DVD7.js} +1 -1
  60. package/dist/{platform-capabilities-PR6YL4KC.js → platform-capabilities-DB4BZPTD.js} +1 -1
  61. package/dist/{project-agent-entry-YFRLKNOB.js → project-agent-entry-YAQCHIMP.js} +1 -1
  62. package/dist/project-intelligence-lens-MRQR2LQW.js +1 -0
  63. package/dist/{project-test-coverage-E2Q4QL44.js → project-test-coverage-4S7MEQ6T.js} +1 -1
  64. package/dist/{pythonRapidkitExec-4YTAMLBD.js → pythonRapidkitExec-VAW5XE4Z.js} +1 -1
  65. package/dist/verified-goal-WM34TTGE.js +1 -0
  66. package/dist/{workspace-XWKEBPS3.js → workspace-HGUZWNAB.js} +1 -1
  67. package/dist/{workspace-agent-sync-FQU6VIEU.js → workspace-agent-sync-GEN3KBAX.js} +1 -1
  68. package/dist/{workspace-context-DPDGFTWJ.js → workspace-context-4WIWFW26.js} +1 -1
  69. package/dist/workspace-contract-7DXK4GF5.js +1 -0
  70. package/dist/{workspace-explain-OU2PEVYO.js → workspace-explain-TE2LGOAV.js} +1 -1
  71. package/dist/workspace-foundation-J3NNRMI3.js +1 -0
  72. package/dist/workspace-graph-stream-PQI7OGCE.js +1 -0
  73. package/dist/workspace-graph-token-efficiency-2I4X374C.js +1 -0
  74. package/dist/{workspace-intelligence-625UN27X.js → workspace-intelligence-6FS26JOQ.js} +1 -1
  75. package/dist/{workspace-intelligence-runner-YQWX5VAM.js → workspace-intelligence-runner-XYUPCSLN.js} +1 -1
  76. package/dist/workspace-knowledge-graph-SWCKDTPF.js +1 -0
  77. package/dist/workspace-knowledge-graph-contract-L3CLAM2M.js +1 -0
  78. package/dist/{workspace-knowledge-graph-query-ON45H6Y7.js → workspace-knowledge-graph-query-FZXSPWGK.js} +1 -1
  79. package/dist/workspace-knowledge-graph-snapshot-M572JRB4.js +1 -0
  80. package/dist/workspace-mcp-serve-IBMTFQDY.js +3 -0
  81. package/dist/workspace-model-ZL6WCICX.js +1 -0
  82. package/dist/{workspace-onboarding-DRFJWRLH.js → workspace-onboarding-X3PWRIIS.js} +1 -1
  83. package/dist/{workspace-registry-summary-VSOBKAJG.js → workspace-registry-summary-LJN4WHIZ.js} +1 -1
  84. package/dist/workspace-repair-engine-NX7I632M.js +3 -0
  85. package/dist/workspace-run-6GT5OBQ5.js +1 -0
  86. package/dist/{workspace-verify-7ENGIY4S.js → workspace-verify-USRRIM2F.js} +1 -1
  87. package/dist/workspace-watch-43YZPLF7.js +1 -0
  88. package/docs/ci-workflows.md +1 -1
  89. package/docs/commands-reference.md +3 -1
  90. package/docs/creating-workspaces-and-projects.md +49 -8
  91. package/docs/real-world-qualification.md +7 -0
  92. package/docs/workspace-knowledge-graph.md +36 -0
  93. package/docs/workspace-operations.md +22 -0
  94. package/docs/workspace-repair-engine.md +17 -0
  95. package/package.json +1 -1
  96. package/dist/analyze-K6JDMF5C.js +0 -1
  97. package/dist/autopilot-release-NUQKFKKK.js +0 -1
  98. package/dist/capabilities-command-VBLZXP2T.js +0 -1
  99. package/dist/chunk-4PUJVYRM.js +0 -1
  100. package/dist/chunk-A4BK7C7M.js +0 -1
  101. package/dist/chunk-GPGEJVVO.js +0 -4
  102. package/dist/chunk-GXPOT3A7.js +0 -144
  103. package/dist/chunk-KCJ3VS6R.js +0 -1
  104. package/dist/chunk-KG3TUTXU.js +0 -2
  105. package/dist/chunk-NA2NXX5P.js +0 -1
  106. package/dist/chunk-NBJ6AP7K.js +0 -2
  107. package/dist/chunk-NVQUBUTY.js +0 -2
  108. package/dist/chunk-O6R7SE6Y.js +0 -1
  109. package/dist/chunk-ODJAKGQF.js +0 -49
  110. package/dist/chunk-PPQL5UTI.js +0 -13
  111. package/dist/chunk-PTNLVI62.js +0 -16
  112. package/dist/chunk-QA62UOE4.js +0 -5
  113. package/dist/chunk-RJIYCDVC.js +0 -1
  114. package/dist/chunk-SCP5LJNO.js +0 -2
  115. package/dist/chunk-T5YRFRJV.js +0 -1
  116. package/dist/chunk-TFOOSYGO.js +0 -8
  117. package/dist/chunk-TTQVOCG6.js +0 -1
  118. package/dist/chunk-TVCJKE2U.js +0 -2
  119. package/dist/chunk-U5WVR74V.js +0 -1
  120. package/dist/chunk-UDXFUASA.js +0 -691
  121. package/dist/chunk-UIBBSKJ3.js +0 -94
  122. package/dist/chunk-VRQLHCE2.js +0 -8
  123. package/dist/chunk-ZCPT6KC3.js +0 -6
  124. package/dist/create-2VELRQAX.js +0 -1
  125. package/dist/goal-pack-HNQHQFRW.js +0 -1
  126. package/dist/project-intelligence-lens-VWBLAGQ7.js +0 -1
  127. package/dist/verified-goal-Y4NTKSWH.js +0 -1
  128. package/dist/workspace-contract-3BWIRSVQ.js +0 -1
  129. package/dist/workspace-foundation-MHKSQDKT.js +0 -1
  130. package/dist/workspace-graph-stream-XTSDKRLM.js +0 -1
  131. package/dist/workspace-graph-token-efficiency-D7CUT6NX.js +0 -1
  132. package/dist/workspace-knowledge-graph-3ZBPSAS7.js +0 -1
  133. package/dist/workspace-knowledge-graph-snapshot-ZI4W735H.js +0 -1
  134. package/dist/workspace-mcp-serve-PYKYJIE6.js +0 -3
  135. package/dist/workspace-model-ETCLINRB.js +0 -1
  136. package/dist/workspace-repair-engine-XZLHR27V.js +0 -3
  137. package/dist/workspace-run-YXI5L466.js +0 -1
  138. package/dist/workspace-watch-2YFSB2WL.js +0 -1
@@ -156,6 +156,38 @@ context, and verify remain available.
156
156
  Use `--skip-python-engine` for workspace creation. For project creation, use
157
157
  `--skip-install` instead.
158
158
 
159
+ ## What Create runs automatically
160
+
161
+ Workspace and project creation finish with a canonical foundation sync. Workspai
162
+ registers created projects and refreshes the workspace contract, model,
163
+ proof-backed graph, diff, impact, agent context, grounding files, and evidence
164
+ index. A successful Create receipt therefore means that the new source and its
165
+ basic Workspace Intelligence artifacts agree.
166
+
167
+ Create does not silently run dependency initialization, Doctor, Analyze,
168
+ Readiness, release gates, or the strict verification chain. Those operations can
169
+ change host state or produce environment-specific verdicts and remain explicit:
170
+
171
+ ```bash
172
+ # Install profile-owned and project dependencies when you want them.
173
+ workspai bootstrap --profile node-only
174
+
175
+ # Produce the complete evidence and verification chain.
176
+ workspai workspace intelligence run --for-agent generic --strict --json
177
+ ```
178
+
179
+ `node-only`, `go-only`, `java-only`, and `dotnet-only` bootstrap never install
180
+ the optional workspace Python engine. A `minimal` workspace installs it on
181
+ demand only when a registered Workspai kit requires that engine. Explicitly
182
+ selecting `python-only`, `polyglot`, or `enterprise` enables the Python-capable
183
+ bootstrap path.
184
+
185
+ The machine-readable source for profiles, every executable kit, runtime
186
+ ownership, Python-engine requirements, and automatic versus explicit lifecycle
187
+ steps is `contracts/create-planner-capabilities.v1.json`. The same contract is
188
+ published through `workspai commands --json` and consumed by Workspai for VS
189
+ Code.
190
+
159
191
  ## If Python is not installed
160
192
 
161
193
  Python-free profiles do not require Python.
@@ -170,8 +202,17 @@ profile when Python is unavailable:
170
202
  | `polyglot` | `node-only` |
171
203
  | `enterprise` | `node-only` |
172
204
 
173
- If Poetry is selected but unavailable, Workspai can use a local virtual
174
- environment instead.
205
+ Before writing workspace files, Workspai probes the selected Python installer.
206
+ Poetry, local venv, and pipx choices show whether their executable and Python
207
+ module prerequisites are usable. Workspai honors the selected method rather
208
+ than silently changing it; missing `venv`, `pip`, Poetry, or pipx support returns
209
+ the exact setup command, and the workspace remains uncreated.
210
+
211
+ Failure receipts include platform-specific installation commands and the
212
+ official documentation URL. On Linux they distinguish Debian/Ubuntu, Fedora,
213
+ Arch, and Alpine package managers; macOS uses Homebrew guidance; and Windows
214
+ uses `winget` or `py -m pip` as appropriate. Advanced diagnostics remain behind
215
+ `--debug` and are not mixed into normal onboarding output.
175
216
 
176
217
  ## Git behavior for a new workspace
177
218
 
@@ -345,13 +386,13 @@ project metadata and performs the selected workspace registration.
345
386
 
346
387
  ## Desktop, extension, and additional backend generators
347
388
 
348
- | Category | Project | Kit | Creation owner |
349
- | --------- | ----------------- | ------------------ | -------------------------------------- |
389
+ | Category | Project | Kit | Creation owner |
390
+ | --------- | ----------------- | ------------------ | ------------------------------------- |
350
391
  | Backend | Axum | `rust.axum` | Workspai deterministic Cargo baseline |
351
- | Backend | Laravel | `php.laravel` | Composer / Laravel |
352
- | Desktop | Tauri | `desktop.tauri` | create-tauri-app |
353
- | Desktop | Electron Forge | `desktop.electron` | create-electron-app |
354
- | Extension | VS Code Extension | `extension.vscode` | generator-code |
392
+ | Backend | Laravel | `php.laravel` | Composer / Laravel |
393
+ | Desktop | Tauri | `desktop.tauri` | create-tauri-app |
394
+ | Desktop | Electron Forge | `desktop.electron` | create-electron-app |
395
+ | Extension | VS Code Extension | `extension.vscode` | generator-code |
355
396
 
356
397
  Every generated project receives a canonical `kind` and `category`. The four
357
398
  user-facing categories are `backend`, `frontend`, `desktop`, and `extension`;
@@ -5,6 +5,9 @@ remain the release gates. Real-world qualification complements them by running
5
5
  the installed CLI against explicitly selected reference repositories through
6
6
  local, network-free Git snapshots
7
7
  without installing dependencies or executing project lifecycle commands.
8
+ Every isolated workspace also receives a private `WORKSPAI_STATE_DIR` beneath
9
+ `--run-root`; qualification cannot read or update the user's canonical registry,
10
+ journals, or legacy registry mirror.
8
11
 
9
12
  ## Isolated and cumulative layouts
10
13
 
@@ -26,6 +29,10 @@ Snapshot mode is the default and never changes adoption metadata, grounding, or
26
29
  workspace links in the source repository. `--source-mode linked` remains an
27
30
  explicit diagnostic escape hatch when uncommitted worktree content must be
28
31
  qualified; it may update governed Workspai metadata in that linked checkout.
32
+ Each `--projects` entry must identify an actual Git repository root. When the
33
+ reference directory is a collection, select its nested repositories explicitly
34
+ (for example, `scanners/agent-audit`) so each receives its own isolated state,
35
+ workspace, model, graph, Doctor evidence, and Goal lifecycle.
29
36
 
30
37
  Use `--shared-workspace` to adopt the repositories cumulatively into one fresh
31
38
  workspace. Every addition reruns the canonical chain, so transition and scale
@@ -116,6 +116,19 @@ symbols are not implied to have been extracted. The graph diagnostic reports
116
116
  the sampled and indexed candidate counts and must not be read as exhaustive
117
117
  symbol coverage.
118
118
 
119
+ Call binding follows the same proof boundary. Workspai binds a call only when
120
+ its target is uniquely defined in the same file or in a locally imported file
121
+ that the Graph already resolved. Overloads, dynamic dispatch, and ambiguous
122
+ names remain explicit unknowns for compiler or language-server evidence; the
123
+ CLI does not turn a repository-wide text match into semantic certainty.
124
+
125
+ When a previous graph has the same project set, provider versions, and live
126
+ project fingerprints, unchanged project slices are reused and only changed
127
+ projects repeat the expensive semantic scan. Workspace-level CI, governance,
128
+ infrastructure, and topology providers still run against the complete current
129
+ workspace. The `incremental-project-cache` provider receipt records reused and
130
+ rescanned scope counts. A provider-version change forces a full rebuild.
131
+
119
132
  ### Fast reads without stale answers
120
133
 
121
134
  The read-oriented `search`, `entities`, `evidence`, `path`, and `benchmark`
@@ -147,6 +160,11 @@ The fingerprint proves compatibility of the exact bounded provider inventory;
147
160
  if a scope reports `truncated: true`, it must not be interpreted as proof about
148
161
  files beyond that declared limit.
149
162
 
163
+ Workspai-generated agent entry projections are downstream consumers and are
164
+ excluded from Graph inventory and Git diff hashing. Regenerating `AGENTS.md`,
165
+ adapter entry files, or the Amazon Q entry rule therefore cannot invalidate the
166
+ Graph that produced them or become circular architecture evidence.
167
+
150
168
  ## Pick the command by question
151
169
 
152
170
  | You want to know… | Use |
@@ -457,6 +475,18 @@ Use full graph export for interchange or offline analysis. Use bounded search
457
475
  for interactive agents. The latter keeps response size proportional to the
458
476
  question instead of workspace size.
459
477
 
478
+ ### Runtime-generated API topology
479
+
480
+ When an authored API contract is wired through framework registration or
481
+ configuration rather than a literal route handler, the
482
+ `dynamic-api-registration-binding` provider creates a proof-backed
483
+ `runtime-unit -> implements -> api` relation. Detection is runtime-specific,
484
+ production-only, filename-aware for routing configuration, and bounded per API.
485
+ It intentionally does not claim endpoint implementation: endpoint coverage
486
+ remains unknown until a method/path or operation-id binding is proven. Consumers
487
+ can distinguish the two guarantees through `bindingCoverage.apiRuntimeRegistration`
488
+ and `bindingCoverage.apiImplementation`.
489
+
460
490
  ## Measuring retrieval payload reduction
461
491
 
462
492
  Workspai does not publish an unqualified “N× fewer tokens” claim. Such a claim
@@ -469,6 +499,10 @@ Measure the current workspace instead:
469
499
  npx workspai workspace graph benchmark "authentication endpoint" --limit 12 --json
470
500
  ```
471
501
 
502
+ Use `--kind <entity-kind>` with search when the task requires a precise
503
+ semantic surface, for example `--kind runtime-unit` for dynamic registration
504
+ units or `--kind endpoint` for authored operations.
505
+
472
506
  The report compares the readable, proof-indexed source corpus with the bounded
473
507
  search payload using a clearly labelled `characters / 4` token estimate. It
474
508
  reports corpus size, retrieval size, estimated ratio, percentage reduction,
@@ -497,6 +531,8 @@ a general performance claim.
497
531
  - The live-input fingerprint enables whole-graph snapshot reuse; it is not yet
498
532
  a per-file incremental graph rebuild or a hosted semantic-vector index.
499
533
  - Compiler/LSP-grade symbol resolution belongs in deeper language providers.
534
+ - Runtime registration evidence proves that an API enters the running topology;
535
+ it does not prove that every authored operation has a reachable handler.
500
536
  - Missing project edges mean “relationship not proven,” not “projects are
501
537
  independent.” Author service contracts or provide API/package/runtime
502
538
  evidence to close that gap.
@@ -226,6 +226,28 @@ npx workspai workspace contract graph --output ./contract-graph.json --json
226
226
 
227
227
  Contract file: `.workspai/workspace.contract.json`. Verification checks schema, duplicate slugs, port collisions, and unknown dependencies.
228
228
 
229
+ Project entries may also declare governance that lives outside the repository:
230
+
231
+ ```json
232
+ {
233
+ "slug": "api",
234
+ "relativePath": "services/api",
235
+ "governance": {
236
+ "ci": { "mode": "external", "provider": "Prow", "reference": "platform/test-infra" },
237
+ "release": { "mode": "external", "provider": "Release Engineering" },
238
+ "ownership": { "mode": "repository" }
239
+ }
240
+ }
241
+ ```
242
+
243
+ Workspai reconciles each control as `repository`, `external-declared`,
244
+ `external-observed`, or `unknown`. Analyze does not misreport an explicitly
245
+ external control as a missing repository file. Observed-but-undeclared external
246
+ governance stays advisory until the canonical contract names its authority.
247
+ The resolved profile is emitted by the Workspace Model, project lens, agent
248
+ context, facts, and project graph attributes so every consumer sees the same
249
+ truth.
250
+
229
251
  `workspace contract graph --json` preserves its original `nodes`, `edges`, and
230
252
  summary fields for existing consumers, and now adds an evidence-backed
231
253
  `dependencyGraph` using the public `workspace-dependency-graph.v1` contract. It
@@ -184,6 +184,23 @@ transaction. If a manifest, required executable, isolated environment, project-d
184
184
  validation, or audit surface is unavailable, the engine returns `decision-required`; it never
185
185
  hides the gap behind a model fallback.
186
186
 
187
+ The same capability contract publishes an executable qualification matrix over
188
+ adapter, scope, failure family, and recovery path. Every failure family has one
189
+ bounded terminal policy: refresh stale/missing evidence, replan no-op/source
190
+ drift/producer failures, require a toolchain decision, rollback failed
191
+ validation, durably resume provider outages or interrupted rollback, and route
192
+ unsupported runtimes to manual repair. Contract generation fails if an adapter
193
+ omits reconcile/audit/test/build closure or a failure family has no recovery
194
+ policy. This matrix is consumed through:
195
+
196
+ ```bash
197
+ npx workspai workspace repair capabilities --json
198
+ ```
199
+
200
+ It describes authority and deterministic recovery; conditional runtime support
201
+ remains conditional until Doctor proves the required executable and project
202
+ surface on the current machine.
203
+
187
204
  ## Consumer contract
188
205
 
189
206
  The latest transaction is written to:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workspai",
3
- "version": "0.63.0",
3
+ "version": "0.65.0",
4
4
  "type": "module",
5
5
  "description": "Open-source workspace intelligence CLI for software systems: create, adopt, govern, verify, and align polyglot workspaces for humans, CI, IDEs, and AI agents.",
6
6
  "keywords": [
@@ -1 +0,0 @@
1
- export{b as printAnalyzeReport,a as runAnalyze}from'./chunk-VRQLHCE2.js';
@@ -1 +0,0 @@
1
- export{b as AUTOPILOT_RELEASE_ALIAS_FILENAME,a as AUTOPILOT_RELEASE_LAST_RUN_FILENAME,c as runAutopilotRelease}from'./chunk-2LLMKTMO.js';
@@ -1 +0,0 @@
1
- export{b as runDoctorCapabilities}from'./chunk-HS3DJMU5.js';
@@ -1 +0,0 @@
1
- var Z="workspace-knowledge-search.v1";function b(e){return e.trim().toLowerCase()}var F=new WeakMap;function A(e){let t=F.get(e);if(t)return t;let o=new Map(e.relations.map(s=>[s.id,s])),a=new Map(e.entities.map(s=>[s.id,s])),l=new Map(e.proofs.map(s=>[s.id,s])),r=new Map,d=new Map,u=(s,p)=>{let g=d.get(s)??[];g.push(p),d.set(s,g);};for(let s of e.entities){let p=[s.id,s.label,s.identity.key,...s.kind==="project"&&s.projectId?[s.projectId]:[],...s.identity.aliases];for(let g of new Set(p.map(b))){let y=r.get(g)??[];y.push(s),r.set(g,y);}}for(let s of e.relations)u(s.from,{from:s.from,to:s.to,relationId:s.id,kind:s.kind,direction:"forward",proofIds:s.proofIds}),u(s.to,{from:s.to,to:s.from,relationId:s.id,kind:s.kind,direction:"reverse",proofIds:s.proofIds});for(let s of r.values())s.sort((p,g)=>p.id.localeCompare(g.id));for(let s of d.values())s.sort((p,g)=>p.to.localeCompare(g.to)||p.relationId.localeCompare(g.relationId));let c={entitiesById:a,relationsById:o,entitiesByAlias:r,proofsById:l,adjacency:d};return F.set(e,c),c}function O(e,t){let o=A(e),a=o.relationsById.get(t);if(a)return {found:true,targetType:"relation",relation:a};let l=b(t),r=o.entitiesByAlias.get(l)??[];return r.length===1?{found:true,targetType:"entity",entity:r[0]}:{found:false,query:t,candidates:r.map(d=>d.id).sort()}}function fe(e,t){let o=O(e,t);if(!o.found)return {query:t,found:false,target:null,proofs:[],candidates:o.candidates};let a=o.targetType==="entity"?o.entity:o.relation,l=new Set(a.proofIds);return {query:t,found:true,target:a,candidates:[],proofs:[...l].map(r=>A(e).proofsById.get(r)).filter(r=>!!r).sort((r,d)=>r.id.localeCompare(d.id))}}function ke(e,t,o){let a=O(e,t),l=O(e,o);if(!a.found||a.targetType!=="entity"||!l.found||l.targetType!=="entity")return {from:t,to:o,found:false,resolvedFrom:a.found&&a.targetType==="entity"?a.entity.id:null,resolvedTo:l.found&&l.targetType==="entity"?l.entity.id:null,entityPath:[],hops:[],proofs:[]};let r=A(e),d=[a.entity.id],u=new Map,c=new Set(d),s=0;for(;s<d.length&&!c.has(l.entity.id);){let h=d[s++];for(let k of r.adjacency.get(h)??[])c.has(k.to)||(c.add(k.to),u.set(k.to,k),d.push(k.to));}if(!c.has(l.entity.id))return {from:t,to:o,found:false,resolvedFrom:a.entity.id,resolvedTo:l.entity.id,entityPath:[],hops:[],proofs:[]};let p=[],g=l.entity.id;for(;g!==a.entity.id;){let h=u.get(g);if(!h)break;p.push(h),g=h.from;}p.reverse();let y=new Set(p.flatMap(h=>h.proofIds));return {from:t,to:o,found:true,resolvedFrom:a.entity.id,resolvedTo:l.entity.id,entityPath:[a.entity.id,...p.map(h=>h.to)],hops:p,proofs:[...y].map(h=>r.proofsById.get(h)).filter(h=>!!h).sort((h,k)=>h.id.localeCompare(k.id))}}function we(e,t){return e.entities.filter(o=>!t||o.kind===t).sort((o,a)=>o.kind.localeCompare(a.kind)||o.label.localeCompare(a.label))}var m={relations:24,relatedEntities:24,proofs:16,proofIdsPerItem:4,aliasesPerEntity:8,attributeArrayItems:8,attributeStringCharacters:256};function J(e){let t=[],o=new Set;for(let a=0;a<m.proofIdsPerItem&&t.length<m.proofs;a+=1)for(let l of e){let r=l.proofIds[a];if(!(!r||o.has(r))&&(o.add(r),t.push(r),t.length>=m.proofs))break}return t}function ee(e,t,o){let a=e.identity.aliases.slice(0,m.aliasesPerEntity);o.aliases+=e.identity.aliases.length-a.length;let l=Object.fromEntries(Object.entries(e.attributes).map(([d,u])=>{if(Array.isArray(u)){let c=u.slice(0,m.attributeArrayItems);return o.attributeValues+=u.length-c.length,[d,c]}return typeof u=="string"&&u.length>m.attributeStringCharacters?(o.attributeValues+=1,[d,u.slice(0,m.attributeStringCharacters)]):[d,u]})),r=e.proofIds.filter(d=>t.has(d)).slice(0,m.proofIdsPerItem);return o.proofReferences+=e.proofIds.length-r.length,{...e,identity:{...e.identity,aliases:a},attributes:l,proofIds:r}}function te(e){let t=Object.values(e.attributes).flatMap(o=>Array.isArray(o)?o:[o]);return [e.id,e.kind,e.label,e.projectId??"",e.identity.key,...e.identity.aliases,...t.map(o=>String(o??""))].join(" ").toLowerCase()}var ne=new Set(["a","an","and","are","as","at","be","been","being","by","can","check","could","did","do","does","find","for","from","give","had","has","have","how","i","in","into","is","it","its","may","might","of","on","or","our","show","should","that","the","their","them","then","there","these","they","this","those","tell","to","was","we","were","what","when","where","which","who","why","will","with","would","you","your"]);function T(e){let t=o=>b(o).split(/[^a-z0-9]+/u).filter(a=>a.length>1);return [...new Set([...t(e),...t(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2"))])]}function oe(e){let t=b(e.label),o=b(e.identity.key),a=e.identity.aliases.map(b),l=te(e);return {entity:e,label:t,identity:o,aliases:a,haystack:l,labelTokens:new Set(T(e.label)),identityTokens:new Set(T(e.identity.key)),aliasTokens:new Set(e.identity.aliases.flatMap(T)),allTokens:new Set(T(l))}}function S(e,t){return e.has(t)||t.length>=3&&[...e].some(o=>o.startsWith(t))}function G(e,t){return S(e.labelTokens,t)||S(e.identityTokens,t)||S(e.aliasTokens,t)||S(e.allTokens,t)}function se(e,t,o,a){let{label:l,identity:r,aliases:d,haystack:u}=e,c=0;(l===t||r===t||d.includes(t))&&(c+=1e4),(l.startsWith(t)||r.startsWith(t))&&(c+=250),u.includes(t)&&(c+=100);let s=0;for(let p of o){let g=a.get(p)??1,y=S(e.labelTokens,p),h=S(e.identityTokens,p),k=S(e.aliasTokens,p),f=G(e,p);f&&(s+=1),l===p?c+=80*g:y&&(c+=36*g),h&&(c+=24*g),k&&(c+=20*g),f&&(c+=10*g);}return o.length>0&&(c+=s/o.length*120),c}function ae(e,t){return t.filter(o=>G(e,o)).length}var re=new Map([["clojure","clojure"],["cplusplus","cpp"],["cpp","cpp"],["typescript","typescript"],["ts","typescript"],["javascript","javascript"],["js","javascript"],["nodejs","javascript"],["python","python"],["py","python"],["go","go"],["golang","go"],["csharp","csharp"],["dotnet","csharp"],["dart","dart"],["elixir","elixir"],["fsharp","fsharp"],["java","java"],["kotlin","kotlin"],["lua","lua"],["php","php"],["ruby","ruby"],["rust","rust"],["scala","scala"],["svelte","svelte"],["swift","swift"],["vue","vue"]]);function ie(e){return new Set(e.map(t=>re.get(t)).filter(t=>!!t))}function U(e){let t=e.attributes.language;return typeof t=="string"?b(t):null}function ce(e){return {project:1e3,service:900,api:900,package:850,endpoint:800,container:700,deployment:700,environment:650,pipeline:600,"test-suite":550,owner:500,decision:450,document:400}[e.kind]??0}function le(e,t){let o=t.has("language")||t.has("languages"),a=t.has("binding")||t.has("bindings")||t.has("bridge")||t.has("bridges"),l=t.has("dependency")||t.has("dependencies")||t.has("depends"),r=t.has("core")||t.has("runtime"),d=t.has("owner")||t.has("owners")||t.has("ownership")||t.has("maintainer"),u=t.has("ci")||t.has("pipeline")||t.has("pipelines")||t.has("workflow"),c=t.has("deploy")||t.has("deployment")||t.has("infrastructure")||t.has("container"),s=t.has("doc")||t.has("docs")||t.has("document")||t.has("documentation"),p=t.has("service")||t.has("services")||t.has("api")||t.has("rpc"),g=t.has("schema")||t.has("schemas")||t.has("message")||t.has("protobuf")||t.has("proto")||t.has("contract"),y=typeof e.attributes.mechanism=="string"?b(e.attributes.mechanism):"",h=typeof e.attributes.specification=="string"?b(e.attributes.specification):"",k=b(e.label),f=0;if(o&&e.kind==="language"){let j=typeof e.attributes.fileCount=="number"?e.attributes.fileCount:0;f+=900+Math.min(j,1e4)/10;}return a&&e.kind==="protocol"&&(f+=800),l&&e.kind==="package"&&(f+=650),r&&e.kind==="package"&&/(?:^|[_-])core(?:$|[_-])/u.test(k)&&(f+=700),r&&e.kind==="protocol"&&y.includes("core")&&(f+=300),d&&e.kind==="owner"&&(f+=850),u&&e.kind==="pipeline"&&(f+=800),c&&["deployment","container","environment"].includes(e.kind)&&(f+=775),s&&["document","decision"].includes(e.kind)&&(f+=725),p&&["api","endpoint","service"].includes(e.kind)&&(f+=700),g&&(e.kind==="schema"||(e.kind==="api"||e.kind==="protocol")&&(h.includes("protobuf")||y.includes("protobuf")))&&(f+=750),f}function de(e){return [e.has("language")||e.has("languages"),e.has("binding")||e.has("bindings")||e.has("bridge")||e.has("bridges"),e.has("dependency")||e.has("dependencies")||e.has("depends"),e.has("core")||e.has("runtime"),e.has("owner")||e.has("ownership")||e.has("maintainer"),e.has("ci")||e.has("pipeline")||e.has("workflow"),e.has("deploy")||e.has("deployment")||e.has("infrastructure"),e.has("doc")||e.has("docs")||e.has("documentation"),e.has("service")||e.has("api")||e.has("rpc"),e.has("schema")||e.has("protobuf")||e.has("proto")||e.has("contract")].filter(Boolean).length>=3}function ye(e,t){let o=b(t.query),a=[...new Set(T(t.query))],l=new Set(T(t.projectId??"")),r=t.projectId?a.filter(n=>!l.has(n)):a,d=!!(t.projectId&&a.length>0&&r.length===0),u=r.filter(n=>!ne.has(n)),c=u.length>0?u:r,s=ie(c),p=new Set(c),g=de(p),y=c.length<=1?c.length:Math.min(3,Math.ceil(c.length/3)),h=t.minimumTermMatches===void 0?y:Math.min(y,Math.max(1,Math.trunc(t.minimumTermMatches))),k=Math.max(1,Math.min(Math.trunc(t.limit??12),100)),f=Math.max(0,Math.min(Math.trunc(t.relationsPerEntity??4),20)),j=new Set;if(t.projectId){let n=new Set(e.entities.filter(i=>i.kind==="project"&&(i.projectId===t.projectId||i.label===t.projectId)).map(i=>i.id));for(let i of e.relations)n.has(i.from)&&j.add(i.to),n.has(i.to)&&j.add(i.from);}let x=e.entities.filter(n=>(!t.kind||n.kind===t.kind)&&(!t.projectId||n.projectId===t.projectId||n.projectId===void 0&&j.has(n.id))).map(oe),Q=new Map(c.map(n=>{let i=x.filter(w=>G(w,n)).length;return [n,Math.log((x.length+1)/(i+1))+1]})),P=x.map(n=>{let i=ae(n,c),w=U(n.entity),I=w&&s.has(w)?400:0,K=le(n.entity,p);return {entity:n.entity,matchedTerms:i,intentScore:K,score:d?ce(n.entity):se(n,o,c,Q)+I+K}}).filter(n=>{let i=U(n.entity);return (s.size===0||i===null||s.has(i))&&(o.length===0||n.score>0&&(d||n.matchedTerms>=h||n.intentScore>0&&(g||c.length<=2)))}).sort((n,i)=>i.score-n.score||n.entity.kind.localeCompare(i.entity.kind)||n.entity.label.localeCompare(i.entity.label)),E=(g?(()=>{let n=[],i=[],w=new Map,I=new Set;for(let K of P){let V=w.get(K.entity.kind)??0,z=b(K.entity.label);V<2&&!I.has(z)?(n.push(K),w.set(K.entity.kind,V+1),I.add(z)):i.push(K);}return [...n,...i]})():P).slice(0,k).map(n=>n.entity),v=new Set(E.map(n=>n.id)),D=new Map,B=e.relations.filter(n=>{if(!(v.has(n.from)||v.has(n.to)))return false;let w=v.has(n.from)?n.from:n.to,I=D.get(w)??0;return I>=f?false:(D.set(w,I+1),true)}),W=t.projection==="agent",M=W?B.slice(0,m.relations):B,H=A(e),_=[...new Set(M.flatMap(n=>[n.from,n.to]).filter(n=>!v.has(n)))].map(n=>H.entitiesById.get(n)).filter(n=>!!n).map(({id:n,kind:i,label:w,projectId:I})=>({id:n,kind:i,label:w,...I?{projectId:I}:{}})).sort((n,i)=>n.kind.localeCompare(i.kind)||n.label.localeCompare(i.label)),L=W?_.slice(0,m.relatedEntities):_,N=new Set([...E.flatMap(n=>n.proofIds),...M.flatMap(n=>n.proofIds)]),$=W?J([...E,...M]):[...N],C=new Set($),R={entities:P.length-E.length,relations:B.length-M.length,relatedEntities:_.length-L.length,proofs:N.size-C.size,proofReferences:0,aliases:0,attributeValues:0},q=W?E.map(n=>ee(n,C,R)):E,Y=W?M.map(n=>{let i=n.proofIds.filter(w=>C.has(w)).slice(0,m.proofIdsPerItem);return R.proofReferences+=n.proofIds.length-i.length,{...n,proofIds:i}}):M,X=[...C].map(n=>H.proofsById.get(n)).filter(n=>!!n).sort((n,i)=>n.id.localeCompare(i.id));return {schemaVersion:Z,query:t.query,kind:t.kind??null,...t.projectId?{projectId:t.projectId}:{},limit:k,totalMatches:P.length,truncated:P.length>q.length||W&&Object.values(R).some(n=>n>0),entities:q,relatedEntities:L,relations:Y,proofs:X,...W?{budget:{mode:"agent",limits:{...m},omitted:R}}:{}}}export{Z as a,O as b,fe as c,ke as d,we as e,ye as f};
@@ -1 +0,0 @@
1
- import {c,d as d$1}from'./chunk-TFOOSYGO.js';import {d}from'./chunk-CCDGHPEJ.js';import {e,f as f$1}from'./chunk-NZ3WZYD5.js';import A from'fs-extra';function t(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function W(e){let s=t(e);return !!(s&&s.schemaVersion===f$1.model&&t(s.workspace)&&Array.isArray(s.projects)&&(t(s.projectTopology)||t(s.graph)))}function G(e){let s=t(e);return !!(s&&s.schemaVersion===f$1.knowledgeGraph&&t(s.source)&&t(s.workspace)&&Array.isArray(s.entities)&&Array.isArray(s.relations)&&Array.isArray(s.proofs)&&Array.isArray(s.providers)&&t(s.quality))}async function f(e){try{return await A.readJson(e)}catch{return null}}async function I(e$1){let[s,n]=await Promise.all([d(e$1,e.model),d(e$1,e.knowledgeGraph)]);if(!s)return {status:"miss",reason:"missing-model"};if(!n)return {status:"miss",reason:"missing-graph"};let[i,o]=await Promise.all([f(s),f(n)]);if(!W(i))return {status:"miss",reason:"invalid-model"};if(!G(o))return {status:"miss",reason:"invalid-graph"};if(o.proofs.some(r=>r.freshness==="stale"))return {status:"miss",reason:"stale-proof"};try{c(o,i);}catch{return {status:"miss",reason:"source-mismatch"}}let a=o.source.inputs;if(!a)return {status:"miss",reason:"missing-input-fingerprint"};let d$2=a.scopes.filter(r=>r.kind==="workspace"),p=a.scopes.filter(r=>r.kind==="project"),k=i.projects.map(r=>r.name).sort(),w=p.map(r=>r.id).sort(),y=new Set(p.map(r=>r.fileLimit));if(a.schemaVersion!=="workspace-knowledge-graph-inputs.v1"||a.strategy!=="hybrid-git-content-v2"||a.hashAlgorithm!=="sha256"||d$2.length!==1||y.size>1||JSON.stringify(k)!==JSON.stringify(w))return {status:"miss",reason:"invalid-input-fingerprint"};let c$1;try{c$1=await d$1({workspacePath:e$1,projects:i.projects.map(r=>({id:r.name,path:r.path,...r.absolutePath?{absolutePath:r.absolutePath}:{}})),projectFileLimit:p[0]?.fileLimit??2e4,workspaceFileLimit:d$2[0].fileLimit});}catch{return {status:"miss",reason:"input-scan-failed"}}return !c$1||c$1.hash!==a.hash?{status:"miss",reason:"live-input-mismatch"}:{status:"hit",model:i,graph:o,modelPath:s,graphPath:n}}export{I as a};
@@ -1,4 +0,0 @@
1
- import {f,e}from'./chunk-ILIBOMYL.js';import {a,b}from'./chunk-QJCCZLOF.js';import {a as a$1,b as b$2}from'./chunk-X7FYEKLI.js';import {c as c$1,d}from'./chunk-HCFWT42C.js';import {i,j as j$1,l,k,n}from'./chunk-SCP5LJNO.js';import {a as a$2,e as e$2}from'./chunk-CCDGHPEJ.js';import {b as b$1}from'./chunk-D65FCQIO.js';import {f as f$1,e as e$1}from'./chunk-NZ3WZYD5.js';import {s}from'./chunk-MOSXTVPU.js';import u from'chalk';import c from'fs';import y from'path';var H=e$1.readiness,K=f$1.readiness;function U(n,e){let t=y.resolve(n);if(!b(t))return t;let a=M(e,"workspace.contract.json");if(c.existsSync(a))try{let o=JSON.parse(c.readFileSync(a,"utf-8")),s=Array.isArray(o.projects)?o.projects:[];for(let i of s){let l=m(i),p=typeof l.relativePath=="string"?l.relativePath.trim():"";if(p)return y.join(e,p)}}catch{}let r=T(e),d=Array.isArray(r.payload?.projects)?r.payload.projects:[];for(let o of d){let s=m(o),i=typeof s.path=="string"?s.path.trim():"";if(i)return y.resolve(i)}return t}function z(n$1){let e=i(n$1);return j$1(e,n$1)?"go":l(e,n$1)?"java":k(e,n$1)?"node":n(e,n$1)?"python":"unknown"}function _(n,e){if(!c.existsSync(n))return null;let t=c.readdirSync(n).filter(a=>a.endsWith(".json")&&e.some(r=>r.test(a))).map(a=>y.join(n,a));return t.length===0?null:(t.sort((a,r)=>c.statSync(r).mtimeMs-c.statSync(a).mtimeMs),t[0])}function m(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function J(n){for(let e of n)if(c.existsSync(e))return e;return null}function M(n,...e){let t=s(n,...e);return J(t)??t[0]}function j(n,e){let t=a$2(n,`.workspai/reports/${e}`);return J([t,y.join(n,".rapidkit","reports",e)])??t}async function B(n){let{readWorkspaceRegistrySummary:e,resolveWorkspaceRegisteredProjects:t}=await import('./workspace-registry-summary-VSOBKAJG.js'),a=await e(n);return a?a.projectCount:(await t(n)).summary.projectCount}function Q(n,e,t){let a=M(n,"toolchain.lock");if(!c.existsSync(a))return {gate:"env",status:"fail",summary:"toolchain.lock is missing",details:["Run workspai bootstrap to pin runtime versions and generate a reproducible toolchain."],evidencePath:a};try{let r=JSON.parse(c.readFileSync(a,"utf-8")),d=m(r.runtime),s=["python","node","go","java"].filter(p=>{let f=m(d[p]);return typeof f.version=="string"&&f.version.trim().length>0});if(s.length===0)return {gate:"env",status:"fail",summary:"No runtime versions are pinned in toolchain.lock",details:["Pin at least one runtime version via workspai setup <runtime> and re-run bootstrap."],evidencePath:a};let l=[...new Set((Array.isArray(e)?e:[e]).filter(p=>p!=="unknown"))].filter(p=>{let f=m(d[p]);return typeof f.version!="string"||f.version.trim().length===0});return l.length>0?{gate:"env",status:"fail",summary:`${t?.hasRegisteredProjects?"Project runtime":"Workspace"}${l.length===1?"":"s"} (${l.join(", ")}) ${l.length===1?"is":"are"} not pinned in toolchain.lock`,details:l.map(f=>`Run workspai setup ${f} and workspai bootstrap to lock ${f} for this workspace.`),evidencePath:a}:{gate:"env",status:"pass",summary:`Pinned runtimes: ${s.join(", ")}`,details:[],evidencePath:a}}catch{return {gate:"env",status:"fail",summary:"toolchain.lock is invalid JSON",details:["Regenerate lockfile with workspai bootstrap."],evidencePath:a}}}function T(n){let e=j(n,"doctor-last-run.json");if(!c.existsSync(e))return {payload:null,path:e};try{let t=JSON.parse(c.readFileSync(e,"utf-8"));return c$1(t,"workspace")?(d(t),{payload:t,path:e}):{payload:null,path:e}}catch{return {payload:null,path:e}}}function X(n){let e=T(n);if(!e.payload)return {gate:{gate:"doctor",status:"fail",summary:"Doctor evidence is missing",details:["Run workspai doctor workspace --json before release readiness checks."],evidencePath:e.path},payload:null};let t=a$1(e.payload);if(t.hasSystemErrors)return {gate:{gate:"doctor",status:"fail",summary:"Doctor reported system errors",details:["Resolve system-level doctor errors before proceeding."],evidencePath:e.path},payload:e.payload};if(t.blockingFindings>0)return {gate:{gate:"doctor",status:"fail",summary:`Doctor reported ${t.blockingFindings} blocking finding(s)`,details:["Resolve the canonical Doctor findings and regenerate fresh Doctor evidence."],evidencePath:e.path},payload:e.payload};let a=[...t.advisoryFindings>0?[`${t.advisoryFindings} advisory finding(s)`]:[],...t.unknownFindings>0?[`${t.unknownFindings} unknown finding(s)`]:[],...t.contradictionCount>0?[`${t.contradictionCount} evidence contradiction(s)`]:[],...t.missingDiagnosisProjects>0?[`${t.missingDiagnosisProjects} project(s) without canonical diagnosis`]:[],...t.staleEvidence?["stale Doctor evidence"]:[],...t.unknownFreshness?["unknown Doctor evidence freshness"]:[],...t.minimumDiagnosisCompleteness<100?[`diagnosis completeness ${t.minimumDiagnosisCompleteness}%`]:[]];return a.length>0?{gate:{gate:"doctor",status:"warn",summary:"Doctor evidence requires attention",details:a,evidencePath:e.path},payload:e.payload}:{gate:{gate:"doctor",status:"pass",summary:"Doctor checks passed without issues",details:[],evidencePath:e.path},payload:e.payload}}function Y(n){let e=j(n,"analyze-last-run.json");if(!c.existsSync(e))return {gate:"analyze",status:"fail",summary:"Analyze evidence is missing",details:["Run workspai analyze --json before release readiness checks."],evidencePath:e};try{let t=JSON.parse(c.readFileSync(e,"utf-8"));b$1(e$1.analyze,t,e);let a=m(t.summary),r=String(a.verdict??"").toLowerCase(),d=Number(a.score??0),o=m(a.findings),s=Number(o.fail??0);return r==="blocked"||s>0?{gate:"analyze",status:"fail",summary:`Analyze verdict is blocked (score ${d}/100)`,details:["Resolve analyze findings and regenerate analyze-last-run.json."],evidencePath:e}:r==="needs-attention"?{gate:"analyze",status:"warn",summary:`Analyze needs attention (score ${d}/100)`,details:["Review analyze warnings before release."],evidencePath:e}:{gate:"analyze",status:"pass",summary:`Analyze passed (score ${d}/100)`,details:[],evidencePath:e}}catch{return {gate:"analyze",status:"fail",summary:"Analyze evidence is invalid or violates its contract",details:["Re-run workspai analyze --json to regenerate evidence."],evidencePath:e}}}function Z(n){try{let e=JSON.parse(c.readFileSync(n,"utf-8")),t=String(e.status??"").toLowerCase(),a=m(e.summary),r=Number(a.failedChecks??0);return t==="fail"||r>0?{gate:"verify",status:"fail",summary:"Verify-pack contract reports failed checks",details:["Fix failed verify checks and regenerate verify-pack contract evidence."],evidencePath:n}:t==="pass"?{gate:"verify",status:"pass",summary:"Verify-pack contract passed",details:[],evidencePath:n}:{gate:"verify",status:"warn",summary:"Verify-pack contract status is not explicit",details:["Ensure contract status is pass/fail and keep schema aligned with v1 contract."],evidencePath:n}}catch{return {gate:"verify",status:"fail",summary:"Verify-pack contract is invalid JSON",details:["Regenerate verify-pack contract artifact."],evidencePath:n}}}async function ee(n,e){if(e.skipVerify)return {gate:"verify",status:"pass",summary:"Verify gate skipped (--skip-verify)",details:["Verification was explicitly skipped for this readiness run."]};let t=[a$2(n,".workspai/reports"),y.join(n,".rapidkit","reports")],a=t[0],r=t.map(s=>_(s,[/verify-pack-contract/i,/^verify.*\.json$/i])).find(s=>typeof s=="string")??null;if(r)return Z(r);let d=a$2(n,e$1.contractVerify),o=t.map(s=>_(s,[/workspace-contract-verify-last-run/i,/workspace-contract-verify/i])).find(s=>typeof s=="string")??null;if(o)try{let s=JSON.parse(c.readFileSync(o,"utf-8")),i=String(s.status??"").toLowerCase();if(i==="passed"||i==="pass")return {gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI cache)",details:[],evidencePath:o};if(i==="failed"||i==="fail")return {gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI cache)",details:(Array.isArray(s.violations)?s.violations:[]).slice(0,5),evidencePath:o}}catch{}try{let{verifyWorkspaceContract:s}=await import('./workspace-contract-3BWIRSVQ.js'),i=await s({workspacePath:n}),l={schemaVersion:"v1",source:"cli",generatedAt:new Date().toISOString(),status:i.status,contractPath:i.contractPath,projectCount:i.projectCount,checks:i.checks,violations:i.violations};return await e$2(n,e$1.contractVerify,l),i.status==="failed"?{gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI)",details:i.violations.slice(0,5),evidencePath:d}:{gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI)",details:[],evidencePath:d}}catch(s){return {gate:"verify",status:"fail",summary:"No verify evidence and workspace contract verification unavailable",details:["Run workspai workspace contract verify --json or export verify-pack contract from CI.",s instanceof Error?s.message:String(s)],evidencePath:y.join(a,"*verify*.json")}}}function te(n,e){let t=j(e,"doctor-last-run.json");if(!n)return {gate:"dependency",status:"warn",summary:"Dependency risk check skipped (doctor evidence missing)",details:["Run workspai doctor workspace --json to include dependency findings."],evidencePath:t};let a=b$2(n);return a.blockingFindings>0||a.vulnerableDependencies>0?{gate:"dependency",status:"fail",summary:`${Math.max(a.blockingFindings,a.vulnerableDependencies)} blocking dependency/security vulnerability finding(s) reported`,details:["Resolve the typed dependency/security findings and regenerate focused audit evidence."],evidencePath:t}:a.auditFailed>0?{gate:"dependency",status:"fail",summary:`${a.auditFailed} dependency audit(s) failed`,details:["Repair the audit runner or dependency environment; failed audits are not clean."],evidencePath:t}:a.missingDependencies>0||a.auditUnavailable>0||a.unknownFindings>0||a.advisoryFindings>0?{gate:"dependency",status:"warn",summary:"Dependency evidence is incomplete or requires attention",details:[...a.missingDependencies>0?[`${a.missingDependencies} project(s) have no materialized dependency tree.`]:[],...a.auditUnavailable>0?[`${a.auditUnavailable} audit provider(s) are unavailable or unsupported.`]:[],...a.unknownFindings>0?[`${a.unknownFindings} dependency/security finding(s) remain unknown.`]:[],...a.advisoryFindings>0?[`${a.advisoryFindings} dependency/security advisory finding(s) remain.`]:[]],evidencePath:t}:{gate:"dependency",status:"pass",summary:"No dependency vulnerabilities reported",details:[],evidencePath:t}}function ne(n){return n.some(e=>e.status==="fail")?"fail":n.some(e=>e.status==="warn")?"warn":"pass"}async function ae(n,e){return e$2(n,H,e)}async function se(n={}){let e$1=y.resolve(n.startPath??process.cwd()),t=a(e$1)??e$1,a$1=await B(t)>0,r=a$1&&b(e$1)?t:U(e$1,t),d=r===t?"unknown":z(r),o=a$1?d:"unknown";if(a$1&&r===t){let{resolveWorkspaceRegisteredProjects:g}=await import('./workspace-registry-summary-VSOBKAJG.js');o=(await g(t)).summary.projects.map(q=>z(y.resolve(t,q.relativePath)));}let s=Q(t,o,{hasRegisteredProjects:a$1}),i=X(t),l=Y(t),p=await ee(t,{skipVerify:n.skipVerify}),f$1=te(i.payload,t),w=[s,i.gate,l,p,f$1],k=ne(w),v={schemaVersion:K,generatedAt:new Date().toISOString(),workspacePath:t,projectPath:r,action:n.action,overallStatus:k,blocking:k==="fail",blockingReasons:w.filter(g=>g.status==="fail").map(g=>`${g.gate}: ${g.summary}`),gates:w};if(n.writeReport!==false){let g=f(v,{commandId:"workspaceReadiness",exitCode:k==="fail"?2:k==="warn"?1:0,generatedAt:v.generatedAt,blockers:v.blockingReasons,runId:e()});v.evidencePath=await ae(t,g);}return v}function re(n){return n==="pass"?u.green("PASS"):n==="warn"?u.yellow("WARN"):u.red("FAIL")}function ie(n){return n==="pass"?u.green("PASS"):n==="warn"?u.yellow("WARN"):u.red("FAIL")}async function Pe(n){let e=await se({startPath:n.workspace,writeReport:true,skipVerify:n.skipVerify===true});if(n.json)console.log(JSON.stringify(e,null,2));else {console.log(u.bold.cyan(`
2
- \u{1F6A6} Workspai Release Readiness
3
- `)),console.log(u.bold(`Workspace: ${u.cyan(y.basename(e.workspacePath))}`)),console.log(u.gray(`Path: ${e.workspacePath}`)),console.log(`Overall: ${ie(e.overallStatus)}`);for(let t of e.gates){console.log(` - ${t.gate}: ${re(t.status)} ${t.summary}`);for(let a of t.details)console.log(u.gray(` ${a}`));t.evidencePath&&console.log(u.gray(` evidence: ${t.evidencePath}`));}e.evidencePath&&console.log(u.gray(`
4
- Evidence saved: ${e.evidencePath}`));}n.strict&&e.overallStatus!=="pass"&&process.exit(1);}export{se as a,Pe as b};
@@ -1,144 +0,0 @@
1
- import {g,b,i as i$1,d as d$2,e as e$1,f}from'./chunk-Z5L2IK54.js';import {c}from'./chunk-GPOZILMY.js';import {c as c$1}from'./chunk-X7FYEKLI.js';import {d as d$3,b as b$1,a as a$1}from'./chunk-3RBUSW7H.js';import {d as d$1}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-AFIFZTOY.js';import {h,e,i}from'./chunk-NZ3WZYD5.js';import {t,h as h$1,g as g$1}from'./chunk-MOSXTVPU.js';import le from'crypto';import H from'fs';import k from'fs/promises';import d from'path';import {execa}from'execa';import he from'fs-extra';var ke=h.projectContextAgent.schemaVersion,Ze=["managed","local","off"],de="<!-- WORKSPAI:PROJECT-GROUNDING:START -->",pe="<!-- WORKSPAI:PROJECT-GROUNDING:END -->";function oe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}async function E(e){try{return JSON.parse(await k.readFile(e,"utf8"))}catch(t){return null}}function x(e){return e.replace(/\\/g,"/").replace(/^\.\/+/,"")}function O(e,t,n){let o=e.replace(/\\/g,"/"),i=/^[A-Za-z]:\//.test(o);if(!d.isAbsolute(e)&&!i)return x(o);if(i&&process.platform!=="win32")return null;let c=d.resolve(e),s=d.relative(n,c);if(s&&!s.startsWith("..")&&!d.isAbsolute(s))return x(s);let l=d.relative(t,c);return l&&!l.startsWith("..")&&!d.isAbsolute(l)?`workspace:${x(l)}`:null}function P(e,t,n){return [[n,"project:"],[n.replace(/\\/g,"/"),"project:"],[t,"workspace:"],[t.replace(/\\/g,"/"),"workspace:"]].reduce((i,[c,s])=>c.length>0?i.split(c).join(s):i,e)}function ge(e,t){return oe(e?.adoption)?.mode==="linked"?"adopted":oe(e?.import)?"imported":t}function we(e){if(!e.model)return null;let t=x(e.relativePath);return e.model.projects.find(n=>n.name===e.projectName||x(n.path)===t)??null}function ne(e,t){e[t]=(e[t]??0)+1;}var ye=["project","language","service","api","endpoint","schema","protocol","runtime-unit","lifecycle-stage","database","queue","container","deployment","pipeline","environment","test-suite","owner","decision","document","package","file","module","symbol"];function je(e,t=160){let n={language:32,api:32,service:32,endpoint:32,schema:32,protocol:32,"runtime-unit":32,"lifecycle-stage":32,file:8,module:8,symbol:8},o=[];for(let i of ye){let c=e.filter(s=>s.kind===i).sort((s,l)=>s.label.localeCompare(l.label)||s.id.localeCompare(l.id)).slice(0,n[i]??32);for(let s of c){if(o.length>=t)return o;o.push(s);}}return o}function Pe(e,t){if(!e)return {entityCount:0,relationCount:0,proofCount:0,entitiesByKind:{},relationsByKind:{},languages:{},semantic:{protocolConceptCount:0,protocolImplementationBindings:0,equivalenceBindings:0,generationBindings:0,runtimeUnitCount:0,lifecycleStageCount:0,runtimeCoverage:[]},relatedProjects:[],proofArtifacts:[],entities:[],relations:[],proofs:[],topology:{status:"unavailable",dependencies:[],dependents:[]},diagnostics:[]};let n=e.entities.find(r=>r.kind==="project"&&(r.id===t||r.label===t||r.projectId===t)),o=new Set(e.entities.filter(r=>r.projectId===t||r.id===n?.id||r.kind==="project"&&r.label===t).map(r=>r.id));n&&o.add(n.id);let i=e.relations.filter(r=>o.has(r.from)||o.has(r.to)),c=new Set(o);for(let r of i)c.add(r.from),c.add(r.to);let s=e.entities.filter(r=>c.has(r.id)),l=new Set,p={},u={},f={},w=new Set(s.filter(r=>r.kind==="language").map(r=>r.attributes.language).filter(r=>typeof r=="string"));for(let r of s){ne(p,r.kind);let a=typeof r.attributes.language=="string"?r.attributes.language:void 0;if(a&&r.kind==="language")f[a]={fileCount:typeof r.attributes.fileCount=="number"?r.attributes.fileCount:0,symbolCount:f[a]?.symbolCount??0,generatedFileCount:typeof r.attributes.generatedFileCount=="number"?r.attributes.generatedFileCount:0};else if(a&&(r.kind==="file"||r.kind==="symbol")){let h=f[a]??{fileCount:0,symbolCount:0,generatedFileCount:0};r.kind==="file"&&!w.has(a)?(h.fileCount+=1,r.attributes.generated===true&&(h.generatedFileCount+=1)):r.kind==="symbol"&&(h.symbolCount+=1),f[a]=h;}for(let h of r.proofIds)l.add(h);}for(let r of i){ne(u,r.kind);for(let a of r.proofIds)l.add(a);}let y=e.proofs.filter(r=>l.has(r.id)),b=[...new Set(e.entities.filter(r=>c.has(r.id)&&r.projectId&&r.projectId!==t).map(r=>r.projectId))].sort(),m=e.diagnostics.filter(r=>r.entityIds?.some(a=>c.has(a))||r.relationIds?.some(a=>i.some(h=>h.id===a))).map(r=>({code:r.code,severity:r.severity,message:r.message,...r.recommendation?{recommendation:r.recommendation}:{}})),g=(r,a)=>({project:a,kind:r.kind,source:r.source,confidence:r.confidence,evidence:[...new Set(r.evidence.map(h=>h.file.replace(/\\/g,"/")))].sort()}),v=e.projectTopology.edges.filter(r=>r.from===t).map(r=>g(r,r.to)).sort((r,a)=>`${r.project}:${r.kind}`.localeCompare(`${a.project}:${a.kind}`)),C=e.projectTopology.edges.filter(r=>r.to===t).map(r=>g(r,r.from)).sort((r,a)=>`${r.project}:${r.kind}`.localeCompare(`${a.project}:${a.kind}`)),R=je(s),S=s.filter(r=>r.kind==="runtime-unit"),j=new Set(R.map(r=>r.id)),_=[...i].sort((r,a)=>{let h=Number(j.has(r.from)||j.has(r.to));return Number(j.has(a.from)||j.has(a.to))-h||r.id.localeCompare(a.id)}).slice(0,128),W=new Set([...R.flatMap(r=>r.proofIds),..._.flatMap(r=>r.proofIds)]);return {entityCount:s.length,relationCount:i.length,proofCount:y.length,entitiesByKind:p,relationsByKind:u,languages:Object.fromEntries(Object.entries(f).sort(([r],[a])=>r.localeCompare(a))),semantic:{protocolConceptCount:p.protocol??0,protocolImplementationBindings:u["implements-protocol"]??0,equivalenceBindings:u["equivalent-to"]??0,generationBindings:(u["generated-from"]??0)+(u["generated-by"]??0),runtimeUnitCount:S.length,lifecycleStageCount:p["lifecycle-stage"]??0,runtimeCoverage:[...new Set(S.map(r=>r.attributes.runtime).filter(r=>typeof r=="string"))].sort()},relatedProjects:b,proofArtifacts:[...new Set(y.map(r=>r.artifact))].sort(),entities:R,relations:_,proofs:y.filter(r=>W.has(r.id)).sort((r,a)=>r.id.localeCompare(a.id)).slice(0,128),topology:{status:v.length>0||C.length>0?"proven":e.projectTopology.nodes.some(r=>r.id===t)?"unproven":"unavailable",dependencies:v,dependents:C},diagnostics:m}}function ue(e,t,n){return Array.isArray(e)?e.map(o=>typeof o=="string"?P(o,t,n):o):typeof e=="string"?P(e,t,n):e}function be(e,t,n){return {id:e.id,kind:e.kind,label:P(e.label,t,n),attributes:Object.fromEntries(Object.entries(e.attributes).map(([o,i])=>[o,ue(i,t,n)])),proofIds:[...e.proofIds].sort()}}function ve(e,t,n){let o=(...c)=>e.filter(s=>c.includes(s.kind)).map(s=>be(s,t,n)).slice(0,32),i=[];for(let c of e){for(let[s,l]of Object.entries(c.attributes))if(/(?:^|[-_.])ports?(?:$|[-_.])/i.test(s)&&(i.push({entityId:c.id,label:P(c.label,t,n),attribute:s,value:ue(l,t,n)}),i.length>=32))break;if(i.length>=32)break}return {services:o("service"),packages:o("package"),protocols:o("protocol"),runtimeUnits:o("runtime-unit"),lifecycleStages:o("lifecycle-stage"),apis:o("api"),endpoints:o("endpoint"),dataStores:o("database","queue"),deployments:o("container","deployment","environment"),pipelines:o("pipeline"),tests:o("test-suite"),owners:o("owner"),decisions:o("decision"),ports:i}}function Ae(e,t,n){let o=O(e.artifact,t,n);return o?{id:e.id,provider:e.provider,artifact:o,...e.pointer?{pointer:P(e.pointer,t,n)}:{},...e.line!==void 0?{line:e.line}:{},derivation:e.derivation,trust:e.trust,confidence:e.confidence,freshness:e.freshness}:null}async function Ee(e,t,n){let o=[],i=await E(d.join(e,".workspai","reports","INDEX.json"));if(Array.isArray(i?.blockers))for(let s of i.blockers)typeof s=="string"&&(s.startsWith(`${n}:`)||s.includes(`project:${n}`)||s.includes(`project ${n}`))&&o.push({source:"workspace-report-index",severity:"error",message:P(s,e,t)});let c=await E(d.join(e,".workspai","reports","doctor-project-last-run.json"));if(c?.projectName===n)for(let s of c$1({project:c.project}))o.push({source:"doctor-project",severity:s.status==="blocking"?"error":"warning",message:P(s.message,e,t),...s.id?{code:s.id}:{}});return [...new Map(o.map(s=>[`${s.source}:${s.code??""}:${s.message}`,s])).values()].slice(0,32)}function U(e,t=[]){return typeof e=="string"?/^[A-Za-z]:[\\/]/.test(e)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(e)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(e)||t.some(n=>n.length>0&&(e.includes(n)||e.includes(n.replace(/\\/g,"/")))):Array.isArray(e)?e.some(n=>U(n,t)):e&&typeof e=="object"?Object.values(e).some(n=>U(n,t)):false}function Ce(e){return le.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Re(e$1){let t$1=d.resolve(e$1.workspacePath),n=d.resolve(e$1.projectPath),o=t(n,"project.json").find(a=>H.existsSync(a)),i$1=o?await E(o):null,c=await E(d.join(t$1,".workspai","workspace.contract.json")),s=d.resolve(n),l=c?.projects?.find(a=>a.externalPath?d.resolve(a.externalPath)===s:!a.relativePath||a.relativePath.startsWith("external/")?false:d.resolve(t$1,a.relativePath)===s)??c?.projects?.find(a=>a.slug===e$1.projectName||a.slug===d.basename(n)),p=e$1.projectName??(typeof i$1?.name=="string"?i$1.name:void 0)??l?.slug??d.basename(n),u=l?.relativePath??(()=>{let a=x(d.relative(t$1,n));return !a||a.startsWith("..")?`external/${p}`:a})(),f=await E(d.join(t$1,e.model)),w=await E(d.join(t$1,e.knowledgeGraph)),y=f?d$1(f):void 0,b$1=!!(y&&w?.source.hash===y),m=we({model:f,projectName:p,relativePath:u}),g=Pe(b$1?w:null,p),v=await Ee(t$1,n,p),C=g.proofs.map(a=>a.freshness),R=w?!b$1||C.includes("stale")?"stale":C.includes("unknown")?"unknown":"fresh":"missing",S=f?f.factFreshness?.status??"unknown":"missing",j=[...f?[]:[{code:"project.context.model-missing",severity:"warning",message:"The canonical Workspace Model has not been generated yet. Refresh workspace intelligence before relying on project topology."}],...f&&!m?[{code:"project.context.project-not-materialized",severity:"warning",message:"The project is registered in the workspace contract but is not present in the current Workspace Model."}]:[],...w?[]:[{code:"project.context.graph-missing",severity:"warning",message:"The Workspace Knowledge Graph has not been generated yet. Run the workspace intelligence loop to build proof-backed relationships."}],...w&&!b$1?[{code:"project.context.graph-model-mismatch",severity:"warning",message:"The persisted Knowledge Graph does not match the current Workspace Model and was excluded from this project lens."}]:[]],_=ge(i$1,e$1.relationship??l?.relationship??"managed"),W={schemaVersion:ke,generatedAt:(e$1.now??new Date).toISOString(),workspace:{name:c?.workspace?.name??f?.workspace.name??d.basename(t$1),...c?.workspace?.profile||f?.workspace.profile?{profile:c?.workspace?.profile??f?.workspace.profile}:{},relationship:_,contract:`workspace:${i.workspaceContract}`,index:`workspace:${e.agentIndex}`,context:`workspace:${e.agentContext}`,skillsIndex:`workspace:${e.skillsIndex}`,boundedGraphSearch:`workspai workspace graph search <task-query> --scope project:${p} --limit 12 --json`,access:{localBinding:i.projectWorkspaceLink,canonicalEvidenceAvailableAtGeneration:true,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"}},project:{name:p,relativePath:u,...m?.kind?{kind:m.kind}:{},...m?.runtime||l?.runtime?{runtime:m?.runtime??l?.runtime}:{},...m?.runtimeCandidates?.length?{runtimeCandidates:[...m.runtimeCandidates].sort()}:{},...m?.framework||l?.framework?{framework:m?.framework??l?.framework}:{},...m?.kit||l?.kit?{kit:m?.kit??l?.kit}:{},...m?.supportTier?{supportTier:m.supportTier}:{},commands:{supported:[...m?.commands.supported??[]].sort(),unsupported:[...m?.commands.unsupported??[]].sort(),fleetStages:[...m?.commands.fleetStages??[]].sort()},importantFiles:[...new Set((m?.importantFiles??[]).map(a=>O(a,t$1,n)).filter(a=>a!==null))].sort()},intelligence:{...f?.generatedAt?{modelGeneratedAt:f.generatedAt}:{},...w?.generatedAt?{graphGeneratedAt:w.generatedAt}:{},...w?.source.hash?{graphModelHash:w.source.hash}:{},entityCount:g.entityCount,relationCount:g.relationCount,proofCount:g.proofCount,entitiesByKind:g.entitiesByKind,relationsByKind:g.relationsByKind,languages:g.languages,semantic:g.semantic,relatedProjects:g.relatedProjects,freshness:{model:S,graph:R,graphMatchesModel:b$1},topology:{...g.topology,dependencies:g.topology.dependencies.map(a=>({...a,evidence:a.evidence.map(h=>O(h,t$1,n)).filter(h=>h!==null)})),dependents:g.topology.dependents.map(a=>({...a,evidence:a.evidence.map(h=>O(h,t$1,n)).filter(h=>h!==null)}))},surfaces:ve(g.entities,t$1,n),diagnostics:[...j,...g.diagnostics].map(a=>({...a,message:P(a.message,t$1,n),...a.recommendation?{recommendation:P(a.recommendation,t$1,n)}:{}}))},evidence:{readOrder:[b,".workspai/PROJECT-GROUNDING.md",i.projectContextAgent,"AGENTS.md","workspace:.workspai/goals/index.json",`workspace:${i.goalPackLastRun}`,"workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json","workspace:.workspai/reports/workspace-skills-index.json",`command:workspai workspace graph search <task-query> --scope project:${p} --limit 12 --json`],projectProofArtifacts:[...new Set(g.proofArtifacts.map(a=>O(a,t$1,n)).filter(a=>a!==null))],relations:g.relations.map(a=>({id:a.id,from:a.from,to:a.to,kind:a.kind,derivation:a.derivation,trust:a.trust,confidence:a.confidence,proofIds:[...a.proofIds].sort()})),proofs:g.proofs.map(a=>Ae(a,t$1,n)).filter(a=>a!==null)},blockers:v,agentRouting:{enforcement:"required",mandatoryPreflight:{command:"workspai agent bootstrap --for-agent generic --strict --json",successCondition:"ready"},workspaceLocator:{command:"workspai project workspace status --json",successCondition:"resolved",outputClassification:"machine-local",persistence:"forbidden",disclosure:"forbidden",portableUriScheme:"workspace:"},workspaceEvidenceRequiredFor:["repository-analysis","architecture-analysis","change-impact","cross-project-change","contract-change","infrastructure-change","release-readiness"],requiredReadOrder:[b,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",i.projectContextAgent,"workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json","workspace:.workspai/reports/workspace-skills-index.json",`command:workspai workspace graph search ${JSON.stringify(p)} --scope ${JSON.stringify(`project:${p}`)} --limit 12 --json`],degradedMode:{allowCompleteArchitectureClaims:false,requireDisclosure:true}},commands:{refresh:"workspai workspace intelligence run --for-agent generic --strict --json",verify:"workspai workspace verify --strict --json",graphSearch:`workspai workspace graph search ${JSON.stringify(p)} --scope ${JSON.stringify(`project:${p}`)} --limit 12 --json`,doctor:"workspai doctor project --json",workspaceStatus:"workspai project workspace status --json"}};if(U(W,[t$1,n]))throw new Error("Project context lens rejected a non-portable absolute path.");let r={...W,integrity:{algorithm:"sha256",...y?{modelHash:y}:{},payloadHash:Ce(W),portable:true,absolutePathsEmitted:false}};return a(r,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent"),r}function Te(e){let t=e.intelligence.relatedProjects.length>0?e.intelligence.relatedProjects.map(i=>`\`${i}\``).join(", "):"No proven cross-project relation is currently available.",n=e.intelligence.diagnostics.length>0?e.intelligence.diagnostics.slice(0,8).map(i=>`- **${i.severity} \xB7 ${i.code}:** ${i.message}`).join(`
2
- `):"- No project-scoped graph diagnostic is currently recorded.",o=e.blockers.length>0?e.blockers.slice(0,12).map(i=>`- **${i.severity}${i.code?` \xB7 ${i.code}`:""}:** ${i.message}`).join(`
3
- `):"- No current project-scoped blocker is recorded.";return `# Workspai project grounding
4
-
5
- This project is adopted into the **${e.workspace.name}** Workspai workspace.
6
- That value is the canonical workspace identity, not its filesystem path. Workspai
7
- commands launched here resolve the machine-local workspace automatically.
8
-
9
- ## Mandatory first contact
10
-
11
- Do not begin broad repository discovery, architecture claims, planning, or mutation
12
- until this sequence is complete:
13
-
14
- 1. Read \`.workspai/agent-entry.v1.json\` to discover the portable protocol.
15
- 2. Run \`workspai agent bootstrap --for-agent generic --strict --json\`.
16
- 3. Follow the receipt's \`requiredReadOrder\` exactly.
17
- 4. Read \`.workspai/reports/project-context-agent.json\`.
18
- 5. If the receipt reports an active Goal, read its immutable Goal Pack and agent
19
- handoff before choosing or expanding work.
20
- 6. Read the compact workspace Skills index and load only a matching playbook.
21
- 7. Query the bounded Workspace Graph with the user's actual task before opening broad
22
- source, then inspect only returned proof paths and targeted live files.
23
-
24
- Receipt policy:
25
-
26
- - \`ready\`: continue with bounded evidence and targeted source inspection.
27
- - \`degraded\`: disclose the limitation and do not claim complete architecture or verification.
28
- - \`blocked\`: stop governed claims, execute \`nextActions\`, and rerun bootstrap.
29
-
30
- ## Workspace location and portable paths
31
-
32
- - \`${e.workspace.name}\` is an identity, not a directory name to guess.
33
- - Project-local paths begin with \`.workspai/\`.
34
- - Canonical workspace paths begin with \`workspace:\`.
35
- - Resolve the exact local workspace root only when direct file access is necessary by
36
- running \`workspai project workspace status --json\` from this project.
37
- - The resolver's absolute paths are machine-local runtime data. Never persist or copy
38
- them into answers, shared logs, commits, prompts, telemetry, or portable artifacts.
39
-
40
- ## Authority boundary
41
-
42
- The Workspace Model owns canonical project identity and its compact \`projectTopology\`.
43
- The Workspace Knowledge Graph is a separate, proof-backed enrichment containing
44
- files, symbols, APIs, infrastructure, tests, owners, and decisions. Do not treat
45
- an unproven topology edge as proof that two projects are independent. Live source owns
46
- exact implementation. CLI evidence owns Goal, readiness, repair, and verification claims.
47
- Repository-authored instructions remain authoritative for source changes after this
48
- entry gate; Workspai preserves rather than replaces them.
49
-
50
- ## Project
51
-
52
- - Name: \`${e.project.name}\`
53
- - Workspace-relative identity: \`${e.project.relativePath}\`
54
- - Runtime: \`${e.project.runtime??"unknown"}\`
55
- - Framework: \`${e.project.framework??"unknown"}\`
56
- - Relationship: \`${e.workspace.relationship}\`
57
- - Related projects: ${t}
58
- - Topology status: \`${e.intelligence.topology.status}\`
59
- - Model freshness: \`${e.intelligence.freshness.model}\`
60
- - Knowledge Graph freshness: \`${e.intelligence.freshness.graph}\`
61
-
62
- ## Current evidence coverage
63
-
64
- - Project-scoped entities: ${e.intelligence.entityCount}
65
- - Project-scoped relations: ${e.intelligence.relationCount}
66
- - Portable proofs: ${e.intelligence.proofCount}
67
-
68
- ${n}
69
-
70
- ## Current project blockers
71
-
72
- ${o}
73
-
74
- ## Safe commands from this project
75
-
76
- \`\`\`bash
77
- ${e.commands.workspaceStatus}
78
- ${e.commands.doctor}
79
- ${e.commands.graphSearch}
80
- ${e.commands.verify}
81
- \`\`\`
82
-
83
- The machine-local workspace binding lives only in
84
- \`.workspai/workspace-link.local.json\`, which is gitignored. Portable grounding files
85
- never publish its value.
86
- `}function Se(e){return `# Workspai agent entry gate (mandatory)
87
-
88
- - Project: \`${e.project.name}\`
89
- - Workspace identity: \`${e.workspace.name}\` (logical name, not a filesystem path)
90
- - Entry contract: \`.workspai/agent-entry.v1.json\`
91
-
92
- Before broad repository discovery, architecture claims, planning, or mutation:
93
-
94
- 1. Read \`.workspai/agent-entry.v1.json\`.
95
- 2. Run \`workspai agent bootstrap --for-agent generic --strict --json\`.
96
- 3. Follow the receipt's \`requiredReadOrder\` exactly.
97
- 4. If a Goal is active, read its immutable Goal Pack and handoff before acting.
98
- 5. Read the compact workspace Skills index and load only a matching playbook.
99
- 6. Query the bounded Workspace Graph with the user's task, then inspect only returned proofs and targeted live source.
100
-
101
- Receipt policy: \`ready\` may proceed; \`degraded\` must disclose limitations and may not claim complete architecture or verification; \`blocked\` must stop governed claims, execute \`nextActions\`, and rerun bootstrap.
102
-
103
- \`workspace:\` paths belong to the canonical workspace, not this project's \`.workspai\` directory. Resolve their machine-local root at runtime with \`workspai project workspace status --json\`. That output is machine-local: never copy it into answers, shared logs, commits, or portable artifacts.
104
-
105
- Authority: Workspai evidence owns identity, topology, goals, readiness, and verification. Live source and repository-authored rules own exact implementation and source conventions.`}function se(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function q(e,t){return new RegExp(`${se(e)}[\\s\\S]*?${se(t)}`,"m")}function me(e){let t=e.replace(q(de,pe),"");return d$3(t)?.includes("# Workspai project boundary")&&(t=t.replace(q(a$1,b$1),"")),t.replace(/\n{3,}/g,`
106
-
107
- `).trim()}function Ne(e,t){let n=me(e),o=`${de}
108
- ${t.trim()}
109
- ${pe}`;return n?`${o}
110
-
111
- ${n}
112
- `:`${o}
113
- `}async function G(e,t){await k.mkdir(d.dirname(e),{recursive:true});let n=`${e}.${process.pid}.${le.randomUUID()}.tmp`;try{await k.writeFile(n,t,"utf8");try{await k.rename(n,e);}catch(o){let i=o.code;if(i!=="EEXIST"&&i!=="EPERM")throw o;await he.move(n,e,{overwrite:true});}}finally{await k.rm(n,{force:true}).catch(()=>{});}}async function fe(e,t){let n;try{n=await execa("git",["rev-parse","--show-toplevel"],{cwd:e,reject:false});}catch{return false}if(n?.exitCode!==0)return false;let o=n.stdout.trim();if(!o)return false;let i,c;try{[i,c]=await Promise.all([k.realpath(d.resolve(o)),k.realpath(e)]);}catch{return false}let s=d.resolve(c,t),l=d.relative(i,s).replace(/\\/g,"/");if(!l||d.isAbsolute(l)||l===".."||l.startsWith("../"))return false;let p;try{p=await execa("git",["cat-file","-e",`HEAD:${l}`],{cwd:i,reject:false});}catch{return false}if(p?.exitCode!==0)return false;let u;try{u=await execa("git",["ls-files","--deleted","--error-unmatch","--",`:(top)${l}`],{cwd:i,reject:false});}catch{return false}return u?.exitCode===0}async function ae(e,t){let n=d.join(e,".gitignore"),o=await k.readFile(n,"utf8").catch(l=>{if(l.code==="ENOENT")return "";throw l}),i=[g$1,h$1,b],c=o.split(/\r?\n/).filter(l=>l.trim()!=="# Workspai local project grounding"&&!i.includes(l.trim()));for(;c.length>0&&c[c.length-1]==="";)c.pop();t==="local"&&(c.length>0&&c.push(""),c.push("# Workspai local project grounding",...i));let s=c.length>0?`${c.join(`
114
- `)}
115
- `:"";s!==o&&await G(n,s);}var L=[{host:"claude",relativePath:"CLAUDE.md",importFromAgents:"@AGENTS.md",importFromGrounding:"@.workspai/PROJECT-GROUNDING.md"},{host:"gemini",relativePath:"GEMINI.md",importFromAgents:"@./AGENTS.md",importFromGrounding:"@./.workspai/PROJECT-GROUNDING.md"},{host:"qwen",relativePath:"QWEN.md",importFromAgents:"@AGENTS.md",importFromGrounding:"@.workspai/PROJECT-GROUNDING.md"},{host:"amazon-q",relativePath:".amazonq/rules/workspai-agent-entry.md",importFromAgents:"",importFromGrounding:""}];if(L.length!==g.length||L.some((e,t)=>e.relativePath!==g[t]))throw new Error("Project agent adapter paths must match the portable entry contract.");async function Ie(e,t){let n=t.split("/").slice(0,-1),o=e;for(let i of n){o=d.join(o,i);let c=await k.lstat(o).catch(s=>{if(s.code==="ENOENT")return null;throw s});if(!c)return null;if(c.isSymbolicLink()||!c.isDirectory())return d.relative(e,o).split(d.sep).join("/")}return null}function xe(e){let t=e.agentsAvailable?e.adapter.importFromAgents:e.adapter.importFromGrounding;return t?`${t}
116
-
117
- # Workspai host binding \xB7 ${e.adapter.host}
118
-
119
- The imported Workspai entry gate is mandatory. Validate this host with
120
- \`workspai agent bootstrap --for-agent ${e.adapter.host} --strict --json\`, then follow
121
- the receipt's \`requiredReadOrder\`, Goal handoff, bounded Graph queries, proof paths,
122
- status policy, workspace locator privacy policy, and authority boundary. Do not repeat
123
- the imported instructions or replace repository-authored source rules.`:`# Workspai entry for ${e.adapter.host}
124
-
125
- Before broad repository discovery, architecture claims, planning, or mutation:
126
-
127
- 1. Read \`.workspai/agent-entry.v1.json\`.
128
- 2. Run \`workspai agent bootstrap --for-agent ${e.adapter.host} --strict --json\`.
129
- 3. Follow \`requiredReadOrder\`, any active Goal handoff, bounded Graph queries, and returned proof paths.
130
-
131
- Receipt policy: \`ready\` may proceed; \`degraded\` must disclose limitations; \`blocked\` must execute \`nextActions\` and rerun bootstrap before governed claims.
132
-
133
- The workspace name is a logical identity, not a path. Resolve \`workspace:\` URIs at runtime with \`workspai project workspace status --json\`; its absolute paths are machine-local and must never be copied into shared output or portable artifacts. Live source owns exact implementation; Workspai evidence owns identity, topology, goals, readiness, and verification. Repository-authored rules remain authoritative for source changes after this entry gate.`}async function ie(e){let t=await Ie(e.projectPath,e.adapter.relativePath);if(t)return {reason:`${e.adapter.relativePath} has an unsafe repository-authored parent at ${t}.`};let n=d.join(e.projectPath,e.adapter.relativePath),o=await k.lstat(n).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(o?.isSymbolicLink())return {reason:`${e.adapter.relativePath} is a repository-authored symbolic link.`};let i=o?.isFile()===true,c=await k.readFile(n,"utf8").catch(u=>{if(u.code==="ENOENT")return "";throw u});if(e.mode==="managed"&&!i&&await fe(e.projectPath,e.adapter.relativePath))return {reason:`${e.adapter.relativePath} has an authored tracked deletion.`};let s=c.replace(q(d$2,e$1),"").replace(/\n{3,}/g,`
134
-
135
- `).trim(),l=e.mode==="managed"?[s,`${d$2}
136
- ${xe(e).trim()}
137
- ${e$1}`].filter(Boolean).join(`
138
-
139
- `):s;if(!l)return i&&await k.rm(n,{force:true}),{};let p=`${l.trimEnd()}
140
- `;return p!==c&&await G(n,p),e.mode==="managed"?{path:e.adapter.relativePath}:{}}function Ge(e){let t={id:"generic",discovery:"portable-fallback",entryFiles:[g$1],status:"ready",managed:e.mode==="managed"},o=["codex","kimi","grok","copilot","cursor","windsurf"].map(s=>({id:s,discovery:"native",entryFiles:["AGENTS.md"],status:e.agentsAvailable?"ready":"blocked",managed:e.mode==="managed"&&e.agentsAvailable,...e.agentsAvailable?{}:{reason:"AGENTS.md could not be managed without overriding authored repository state."}})),i=L.map(s=>{let l=e.adapters.get(s.host);return {id:s.host,discovery:"adapter",entryFiles:[s.relativePath],status:l?.path?"ready":e.mode==="managed"?"blocked":"degraded",managed:!!l?.path,...l?.path?{}:{reason:l?.reason??"Provider adapter generation is disabled by the project grounding policy."}}}),c=[t,...o,...i];return f.map(s=>c.find(l=>l.id===s))}async function ce(e,t,n){let o=d.join(e,"AGENTS.md"),i=await k.lstat(o).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(i?.isSymbolicLink())return;let c=i?.isFile()===true,s=await k.readFile(o,"utf8").catch(u=>{if(u.code==="ENOENT")return "";throw u});if(t==="managed"&&!n)throw new Error("Managed project grounding requires a project context.");if(t==="managed"&&!c&&await fe(e,"AGENTS.md"))return;let l=t==="managed"&&n?Ne(s,Se(n)):me(s);if(!l){c&&await k.rm(o,{force:true});return}let p=`${l.trimEnd()}
141
- `;return p!==s&&await G(o,p),t==="managed"?o:void 0}async function We(e){let t$1=e.mode??"managed",n=d.resolve(e.workspacePath),o=d.resolve(e.projectPath);if(t$1==="off"){let g=t(o,"project.json").find(j=>H.existsSync(j)),v=g?await E(g):null,C=e.projectName??(typeof v?.name=="string"?v.name:void 0)??d.basename(o),R=ge(v,e.relationship??"managed"),S=await c({workspacePath:n,projectPath:o,projectName:C,relationship:R,now:e.now});return await ae(o,t$1),await ce(o,t$1),await Promise.all(L.map(j=>ie({projectPath:o,adapter:j,mode:t$1,agentsAvailable:false}))),await Promise.all([k.rm(d.join(o,h$1),{force:true}),k.rm(d.join(o,g$1),{force:true}),k.rm(d.join(o,b),{force:true})]),{mode:t$1,projectPath:o,linkPath:S.linkPath,writtenFiles:[i.projectWorkspaceLink]}}let i$2=await Re(e),c$1=i$2.workspace.relationship,s=await c({workspacePath:n,projectPath:o,projectName:i$2.project.name,relationship:c$1,workspaceName:i$2.workspace.name,relativePath:i$2.project.relativePath,now:e.now});await ae(o,t$1);let l=await ce(o,t$1,i$2),p=new Map;for(let g of L)p.set(g.host,await ie({projectPath:o,adapter:g,mode:t$1,agentsAvailable:!!l}));let u=Ge({mode:t$1,agentsAvailable:!!l,adapters:p}),f=d.join(o,h$1),w=d.join(o,g$1),y=d.join(o,b),b$1=i$1({context:i$2,hosts:u});await G(f,`${JSON.stringify(i$2,null,2)}
142
- `),await G(w,`${Te(i$2).trimEnd()}
143
- `),await G(y,`${JSON.stringify(b$1,null,2)}
144
- `);let m=[i.projectWorkspaceLink,h$1,g$1,b];l&&m.push("AGENTS.md");for(let g of p.values())g.path&&m.push(g.path);return {mode:t$1,projectPath:o,linkPath:s.linkPath,groundingPath:w,contextPath:f,agentEntryPath:y,agentsPath:l,hostCoverage:u,writtenFiles:m}}async function et(e){let t=d.resolve(e.workspacePath),n=e.mode??"managed",o=await $e(t),i=[],c=[];for(let s of o.resolved)try{i.push(await We({workspacePath:t,projectPath:s.projectPath,projectName:s.name,relationship:s.relationship,mode:n,now:e.now}));}catch(l){c.push({name:s.name,reason:l instanceof Error?l.message:String(l)});}return {workspacePath:t,mode:n,projects:i,skipped:[...o.skipped,...c]}}async function $e(e){let t=d.resolve(e),n=await E(d.join(t,".workspai","workspace.contract.json")),o=[],i=[];for(let c of n?.projects??[]){let s=c.slug??c.relativePath??"unknown-project",l=typeof c.externalPath=="string"?d.resolve(c.externalPath):typeof c.relativePath=="string"&&!c.relativePath.startsWith("external/")?d.resolve(t,c.relativePath):null;if(!l||!H.existsSync(l)){i.push({name:s,reason:"project path is unavailable on this machine"});continue}o.push({name:s,projectPath:l,relationship:c.relationship??"managed"});}return {resolved:o,skipped:i}}export{ke as a,Ze as b,de as c,pe as d,Re as e,We as f,et as g,$e as h};
@@ -1 +0,0 @@
1
- import {a as a$1}from'./chunk-A5FBGRJA.js';import {d as d$1,m}from'./chunk-KG3TUTXU.js';import {d,e}from'./chunk-CCDGHPEJ.js';import {i,h}from'./chunk-NZ3WZYD5.js';import {s}from'./chunk-MOSXTVPU.js';import {s as s$1,q}from'./chunk-RJIYCDVC.js';import a from'path';import {existsSync}from'fs';import m$1 from'fs-extra';var f=i.workspaceRegistry,w=h.workspaceRegistry.schemaVersion;function E(r){return {slug:r.slug,relativePath:r.relativePath,framework:r.framework,kit:r.kit,source:r.source}}async function b(r){let e=s(r,"workspace.json").find(t=>existsSync(t));if(!e)return {exists:false,legacyProjectCount:0};try{let t=await m$1.readJson(e),c=Array.isArray(t.projects)?t.projects.length:0,o=typeof t.workspace_name=="string"&&t.workspace_name.trim()||typeof t.name=="string"&&t.name.trim()||a.basename(r);return {exists:true,manifestPath:e,workspaceName:o,profile:typeof t.profile=="string"?t.profile:void 0,legacyProjectCount:c}}catch{return {exists:true,manifestPath:e,legacyProjectCount:0,workspaceName:a.basename(r)}}}async function _(r){let e=a$1(r);for(let t of s$1())if(await m$1.pathExists(t))try{let o=((await m$1.readJson(t)).workspaces||[]).find(s=>a$1(s.path)===e);if(o)return {exists:true,projectCount:Array.isArray(o.projects)?o.projects.length:0,registryPath:t}}catch{continue}return {exists:false,projectCount:0,registryPath:a.join(q(),"workspaces.json")}}async function T(r,e){let t=a.resolve(r),c=await d(t,d$1),o=await b(t),s=await _(t),i=e?.contract!==void 0||!!c,n=[];if(e?.contract)n=e.contract.projects||[];else if(i)try{let{contract:A}=await m({workspacePath:t});n=A.projects||[];}catch{n=[];}let d$2={contract:{exists:i,projectCount:n.length,path:d$1},globalRegistry:{exists:s.exists,projectCount:s.projectCount,path:s.registryPath},legacyWorkspaceJson:{exists:o.exists,projectCount:o.legacyProjectCount,path:o.manifestPath?a.relative(t,o.manifestPath):void 0}},p="none",u=[],y=0;return i?(p="workspace.contract.json",u=n.map(E),y=u.length):s.projectCount>0?(p="global-registry",y=s.projectCount):o.legacyProjectCount>0&&(p="legacy-workspace.json",y=o.legacyProjectCount),{contractExists:i,summary:{schemaVersion:w,kind:"rapidkit.workspace.registry",workspacePath:t,workspaceName:o.workspaceName||a.basename(t),profile:o.profile,projectCount:y,authority:p,contractPath:d$1,projects:u,sources:d$2}}}async function U(r){let e=await d(r,f);if(!e)return null;try{let t=await m$1.readJson(e);return t?.schemaVersion!==w?null:t}catch{return null}}async function D(r,e$1){let t=await M(r,e$1);return await e(r,f,t),t}async function M(r,e){return {...(await T(r,{contract:e?.contract})).summary,generatedAt:(e?.now??new Date).toISOString(),registrySummaryPath:f}}function F(r,e=""){return r.projectCount>0?r.authority==="workspace.contract.json"?`${r.projectCount} project(s) registered in workspace contract${e}.`:r.authority==="global-registry"?`${r.projectCount} project(s) registered in global workspace registry${e}.`:`${r.projectCount} project(s) registered in legacy workspace manifest${e}.`:`Workspace state exists, but no projects are registered yet${e}.`}export{f as a,w as b,T as c,U as d,D as e,M as f,F as g};
@@ -1,2 +0,0 @@
1
- import {w}from'./chunk-SCP5LJNO.js';import {a as a$1}from'./chunk-T5YRFRJV.js';import {a}from'./chunk-GR6442P7.js';import {a as a$2,d,c as c$1,e as e$1}from'./chunk-CCDGHPEJ.js';import {b}from'./chunk-D65FCQIO.js';import {i,e,h,f}from'./chunk-NZ3WZYD5.js';import {l}from'./chunk-OCGZNSOE.js';import {c}from'./chunk-VR6XMUF3.js';import {t,s}from'./chunk-MOSXTVPU.js';import g from'path';import h$1 from'fs-extra';var ue="unknown-run";function Z(e){let t=c();return !t||t===ue?e:{...e,runId:t}}var xe="workspace-dependency-graph.v1",Q=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],X=["inferred","contract","manual"];var E=i.workspaceContract,me=e.contractVerify,S=h.workspaceContract.schemaVersion,ge=f.contractVerify,x=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function ne(e){return e.replace(/\\/g,"/")}function V(e){let t=ne(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function ee(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function fe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function te(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(p=>{if(!p||typeof p!="object"||Array.isArray(p))return null;let c=p,m=Number(c.port);if(!Number.isInteger(m)||m<1||m>65535)return null;let d=c.protocol==="https"||c.protocol==="grpc"||c.protocol==="tcp"||c.protocol==="udp"?c.protocol:"http";return {name:typeof c.name=="string"&&c.name.trim()?c.name:"http",port:m,protocol:d}}).filter(p=>p!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,a=Number(e.port??o?.default_port);return Number.isInteger(a)&&a>=1&&a<=65535?[{name:"http",port:a,protocol:"http"}]:[]}async function he(e){let t=g.join(e,"Dockerfile");if(!await h$1.pathExists(t))return [];try{let r=await h$1.readFile(t,"utf8"),o=new Map;for(let a of r.matchAll(/^\s*EXPOSE\s+(.+)$/gim))for(let p of a[1].split(/\s+/)){let c=p.match(/^(\d{1,5})(?:\/(tcp|udp))?$/i),m=Number(c?.[1]);if(!c||!Number.isInteger(m)||m<1||m>65535)continue;let d=c[2]?.toLowerCase();o.set(m,{name:"http",port:m,protocol:d==="udp"?"udp":"http"});}return [...o.values()].sort((a,p)=>a.port-p.port)}catch{return []}}async function G(e){for(let t of e)if(await h$1.pathExists(t))return t;return null}async function ke(e){for(let t of s(e,"workspace.json"))try{let r=await h$1.readJson(t);return {name:typeof r.workspace_name=="string"&&r.workspace_name.trim()||typeof r.name=="string"&&r.name.trim()||g.basename(e),profile:typeof r.profile=="string"?r.profile:void 0}}catch{}return {name:g.basename(e)}}async function we(e){let t$1=[],r=[e],o=new Set,a$1=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let p=r.shift();if(!p||o.has(p))continue;o.add(p);let c=await G(t(p,"project.json")),m=await G(t(p,"context.json"));if(c||m){t$1.push(c??m??"");continue}let d;try{d=await h$1.readdir(p,{withFileTypes:true});}catch{continue}for(let l of d)!l.isDirectory()||a$1.has(l.name)||a(l.name)||r.push(g.join(p,l.name));}return t$1.sort()}function Pe(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function Ce(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return r.includes("vscode-extension")?null:r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:r.startsWith("adopted.")?null:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function I(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function T(e,t,r){let o=e!==void 0&&e.source===void 0,a=Ce(t.kit,t.runtime),p=e?.ports||[],c=t.ports||[],m=(t.kit||"").toLowerCase().includes("vscode-extension"),d=t.source==="adopted-local"&&e?.source==="adopted-local",l=d,i=(m&&c.length===0?[]:d?c.length>0?c:a?[{name:"http",port:I(a,r),protocol:"http"}]:[]:p.length>0?p:c.length>0?c:a?[{name:"http",port:I(a,r),protocol:"http"}]:[]).map(P=>({...P,port:I(P.port,r)}));for(let P of i)r.add(P.port);let k={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&V(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:l?t.runtime:e?.runtime||t.runtime,framework:l?t.framework:e?.framework||t.framework,kit:l?t.kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:i,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},f=JSON.stringify(e||null)!==JSON.stringify(k);return {project:k,changed:f}}async function ae(e){let t$1=g.resolve(e.workspacePath),r=await ke(t$1),o=await we(t$1),a=await a$1(t$1),p=[];for(let l of a){let s=g.resolve(l.path),i=await G(t(s,"project.json"))??await G(t(s,"context.json"));!i||o.some(k=>g.resolve(k)===g.resolve(i))||p.push({projectJsonPath:i,registryEntry:l});}let c=[],m=[...o.map(l=>({projectJsonPath:l})),...p];for(let{projectJsonPath:l,registryEntry:s}of m){let i=g.dirname(g.dirname(l)),k=ne(g.relative(t$1,i)),f=s!==void 0&&!V(k),P=ee(s?.name||g.basename(i),g.basename(i)),C=f?`external/${P}`:k||P,w=await h$1.readJson(l),j=typeof w.kit_name=="string"&&w.kit_name||typeof w.kit=="string"&&w.kit||void 0,n=typeof w.framework=="string"&&w.framework||Pe(j);c.push({slug:s?.name||C||g.basename(i),relativePath:C,source:s?.source??"workspace",relationship:s?.relationship,externalPath:f?i:void 0,runtime:typeof w.runtime=="string"?w.runtime:void 0,framework:n,kit:j,modules:fe(w.modules),ports:te(w).length>0?te(w):await he(i),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let d=new Map;for(let l of c){let s=ee(l.slug,l.relativePath),i=d.get(s);(!i||i.source!=="workspace"&&l.source==="workspace")&&d.set(s,l);}return {schemaVersion:S,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...d.values()]}}async function Ue(e){let t=g.resolve(e.outputPath||a$2(e.workspacePath,E));if(await h$1.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await ae({workspacePath:e.workspacePath,now:e.now}),o=new Set,a={...r,projects:r.projects.map(c=>T(void 0,c,o).project)},p=await ie({workspacePath:e.workspacePath,contractPath:t,contract:a});if(e.strict&&p.status==="failed")throw new x(p);return await se({workspacePath:e.workspacePath,contractPath:t,contract:a,now:e.now}),{contractPath:t,contract:a}}async function ze(e){let t=g.resolve(e.workspacePath),r=a$2(t,E),o=await d(t,E)??r,a=await ae({workspacePath:t,now:e.now}),p=await h$1.pathExists(o)?await h$1.readJson(o):null,c=new Map((p?.projects||[]).map(f=>[f.slug,f])),m=new Set,d$1=[],l=[],s=[];for(let f of a.projects){let P=c.get(f.slug),C=T(P,f,m);P?C.changed&&l.push(f.slug):d$1.push(f.slug),s.push(C.project),c.delete(f.slug);}for(let f of c.values()){if(f.source)continue;let P=T(f,f,m);s.push(P.project);}let i={schemaVersion:S,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...p?.workspace||{},...a.workspace,name:a.workspace.name||p?.workspace?.name||g.basename(t)},projects:s.sort((f,P)=>f.slug.localeCompare(P.slug))},k=await ie({workspacePath:t,contractPath:r,contract:i});if(e.strict&&k.status==="failed")throw new x(k);return await se({workspacePath:t,contractPath:r,contract:i,now:e.now}),{contractPath:r,contract:i,addedProjects:d$1,updatedProjects:l,verification:k}}async function re(e){return await h$1.pathExists(e)?{exists:true,contents:await h$1.readFile(e)}:{exists:false}}async function oe(e,t){if(!t.exists){await h$1.remove(e);return}await h$1.outputFile(e,t.contents);}async function se(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-VSOBKAJG.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),a=a$2(e.workspacePath,r),p=c=>{if(!c||typeof c!="object"||Array.isArray(c))return JSON.stringify(c);let{generatedAt:m,...d}=c;return JSON.stringify(d)};if(await h$1.pathExists(e.contractPath)&&await h$1.pathExists(a)){let[c,m]=await Promise.all([h$1.readJson(e.contractPath),h$1.readJson(a)]);if(p(c)===p(e.contract)&&p(m)===p(o))return}b(E,e.contract),b(r,o),await c$1(e.workspacePath,E,async()=>{let[c,m]=await Promise.all([re(e.contractPath),re(a)]);try{if(e.contractPath===a$2(e.workspacePath,E)?await e$1(e.workspacePath,E,e.contract):(await h$1.ensureDir(g.dirname(e.contractPath)),await h$1.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await e$1(e.workspacePath,r,o);}catch(d){let s=(await Promise.allSettled([oe(e.contractPath,c),oe(a,m)])).filter(i=>i.status==="rejected");throw s.length>0?new AggregateError([d,...s.map(i=>i.reason)],"Workspace contract publication failed and rollback was incomplete."):d}});}async function ce(e){let t=e.contractPath??(await d(e.workspacePath,E)||a$2(e.workspacePath,E)),r=await h$1.readJson(t);return {contractPath:t,contract:r}}var ye={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function Ee(e,t){return t.externalPath?g.resolve(t.externalPath):g.resolve(e,t.relativePath)}async function be(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(ye))for(let a of o)await h$1.pathExists(g.join(e,a))&&t[r].push(a);try{let r=await h$1.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,a)=>o.localeCompare(a));return t}function A(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function We(e){try{let t=await h$1.readJson(g.join(e,"package.json")),r={runtime:A(t.dependencies),development:A(t.devDependencies),peer:A(t.peerDependencies),optional:A(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:A(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function ve(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await h$1.readFile(g.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,a)=>o.localeCompare(a))}catch{}return []}function Ae(e,t){try{let r=w(e);if(r.engine!=="unknown")return r;let o=h$1.pathExistsSync(g.join(e,"package.json"))?"npm":h$1.pathExistsSync(g.join(e,"pyproject.toml"))?"python":h$1.pathExistsSync(g.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",runtimeCandidates:["unknown"],compositeRuntime:false,lifecycleCoverage:"complete",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function Se(e,t,r){let o=e.projects.map(a=>({id:a.slug,path:a.relativePath,runtime:a.runtime,framework:a.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function Ye(e$1){let{contractPath:t,contract:r}=await ce(e$1),o=e$1.now??new Date,a=o.toISOString(),{buildWorkspaceModel:p,workspaceModelProjectTopology:c}=await import('./workspace-model-ETCLINRB.js'),{hashWorkspaceModel:m}=await import('./workspace-model-hash-ZXYPIGCW.js'),d=await p({workspacePath:e$1.workspacePath,includeEvidence:false,now:o}),l=c(d)??Se(r,a,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(l.nodes.map(n=>[n.id,n.operationalProfile])),{buildWorkspaceKnowledgeGraph:i}=await import('./workspace-knowledge-graph-3ZBPSAS7.js'),k=await i({workspacePath:e$1.workspacePath,workspace:{name:d.workspace.name,...d.workspace.profile?{profile:d.workspace.profile}:{}},contract:r,projectTopology:l,now:o,projects:d.projects.map(n=>({id:n.name,path:n.path,...n.absolutePath?{absolutePath:n.absolutePath}:{},runtime:n.runtime,runtimeCandidates:n.runtimeCandidates,framework:n.framework,...n.kit?{kit:n.kit}:{}})),source:{kind:"workspace-model",artifact:e.model,hashAlgorithm:"sha256",hash:m(d)}}),f=await Promise.all(r.projects.map(async n=>{let u=Ee(e$1.workspacePath,n),[R,W,pe]=await Promise.all([be(u),We(u),ve(u)]),y=Ae(u,n);return {id:n.slug,label:n.slug,relativePath:n.relativePath,source:n.source,relationship:n.relationship,externalPath:n.externalPath,runtime:n.runtime??y.runtime,framework:n.framework??y.framework,kit:n.kit,modules:n.modules,ports:n.ports,apis:n.contracts.apis,owns:n.contracts.owns,env:[...new Set([...n.contracts.env,...pe])].sort((le,de)=>le.localeCompare(de)),contracts:{owns:[...n.contracts.owns],apis:[...n.contracts.apis],publishes:[...n.contracts.publishes],consumes:[...n.contracts.consumes],dependsOn:[...n.contracts.dependsOn],env:[...n.contracts.env]},capabilities:{engine:y.engine,supportTier:y.frameworkSupportTier,runtimeSupportTier:y.runtimeSupportTier,doctorSupport:y.runtimeDoctorSupport,moduleSupport:y.moduleSupport,fleetStages:[...y.fleetStages],localOnlyCommands:[...y.localOnlyCommands],supportedCommands:[...y.supportedCommands]},files:R,...W?{package:W}:{},...s.get(n.slug)?{operationalProfile:s.get(n.slug)}:{}}})),P=new Set(f.map(n=>n.id)),C=new Map,w=[];for(let n of r.projects){for(let u of n.contracts.dependsOn||[])P.has(u)&&w.push({from:u,to:n.slug,type:"dependency",label:"dependsOn"});for(let u of n.contracts.publishes||[])C.has(u)||C.set(u,new Set),C.get(u)?.add(n.slug);}for(let n of r.projects)for(let u of n.contracts.consumes||[]){let R=C.get(u);if(R)for(let W of R)W!==n.slug&&w.push({from:W,to:n.slug,type:"event",label:u});}let j={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:a,nodes:f.sort((n,u)=>n.id.localeCompare(u.id)),edges:w.sort((n,u)=>`${n.from}:${n.to}:${n.type}:${n.label}`.localeCompare(`${u.from}:${u.to}:${u.type}:${u.label}`)),dependencyGraph:l,knowledgeGraph:k,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:f.length,dependencyEdges:w.filter(n=>n.type==="dependency").length,eventEdges:w.filter(n=>n.type==="event").length,portCount:f.reduce((n,u)=>n+u.ports.length,0),apiCount:f.reduce((n,u)=>n+u.apis.length,0),relationshipEdges:l.stats.edgeCount,inferredEdges:l.stats.inferredEdges,authoritativeEdges:l.stats.authoritativeEdges,orphanProjects:l.stats.orphanCount,hotspotProjects:l.stats.hotspotCount,evidenceCoverageRatio:l.stats.evidenceCoverageRatio,edgeCoverageRatio:l.stats.edgeCoverageRatio,connectedProjects:l.stats.connectedNodeCount,lowConfidenceEdges:l.stats.lowConfidenceEdges,hasCycle:l.stats.hasCycle,manifestCount:f.reduce((n,u)=>n+u.files.manifests.length,0),entrypointCount:f.reduce((n,u)=>n+u.files.entrypoints.length,0),diagnostics:l.diagnostics?.length??0,relationshipKinds:Object.fromEntries(Q.map(n=>[n,l.edges.filter(u=>u.kind===n).length])),relationshipSources:Object.fromEntries(X.map(n=>[n,l.edges.filter(u=>u.source===n).length])),entityCount:k.quality.entityCount,knowledgeRelations:k.quality.relationCount,proofCount:k.quality.proofCount,providerCount:k.providers.length,knowledgeUnknowns:k.quality.unknownCount}};return {contractPath:t,graph:j}}async function ie(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,E),contract:e.contract}:await ce(e),{contractPath:r,contract:o}=t,a=[],p=[];o.kind!=="rapidkit.workspace.contract"&&a.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==S&&a.push(`Contract schemaVersion must be ${S}.`),o.workspace?.name||a.push("Contract workspace.name is required."),Array.isArray(o.projects)||a.push("Contract projects must be an array.");let c=new Set,m=new Map;for(let s of o.projects||[]){if(!s.slug){a.push("Every project must declare slug.");continue}c.has(s.slug)&&a.push(`Duplicate project slug: ${s.slug}.`),c.add(s.slug),s.relativePath?V(s.relativePath)||a.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):a.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||a.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),g.isAbsolute(s.externalPath)||a.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let i of s.ports||[]){(!Number.isInteger(i.port)||i.port<1||i.port>65535)&&a.push(`Project ${s.slug} declares invalid port: ${i.port}.`);let k=m.get(i.port);k&&a.push(`Port ${i.port} is claimed by both ${k} and ${s.slug}.`),m.set(i.port,s.slug);}for(let i of s.contracts?.apis||[])(!i.name?.trim()||!i.basePath?.startsWith("/"))&&a.push(`Project ${s.slug} declares invalid API contract.`);for(let i of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])i.trim()||a.push(`Project ${s.slug} declares an empty event contract.`);for(let i of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(i)||a.push(`Project ${s.slug} declares invalid env contract: ${i}.`);for(let i of s.contracts?.dependsOn||[])c.has(i);}for(let s of o.projects||[])for(let i of s.contracts?.dependsOn||[])c.has(i)||a.push(`Project ${s.slug} depends on unknown project: ${i}.`);p.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===S?"passed":"failed",message:"Contract schema and kind are valid."}),p.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),p.push({id:"ports",status:a.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),p.push({id:"dependencies",status:a.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),p.push({id:"contracts",status:a.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let d=await l(e.workspacePath);if(d.moduleCount>0){for(let s of d.issues)a.push(`${g.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);p.push({id:"module-paths",status:d.status,message:d.status==="passed"?`All ${d.moduleCount} registered module(s) resolve under canonical paths.`:`${d.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&p.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:a.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:p,violations:a}}async function qe(e){let t=g.resolve(e.workspacePath),r={schemaVersion:ge,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return e$1(t,me,Z(r))}
2
- export{Z as a,xe as b,Q as c,E as d,me as e,S as f,ge as g,x as h,we as i,ae as j,Ue as k,ze as l,ce as m,Ye as n,ie as o,qe as p};