workspai 0.60.1 → 0.61.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.
- package/README.md +90 -33
- package/contracts/analyze-last-run.v1.json +7 -1
- package/contracts/extension-cli-compatibility.v1.json +1 -1
- package/contracts/studio-card-repair-capabilities.v1.json +1 -1
- package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +1 -0
- package/dist/analyze-K6JDMF5C.js +1 -0
- package/dist/autopilot-release-7Q5JT7YN.js +1 -0
- package/dist/{chunk-AJ535F22.js → chunk-2FPANIX3.js} +1 -1
- package/dist/{chunk-WLFJHRB3.js → chunk-2JVRDBJC.js} +1 -1
- package/dist/{chunk-WUB6QGC7.js → chunk-4KNDIFJ5.js} +1 -1
- package/dist/{chunk-KTW4EN47.js → chunk-5YNZR74I.js} +1 -1
- package/dist/chunk-ASOFWN6J.js +1 -0
- package/dist/{chunk-S4CWUZ4K.js → chunk-BQCGULHR.js} +1 -1
- package/dist/{chunk-MDF2FBLS.js → chunk-GWMC6SSY.js} +1 -1
- package/dist/{chunk-VV55EAWO.js → chunk-JEGG4EEZ.js} +1 -1
- package/dist/chunk-JRIEP4BY.js +2 -0
- package/dist/{chunk-TYQMO36U.js → chunk-NJ6WJ7VU.js} +1 -1
- package/dist/chunk-RALI2ESF.js +49 -0
- package/dist/chunk-VRQLHCE2.js +8 -0
- package/dist/{chunk-KNTPDRZB.js → chunk-YGONW6VG.js} +1 -1
- package/dist/{chunk-I2O6AC2Z.js → chunk-ZJ62F4U3.js} +1 -1
- package/dist/{create-ZLDOBXG4.js → create-TPUFKW6B.js} +1 -1
- package/dist/{goal-lifecycle-OV6NZDD6.js → goal-lifecycle-BNLXDHED.js} +1 -1
- package/dist/{goal-pack-Q3O2Z7R5.js → goal-pack-2PF775AU.js} +1 -1
- package/dist/index.js +19 -19
- package/dist/{pipeline-NICVJLZF.js → pipeline-BY2YL7C6.js} +1 -1
- package/dist/{project-agent-entry-DVPKQST7.js → project-agent-entry-VXCOXRJB.js} +1 -1
- package/dist/{project-intelligence-lens-RLYSPJB2.js → project-intelligence-lens-BA6JLXQH.js} +1 -1
- package/dist/{verified-goal-2BRQZQBL.js → verified-goal-5OV4BALK.js} +1 -1
- package/dist/{workspace-LQ77WAHC.js → workspace-J4OGSSNO.js} +1 -1
- package/dist/workspace-agent-sync-MU7W3C4S.js +1 -0
- package/dist/{workspace-context-YAK5XX27.js → workspace-context-MDACPLHD.js} +1 -1
- package/dist/workspace-explain-NWP3JTFR.js +1 -0
- package/dist/{workspace-explain-contract-ZL4NMLZI.js → workspace-explain-contract-JWFM22L4.js} +1 -1
- package/dist/{workspace-foundation-G4KPT5CN.js → workspace-foundation-3X5OBEMM.js} +1 -1
- package/dist/{workspace-intelligence-runner-T6CVJIQQ.js → workspace-intelligence-runner-DEW3CZKA.js} +1 -1
- package/dist/{workspace-mcp-serve-ALIZV72K.js → workspace-mcp-serve-S5IXSJJL.js} +1 -1
- package/dist/{workspace-onboarding-46BE3EQD.js → workspace-onboarding-LK5IK6LE.js} +1 -1
- package/dist/workspace-repair-engine-3OLRNXD6.js +3 -0
- package/dist/workspace-run-JTEIX4WA.js +1 -0
- package/docs/README.md +16 -14
- package/docs/ci-workflows.md +1 -1
- package/docs/workspace-repair-engine.md +48 -2
- package/package.json +1 -1
- package/dist/analyze-FYNMI5KT.js +0 -1
- package/dist/autopilot-release-IRXB2VOH.js +0 -1
- package/dist/chunk-7ITSLGPZ.js +0 -8
- package/dist/chunk-KBR4Y4RW.js +0 -1
- package/dist/chunk-NRVSDL4J.js +0 -39
- package/dist/chunk-OU7DF6MP.js +0 -2
- package/dist/workspace-agent-sync-YLP75OWF.js +0 -1
- package/dist/workspace-explain-QH4FXQW5.js +0 -1
- package/dist/workspace-repair-engine-SZZKV3JF.js +0 -3
- package/dist/workspace-run-JTEFCQYQ.js +0 -1
- /package/dist/{chunk-HQWDW2BV.js → chunk-JMFCMPWI.js} +0 -0
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
# Workspace Repair Engine
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## What it does
|
|
4
|
+
|
|
5
|
+
When Doctor or Verify finds a problem—a failing test, a missing dependency, a
|
|
6
|
+
broken build—the Repair Engine fixes it safely. You approve a plan, the CLI
|
|
7
|
+
executes it in a checkpointed transaction, verifies the result, and either
|
|
8
|
+
closes the repair or rolls back without leaving your workspace in a broken state.
|
|
9
|
+
|
|
10
|
+
**Think of it as `git stash` meets a governed CI pipeline, but for individual
|
|
11
|
+
blocker fixes.**
|
|
12
|
+
|
|
13
|
+
### Quick example
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
# 1. See what can be repaired
|
|
17
|
+
npx workspai workspace repair capabilities --json
|
|
18
|
+
|
|
19
|
+
# 2. Plan a fix for a failing test
|
|
20
|
+
npx workspai workspace repair plan --card doctor --project api --json
|
|
21
|
+
|
|
22
|
+
# 3. Approve and execute
|
|
23
|
+
npx workspai workspace repair approve --transaction <id> --approved-by local-user --json
|
|
24
|
+
npx workspai workspace repair execute --transaction <id> --json
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The CLI checkpoints files before any change, runs the fix, verifies the result,
|
|
28
|
+
and reports success or rolls back. No manual cleanup needed.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## How it works
|
|
33
|
+
|
|
34
|
+
The Repair Engine is the CLI-owned execution boundary for blocker repair. IDEs,
|
|
4
35
|
agents, and CI may request work and render progress, but they do not invent commands or decide
|
|
5
36
|
that a repair is complete.
|
|
6
37
|
|
|
@@ -76,6 +107,20 @@ project in `workspace.contract.json`; the authorized boundary is that project's
|
|
|
76
107
|
its parent or a sibling repository. Dependency manifest proposals still receive CLI-inferred
|
|
77
108
|
reconcile, audit, test, and build stages before strict verification.
|
|
78
109
|
|
|
110
|
+
Proposal validation separates model-correctable rejection from an operator decision. A no-op,
|
|
111
|
+
stale hash, protected generated-evidence target, duplicate path, or escaped source scope is
|
|
112
|
+
returned as a failed proposal precondition with only the safe cancel option. An autonomous
|
|
113
|
+
consumer must use that typed receipt to inspect the exact producer finding and submit materially
|
|
114
|
+
different bounded source; it must not ask the operator to decide how to repair the model's own
|
|
115
|
+
invalid proposal. Missing or unlaunchable executables, unsupported runtime adapters, credentials,
|
|
116
|
+
risk elevation, and policy exceptions remain explicit user/toolchain boundaries.
|
|
117
|
+
|
|
118
|
+
Planning is idempotent while a decision-required transaction is still current. Repeating the same
|
|
119
|
+
target, policy, source hashes, adapter state, executable state, stages, and decision causes returns
|
|
120
|
+
the existing durable transaction instead of creating another transaction id. A fresh transaction
|
|
121
|
+
is created automatically once source, evidence, policy, or toolchain preconditions materially
|
|
122
|
+
change.
|
|
123
|
+
|
|
79
124
|
Doctor also publishes a distinct `dependency-materialization` transaction when manifests exist
|
|
80
125
|
but the installed runtime tree is missing. Its install or restore invocation is the repair stage
|
|
81
126
|
itself; it does not require a manifest or lockfile diff and is never run twice. Declared tests and
|
|
@@ -114,7 +159,8 @@ tool before the environment-creation stage runs.
|
|
|
114
159
|
close while unrelated governed findings keep the workspace blocked. Those findings remain the
|
|
115
160
|
next repair target and never trigger rollback of a valid bounded repair.
|
|
116
161
|
- Required executables are resolved before approval and again immediately before execution. A
|
|
117
|
-
missing or changed toolchain expires approval instead of starting a partial
|
|
162
|
+
missing, broken-shebang, or changed toolchain expires approval instead of starting a partial
|
|
163
|
+
transaction. Filesystem presence alone is not launchability proof.
|
|
118
164
|
- The exact card producer is run twice: first as a no-mutation causal precondition, then after
|
|
119
165
|
repair as card-local evidence. An aggregate workspace gate cannot substitute for either run.
|
|
120
166
|
- A Goal-bound proposal is linked to the active Goal before execution. Closure seals the fresh
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "workspai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.61.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": [
|
package/dist/analyze-FYNMI5KT.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{b as printAnalyzeReport,a as runAnalyze}from'./chunk-7ITSLGPZ.js';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{b as AUTOPILOT_RELEASE_ALIAS_FILENAME,a as AUTOPILOT_RELEASE_LAST_RUN_FILENAME,c as runAutopilotRelease}from'./chunk-TYQMO36U.js';
|
package/dist/chunk-7ITSLGPZ.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import {f as f$1,e as e$1}from'./chunk-ILIBOMYL.js';import {a,b}from'./chunk-QJCCZLOF.js';import {a as a$1}from'./chunk-27UR373Z.js';import {a as a$2}from'./chunk-T5YRFRJV.js';import {h,j as j$1}from'./chunk-ZCPT6KC3.js';import {e as e$2}from'./chunk-CCDGHPEJ.js';import {e,f}from'./chunk-NZ3WZYD5.js';import {j,s,t}from'./chunk-MOSXTVPU.js';import w from'fs';import c from'path';import i from'chalk';var L=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function D(e){try{return await w.promises.access(e,w.constants.F_OK),true}catch{return false}}async function z(e){try{let t=JSON.parse(await w.promises.readFile(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async function K(e){try{return await w.promises.readFile(e,"utf-8")}catch{return ""}}function B(e){return a(e)}async function U(e,t$1){return await M([...t(e,"project.json"),...t(e,"context.json")])?true:b(e)?false:c.resolve(e)===c.resolve(t$1)?h(e).length>0:h(e).length>0}async function V(e){let t=await a$1(e,{skipDirs:L,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:U}),r=(await a$2(e)).filter(o=>o.relationship==="adopted"||o.source==="adopted-local").map(o=>c.resolve(o.path)).filter(o=>w.existsSync(o)),s=[...new Set([...t.map(o=>c.resolve(o)),...r])];return s.length>0?s:b(e)?[]:h(e).length>0?[e]:[]}function q(e,t){return c.relative(e,t).replace(/\\/g,"/")||"."}async function A(e,t){for(let n of t)if(await D(c.join(e,n)))return true;return false}async function M(e){for(let t of e)if(await D(t))return true;return false}async function Q(e){if(await A(e,[".gitlab-ci.yml",".circleci/config.yml","azure-pipelines.yml","bitbucket-pipelines.yml","cloudbuild.yaml"]))return true;try{return (await w.promises.readdir(c.join(e,".github","workflows"),{withFileTypes:true})).some(n=>n.isFile()&&/\.(?:ya?ml)$/i.test(n.name)&&!n.name.startsWith("."))}catch{return false}}async function O(e){for(let t of e){let n=await z(t);if(n)return n}return null}async function X(e){return A(e,["health","health.ts","health.js","health.py","health.go","health.kt","health.rb","health.php","healthcheck","health-check","src/health.ts","src/health.js","src/health.py","src/health.go","src/health.kt","src/health.rb","src/health.php","src/healthcheck.ts","src/healthcheck.js","src/liveness.ts","src/readiness.ts","src/ping.ts"])}async function Y(e){if(await A(e,["tests","test","__tests__","src/__tests__","pytest.ini","vitest.config.ts","jest.config.ts"]))return true;let n=await z(c.join(e,"package.json")),r=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return typeof r.test=="string"&&r.test.trim().length>0}async function Z(e){let t=await z(c.join(e,"package.json")),n=t?.scripts&&typeof t.scripts=="object"?t.scripts:{};return Object.keys(n).sort()}function g(e,t,n,r,s,o){return {id:e,severity:t,target:n,title:r,detail:s,remediation:o}}function ee(e){let t=e.reduce((n,r)=>r.severity==="fail"?n+28:r.severity==="warn"?n+12:n+3,0);return Math.max(0,100-t)}async function ne(e,t$1){let n=await O(t(t$1,"project.json")),r=j$1(t$1,n),s=h(t$1),o=r.runtime==="unknown"?s[0]||"unknown":r.runtime,a=q(e,t$1),p=a,u=await Z(t$1),f=await M([...t(t$1,"project.json"),...t(t$1,"context.json")]),l=await Y(t$1),h$1=await A(t$1,["Dockerfile","dockerfile"]),k=await A(t$1,[".env.example","env.example","config/env.example"]),P=await Q(t$1),C=await X(t$1),m=[];return r.key==="unknown"&&m.push(g("project.stack.unknown","fail",p,"Project stack is unknown","Workspai cannot confidently classify this backend project.","Add .workspai/project.json metadata or import the project with `workspai import`.")),f||m.push(g("project.marker.missing","warn",p,"Workspai marker is missing","The project can be detected by files, but it is not registered with Workspai metadata.","Run `workspai import <path>` from a workspace or create the project through Workspai.")),l||m.push(g("project.tests.missing","warn",p,"Test entrypoint is missing","No common test folder, config, or package test script was found.","Add a test command so `workspai workspace run test --affected` can gate changes.")),k||m.push(g("project.env.example.missing","info",p,"Environment example is missing","No .env.example or env.example file was found.","Add an env example for onboarding and CI secret documentation.")),P||m.push(g("project.ci.missing","warn",p,"Continuous integration is missing","No recognized CI/CD configuration file was detected for this project.","Add CI configuration so tests and checks run automatically for every change.")),C||m.push(g("project.health.missing","info",p,"Health or readiness probe is missing","The project has no obvious health or readiness endpoint to support automated deployment and runtime checks.","Add a simple health endpoint and document it for readiness gates and observability.")),h$1||m.push(g("project.container.missing","info",p,"Container recipe is missing","No Dockerfile was found for this project.","Add a Dockerfile when the service is intended for containerized deployment.")),{name:typeof n?.name=="string"&&n.name.trim()?n.name.trim():c.basename(t$1),path:t$1,relativePath:a,runtime:o,framework:r.key,confidence:r.confidence,supportTier:r.supportTier,hasRapidKitMarker:f,hasTests:l,hasDockerfile:h$1,hasEnvExample:k,hasCiConfig:P,hasHealthEndpoint:C,scripts:u,findings:m,score:ee(m)}}function te(e){return e.name.toLowerCase()}async function re(e){let t=new Map(e.map(s=>[te(s),s])),n=[];for(let s of e){let o=await z(c.join(s.path,"package.json")),a={...o?.dependencies??{},...o?.devDependencies??{},...o?.peerDependencies??{}};for(let u of Object.keys(a)){let f=u.replace(/^@[^/]+\//,"").toLowerCase(),l=t.get(f);l&&l.relativePath!==s.relativePath&&n.push({from:s.relativePath,to:l.relativePath,kind:"package"});}let p=await K(c.join(s.path,"pyproject.toml"));for(let u of e)u.relativePath!==s.relativePath&&p.includes(u.name)&&n.push({from:s.relativePath,to:u.relativePath,kind:"workspace-reference"});}let r=new Set;return n.filter(s=>{let o=`${s.from}\0${s.to}\0${s.kind}`;return r.has(o)?false:(r.add(o),true)})}function se(e,t){let n=new Map;for(let r of e)n.set(r.relativePath,{project:r.relativePath,directDependents:0,directDependencies:0});for(let r of t){let s=n.get(r.from),o=n.get(r.to);s&&(s.directDependencies+=1),o&&(o.directDependents+=1);}return Array.from(n.values()).sort((r,s)=>s.directDependents-r.directDependents||s.directDependencies-r.directDependencies)}async function oe(e){let t=await O(s(e,"workspace.json"));return typeof t?.profile=="string"?t.profile:null}function ie(e){return {fail:e.filter(t=>t.severity==="fail").length,warn:e.filter(t=>t.severity==="warn").length,info:e.filter(t=>t.severity==="info").length}}function ae(e){if(e.projectCount===0)return e.workspaceDetected?["Add your first project: npx workspai create project <name> --kit <kit>","Import an existing service: npx workspai import <path>"]:["Create a Workspai workspace: npx workspai create workspace my-workspace --profile polyglot","Import an existing service: npx workspai import ../service"];let t=[];return e.findings.some(n=>n.id==="workspace.marker.missing")&&t.push("Initialize workspace metadata with `workspai bootstrap --profile polyglot`."),e.findings.some(n=>n.id==="project.marker.missing")&&t.push("Register detected projects with `workspai import <path>` or recreate them via `workspai create project`."),e.findings.some(n=>n.id==="project.tests.missing")&&t.push("Add test entrypoints, then gate changes with `workspai workspace run test --affected --strict`."),e.findings.some(n=>n.id==="project.ci.missing")&&t.push("Add CI/CD configuration to catch regressions early and make workspace health checks actionable."),e.findings.some(n=>n.id==="project.health.missing")&&t.push("Add a health/readiness endpoint so runtime probes and deployment checks can verify service health."),e.hasGraph||t.push("Create `.workspai/workspace-dependency-graph.json` or use analyze output as the first graph seed."),t.push("Run `workspai autopilot release --mode audit --json` before release."),Array.from(new Set(t))}async function ve(e$3={}){let t=c.resolve(e$3.workspacePath||process.cwd());if(!await D(t))throw new Error(`Workspace path does not exist: ${t}`);let n=B(t)??t,r=j(n),s=await oe(n),o=await V(n),a=await Promise.all(o.map(d=>ne(n,d))),p=await re(a),u=se(a,p),f$2=[];r||f$2.push(g("workspace.marker.missing","warn",".","Workspace metadata is missing","The directory can be analyzed, but it is not a registered Workspai workspace.","Run `workspai create workspace` or `workspai bootstrap --profile polyglot` in a workspace root.")),a.length===0&&f$2.push(g("workspace.projects.missing","warn",".","No backend projects detected","Workspai did not find runtime markers or project metadata under this root.","Create a project with `workspai create project` or import one with `workspai import <path>`."));let l=[...f$2,...a.flatMap(d=>d.findings)],h=ie(l),k={};for(let d of a)k[d.runtime]=(k[d.runtime]||0)+1;let P=a.length>0?Math.round(a.reduce((d,y)=>d+y.score,0)/a.length):0,C=f$2.reduce((d,y)=>d+(y.severity==="fail"?20:y.severity==="warn"?8:2),0),m=Math.max(0,P-C),J=a.length===0&&h.fail===0&&l.length>0&&l.every(d=>d.id==="workspace.projects.missing"&&d.severity==="warn"),H=h.fail>0||e$3.strict&&h.warn>0&&!J?"blocked":h.warn>0?"needs-attention":"ready",j$1={schemaVersion:f.analyze,generatedAt:new Date().toISOString(),workspacePath:n,workspaceDetected:r,profile:s,summary:{score:m,verdict:H,projectCount:a.length,runtimeCount:Object.keys(k).length,findings:h},runtimes:k,projects:a,dependencyGraph:{status:p.length>0?"generated":"empty",edges:p,topImpactedProjects:u.slice(0,5)},findings:l,nextActions:ae({findings:l,projectCount:a.length,hasGraph:p.length>0,workspaceDetected:r}),enterpriseControls:{jsonReady:true,ciGateCommand:"workspai analyze --json --strict",releaseGateCommand:"workspai autopilot release --mode enforce --json",evidencePath:e.analyze}};if(e$3.output&&(await w.promises.mkdir(c.dirname(c.resolve(e$3.output)),{recursive:true}),await w.promises.writeFile(c.resolve(e$3.output),`${JSON.stringify(j$1,null,2)}
|
|
2
|
-
`)),!e$3.output&&r){let d=f$1(j$1,{commandId:"workspaceAnalyze",exitCode:j$1.summary.verdict==="blocked"?2:j$1.summary.verdict==="needs-attention"?1:0,generatedAt:j$1.generatedAt,blockers:j$1.findings.filter(y=>y.severity==="fail").map(y=>y.title).slice(0,12),runId:e$1()});await e$2(n,e.analyze,d);}return j$1}function be(e){let t=e.summary.verdict==="ready"?i.green:e.summary.verdict==="needs-attention"?i.yellow:i.red;if(console.log(i.bold(`
|
|
3
|
-
Workspai Workspace Analysis
|
|
4
|
-
`)),console.log(i.cyan("Workspace:"),e.workspacePath),console.log(i.cyan("Profile:"),e.profile||"not configured"),console.log(i.cyan("Score:"),`${e.summary.score}/100`),console.log(i.cyan("Verdict:"),t(e.summary.verdict)),console.log(i.gray(`Projects: ${e.summary.projectCount}, runtimes: ${e.summary.runtimeCount}, findings: ${e.summary.findings.fail} fail / ${e.summary.findings.warn} warn / ${e.summary.findings.info} info`)),e.projects.length>0){console.log(i.bold(`
|
|
5
|
-
Projects`));for(let n of e.projects){let r=n.score>=85?i.green("pass"):n.score>=65?i.yellow("watch"):i.red("risk");console.log(` ${n.relativePath} ${i.gray(`${n.runtime}/${n.framework}`)} ${r} ${n.score}/100`);}}if(e.dependencyGraph.status==="generated"&&(console.log(i.bold(`
|
|
6
|
-
Dependency Graph`)),console.log(i.gray(` edges: ${e.dependencyGraph.edges.length}`)),e.dependencyGraph.topImpactedProjects.length>0)){console.log(i.gray(" Top impacted projects:"));for(let n of e.dependencyGraph.topImpactedProjects.slice(0,3))console.log(` ${n.project} (${n.directDependents} dependents, ${n.directDependencies} dependencies)`);}if(e.findings.length>0){console.log(i.bold(`
|
|
7
|
-
Top Findings`));for(let n of e.findings.slice(0,8)){let r=n.severity==="fail"?i.red:n.severity==="warn"?i.yellow:i.gray;console.log(` ${r(n.severity.toUpperCase())} ${n.target}: ${n.title}`),console.log(i.gray(` ${n.remediation}`));}}console.log(i.bold(`
|
|
8
|
-
Next Actions`));for(let n of e.nextActions.slice(0,5))console.log(i.gray(` - ${n}`));console.log();}export{ve as a,be as b};
|
package/dist/chunk-KBR4Y4RW.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {i as i$1,e}from'./chunk-NZ3WZYD5.js';var i=".workspai/skills";var _=e.skillsIndex,a=e.explain,P=i$1.workspaceWhy,O=i$1.workspaceTrace,c=".workspai/AGENT-GROUNDING.md",I=".rapidkit/AGENT-GROUNDING.md",A=".cursor/rules/workspai-grounding.mdc",T=".cursor/rules/rapidkit-grounding.mdc",E=".claude/rules/workspai-evidence.md",R=".claude/rules/rapidkit-evidence.md",L=".github/instructions/workspai-workspace.instructions.md",d=".github/instructions/rapidkit-workspace.instructions.md",S=".github/instructions/workspai-evidence.instructions.md",C=".github/instructions/rapidkit-evidence.instructions.md",k=".github/prompts/workspai-diagnose.prompt.md",N=".github/prompts/rapidkit-diagnose.prompt.md",l=".github/prompts/workspai-repair.prompt.md",m=".github/prompts/rapidkit-repair.prompt.md",u=".github/prompts/workspai-release-readiness.prompt.md",g=".github/prompts/rapidkit-release-readiness.prompt.md",K=".github/prompts/workspai-project-onboard.prompt.md",G=".github/prompts/rapidkit-project-onboard.prompt.md",x=".github/prompts/workspai-adopt-project.prompt.md",w=".github/prompts/rapidkit-adopt-project.prompt.md",H=".github/skills/workspai-grounding/SKILL.md",D=".github/skills/rapidkit-grounding/SKILL.md",W=".github/skills/workspai-workspace-intelligence/SKILL.md",h=".github/skills/rapidkit-workspace-intelligence/SKILL.md",U=i$1.workspaiMcpDesign,b=i$1.legacyMcpDesign,M=i$1.agentHooks,Y=".vscode/rapidkit-agent-hooks.json";function f(r){let s=r.trim();if(!s||s.includes("..")||s.includes("/"))throw new Error(`Invalid operational skill id: ${r}`);return `${i}/${s}.md`}var B={"workspai-diagnose-api-failure":"workspai-diagnose","workspai-release-readiness":"workspai-release-readiness","workspai-safe-schema-migration":"workspai-safe-schema-migration","workspai-dependency-upgrade":"workspai-dependency-upgrade","workspai-rename-contract":"workspai-rename-contract"};export{D as A,W as B,h as C,U as D,b as E,M as F,Y as G,f as H,B as I,i as a,_ as b,a as c,P as d,O as e,c as f,I as g,A as h,T as i,E as j,R as k,L as l,d as m,S as n,C as o,k as p,N as q,l as r,m as s,u as t,g as u,K as v,G as w,x,w as y,H as z};
|
package/dist/chunk-NRVSDL4J.js
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import {b as b$3,a}from'./chunk-THIOE2PB.js';import {h,g as g$2}from'./chunk-AJ535F22.js';import {b as b$4,g as g$1}from'./chunk-I2O6AC2Z.js';import {b as b$1,f as f$3,j,k,h as h$2,i as i$2,l,m as m$1,n,o,p as p$1,q,r,t,v,x,s,u as u$1,w,y as y$1,z,A,B,C,D,E,F,G,H as H$1,a as a$2,I}from'./chunk-KBR4Y4RW.js';import {b,c,d as d$1}from'./chunk-OU7DF6MP.js';import {b as b$2}from'./chunk-WQX3JYEP.js';import {d as d$2}from'./chunk-O6R7SE6Y.js';import {p,k as k$1,f as f$4}from'./chunk-NA2NXX5P.js';import {m}from'./chunk-KG3TUTXU.js';import {d}from'./chunk-CCDGHPEJ.js';import {a as a$1,b as b$5}from'./chunk-D65FCQIO.js';import {f,e,i,h as h$3}from'./chunk-NZ3WZYD5.js';import {f as f$1,g,h as h$1}from'./chunk-MOSXTVPU.js';import i$1 from'path';import f$2 from'fs-extra';var te=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var yt="workspace-operational-skill.v1";function St(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function at(e){let t=St(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:yt,skillId:t,canonicalPath:H$1(t),title:e.title,triggers:[...e.triggers].sort((r,n)=>r.localeCompare(n)),requiredReports:[...e.requiredReports].sort((r,n)=>r.localeCompare(n)),scopedProjects:[...e.scopedProjects??[]].sort((r,n)=>r.localeCompare(n)),verificationCommands:[...e.verificationCommands],answerContractSections:[...te],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var Ct=f.skillsIndex;function ot(e){let t=[...e.skills].sort((n,c)=>n.skillId.localeCompare(c.skillId)),r=e.inputsHash??f$4({skillIds:t.map(n=>n.skillId),paths:t.map(n=>n.canonicalPath)});return {schemaVersion:Ct,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(n=>({skillId:n.skillId,path:n.canonicalPath,schemaVersion:n.schemaVersion,title:n.title}))}}var it=[e.agentIndex,b,d$2],Et=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${e.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${e.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."]},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${e.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${e.verify}\` for verdict and blocking reasons.`,`Read \`${i.artifactRemediationPlan}\` when a Studio or agent repair path is needed.`,"List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."]},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Require project-scoped test/build commands before promoting the migration.","Document rollback and verification signals."]},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Prefer workspace run test/build for affected projects.","Re-run `workspace verify` after evidence refresh."]},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:[`Read \`${i.workspaceContract}\` for publishes/consumes/owns edges.`,"List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."]}];function re(e){return `npx workspai ${e}`.trim()}function bt(e){let t=[`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",...it.map(r=>`- \`${r}\``),"","## Procedure","",...e.template.steps.map((r,n)=>`${n+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",re("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
|
|
2
|
-
`)}function It(e){return e?.safeCommands?.length?e.safeCommands.slice(0,8).map(t=>t.display):[re("workspace verify --json"),re("doctor workspace --json")]}function xt(e){return e?.projects?.length?e.projects.slice(0,12).map(r=>{let n=r.contracts?.owns?.join(", ")||"none",c=r.contracts?.publishes?.join(", ")||"none",l=r.contracts?.consumes?.join(", ")||"none";return `- **${r.slug}**: owns \`${n}\`; publishes \`${c}\`; consumes \`${l}\``}).join(`
|
|
3
|
-
`):void 0}function st(e){let t=e.model.workspace.name,r=e.model.projects.map(l=>l.name).sort(),n=It(e.context??null),c=xt(e.contract??null);return Et.map(l=>{let p=bt({template:l,workspaceName:t,scopedProjects:r,verificationCommands:n,contractSummary:c});return at({skillId:l.skillId,title:l.title,triggers:l.triggers,requiredReports:[...it],scopedProjects:r,verificationCommands:n,promptStem:I[l.skillId],markdown:p})})}async function ct(e){let t=i$1.resolve(e.workspacePath),r=[],n=f$4({skills:e.skills.map(l=>({id:l.skillId,path:l.canonicalPath,hash:f$4({markdown:l.markdown})}))}),c=ot({generatedAt:e.generatedAt,skills:e.skills,inputsHash:n});if(e.write){for(let p of e.skills){let o=i$1.join(t,p.canonicalPath);await f$2.ensureDir(i$1.dirname(o)),await f$2.writeFile(o,p.markdown,"utf8"),r.push(p.canonicalPath);}let l=i$1.join(t,b$1);await f$2.ensureDir(i$1.dirname(l)),await f$2.writeJson(l,c,{spaces:2}),r.push(b$1);}return {skills:e.skills,index:c,writtenPaths:r}}function lt(e){return ["## Operational skills (canonical)","","Read workspace-native playbooks from `.workspai/skills/` before generic repo scans. Legacy `.rapidkit/skills/` playbooks are read only when already present from older workspaces:","",...e.skills.map(r=>`- \`${r.path}\` \u2014 ${r.title} (\`${r.skillId}\`)`),"","Regenerate:","","```bash",re("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
4
|
-
`)}var Tt={"workspai-diagnose-api-failure":p$1,"workspai-release-readiness":t},Ie="## Workspace verification (hydrated)";function Ot(e){let t=[Ie,"","Verification commands for this workspace:","",...e.verificationCommands.length?e.verificationCommands.map(r=>`- \`${r}\``):["- `npx workspai workspace verify --json`"]];return e.scopedProjects.length>0&&t.push("","Scoped projects:","",...e.scopedProjects.map(r=>`- ${r}`)),t.push(""),t.join(`
|
|
5
|
-
`)}async function dt(e){let t=i$1.resolve(e.workspacePath),r=[];for(let n of e.skills){let c=Tt[n.skillId];if(!c)continue;let l=i$1.join(t,c);if(!await f$2.pathExists(l))continue;let p=await f$2.readFile(l,"utf8"),o=Ot(n),A=p.includes(Ie)?p.replace(new RegExp(`${Ie}[\\s\\S]*$`),o.trimEnd()):`${p.trimEnd()}
|
|
6
|
-
|
|
7
|
-
${o}`;e.write&&await f$2.writeFile(l,`${A.trimEnd()}
|
|
8
|
-
`,"utf8"),r.push(c);}return r}var _t="workspai-agent-customization-pack-capabilities.v1";function pt(){return {schemaVersion:_t,presets:{minimal:{meaning:"Generate the portable grounding index, AGENTS.md, and provider-specific lightweight instructions.",requiredOutputs:[e.agentIndex,e.agentCustomizationPack,e.agents]},enterprise:{meaning:"Generate the full VS Code-native pack: instructions, prompts, skills, custom agents, and validation metadata.",requiredOutputs:[e.agentIndex,e.agentCustomizationPack,e.agents,l,p$1,B,".github/agents/workspai-advisor.agent.md",D,b$1]}},targets:{all:{meaning:"Generate every supported customization surface.",outputFamilies:["portable","vscode","copilot","cursor","claude","gemini","qwen","kimi","grok","windsurf","amazon-q"]},vscode:{meaning:"Generate VS Code-native customizations for Copilot Chat and agent workflows.",outputFamilies:["instructions","prompts","skills","agents","hooks"]},agents:{meaning:"Generate portable AGENTS.md grounding for any agent.",outputFamilies:["portable"]},copilot:{meaning:"Generate GitHub Copilot instructions, prompts, and skills.",outputFamilies:["instructions","prompts","skills"]},cursor:{meaning:"Generate Cursor rules.",outputFamilies:["rules"]},claude:{meaning:"Generate Claude Code grounding files.",outputFamilies:["rules","portable"]},codex:{meaning:"Use AGENTS.md and the report index as the Codex grounding layer.",outputFamilies:["portable"]},gemini:{meaning:"Generate Gemini CLI grounding through GEMINI.md and canonical AGENTS.md.",outputFamilies:["adapter","portable"]},qwen:{meaning:"Generate Qwen Code grounding through QWEN.md and canonical AGENTS.md.",outputFamilies:["adapter","portable"]},kimi:{meaning:"Use AGENTS.md and the report index as the Kimi Code grounding layer.",outputFamilies:["portable"]},grok:{meaning:"Use AGENTS.md and the report index as the xAI Grok grounding layer.",outputFamilies:["portable"]},windsurf:{meaning:"Use AGENTS.md and the report index as the Windsurf grounding layer.",outputFamilies:["portable"]},"amazon-q":{meaning:"Generate an Amazon Q project rule that routes agents to canonical evidence.",outputFamilies:["rules","portable"]},orca:{meaning:"Legacy compatibility alias for AGENTS.md consumers; prefer the grok target.",outputFamilies:["portable"]}},standardAnswerContract:[...te],requiredReports:K.map(e=>({path:e.relativePath,label:e.label,required:e.required})),strictRules:["Required reports must exist.","Generated report paths must stay inside the workspace root.","Generated customization text must be English-only.","Agent answers must not claim pass, ready, or healthy without cited evidence.","Commands must distinguish display guidance from execution requests.","Agent hook files must be advisory and disabled by default unless the user explicitly enables them.","MCP design artifacts must stay read-mostly until write tools have explicit approval boundaries."],outputKinds:["report","grounding","instruction","prompt","skill","skill-resource","operational-skill","skills-index","explain-report","agent","rule","hook","mcp-design"],pathLayers:{l1CanonicalRoots:[".workspai/reports/",`${a$2}/`],l2PrefixedMirrorRoots:[".github/",".cursor/",".claude/",".amazonq/"],l3SharedIndustryFiles:["AGENTS.md",".github/copilot-instructions.md","CLAUDE.md","GEMINI.md","QWEN.md"]}}}var vt=f.agentIndex,Wt=f.agentCustomizationPack,V=e.agentIndex,H=e.agentCustomizationPack;var K=[{relativePath:i.goalIndex,label:"Active Goal Pack index",required:false},{relativePath:i.goalPackLastRun,label:"Latest governed Goal Pack",required:false},{relativePath:b,label:"Agent context pack",required:true},{relativePath:b$1,label:"Operational skills index",required:true},{relativePath:e.model,label:"Workspace model",required:false},{relativePath:e.knowledgeGraph,label:"Workspace knowledge graph",required:false},{relativePath:e.evaluationLastRun,label:"Workspace Intelligence evaluation",required:false},{relativePath:e.doctor,label:"Workspace doctor",required:false},{relativePath:i.doctorProject,label:"Project doctor",required:false},{relativePath:i.doctorRemediationPlan,label:"Doctor remediation plan",required:false},{relativePath:i.artifactRemediationPlan,label:"Artifact remediation plan",required:false},{relativePath:i.doctorFixResult,label:"Doctor fix result",required:false},{relativePath:e.analyze,label:"Workspace analyze",required:false},{relativePath:i.pipelineLastRun,label:"Governance pipeline",required:false},{relativePath:e.readiness,label:"Release readiness",required:false},{relativePath:e.impact,label:"Workspace impact",required:false},{relativePath:e.verify,label:"Workspace verify",required:false},{relativePath:e.snapshot,label:"Workspace model snapshot",required:false},{relativePath:e.diff,label:"Workspace model diff",required:false},{relativePath:e.explain,label:"Workspace explain",required:false},{relativePath:e.contractVerify,label:"Workspace contract verify",required:false},{relativePath:e.history,label:"Workspace intelligence history",required:false}];function Lt(){let e=K.map(n=>n.relativePath),r=b$2().consumers.agents.canonicalReadOrder.filter(n=>n!==V&&e.includes(n));return [...new Set([i.goalIndex,i.goalPackLastRun,...r,...e])]}function y(e){return `npx workspai ${e}`.trim()}function ve(e){return e&&typeof e=="object"?e:null}function xe(e,t=12){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0).slice(0,t):[]}function Nt(e){let t=xe(e.blockers,12);if(t.length>0)return t;let r=xe(e.blockingReasons,12);if(r.length>0)return r;let n=ve(e.summary);return n&&Array.isArray(n.blockingReasons)?xe(n.blockingReasons,12):[]}function jt(e){let t=[...new Set(e.map(r=>r.trim()).filter(Boolean))];return t.filter(r=>{let n=r.toLowerCase();return !t.some(c=>{if(c===r||!c.includes(":"))return false;let l=c.toLowerCase();return l.length>n.length&&l.endsWith(n)})})}function Gt(e){for(let t of ["generatedAt","updatedAt","timestamp"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}if(Array.isArray(e.entries)){let t=e.entries.map(r=>ve(r)?.generatedAt).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim()).filter(r=>Number.isFinite(Date.parse(r)));if(t.length>0)return t.reduce((r,n)=>Date.parse(n)>Date.parse(r)?n:r)}}function Dt(e,t,r){if(!e)return true;let n=Date.parse(e);return Number.isFinite(n)?r.getTime()-n>t*60*60*1e3:true}function $t(e$1,t,r){return e$1.path===e.snapshot?false:Dt(e$1.generatedAt,t,r)}function qt(e){let t=e&&e.length>0?e:["all"];return t.includes("all")?new Set(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"]):new Set(t)}function R(e,t){return e.has("all")||e.has(t)}function wt(e){return R(e,"copilot")||R(e,"vscode")}function Mt(e,t){return t==="generic"?R(e,"agents"):t==="copilot"?wt(e):t==="grok"?R(e,"grok")||R(e,"orca"):R(e,t)}function Kt(e){return e??"enterprise"}function Ht(e){return e===b$1?"skills-index":e.includes("workspace-explain-last-run.json")?"explain-report":(e.startsWith(`${a$2}/`)||e.startsWith(".rapidkit/skills/"))&&e.endsWith(".md")?"operational-skill":e.includes("hooks")||e===F||e===G?"hook":e.includes("mcp")||e===D||e===E?"mcp-design":e.endsWith(".json")?"report":e.includes("/instructions/")||e.endsWith("copilot-instructions.md")?"instruction":e.includes("/prompts/")?"prompt":e.includes("/skills/")&&e.endsWith("/SKILL.md")?"skill":e.includes("/skills/")?"skill-resource":e.includes("/agents/")?"agent":e.includes("/rules/")||e.endsWith(".mdc")?"rule":"grounding"}function Vt(e){return e.startsWith(".github/")?["vscode","copilot"]:e.startsWith(".cursor/")?["cursor"]:e.startsWith(".claude/")||e==="CLAUDE.md"?["claude"]:e==="GEMINI.md"?["gemini"]:e==="QWEN.md"?["qwen"]:e.startsWith(".amazonq/")?["amazon-q"]:e==="AGENTS.md"||e.startsWith(".rapidkit/")?["agents","codex","kimi","grok","copilot","cursor","windsurf","orca","vscode"]:e.startsWith(".vscode/")?["vscode"]:["agents"]}function Ft(e,t){return pt().presets[t].requiredOutputs.includes(e)}async function Ut(e,t){if(t)return t;let r=await d(e,k$1)??i$1.join(e,k$1);if(await f$2.pathExists(r))try{let n=await f$2.readJson(r);return b$5(k$1,n,r),n}catch{}return p({workspacePath:e,includeEvidence:true})}function zt(e){return e.length>0&&!i$1.isAbsolute(e)&&!e.split(/[\\/]+/).includes("..")}function Bt(e){return Object.fromEntries(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"].map(r=>[r,{enabled:e.targets.includes("all")||e.targets.includes(r),outputs:e.outputs.filter(n=>n.targets.includes(r)).map(n=>n.path).sort()}]))}async function Jt(e,t){try{if(!await f$2.pathExists(e))return {payload:null,exists:false,validity:"missing"};let r=await f$2.readJson(e),n=ve(r);return n?a$1(t)?(b$5(t,n,e),{payload:n,exists:true,validity:"valid"}):{payload:n,exists:true,validity:"uncontracted"}:{payload:null,exists:true,validity:"invalid",validationError:"Artifact root must be a JSON object"}}catch(r){return {payload:null,exists:true,validity:"invalid",validationError:r instanceof Error?r.message:String(r)}}}async function ut(e){let t=e.now??new Date,r=e.staleAfterHours??24,n=[],c=[];for(let o of K){let A=await d(e.workspacePath,o.relativePath)??i$1.join(e.workspacePath,o.relativePath),h=await Jt(A,o.relativePath),m=h.payload;h.validity==="invalid"?c.push(`Invalid evidence contract: ${o.relativePath}`):m&&c.push(...Nt(m)),n.push({path:o.relativePath,label:o.label,required:o.required,exists:h.exists,validity:h.validity,validationError:h.validationError,generatedAt:m?Gt(m):void 0,commandId:typeof m?.commandId=="string"?m.commandId:void 0,exitCode:typeof m?.exitCode=="number"?m.exitCode:void 0});}let l=jt(c).slice(0,16),p=b$2();return {schemaVersion:vt,generatedAt:t.toISOString(),workspaceRoot:e.workspacePath,intelligenceChain:{schemaVersion:p.schemaVersion,contractPath:p.contractPath,currentStep:"agent-sync"},readOrder:Lt(),blockers:l,staleAfterHours:r,reports:n,refreshCommand:y("workspace agent-sync --write --refresh-context")}}function Yt(e$1){let t=["# Workspai agent grounding","","Cross-tool instructions for Copilot, Cursor, Claude Code, Codex, Grok, and other agents.","","## Read order (mandatory before workspace diagnosis)","",`1. \`${e.agentIndex}\` \u2014 latest blockers, timestamps, and report paths`,`2. \`${i.goalIndex}\` \u2014 when present, read the active Goal Pack and its handoff before choosing work.`,`3. \`${e.agentContext}\` \u2014 read only task-relevant context`,"4. Read only the task-relevant evidence artifacts listed in the index.","5. Use the Goal Pack retrieval queries, `workspace graph search <query> --limit 12 --json`, or MCP `searchWorkspaceGraph` before loading the full graph.","","Do **not** full-repo scan or inject the complete graph when a bounded query can answer the task.","","## Regenerate intelligence","","```bash",y("workspace agent-sync --write --refresh-context"),y("workspace context --for-agent --json --write"),y("pipeline --json --write"),"```",""];if(e$1.index.blockers.length>0){t.push("## Current blockers","");for(let r of e$1.index.blockers.slice(0,12))t.push(`- ${r}`);t.push("");}if(e$1.context?.safeCommands?.length){t.push("## Safe commands (prefer these)","");for(let r of e$1.context.safeCommands.slice(0,10))t.push(`- \`${r.display}\` \u2014 ${r.description}`);t.push("");}return t.push("## Rules","","- Treat `.workspai/reports/*` as the source of truth for health, gates, and release posture.","- Prefer deterministic Workspai CLI commands over heuristic framework guesses.","- If evidence is missing or stale, run the refresh commands above before proposing fixes.","- Keep project-scoped advice aligned with the active project named in the context pack.","- Never claim that an active goal is satisfied until its CLI-owned verification lifecycle is `verified`.",""),t.join(`
|
|
9
|
-
`)}function Xt(e$1){return ["# Workspai agent grounding","",`Generated: ${e$1.generatedAt}`,"",`This file is tool-agnostic. Synced agents should read it together with \`${e.agentIndex}\`.`,"","## Mandatory read order","",...e$1.readOrder.map((t,r)=>`${r+1}. \`${t}\``),"",e$1.blockers.length>0?"## Blockers":"",...e$1.blockers.length>0?e$1.blockers.map(t=>`- ${t}`):[],"","## Refresh","","```bash",e$1.refreshCommand,"```",""].filter(t=>t!=="").join(`
|
|
10
|
-
`)}function Qt(){return ["# Workspai workspace grounding","","Before answering workspace, release, or architecture questions:","","1. Read `AGENTS.md` (managed Workspai section).",`2. Read \`${e.agentIndex}\` and only task-relevant context from \`${e.agentContext}\`.`,"3. Use bounded `workspace graph search` or MCP `searchWorkspaceGraph` before scanning the full repository.","","Regenerate stale intelligence:","","```bash",y("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
11
|
-
`)}function Zt(){return ["## Claude Code","",`- Load \`${e.agentIndex}\` before diagnosing blockers.`,"- Use `.claude/rules/workspai-evidence.md` for scoped Workspai evidence rules.","- Treat `.claude/rules/rapidkit-evidence.md` as a legacy compatibility mirror.","- Refresh grounding with `npx workspai workspace agent-sync --write`.",""].join(`
|
|
12
|
-
`)}function Te(e$1){return [`## ${e$1}`,"","- Treat `AGENTS.md` as the portable workspace instruction authority.",`- Load \`${e.agentIndex}\` before diagnosing blockers or architecture.`,`- Read only task-relevant context from \`${e.agentContext}\`.`,"- Use bounded Workspace Knowledge Graph search before broad source discovery.","- Refresh grounding with `workspai workspace agent-sync --write --refresh-context`.",""].join(`
|
|
13
|
-
`)}function er(){return ["---","description: Workspai workspace evidence and intelligence grounding","globs: []","alwaysApply: true","---","","Before proposing fixes in this workspace:","",`1. Read \`${e.agents}\` and \`${e.agentIndex}\`.`,`2. Read only task-relevant context from \`${e.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","Refresh when stale:","","```bash",y("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
14
|
-
`)}function tr(){return ["---",'applyTo: ".workspai/**,**/.workspai/**,.rapidkit/**,**/.rapidkit/**"',"description: Workspai evidence and intelligence artifacts","---","","When working under `.workspai/` or legacy `.rapidkit/`:","","- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.",`- Start from \`${e.agentIndex}\` for read order and blockers.`,"- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.",""].join(`
|
|
15
|
-
`)}function rr(){return ["---",'applyTo: "**"',"description: Workspai workspace scope, evidence, and command discipline","---","","# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Scope rules","",`- Start from \`${e.agentIndex}\`; read only task-relevant context and evidence.`,"- Prefer bounded `workspace graph search` or MCP `searchWorkspaceGraph` over loading the complete graph.","- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","- Do not translate unsupported stack requests into unrelated native kits.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
|
|
16
|
-
`)}function nr(){return ["# Workspai evidence","","Applies when reading or editing `.workspai/reports/*`.","","- Start from `INDEX.json`, then `workspace-context-agent.json`.","- Use report blockers as the primary fix target.","- Regenerate with `npx workspai workspace agent-sync --write`.",""].join(`
|
|
17
|
-
`)}function ar(){return ["# Legacy RapidKit evidence alias","","Compatibility path only. Use `.claude/rules/workspai-evidence.md` as the canonical rule.",""].join(`
|
|
18
|
-
`)}function or(){return ["---","description: Legacy RapidKit metadata compatibility alias",'globs: [".rapidkit/**", "**/.rapidkit/**"]',"alwaysApply: false","---","","Use `.cursor/rules/workspai-grounding.mdc` for canonical Workspai grounding.",""].join(`
|
|
19
|
-
`)}function gt(e){return ["---",'applyTo: ".rapidkit/**,**/.rapidkit/**"',"description: Legacy RapidKit metadata compatibility alias","---","",`Use \`.github/instructions/workspai-${e}.instructions.md\` as the canonical Workspai instruction.`,""].join(`
|
|
20
|
-
`)}function mt(){return ["---","description: Diagnose Workspai workspace blockers from evidence reports","---","","Diagnose this workspace using Workspai evidence only.","","Read:","",`- \`${e.agentIndex}\``,`- \`${e.agentContext}\``,"- Any fail/warn reports referenced in the index","","Return:","","1. Root cause grounded in report blockers","2. Smallest safe fix path (commands + file edits)","3. One verification command to prove recovery",""].join(`
|
|
21
|
-
`)}function ne(e$1){return ["---",`description: ${e$1.description}`,"---","",e$1.objective,"","Read first:","",`- \`${e.agentIndex}\``,`- \`${e.agentContext}\``,"- Any report referenced by the current blocker or task","","Return:","",...e$1.expectedOutput.map((t,r)=>`${r+1}. ${t}`),"","Use the standard Workspai answer contract: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
|
|
22
|
-
`)}function L(e){return ["# "+e.title,"",...e.lines,""].join(`
|
|
23
|
-
`)}function ir(){return L({title:"MCP Tool Design",lines:["Workspai MCP is a read-mostly bridge over contract-validated workspace artifacts.","","Candidate read tools:",`- \`getWorkspaceModel\` \u2014 read \`${e.model}\`.`,`- \`getWorkspaceKnowledgeGraph\` \u2014 read \`${e.knowledgeGraph}\`.`,`- \`getWorkspaceEvaluation\` \u2014 read \`${e.evaluationLastRun}\` (or the live evaluation when requested).`,"- `queryWorkspaceEntities` \u2014 filter proof-backed graph entities by kind.","- `searchWorkspaceGraph` \u2014 retrieve bounded proof-backed context by text query.","- `getWorkspaceGraphEvidence` \u2014 resolve evidence for an entity or relation.","- `findWorkspaceGraphPath` \u2014 find a shortest proof-carrying relationship path.",`- \`getEvidenceIndex\` \u2014 read \`${e.agentIndex}\`.`,"- `getBlockers` \u2014 derive current blockers from INDEX and gate reports.","- `getSafeCommands` \u2014 read safe commands from `workspace-context-agent.json`.","- `getProjectContext` \u2014 return one project-scoped slice of the workspace model.","- `getArtifact` \u2014 read one explicit artifact path inside the workspace root.",`- \`listOperationalSkills\` \u2014 read \`${e.skillsIndex}\`.`,"- `getWorkspaceExplain` \u2014 read/build workspace explain for release-blocked or project scope.","- `refreshWorkspaceIntelligence` \u2014 explicit user-approved refresh command only.","","Write or repair tools require explicit approval boundaries and are intentionally not part of the first read-mostly design."]})}function sr(e$1){return `${JSON.stringify({schemaVersion:h$3.workspaiMcpDesign.schemaVersion,generatedAt:e$1.generatedAt,workspaceRoot:e$1.workspacePath,status:"design-only",mode:"read-mostly",safety:{writeToolsEnabled:false,approvalRequiredForRefresh:true,artifactReadsMustStayInsideWorkspace:true},candidateTools:[{name:"getWorkspaceModel",reads:[e.model],mutates:false},{name:"getWorkspaceKnowledgeGraph",reads:[e.knowledgeGraph],mutates:false},{name:"getWorkspaceEvaluation",reads:[e.evaluationLive,e.evaluationLastRun],mutates:false},{name:"queryWorkspaceEntities",reads:[e.knowledgeGraph],mutates:false},{name:"searchWorkspaceGraph",reads:[e.knowledgeGraph],mutates:false},{name:"getWorkspaceGraphEvidence",reads:[e.knowledgeGraph],mutates:false},{name:"findWorkspaceGraphPath",reads:[e.knowledgeGraph],mutates:false},{name:"getEvidenceIndex",reads:[e.agentIndex],mutates:false},{name:"getBlockers",reads:[e.agentIndex,e.verify,i.pipelineLastRun],mutates:false},{name:"getSafeCommands",reads:[e.agentContext],mutates:false},{name:"getProjectContext",reads:[e.model,e.agentContext],mutates:false},{name:"getArtifact",reads:["requested workspace-relative artifact path"],mutates:false},{name:"listOperationalSkills",reads:[e.skillsIndex],mutates:false},{name:"getWorkspaceExplain",reads:[e.explain,e.verify,e.impact],mutates:false},{name:"refreshWorkspaceIntelligence",command:y("workspace agent-sync --write --refresh-context"),mutates:true,approvalRequired:true}]},null,2)}
|
|
24
|
-
`}function cr(e$1){return `${JSON.stringify({schemaVersion:h$3.agentHooks.schemaVersion,generatedAt:e$1.generatedAt,workspaceRoot:e$1.workspacePath,enabledByDefault:false,mode:"advisory",hooks:[{name:"workspai-pre-tool-use-workspace-boundary",event:"PreToolUse",purpose:"Block or warn on state-changing commands outside the active workspace root.",defaultAction:"warn",rules:["Allow read-only commands.","Warn before write/delete commands outside workspaceRoot.","Never run destructive commands without explicit user approval."]},{name:"workspai-post-tool-use-verify-suggestion",event:"PostToolUse",purpose:"Suggest non-destructive verification commands after edits.",defaultAction:"suggest",commands:[y("doctor workspace"),y("workspace verify --strict --json")]},{name:"workspai-user-prompt-submit-scope-hint",event:"UserPromptSubmit",purpose:"Inject lightweight workspace scope and evidence index hints.",defaultAction:"inject-context-hint",reads:[e.agentIndex,e.agentContext]}]},null,2)}
|
|
25
|
-
`}function kt(e$1){let t=["---","name: workspai-workspace-intelligence","description: Use Workspai workspace intelligence reports to answer, repair, verify, and release with evidence","---","","# Workspai Workspace Intelligence","","Use this skill for workspace architecture, project lifecycle, blocker repair, release readiness, agent grounding, and CI evidence questions.","","## Decision flow","","1. Load `resources/scope-model.md`.",`2. Load \`${e.agentIndex}\`.`,`3. Load \`${e.agentContext}\`.`,`4. Load \`${e.skillsIndex}\` when operational playbooks are needed.`,"5. Load the smallest evidence report required for the task.","6. Answer with Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Rules","","- Prefer Workspai reports over full-repo scans.","- Never claim a gate passed without a cited report.","- Separate display commands from execution requests.","- Keep project-scoped fixes inside the active project unless workspace evidence says otherwise.",""];return e$1?.trim()&&t.push(e$1.trim(),""),t.join(`
|
|
26
|
-
`)}function ae(e$1){return ["---",`name: ${e$1.name}`,`description: ${e$1.description}`,`tools: [${e$1.tools.map(t=>`'${t}'`).join(", ")}]`,"---","",`You are the ${e$1.name} agent for Workspai Workspace Intelligence.`,"",`Mode: ${e$1.mode}.`,"",`Start every task by reading \`${e.agentIndex}\` and \`${e.agentContext}\`.`,"","Use this answer contract:","","- Scope","- Evidence","- Diagnosis","- Fix Plan","- Run","- Verify","- Assumptions","","Do not invent health, readiness, or policy status. Cite report paths and command outputs.",""].join(`
|
|
27
|
-
`)}function ft(){return ["---","name: workspai-grounding","description: Load Workspai workspace intelligence reports before diagnosing or changing code","---","","# Workspai grounding","","Use when the user asks about workspace health, release gates, doctor/pipeline failures, or project structure.","","## Workflow","",`1. Read \`${e.agentIndex}\``,`2. Read \`${e.agentContext}\``,"3. Read fail/warn evidence artifacts listed in the index","4. Propose the smallest safe fix with explicit verification commands","","## Refresh stale evidence","","```bash",y("workspace agent-sync --write --refresh-context"),"```",""].join(`
|
|
28
|
-
`)}async function u(e,t,r){return r?(await f$2.ensureDir(i$1.dirname(e)),await f$2.writeFile(e,t,"utf8"),"written"):"skipped"}async function Oe(e){if(!e.write)return "skipped";await We(e.workspacePath,e.absolutePath);let t=await f$2.pathExists(e.absolutePath)?await f$2.readFile(e.absolutePath,"utf8"):null,{upsertManagedAgentSection:r}=await import('./managed-agent-markers-COE5DJ3W.js'),n=r(t,e.generatedBody),c=e.preamble?`${e.preamble.trimEnd()}
|
|
29
|
-
|
|
30
|
-
${n}`:n;return await f$2.ensureDir(i$1.dirname(e.absolutePath)),await f$2.writeFile(e.absolutePath,c,"utf8"),"written"}async function ht(e){if(!e.write)return "skipped";await We(e.workspacePath,e.absolutePath);let t=await f$2.pathExists(e.absolutePath)?await f$2.readFile(e.absolutePath,"utf8"):"",{upsertManagedAgentSection:r}=await import('./managed-agent-markers-COE5DJ3W.js'),n=r(t,e.generatedBody),c=n.includes(e.importLine)?n:`${e.importLine}
|
|
31
|
-
|
|
32
|
-
${n}`;return await f$2.ensureDir(i$1.dirname(e.absolutePath)),await f$2.writeFile(e.absolutePath,c,"utf8"),"written"}async function We(e,t){let r=i$1.resolve(e),n=i$1.resolve(t),c=i$1.relative(r,n);if(!c||c===".."||c.startsWith(`..${i$1.sep}`)||i$1.isAbsolute(c))throw new Error("Agent output path must remain inside the canonical workspace.");let l=c.split(i$1.sep),p=r;for(let[o,A]of l.entries()){p=i$1.join(p,A);let h=await f$2.lstat(p).catch(_=>{if(_.code==="ENOENT")return null;throw _});if(!h)return;let m=o===l.length-1;if(h.isSymbolicLink()||(m?!h.isFile():!h.isDirectory()))throw new Error(`Agent output path is blocked by authored repository state: ${c}`)}}function nn(e){if(!e?.trim())return;let t=new Set(["all","vscode","agents","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"]),r=e.split(",").map(n=>n.trim().toLowerCase()).filter(n=>t.has(n));return r.length>0?r:void 0}function lr(e){let t=[...e.outputs].sort((n,c)=>n.path.localeCompare(c.path)),r=b$2();return {schemaVersion:Wt,generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,preset:e.preset,targets:[...e.targets].sort(),sourceReports:e.index.reports.filter(n=>n.exists).map(n=>n.path).sort(),intelligenceChain:{schemaVersion:r.schemaVersion,contractPath:r.contractPath,currentStep:"agent-sync"},outputInventory:t,capabilityMatrix:Bt({targets:e.targets,outputs:t}),drift:{missingRequired:e.missingRequired,staleReports:e.staleReports,strictViolations:e.strictViolations},answerContract:["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"],refreshCommand:y(`workspace agent-sync --write --refresh-context --preset ${e.preset}`),experimental:{hooksEnabled:e.experimentalHooks,mcpReady:t.some(n=>n.kind==="mcp-design")}}}async function _e(e){let t$1=i$1.resolve(e.workspacePath),r$1=e.now??new Date,n$1=e.staleAfterHours??24,c$1=qt(e.targets),l$1=[...c$1].sort(),p$2=Kt(e.preset),o$1=e.write===true,A$1=e.strict===true,h,m$2=null,_=e.model;e.refreshContext&&(_??=await p({workspacePath:t$1,includeEvidence:true}),m$2=await c({workspacePath:t$1,model:_,agent:e.agent??"generic",scope:e.scope,includeEvidence:true}),o$1&&(h=await d$1(m$2,t$1)));let C$1=[],oe=[],ie=[],se=[],d=(s,k)=>{s==="written"?oe.push(k):ie.push(k),se.push({path:k,kind:Ht(k),targets:Vt(k),required:Ft(k,p$2),status:s==="written"?"written":e.dryRun?"planned":"skipped"});},ce="",At=await Ut(t$1,_),le=null;try{le=(await m({workspacePath:t$1})).contract;}catch{le=null;}let Pt=st({model:At,context:m$2,contract:le}),de=await ct({workspacePath:t$1,skills:Pt,generatedAt:r$1.toISOString(),write:o$1});for(let s of de.skills)d(o$1?"written":"skipped",s.canonicalPath);d(o$1?"written":"skipped",b$1),ce=lt(de.index);let E$1=await ut({workspacePath:t$1,staleAfterHours:n$1,now:r$1});if(d(await u(i$1.join(t$1,V),`${JSON.stringify(E$1,null,2)}
|
|
33
|
-
`,o$1),V),d(await u(i$1.join(t$1,f$3),`${Xt(E$1)}
|
|
34
|
-
`,o$1),f$3),["agents","vscode","copilot","cursor","codex","kimi","grok","windsurf","orca"].some(s=>R(c$1,s))&&d(await Oe({workspacePath:t$1,absolutePath:i$1.join(t$1,"AGENTS.md"),generatedBody:Yt({index:E$1,context:m$2}),write:o$1}),"AGENTS.md"),R(c$1,"claude")){let s=i$1.join(t$1,"CLAUDE.md");if(o$1){await We(t$1,s);let{upsertManagedAgentSection:k}=await import('./managed-agent-markers-COE5DJ3W.js'),g=await f$2.pathExists(s)?await f$2.readFile(s,"utf8"):"",P=k(g,Zt()),b=P.includes("@AGENTS.md")?P:`@AGENTS.md
|
|
35
|
-
|
|
36
|
-
${P}`;await f$2.ensureDir(i$1.dirname(s)),await f$2.writeFile(s,b,"utf8"),oe.push("CLAUDE.md");}else ie.push("CLAUDE.md");d(await u(i$1.join(t$1,j),`${nr()}
|
|
37
|
-
`,o$1),j),d(await u(i$1.join(t$1,k),`${ar()}
|
|
38
|
-
`,o$1),k);}if(R(c$1,"gemini")&&d(await ht({workspacePath:t$1,absolutePath:i$1.join(t$1,"GEMINI.md"),importLine:"@./AGENTS.md",generatedBody:Te("Gemini CLI"),write:o$1}),"GEMINI.md"),R(c$1,"qwen")&&d(await ht({workspacePath:t$1,absolutePath:i$1.join(t$1,"QWEN.md"),importLine:"@AGENTS.md",generatedBody:Te("Qwen Code"),write:o$1}),"QWEN.md"),R(c$1,"amazon-q")&&d(await Oe({workspacePath:t$1,absolutePath:i$1.join(t$1,".amazonq/rules/workspai-agent-entry.md"),generatedBody:Te("Amazon Q Developer"),write:o$1}),".amazonq/rules/workspai-agent-entry.md"),R(c$1,"cursor")&&(d(await u(i$1.join(t$1,h$2),er(),o$1),h$2),d(await u(i$1.join(t$1,i$2),or(),o$1),i$2)),wt(c$1)){if(d(await Oe({workspacePath:t$1,absolutePath:i$1.join(t$1,".github/copilot-instructions.md"),generatedBody:Qt(),write:o$1}),".github/copilot-instructions.md"),d(await u(i$1.join(t$1,l),rr(),o$1),l),d(await u(i$1.join(t$1,m$1),gt("workspace"),o$1),m$1),d(await u(i$1.join(t$1,n),tr(),o$1),n),d(await u(i$1.join(t$1,o),gt("evidence"),o$1),o),d(await u(i$1.join(t$1,p$1),mt(),o$1),p$1),d(await u(i$1.join(t$1,q),mt(),o$1),q),p$2==="enterprise"){let s$1=[[r,ne({description:"Repair Workspai blockers with evidence and verification",objective:"Plan the smallest safe repair for the current Workspai blocker.",expectedOutput:["Blocker and affected workspace/project scope","Evidence paths and exact failing signals","Minimal fix plan","Human-run commands","Verification command and expected success signal"]})],[t,ne({description:"Assess Workspai release readiness from evidence",objective:"Assess whether this workspace is release-ready using Workspai gates.",expectedOutput:["Readiness verdict with cited reports","Blocking gates","Safe next command","Verification checklist"]})],[v,ne({description:"Onboard a project into Workspai Workspace Intelligence",objective:"Guide project onboarding using workspace model and create planner capabilities.",expectedOutput:["Target project scope","Native create, official generator, or existing lane","Safe commands","Post-onboarding verification"]})],[x,ne({description:"Adopt an existing project into Workspai governance",objective:"Adopt an existing project without changing its runtime behavior.",expectedOutput:["Detected stack and confidence","Adoption plan","Generated metadata expectations","Doctor and workspace model verification"]})]];for(let[g,P]of s$1)d(await u(i$1.join(t$1,g),P,o$1),g);let k=[[s,s$1[0][1]],[u$1,s$1[1][1]],[w,s$1[2][1]],[y$1,s$1[3][1]]];for(let[g,P]of k)d(await u(i$1.join(t$1,g),P,o$1),g);if(e.hydratePrompts===true)for(let g of await dt({workspacePath:t$1,skills:de.skills,write:o$1}))d(o$1?"written":"skipped",g);}if(d(await u(i$1.join(t$1,z),ft(),o$1),z),d(await u(i$1.join(t$1,A),ft(),o$1),A),p$2==="enterprise"){d(await u(i$1.join(t$1,B),kt(ce),o$1),B),d(await u(i$1.join(t$1,C),kt(ce),o$1),C);let s=[["artifact-map.md",L({title:"Artifact Map",lines:K.map(g=>`- \`${g.relativePath}\` \u2014 ${g.label}`)})],["command-map.md",L({title:"Command Map",lines:["- `npx workspai workspace agent-sync --write --refresh-context` \u2014 refresh agent grounding.","- `npx workspai workspace model --json --write` \u2014 refresh workspace model.","- `npx workspai doctor workspace` \u2014 refresh health evidence.","- `npx workspai workspace verify --strict --json` \u2014 verify release gates."]})],["scope-model.md",L({title:"Scope Model",lines:["- Workspace scope is the default source of truth.","- Project scope is selected only when the active task targets a specific project.","- Always name the workspace and project when giving repair or lifecycle advice."]})],["runtime-support.md",L({title:"Runtime Support",lines:["- Native create is available only for Workspai-owned scaffold contracts.","- Unsupported stacks should use the official lane when a stable ecosystem generator exists.","- Existing projects should use the existing lane when native create is unavailable."]})],["create-planner-capabilities.md",L({title:"Create Planner Capabilities",lines:["- Use `contracts/create-planner-capabilities.v1.json` to decide native, official, or existing.","- Do not map PHP, WordPress, Laravel, Rails, or Symfony requests to unrelated native kits.","- Explain unsupported native create requests and guide users to adopt/import."]})],["mcp-tools.md",ir()]];for(let[g,P]of s){let b=`${i$1.dirname(B)}/resources/${g}`;d(await u(i$1.join(t$1,b),P,o$1),b);let Ne=`${i$1.dirname(C)}/resources/${g}`;d(await u(i$1.join(t$1,Ne),P,o$1),Ne);}let k=[["workspai-advisor.agent.md",ae({name:"Workspai Advisor",description:"Read-only workspace and project guidance using Workspai evidence",mode:"read-only",tools:["search","read"]})],["workspai-repair.agent.md",ae({name:"Workspai Repair",description:"Turn Workspai blockers into minimal fixes and verification steps",mode:"repair",tools:["search","read","edit"]})],["workspai-release.agent.md",ae({name:"Workspai Release",description:"Assess readiness, governance gates, and release safety from evidence",mode:"release",tools:["search","read"]})],["workspai-project-onboarder.agent.md",ae({name:"Workspai Project Onboarder",description:"Guide create, import, and adopt flows with Workspai contracts",mode:"onboard",tools:["search","read","edit"]})]];for(let[g,P]of k){let b=`.github/agents/${g}`;d(await u(i$1.join(t$1,b),P,o$1),b);}}}if(p$2==="enterprise"){let s=sr({workspacePath:t$1,generatedAt:E$1.generatedAt});b$5(D,JSON.parse(s)),d(await u(i$1.join(t$1,D),s,o$1),D),d(await u(i$1.join(t$1,E),s,o$1),E);}if(p$2==="enterprise"&&e.experimentalHooks===true){let s=cr({workspacePath:t$1,generatedAt:E$1.generatedAt});b$5(F,JSON.parse(s)),d(await u(i$1.join(t$1,F),s,o$1),F),d(await u(i$1.join(t$1,G),s,o$1),G);}let pe=o$1?await ut({workspacePath:t$1,staleAfterHours:n$1,now:r$1}):E$1,F$1=pe.reports.filter(s=>s.required&&!s.exists).map(s=>s.path),U=pe.reports.filter(s=>s.exists&&$t(s,n$1,r$1)).map(s=>s.path);if(A$1){F$1.length>0&&C$1.push(`Missing required reports: ${F$1.join(", ")}`),U.length>0&&C$1.push(`Stale reports (>${n$1}h): ${U.join(", ")}`);let s=se.map(k=>k.path).filter(k=>!zt(k));s.length>0&&C$1.push(`Unsafe generated output paths: ${s.join(", ")}`);}let v$1=o$1?await g$2({workspacePath:t$1,mode:e.projectGrounding??"managed",now:r$1}):void 0;if(A$1&&v$1&&v$1.skipped.length>0&&C$1.push(`Project grounding incomplete: ${v$1.skipped.map(s=>`${s.name} (${s.reason})`).join(", ")}`),A$1&&v$1){let s=v$1.projects.flatMap(k=>(k.hostCoverage??[]).filter(g=>g.status==="blocked"&&Mt(c$1,g.id)).map(g=>`${i$1.basename(k.projectPath)}:${g.id}`));s.length>0&&C$1.push(`Project agent entry coverage blocked: ${s.join(", ")}`);}let Le=lr({workspacePath:t$1,generatedAt:r$1.toISOString(),preset:p$2,targets:l$1,index:pe,outputs:[...se,{path:H,kind:"report",targets:["agents","vscode","copilot","cursor","claude","codex","gemini","qwen","kimi","grok","windsurf","amazon-q","orca"],required:true,status:o$1?"written":e.dryRun?"planned":"skipped"}],missingRequired:F$1,staleReports:U,strictViolations:C$1,experimentalHooks:e.experimentalHooks===true});if(o$1&&process.env.WORKSPAI_TEST_FAIL_AGENT_SYNC_BEFORE_PACK==="1")throw new Error("Injected agent-sync failure before generation commit.");return d(await u(i$1.join(t$1,H),`${JSON.stringify(Le,null,2)}
|
|
39
|
-
`,o$1),H),{workspacePath:t$1,indexPath:i$1.join(t$1,V),packPath:i$1.join(t$1,H),pack:Le,contextPath:h,writtenFiles:oe,skippedFiles:ie,blockers:E$1.blockers,missingRequired:F$1,staleReports:U,strictViolations:C$1,projectLenses:v$1}}async function an(e){if(e.write!==true)return _e(e);let t=i$1.resolve(e.workspacePath),r=i$1.join(t,".workspai","transactions","agent-sync");await b$3(r);let n=await _e({...e,write:false,dryRun:true});if(!n.pack)throw new Error("Agent-sync dry run did not produce an output inventory.");let c=[...n.pack.outputInventory.map(p=>p.path),V,H],l=await a({journalDirectory:r});try{for(let A of [...new Set(c)].sort()){let h=i$1.resolve(t,A),m=i$1.relative(t,h);if(m===".."||m.startsWith(`..${i$1.sep}`)||i$1.isAbsolute(m))throw new Error(`Agent-sync output escapes workspace root: ${A}`);await l.captureFile(h);}let p=await h(t);for(let A of p.resolved)for(let h of [f$1,g,h$1,b$4,...g$1,"AGENTS.md",".gitignore"])await l.captureFile(i$1.join(A.projectPath,h));let o=await _e(e);return await l.commit(),o}catch(p){try{await l.rollback();}catch(o){throw new AggregateError([p,o],"Agent-sync generation failed and rollback was incomplete.")}throw p}}export{yt as a,Ct as b,_t as c,vt as d,Wt as e,V as f,H as g,K as h,Lt as i,ut as j,nn as k,an as l};
|
package/dist/chunk-OU7DF6MP.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {b}from'./chunk-WQX3JYEP.js';import {c as c$1}from'./chunk-TFOOSYGO.js';import {p,h,i}from'./chunk-NA2NXX5P.js';import {a}from'./chunk-KG3TUTXU.js';import {e as e$1,d}from'./chunk-CCDGHPEJ.js';import {f,e}from'./chunk-NZ3WZYD5.js';import I from'path';import R from'fs-extra';var q=f.agentContext,G=e.agentContext;function V(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="gemini"||t==="qwen"||t==="kimi"||t==="grok"||t==="copilot"||t==="windsurf"||t==="amazon-q"||t==="orca"?t:"generic"}function M(e){return `npx --yes --package workspai workspai ${e}`.trim()}function l(e){return `npx workspai ${e}`.trim()}function c(e$1){return {id:e$1.id,scope:e$1.scope,display:l(e$1.args),execute:M(e$1.args),description:e$1.description,...e$1.project?{project:e$1.project}:{},freshness:h({id:`command.${e$1.id}`,label:`${e$1.id} command`,scope:"command",value:{display:l(e$1.args),execute:M(e$1.args)},...e$1.project?{project:e$1.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e$1.generatedAt,now:e$1.now,sourceArtifact:e.model,sourcePath:`safeCommands.${e$1.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function F(e,t){return `workspace run ${t} --scope project:${e.name}`}function L(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function D(e){return [e.name,e.path,I.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function K(e,t,n){let r={generatedAt:e.generatedAt,now:n},i=[c({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...r}),c({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...r}),c({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...r}),c({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...r}),c({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...r}),c({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...r}),c({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...r}),c({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...r})],a=t?[t]:e.projects;for(let s of a)s.commands.fleetStages.includes("test")&&i.push(c({id:`project.${s.name}.test`,scope:"project",project:s.name,args:F(s,"test"),description:`Run tests for ${s.name} through workspace orchestration.`,...r})),s.commands.fleetStages.includes("build")&&i.push(c({id:`project.${s.name}.build`,scope:"project",project:s.name,args:F(s,"build"),description:`Build ${s.name} through workspace orchestration.`,...r}));return i}function z(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function H(e,t){if(!t?.startsWith("project:"))return;let n=L(t);if(n)return e.projects.find(r=>D(r).includes(n))}function B(e,t,n){let r=[...e.validation?.issues??[]];t?.startsWith("project:")&&!n&&r.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let i=r.filter(s=>s.severity==="error").length,a=r.filter(s=>s.severity==="warning").length;return {status:i>0?"failed":a>0?"warning":"passed",errors:i,warnings:a,issues:r}}async function U(e,t){let n=[],r=[];for(let[i,a]of Object.entries(e.evidence))a&&await d(t,a.path)!==null?n.push(`${i}: ${a.path}`):r.push(i);return {available:n.sort(),missing:r.sort()}}function X(e){let t=e.summary.projectCount,n=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",r=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${n}, and ${r}.`}function J(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),e.summary.observedProjects>0&&t.push("Some projects are observed rather than first-class; command support may be partial."),t}async function pe(e$1){let t=e$1.model??await p({workspacePath:e$1.workspacePath,includeEvidence:e$1.includeEvidence===true,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),n=V(e$1.agent),r=H(t,e$1.scope),i$1=B(t,e$1.scope,r);if(e$1.strict===true&&i$1.status!=="passed"){let o=i$1.issues.map(m=>`${m.severity}:${m.code}:${m.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${o}`)}let a=e$1.now??new Date,s=t.facts??[],T=new Set((r?[r]:t.projects).map(o=>o.name)),w=s.filter(o=>o.project?T.has(o.project):true),_=(r?[r]:t.projects).map(o=>{let m=w.filter(N=>N.project===o.name);return {name:o.name,path:o.path,kind:o.kind,category:o.category,runtime:o.runtime,framework:o.frameworkDisplayName,...o.generator?{generator:o.generator}:{},createCapability:o.createCapability,supportTier:o.supportTier,safeCommands:z(o),importantFiles:o.importantFiles,facts:m}}),u=await U(t,e$1.workspacePath),y=I.join(e$1.workspacePath,e.knowledgeGraph),d=await R.pathExists(y)?await R.readJson(y).catch(()=>null):null,C=false;if(d?.schemaVersion===f.knowledgeGraph)try{c$1(d,t),C=true;}catch{}let v=X(t),j=K(t,r,a),O=j.map(o=>h({id:`context.command.${o.id}`,label:`${o.id} safe command`,scope:"command",value:{display:o.display,execute:o.execute,scope:o.scope},...o.project?{project:o.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:a,sourceArtifact:e.agentContext,sourcePath:`safeCommands.${o.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),b$1=[...w,...O],f$1=i({facts:b$1,generatedAt:a.toISOString(),now:a}),k=b();return {schemaVersion:q,generatedAt:a.toISOString(),agent:n,workspaceSummary:v,modelRef:e.model,knowledgeGraph:{artifact:e.knowledgeGraph,schemaVersion:f.knowledgeGraph,available:C,...typeof d?.quality?.entityCount=="number"?{entityCount:d.quality.entityCount}:{},...typeof d?.quality?.relationCount=="number"?{relationCount:d.quality.relationCount}:{},...typeof d?.quality?.proofCount=="number"?{proofCount:d.quality.proofCount}:{},queryCommands:[l("workspace graph search <query> --limit 12 --json"),l("workspace graph entities [kind] --json"),l("workspace graph evidence <entity-or-relation> --json"),l("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:k.schemaVersion,contractPath:k.contractPath,currentStep:"context",canonicalReadOrder:[...k.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:t.workspace.root,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e$1.scope??"workspace",...r?{activeProject:r.name}:{}},projects:_,safeCommands:j,facts:b$1,factFreshness:f$1,evidence:u,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:i$1,agentInstructions:[`Read \`${e.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${e.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...J(t),...f$1.verifyBeforeUseFacts>0?[`${f$1.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[v,`Evidence available: ${u.available.length}. Missing evidence groups: ${u.missing.join(", ")||"none"}.`,r?`Active project scope: ${r.name} (${r.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
|
|
2
|
-
`)}}async function de(e,t){return e$1(t,G,a(e))}export{q as a,G as b,pe as c,de as d};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{g as AGENT_CUSTOMIZATION_PACK_REPORT_PATH,e as AGENT_CUSTOMIZATION_PACK_SCHEMA,f as AGENT_REPORTS_INDEX_PATH,d as AGENT_REPORTS_INDEX_SCHEMA,h as AGENT_REPORT_CATALOG,i as buildCanonicalAgentReportReadOrder,j as buildWorkspaceAgentReportsIndex,k as parseAgentGroundingTargets,l as syncWorkspaceAgentGrounding}from'./chunk-NRVSDL4J.js';export{f as AGENT_GROUNDING_DOC_PATH,g as LEGACY_AGENT_GROUNDING_DOC_PATH,A as LEGACY_COPILOT_GROUNDING_SKILL_PATH,m as LEGACY_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,C as LEGACY_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,i as LEGACY_CURSOR_GROUNDING_RULE_PATH,E as LEGACY_MCP_DESIGN_REPORT_PATH,G as LEGACY_VSCODE_AGENT_HOOKS_PATH,z as WORKSPAI_COPILOT_GROUNDING_SKILL_PATH,l as WORKSPAI_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,B as WORKSPAI_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,h as WORKSPAI_CURSOR_GROUNDING_RULE_PATH,D as WORKSPAI_MCP_DESIGN_REPORT_PATH,F as WORKSPAI_VSCODE_AGENT_HOOKS_PATH}from'./chunk-KBR4Y4RW.js';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{b as buildWorkspaceExplain,a as resolveWorkspaceExplainArtifactPath,c as writeWorkspaceExplainReport}from'./chunk-WLFJHRB3.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-KBR4Y4RW.js';export{e as WORKSPACE_MODEL_DIFF_REPORT_PATH}from'./chunk-NBJ6AP7K.js';
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {c as c$3}from'./chunk-MDF2FBLS.js';import {d as d$2,i,j as j$1,k as k$1,h as h$2,m as m$1,n,o}from'./chunk-VDFHUYAQ.js';import {a as a$2}from'./chunk-7DSYI7YN.js';import {a,c,h,b,e,j,g,d as d$1}from'./chunk-S4CWUZ4K.js';import {h as h$1}from'./chunk-AJ535F22.js';import {l,p}from'./chunk-KNTPDRZB.js';import {a as a$3}from'./chunk-A4BK7C7M.js';import {a as a$4}from'./chunk-AO2ZI42U.js';import {c as c$4,d}from'./chunk-EWZZUQBR.js';import {m}from'./chunk-KG3TUTXU.js';import {c as c$2}from'./chunk-CCDGHPEJ.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {e as e$1}from'./chunk-NZ3WZYD5.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import c$1 from'path';import {execa}from'execa';import k from'fs-extra';var Ce=".workspai/repair",ja="transaction.json",Ia="source-plan.json",oa="checkpoint",Ea="engine.lock",ua=5*1024*1024,Aa=25*1024*1024,$a=25*1024*1024,ha=4*1024*1024,Sa=900*1e3,Wa=new Set(["package.json","pyproject.toml","requirements.txt","go.mod","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","pom.xml","build.gradle","build.gradle.kts","deps.edn","project.clj","build.sbt"]),Ca=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","requirements-dev.txt","uv.lock","poetry.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deno.json","deno.jsonc","deno.lock","Directory.Packages.props","packages.lock.json","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","deps.edn","project.clj","build.sbt"]),H={safe:0,guarded:1,invasive:2},Ta=new Set(["node","npm","npx","pnpm","yarn","bun","deno","python","python3","py","pip","pip3","poetry","uv","pytest","pip-audit","govulncheck","go","cargo","composer","bundle","bundle-audit","dotnet","mvn","mvnw","gradle","gradlew","mix","clojure","lein","sbt","make"]);function Na(e){return [e.kind,e.id,e.projectPath??"",e.adapterId??"",e.executable??""].join("\0")}function D(e,a,r={kind:"failed-precondition"}){return {reason:e,options:a,causes:[{...r,id:r.id??`runtime:${$(e).slice(0,16)}`,message:r.message??e}]}}function ga(e){let a=new Map,r=t=>a.set(Na(t),t);for(let t of e.adapters){(t.support==="unsupported"||t.status==="unsupported")&&r({kind:"unsupported-adapter",id:`adapter:${t.projectPath}:${t.adapterId}`,message:t.message,projectPath:t.projectPath,adapterId:t.adapterId});for(let o of t.missingExecutables)r({kind:"missing-executable",id:`tool:${t.projectPath}:${t.adapterId}:${o}`,message:`Required repair executable is unavailable: ${o} (${t.projectPath}).`,projectPath:t.projectPath,adapterId:t.adapterId,executable:o});}for(let t of e.actions??[]){let o=Re(t);(t.status==="blocked"||t.status==="guidance-only"||!o&&!t.invocation)&&r({kind:"source-repair-required",id:`action:${t.id}`,message:t.blocker||`${t.id} requires a bounded source repair proposal.`,...t.projectPath?{projectPath:t.projectPath}:{}}),H[t.risk]>H[e.maxRisk]&&r({kind:"risk-approval",id:`risk:${t.id}`,message:`${t.id} exceeds the approved ${e.maxRisk} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});}for(let t of e.preconditions.filter(o=>o.status==="failed")){if(t.id==="structured-execution"){r({kind:"source-repair-required",id:`precondition:${t.id}`,message:t.message});continue}if(t.id.startsWith("tool:")){let o=e.stages.find(s=>s.invocation&&`tool:${s.invocation.cwd}:${s.invocation.executable}`===t.id);if(o?.invocation){r({kind:"missing-executable",id:t.id,message:t.message,projectPath:o.invocation.cwd,executable:o.invocation.executable});continue}}r({kind:"failed-precondition",id:`precondition:${t.id}`,message:t.message});}if(e.decisionOptions.has("allow-force")&&r({kind:"policy-exception",id:"policy:allow-force",message:"The proposed repair requires an explicit force-install policy exception."}),e.decisionOptions.has("allow-breaking")&&r({kind:"policy-exception",id:"policy:allow-breaking",message:"The proposed repair requires an explicit breaking-change policy exception."}),a.size===0){let t=e.fallbackReasons.find(o=>o.trim().length>0);t&&r({kind:"failed-precondition",id:`decision:${$(t).slice(0,16)}`,message:t});}return [...a.values()]}function F(e){return (e?.()??new Date).toISOString()}function $(e){return createHash("sha256").update(e).digest("hex")}function K(e){return Array.isArray(e)?`[${e.map(K).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,a])=>a!==void 0).sort(([a],[r])=>a.localeCompare(r)).map(([a,r])=>`${JSON.stringify(a)}:${K(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}var Se="causal-action-integrity:";function fa(e){return $(K([...e].sort((a,r)=>a.id.localeCompare(r.id)).map(a=>({id:a.id,artifactKind:a.artifactKind,cardId:a.cardId,title:a.title,phase:a.phase,scope:a.scope,projectName:a.projectName,projectPath:a.projectPath,sourceStepId:a.sourceStepId,findingId:a.findingId,findingStatus:a.findingStatus,causalKey:a.causalKey,dependsOn:a.dependsOn,strategy:a.strategy,transaction:a.transaction,status:a.status,mode:a.mode,risk:a.risk,requiresApproval:a.requiresApproval,blocker:a.blocker,summary:a.summary,command:a.command,invocation:a.invocation,verifyCommand:a.verifyCommand,cwd:a.cwd,files:a.files,operation:a.operation,rollback:a.rollback,notes:a.notes}))))}function ka(e){if(e.length===0)return;let a=fa(e);return {id:`${Se}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function E(e,a){let r=c$1.relative(c$1.resolve(e),c$1.resolve(a));return r===""||!r.startsWith("..")&&!c$1.isAbsolute(r)}async function _(e,a){let r=await k.realpath(e).catch(()=>c$1.resolve(e)),t=c$1.resolve(a);for(;!await k.pathExists(t);){let s=c$1.dirname(t);if(s===t)return false;t=s;}let o=await k.realpath(t).catch(()=>c$1.resolve(t));return E(r,o)}function O(e,a,r){let t=c$1.isAbsolute(a)?c$1.resolve(a):c$1.resolve(e,a);if(!E(e,t)&&!(r&&E(c$1.resolve(r),t)))throw new Error(`Repair path escapes workspace boundary: ${a}`);return c$1.relative(e,t).split(c$1.sep).join("/")||"."}function sa(e,a,r){return O(e,a,r)}async function qa(e){if(!e.proposal.projectName&&!e.proposal.projectPath)return;let a=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;if(a&&E(e.workspacePath,a))return a;let{contract:r}=await m({workspacePath:e.workspacePath}),t=r.projects.find(o=>{let s=o.externalPath?c$1.resolve(o.externalPath):c$1.resolve(e.workspacePath,o.relativePath);return (!e.proposal.projectName||o.slug===e.proposal.projectName)&&(!a||s===a)});if(!t)throw new Error("Repair proposal project must match one canonical registered project.");return t.externalPath?c$1.resolve(t.externalPath):c$1.resolve(e.workspacePath,t.relativePath)}function oe(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return c$1.join(e,Ce,"transactions",a)}function be(e,a){return a.target.projectPath?c$1.resolve(e,a.target.projectPath):void 0}function ye(e,a){return c$1.join(oe(e,a),ja)}function Te(e,a){return c$1.join(oe(e,a),Ia)}async function Z(e,a){await k.ensureDir(c$1.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await k.writeJson(r,a,{spaces:2}),await k.move(r,e,{overwrite:true});}function I(e,a,r,t={}){e.events.push({sequence:e.events.length+1,at:F(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r});}async function P(e,a,r){a.revision+=1,a.updatedAt=F(r),a$1(a,c,"Workspace repair transaction"),await Z(ye(e,a.transactionId),a),await Z(c$1.join(e,b),a);}async function se(e){let a$2=await k.readJson(ye(e.workspacePath,e.transactionId));if(a$2.schemaVersion!==a)throw new Error(`Unsupported repair transaction schema: ${a$2.schemaVersion}`);return a$1(a$2,c,"Workspace repair transaction"),a$2}async function Pe(e,a){return await k.readJson(Te(e,a))}function re(e){return e.schemaVersion===d$1}function fe(e,a,r){let t=a.scope==="project"&&a.projectPath?a.projectPath:".",o=c$1.isAbsolute(t)?c$1.resolve(t):c$1.resolve(e,t);if(!E(e,o)&&!(r&&c$1.resolve(r)===o))throw new Error(`Repair project scope escapes workspace: ${t}`);return o}function v(e){return {cwd:O(e.workspacePath,e.projectPath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function $e(e){return k.readFile(e,"utf8").catch(()=>"")}async function Da(e){return k.readJson(e).catch(()=>({}))}function ia(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}function Fa(e){let a=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(t=>t.toLowerCase()):[""],r=c$1.extname(e).length>0;return (process.env.PATH??"").split(c$1.delimiter).filter(Boolean).flatMap(t=>r?[c$1.join(t,e)]:a.map(o=>c$1.join(t,`${e}${o}`)))}function na(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function ma(e){let a=c$1.resolve(e.workspacePath,e.invocation.cwd);if(e.toolAvailable)return e.toolAvailable(e.invocation.executable,a);let r=e.invocation.executable;if(c$1.isAbsolute(r)||/^\.{1,2}[\\/]/.test(r)){let t=c$1.isAbsolute(r)?r:c$1.resolve(a,r),o=await k.stat(t).catch(()=>{});return na(o)}for(let t of Fa(r)){let o=await k.stat(t).catch(()=>{});if(na(o))return true}return false}async function Ne(e){let a=new Set;for(let s of e.stages){if(s.kind!=="repair"||!s.invocation)continue;let d=xe(s.invocation.executable);!["python","python3","py"].includes(d)||!s.invocation.args.includes("venv")||!s.invocation.args.includes(".venv")||a.add(c$1.normalize(c$1.join(c$1.resolve(e.workspacePath,s.invocation.cwd),".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python")));}let r=e.stages.filter(s=>s.required&&s.status!=="skipped"&&s.invocation).map(s=>s.invocation),t=new Map;for(let s of r)t.set(`${s.cwd}\0${s.executable}`,s);let o=[];for(let s of t.values()){let d=c$1.isAbsolute(s.executable)?c$1.normalize(s.executable):c$1.normalize(c$1.resolve(e.workspacePath,s.cwd,s.executable));if(a.has(d)){o.push({id:`tool:${s.cwd}:${s.executable}`,status:"passed",message:`Repair stage will create the isolated executable before use: ${s.executable} (${s.cwd}).`});continue}let i=await ma({workspacePath:e.workspacePath,invocation:s,toolAvailable:e.toolAvailable});o.push({id:`tool:${s.cwd}:${s.executable}`,status:i?"passed":"failed",message:i?`Required repair executable is available: ${s.executable} (${s.cwd}).`:`Required repair executable is unavailable: ${s.executable} (${s.cwd}). Install or configure it, then create a fresh plan.`});}return o}function X(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function y(e){return {id:e.id,kind:e.kind,status:e.invocation?"pending":e.required===false?"skipped":"blocked",required:e.required??true,risk:e.risk??"safe",summary:e.summary,...e.invocation?{invocation:e.invocation}:{}}}function Ha(e,a,r){let t=r.strategy?.find(o=>o.kind==="verify"&&o.invocation)?.invocation;if(t)return v({workspacePath:e,projectPath:a,executable:t.executable,args:t.args,purpose:"audit"})}async function Oa(e){let a=fe(e.workspacePath,e.action,e.authorizedProjectRoot),r=O(e.workspacePath,a,a),t=async l=>k.pathExists(c$1.join(a,l)),o=new Set,s=[],d=[],i=l=>`${r}:${e.adapterId}:${l}`,g$1=l=>l.forEach(u=>o.add(O(e.workspacePath,c$1.join(a,u),a))),n=l=>{s.push(l),l.required&&l.status==="blocked"&&d.push(l.summary);},f=Ha(e.workspacePath,a,e.action),m=()=>{let l=g.find(u=>u.id===e.adapterId);if(!l)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:s,checkpointFiles:[...o],blockers:d,adapters:[{adapterId:l.id,ecosystem:l.ecosystem,projectPath:r,manifests:l.manifests,support:l.support,status:d.length>0?"partial":"ready",requiredExecutables:[...new Set(s.filter(u=>u.required&&u.invocation).map(u=>u.invocation.executable))],missingExecutables:[],message:d.length>0?[...new Set(d)].join(" "):`${l.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let l=await Da(c$1.join(a,"package.json")),u=l.scripts&&typeof l.scripts=="object"&&!Array.isArray(l.scripts)?l.scripts:{},w=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",T=w==="bun"?await t("bun.lock")?"bun.lock":"bun.lockb":w==="pnpm"?"pnpm-lock.yaml":w==="yarn"?"yarn.lock":await t("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";g$1(["package.json",T]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${w} manifest, lockfile, and installed tree.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:["install"],purpose:"reconcile"})}));let L=v(w==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:w==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:w==="yarn"?{workspacePath:e.workspacePath,projectPath:a,executable:"yarn",args:["npm","audit","--json","--severity","moderate"],purpose:"audit"}:{workspacePath:e.workspacePath,projectPath:a,executable:"bun",args:["audit","--json"],purpose:"audit"});return n(y({id:i("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:f??L})),n(typeof u.test=="string"&&u.test.trim()?y({id:i("test"),kind:"test",summary:"Run the declared project test contract.",invocation:ia({workspacePath:e.workspacePath,projectPath:a,manager:w,script:"test",purpose:"test"})}):X(i("test"),"test","No test script is declared.")),n(typeof u.build=="string"&&u.build.trim()?y({id:i("build"),kind:"build",summary:"Run the declared project build contract.",invocation:ia({workspacePath:e.workspacePath,projectPath:a,manager:w,script:"build",purpose:"build"})}):X(i("build"),"build","No build script is declared.")),m()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){g$1(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let l=e.action.transaction?.ecosystem.toLowerCase(),u=c$1.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),w=u==="uv"||l==="uv"||await t("uv.lock"),T=!w&&(u==="poetry"||l==="poetry"||await t("poetry.lock")),L=!w&&!T&&["python","python3","py"].includes(u)&&(e.action.invocation?.args??[]).some(ae=>ae==="venv")&&(e.action.invocation?.args??[]).some(ae=>ae===".venv"),j=process.platform==="win32"?"python":"python3",W=c$1.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await k.pathExists(W)||L)&&(j=W);let Q=w?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):T?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&E(e.workspacePath,j)?v({workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&E(e.workspacePath,j)?v({workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:Q})),n(y({id:i("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:f}));let M=await $e(c$1.join(a,"pyproject.toml")),G=await t("tests")||/\[tool\.pytest/i.test(M),ee=v(T?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["run","python","-m","pytest"],purpose:"test"}:w?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["run","python","-m","pytest"],purpose:"test"}:{workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pytest"],purpose:"test"}),B=v(T?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["build"],purpose:"build"}:w?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["build"],purpose:"build"}:{workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","build"],purpose:"build"});return n(G?y({id:i("test"),kind:"test",summary:"Run the Python test contract.",invocation:ee}):X(i("test"),"test","No Python test surface is declared.")),n(/\[build-system\]/i.test(M)?y({id:i("build"),kind:"build",summary:"Build the declared Python package.",invocation:B}):X(i("build"),"build","No Python build contract is declared.")),m()}let b=[{adapterId:"go",manifest:"go.mod",files:["go.mod","go.sum"],reconcile:["go",["mod","tidy"]],audit:["govulncheck",["-json","./..."]],test:["go",["test","./..."]],build:["go",["build","./..."]]},{adapterId:"rust",manifest:"Cargo.toml",files:["Cargo.toml","Cargo.lock"],reconcile:["cargo",["check"]],audit:["cargo",["audit","--json"]],test:["cargo",["test"]],build:["cargo",["build"]]},{adapterId:"php-composer",manifest:"composer.json",files:["composer.json","composer.lock"],reconcile:["composer",["install","--no-interaction"]],audit:["composer",["audit","--format=json"]],test:["composer",["run-script","test"]],build:["composer",["run-script","build"]]},{adapterId:"ruby-bundler",manifest:"Gemfile",files:["Gemfile","Gemfile.lock"],reconcile:["bundle",["install"]],audit:["bundle-audit",["check","--format","json"]],test:["bundle",["exec","rake","test"]],build:["bundle",["exec","rake","build"]]},{adapterId:"elixir-mix",manifest:"mix.exs",files:["mix.exs","mix.lock"],reconcile:["mix",["deps.get"]],audit:["mix",["hex.audit"]],test:["mix",["test"]],build:["mix",["compile","--warnings-as-errors"]]},{adapterId:"deno",manifest:"deno.json",alternateManifest:"deno.jsonc",files:["deno.json","deno.lock"],reconcile:["deno",["install"]],audit:["deno",["audit"]],test:["deno",["task","test"]],build:["deno",["task","build"]]}];for(let l of b){if(l.adapterId!==e.adapterId)continue;let u=await t(l.manifest)?l.manifest:l.alternateManifest&&await t(l.alternateManifest)?l.alternateManifest:void 0;if(!u)continue;g$1(l.files),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${u} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l.reconcile[0],args:l.reconcile[1],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:f??(l.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:l.audit[0],args:l.audit[1],purpose:"audit"}):void 0)}));let w=await $e(c$1.join(a,u)),T=l.manifest==="composer.json"||l.adapterId==="deno"?/["']test["']\s*:/.test(w):l.manifest==="Gemfile"?await t("Rakefile"):true,L=l.manifest==="composer.json"||l.manifest==="deno.json"?/["']build["']\s*:/.test(w):l.manifest==="Gemfile"?(await k.readdir(a)).some(j=>j.endsWith(".gemspec")):true;return n(T?y({id:i("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l.test[0],args:l.test[1],purpose:"test"})}):X(i("test"),"test","No test contract is declared.")),n(L?y({id:i("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l.build[0],args:l.build[1],purpose:"build"})}):X(i("build"),"build","No build contract is declared.")),m()}let R=await k.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&R.some(l=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(l)))return g$1(["Directory.Packages.props","packages.lock.json",...R.filter(l=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(l))]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:f??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),n(y({id:i("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),n(y({id:i("build"),kind:"build",summary:"Build the .NET project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["build","--no-restore"],purpose:"build"})})),m();let x=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return g$1(["pom.xml"]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:x,args:["dependency:resolve"],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:f})),n(y({id:i("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:x,args:["test"],purpose:"test"})})),n(y({id:i("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:x,args:["package","-DskipTests"],purpose:"build"})})),m();let A=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&A){let l=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return g$1([A,"gradle.lockfile","gradle/libs.versions.toml"]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["dependencies"],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:f})),n(y({id:i("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["test"],purpose:"test"})})),n(y({id:i("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["build","-x","test"],purpose:"build"})})),m()}let q=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&q){let l=q==="deps.edn",u=await $e(c$1.join(a,q)),w=l?"clojure":"lein";g$1([q]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${q} dependency graph.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:l?["-P"]:["deps"],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:f}));let T=!l||/:test\b/.test(u);return n(T?y({id:i("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:l?["-M:test"]:["test"],purpose:"test"})}):X(i("test"),"test","No Clojure :test alias is declared.")),n(l?X(i("build"),"build","No portable Clojure CLI build entrypoint is declared."):y({id:i("build"),kind:"build",summary:"Build the Leiningen project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"lein",args:["uberjar"],purpose:"build"})})),m()}return e.adapterId==="scala-sbt"&&await t("build.sbt")?(g$1(["build.sbt"]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve and compile the sbt dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["compile"],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:f})),n(y({id:i("test"),kind:"test",summary:"Run sbt tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),n(y({id:i("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),m()):(d.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),n(y({id:i("reconcile"),kind:"reconcile",required:true,summary:d[0]})),m())}async function wa(e){let a=s=>k.pathExists(c$1.join(e,s)),r=await k.readdir(e).catch(()=>[]),t=[];await a("package.json")&&t.push("node"),(await a("pyproject.toml")||await a("requirements.txt"))&&t.push("python"),await a("go.mod")&&t.push("go"),await a("Cargo.toml")&&t.push("rust"),await a("composer.json")&&t.push("php-composer"),await a("Gemfile")&&t.push("ruby-bundler"),await a("mix.exs")&&t.push("elixir-mix"),(await a("deno.json")||await a("deno.jsonc"))&&t.push("deno"),r.some(s=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s))&&t.push("dotnet"),await a("pom.xml")&&t.push("jvm-maven"),(await a("build.gradle.kts")||await a("build.gradle"))&&t.push("jvm-gradle"),(await a("deps.edn")||await a("project.clj"))&&t.push("clojure"),await a("build.sbt")&&t.push("scala-sbt");let o=new Map(g.map((s,d)=>[s.id,d]));return [...new Set(t)].sort((s,d)=>(o.get(s)??999)-(o.get(d)??999))}function Ma(e){let a=e?.trim().toLowerCase();if(a){if(["npm","pnpm","yarn","bun","node","javascript","typescript"].includes(a))return "node";if(["python","pip","poetry","uv"].includes(a))return "python";if(["go","gomod","go-modules"].includes(a))return "go";if(["rust","cargo"].includes(a))return "rust";if(["php","composer"].includes(a))return "php-composer";if(["ruby","bundler","bundle"].includes(a))return "ruby-bundler";if(["elixir","mix"].includes(a))return "elixir-mix";if(a==="deno")return "deno";if(["dotnet",".net","nuget"].includes(a))return "dotnet";if(["maven","jvm-maven"].includes(a))return "jvm-maven";if(["gradle","jvm-gradle"].includes(a))return "jvm-gradle";if(["clojure","lein","leiningen"].includes(a))return "clojure";if(["scala","sbt","scala-sbt"].includes(a))return "scala-sbt"}}async function ba(e,a={}){let r=fe(e.workspacePath,e.action,e.authorizedProjectRoot),t=O(e.workspacePath,r,r),o=await wa(r),s=Ma(e.action.transaction?.ecosystem),d=s?[s]:o;if(s&&!o.includes(s)){let n=`Doctor declared the ${s} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[y({id:`${t}:${s}:reconcile`,kind:"reconcile",required:true,summary:n})],checkpointFiles:[],blockers:[n],adapters:[{adapterId:s,ecosystem:g.find(f=>f.id===s)?.ecosystem??s,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:n}]}}if(d.length===0){let n=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[y({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:n})],checkpointFiles:[],blockers:[n],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:n}]}}let i={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let n of d){let f=await Oa({...e,adapterId:n});i.stages.push(...f.stages),i.checkpointFiles.push(...f.checkpointFiles),i.blockers.push(...f.blockers),i.adapters.push(...f.adapters);}i.stages=[...new Map(i.stages.map(n=>[n.id,n])).values()],i.checkpointFiles=[...new Set(i.checkpointFiles)].sort(),i.blockers=[...new Set(i.blockers)];let g$1=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let n=new Set(e.action.transaction.requiredStages),f=xe(e.action.invocation?.executable??""),m=e.action.invocation?.args??[],b=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(f)&&m.includes("venv")&&m.includes(".venv");b&&g$1.add(c$1.normalize(c$1.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),i.stages=i.stages.filter(R=>R.kind==="reconcile"?b&&n.has("reconcile"):n.has(R.kind)),i.blockers=i.stages.filter(R=>R.required&&R.status==="blocked").map(R=>R.summary);}for(let n of i.adapters){let f=i.stages.filter(b=>b.id.startsWith(`${n.projectPath}:${n.adapterId}:`)),m=[];n.requiredExecutables=[...new Set(f.filter(b=>b.required&&b.invocation).map(b=>b.invocation.executable))];for(let b of f){if(!b.required||!b.invocation)continue;let R=c$1.isAbsolute(b.invocation.executable)?c$1.normalize(b.invocation.executable):c$1.normalize(c$1.resolve(e.workspacePath,b.invocation.cwd,b.invocation.executable));g$1.has(R)||await ma({workspacePath:e.workspacePath,invocation:b.invocation,toolAvailable:a.toolAvailable})||m.push(b.invocation.executable);}n.missingExecutables=[...new Set(m)],n.missingExecutables.length>0&&(n.status="partial",n.message=`Required executable(s) unavailable: ${n.missingExecutables.join(", ")}.`);}if(d.length===1){let n=`:${d[0]}:`;for(let f of i.stages)f.id=f.id.replace(n,":");}return i}async function $t(e={}){let a=h();if(!e.workspacePath&&!e.projectPath&&!e.project)return a;let r=c$1.resolve(e.workspacePath??process.cwd()),t,o;if(e.project?.trim()){let s=e.project.trim(),d=await h$1(r),i=s.replace(/\\/g,"/").replace(/^\.\//,""),g=c$1.resolve(r,s),n=d.resolved.filter(f=>{let m=E(r,f.projectPath)?O(r,f.projectPath):void 0;return f.name===s||m===i||c$1.resolve(f.projectPath)===g});if(n.length===0){let f=d.skipped.find(m=>m.name===s);throw f?new Error(`Registered project is unavailable for repair capability inspection: ${s} (${f.reason}).`):new Error(`Registered project not found for repair capability inspection: ${s}.`)}if(n.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${s}.`);t=c$1.resolve(n[0].projectPath),o=n[0].name;}else {if(t=c$1.resolve(r,e.projectPath??"."),!E(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=O(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await wa(t)}}}function Re(e){if(e.command){let a=d$2(e.command);if(a)return a}return a$4(e.operation)??void 0}async function Ba(e){let a=new Set(e.dependencyFiles);for(let r of e.actions){let t=fe(e.workspacePath,r);if(!await _(e.workspacePath,t))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${t}`);for(let d of r.files){let i=c$1.isAbsolute(d)?c$1.resolve(d):c$1.resolve(e.workspacePath,d);if(!await _(e.workspacePath,i))throw new Error(`Repair checkpoint path escapes workspace through a symbolic link: ${d}`);a.add(O(e.workspacePath,d));}let o=Re(r);if(!o)continue;let s="path"in o?o.path:void 0;if(s){let d=c$1.resolve(t,s);if(!await _(e.workspacePath,d))throw new Error(`Repair operation target escapes workspace through a symbolic link: ${s}`);a.add(O(e.workspacePath,d));}}return [...a].filter(r=>r!==".").sort()}function _a(e,a){if(!a.invocation)return;let r=fe(e,a);return v({workspacePath:e,projectPath:r,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function qe(e){return $(K({sourceEvidenceHash:e.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],stages:e.stages.map(a=>({id:a.id,kind:a.kind,required:a.required,risk:a.risk,...a.invocation?{invocation:a.invocation}:{}})),checkpointFiles:e.checkpointFiles.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,...a.mode!==void 0?{mode:a.mode}:{}}))}))}function De(e){return qe({sourceEvidenceHash:e.integrity.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations,stages:e.stages.filter(a=>a.kind!=="rollback"),checkpointFiles:e.checkpoint.files})}function va(e){return $(K({transactionId:e.transactionId,state:e.state,planHash:e.integrity.planHash,sourceEvidenceHash:e.integrity.sourceEvidenceHash,approvedPlanHash:e.approval.approvedPlanHash,checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,afterHash:a.afterHash??null,...a.mode!==void 0?{mode:a.mode}:{}}))},verification:e.verification}))}async function St(e){let a=c$1.resolve(e.workspacePath),r=await se({workspacePath:a,transactionId:e.transactionId}),t=await Pe(a,e.transactionId);if(r.state!=="closed"||r.approval.status!=="approved"||r.approval.approvedPlanHash!==r.integrity.planHash||De(r)!==r.integrity.planHash||!r.integrity.closureHash||va(r)!==r.integrity.closureHash||$(K(t))!==r.integrity.sourceEvidenceHash||!re(t)||t.goalId!==e.goalId||r.verification?.status!=="passed"||r.verification.targetStatus!=="passed"||!r.verification.sourceBinding||r.checkpoint.status!=="captured")throw new Error(`Goal repair transaction is not a current, closed, integrity-bound source transition: ${e.transactionId}`);let o=be(a,r);for(let s of r.checkpoint.files){let d=c$1.resolve(a,s.path);if(!E(a,d)&&!(o&&E(o,d)))throw new Error(`Goal repair checkpoint escaped its canonical source boundary: ${s.path}`);let i=await k.lstat(d).catch(()=>{});if(!i){if(s.afterHash!==null)throw new Error(`Goal repair output is no longer current: ${s.path}`);continue}if(!i.isFile()||i.isSymbolicLink())throw new Error(`Goal repair output is no longer a regular source file: ${s.path}`);let g=await k.readFile(d);if(s.afterHash!==$(g))throw new Error(`Goal repair output changed after transaction closure: ${s.path}`);if(s.mode!==void 0&&i.mode!==s.mode)throw new Error(`Goal repair output mode changed after transaction closure: ${s.path}`)}return r.verification.sourceBinding}async function ve(e,a,r){let t=[],o=[],s=0;for(let d of a){let i=c$1.resolve(e,d),g=r&&E(c$1.resolve(r),i)?c$1.resolve(r):e;if(!E(g,i)){o.push(`Checkpoint path escapes authorized workspace/project boundaries: ${d}`);continue}if(!await _(g,i)){o.push(`Checkpoint path resolves through a link outside its authorized boundary: ${d}`);continue}let n=await k.lstat(i).catch(()=>{});if(n?.isSymbolicLink()){o.push(`Checkpoint refuses symbolic link mutation: ${d}`);continue}if(n&&!n.isFile()){o.push(`Checkpoint target is not a regular file: ${d}`);continue}if(n&&n.size>ua){o.push(`Checkpoint file exceeds 5 MiB: ${d}`);continue}if(s+=n?.size??0,s>Aa){o.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let f=n?await k.readFile(i):void 0;t.push({path:d,existed:!!n,beforeHash:f?$(f):null,...n?{mode:n.mode}:{}});}return {entries:t,errors:o}}function ya(e){let a=e.replaceAll("\\","/"),r=a.split("/"),t=r.at(-1)??a;if(a===".workspai-workspace"||a.startsWith(".workspai/"))return "Canonical workspace state and evidence cannot be edited through a model proposal.";if(a===".git"||a.startsWith(".git/"))return "Git internals cannot be edited through a model proposal.";if(r.includes("node_modules"))return "Installed dependency trees cannot be edited through a model proposal.";if(/^\.env(?:\.|$)/i.test(t)&&!/^\.env\.(?:example|sample|template)$/i.test(t))return "Secret-bearing environment files cannot be edited through a model proposal.";if(/\.(?:pem|key|p12|pfx|jks|keystore)$/i.test(t))return "Private key and credential containers cannot be edited through a model proposal."}async function La(e){let a=await k.readJson(c$1.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():c$1.basename(e)}function Ga(e){return Wa.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function Va(e,a){let r=c$1.resolve(e,a),t=c$1.dirname(r);for(;E(e,t);){if((await k.readdir(t).catch(()=>[])).some(Ga))return t;if(c$1.resolve(t)===c$1.resolve(e))break;t=c$1.dirname(t);}return e}function Ka(e,a,r){return r.some(t=>{let o=c$1.resolve(e,t.path);if(!E(a,o))return false;let s=c$1.basename(o);return Ca.has(s)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s)})}function za(e){let a=O(e.workspacePath,e.projectPath,e.projectPath);return {id:`proposal:${e.proposal.cardId}:${a}`,artifactKind:"workspace-repair-proposal",cardId:e.proposal.cardId,findingId:e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal",findingStatus:"blocking",causalKey:[e.proposal.cardId,e.proposal.projectName??a,e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal"].map(r=>r.trim().toLowerCase()).join(":"),title:"Validate model-proposed repair",order:1,phase:"source-repair",scope:a==="."?"workspace":"project",...e.proposal.projectName?{projectName:e.proposal.projectName}:{},...a!=="."?{projectPath:a}:{},status:"ready",mode:"edit-file",risk:"guarded",requiresApproval:true,blocker:"",summary:e.proposal.rationale,verifyCommand:"workspai workspace intelligence run --for-agent generic --strict --json",cwd:a==="."?"workspace":"project",files:e.proposal.changes.map(r=>r.path),rollback:{available:true,strategy:"idempotent"},notes:["Source changes are applied only by the CLI Repair Engine after hash-bound approval."]}}function Ja(e,a){let r=xe(a.executable),[t="",o=""]=a.args;if(a.args.some(i=>/^(?:-e|--eval|-c|--command|-command)$/i.test(i)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let s=["npm","pnpm","yarn","bun"].includes(r);if(!(s&&e.kind==="audit"&&a.args.some(i=>/audit/i.test(i))||s&&["test","build"].includes(e.kind)&&(t==="run"||t===e.kind||o===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(r)||["python","python3","py"].includes(r)&&t==="-m"&&["pytest","unittest","build","pip_audit"].includes(o.replaceAll("-","_"))||r==="poetry"&&["run","check"].includes(t)||r==="uv"&&t==="run"||r==="go"&&["test","build","vet"].includes(t)||r==="cargo"&&["test","build","check","audit"].includes(t)||r==="composer"&&["audit","run-script","validate"].includes(t)||r==="bundle"&&t==="exec"&&o==="rake"||r==="dotnet"&&["test","build"].includes(t)||["mvn","mvnw","gradle","gradlew"].includes(r)&&a.args.some(i=>/^(?:test|build|check|verify|package)$/i.test(i))||r==="mix"&&(t==="test"||t==="compile"||t==="hex.audit"&&e.kind==="audit")||r==="clojure"&&t==="-M:test"&&e.kind==="test"||r==="lein"&&(t==="test"&&e.kind==="test"||t==="uberjar"&&e.kind==="build")||r==="sbt"&&(t==="test"&&e.kind==="test"||t==="package"&&e.kind==="build")||r==="deno"&&(t==="test"||t==="task"&&["test","build"].includes(o))))throw new Error(`Validation ${e.id} must use a runtime-native audit, test, or build command; arbitrary executables are not accepted from a model.`)}async function Ua(e){let a=[],r=new Set,t=[],o=[],s=new Set,d=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let i of e.proposal.validation??[]){let g=c$1.resolve(e.workspacePath,i.cwd),n=O(e.workspacePath,g,d),f=await k.lstat(g).catch(()=>{});if(!f?.isDirectory()||f.isSymbolicLink()||!await _(d??e.workspacePath,g)){t.push(`Validation ${i.id} requires a real directory inside the workspace.`);continue}if(d&&!E(d,g)){t.push(`Validation ${i.id} escapes the declared project scope.`);continue}if(H[i.risk]>H[e.maxRisk]){t.push(`Validation ${i.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let m=v({workspacePath:e.workspacePath,projectPath:g,executable:i.executable,args:i.args,purpose:i.kind,timeoutMs:i.timeoutMs});try{Fe(e.workspacePath,m,e.policy,e.projectRoots),Ja(i,m);}catch(b){t.push(b instanceof Error?b.message:String(b));continue}a.push(y({id:`validation:${i.id}`,kind:i.kind,risk:i.risk,required:i.required,summary:i.summary,invocation:m})),s.add(`${n}:${i.kind}`);}for(let i of e.projectRoots){let g=za({workspacePath:e.workspacePath,projectPath:i,proposal:e.proposal}),n=await ba({workspacePath:e.workspacePath,action:g,authorizedProjectRoot:i},e.dependencies);o.push(...n.adapters);let f=Ka(e.workspacePath,i,e.proposal.changes);if(f){for(let b of n.checkpointFiles)r.add(b);t.push(...n.blockers);}let m=O(e.workspacePath,i,i);for(let b of n.stages)!f&&!["test","build"].includes(b.kind)||s.has(`${m}:${b.kind}`)||a.push(b);}return {stages:[...new Map(a.map(i=>[i.id,i])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(o.map(i=>[`${i.projectPath}:${i.adapterId}`,i])).values()]}}async function Ya(e,a$3={}){let r=c$1.resolve(e.workspacePath),t=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),o=t.actions.filter(h=>h.cardId===e.cardId).filter(h=>!e.projectName||h.projectName===e.projectName).sort((h,C)=>h.order-C.order||h.id.localeCompare(C.id)),s=e.actionId?o.filter(h=>h.id===e.actionId):o,d=t.actions.filter(h=>!e.projectName||!h.projectName||h.projectName===e.projectName).sort((h,C)=>h.order-C.order||h.id.localeCompare(C.id)),i=new Map(d.map(h=>[h.id,h])),g=h=>{let C=new Set(h.map(ce=>ce.id)),N=[...h];for(;N.length>0;){let ce=N.pop();for(let V of ce?.dependsOn??[]){let Y=i.get(V);!Y||C.has(Y.id)||(C.add(Y.id),N.push(Y));}}return d.filter(ce=>C.has(ce.id))},n=s.filter(h=>h.findingStatus==="blocking"||h.notes.includes("Doctor finding status: blocking")),f=n.length>0?n:s.filter(h=>h.findingStatus!=="advisory"&&h.findingStatus!=="informational"),m=e.actionId?s.filter(h=>h.id===e.actionId):[],b$1=f[0],R=b$1?f.filter(h=>h.cardId===b$1.cardId&&h.findingId===b$1.findingId):[],x=g(e.actionId?m:R),A=e.maxRisk??"guarded",q={maxRisk:A,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},l=[{id:"workspace-root",status:await k.pathExists(c$1.join(r,".workspai-workspace"))||await k.pathExists(c$1.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:x.length>0?"passed":"failed",message:x.length>0?`${x.length} governed action(s) selected.`:"No governed remediation action matches this target."}],u=ka(x);u&&l.push(u);let w=[],T=[],L=[],j=[],W=new Set(["manual-repair","cancel"]);for(let h of x){let C=Re(h),N=_a(r,h);if(H[h.risk]<=H[A]||(j.push(`${h.id} exceeds the approved ${A} risk ceiling.`),W.add(h.risk==="invasive"?"approve-invasive":"approve-guarded")),(h.status==="blocked"||h.status==="guidance-only")&&j.push(`${h.id} is ${h.status}: ${h.blocker}`),!C&&!N&&j.push(`${h.id} has no typed operation or structured invocation.`),N)try{Fe(r,N,q);}catch(V){let Y=V instanceof Error?V.message:String(V);j.push(Y),/Force-based/.test(Y)&&W.add("allow-force"),/Breaking dependency/.test(Y)&&W.add("allow-breaking");}if(w.push({id:`action:${h.id}`,kind:"repair",status:C||N?"pending":"blocked",required:true,risk:h.risk,summary:h.summary,...N?{invocation:N}:{}}),h.transaction){let V=await ba({workspacePath:r,action:h},a$3);w.push(...V.stages),T.push(...V.checkpointFiles),j.push(...V.blockers),L.push(...V.adapters);}}let Q=[...new Map(w.map(h=>[h.id,h])).values()];w.splice(0,w.length,...Q),w.unshift({id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."}),w.push({id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."}),w.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),l.push(...await Ne({workspacePath:r,stages:w,toolAvailable:a$3.toolAvailable}));let M=await Ba({workspacePath:r,actions:x,dependencyFiles:T}),G=await ve(r,M);l.push({id:"rollback-coverage",status:x.some(h=>h.mode==="edit-file"||h.mode==="run-command")&&M.length===0?"failed":"passed",message:M.length>0?`${M.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),l.push({id:"structured-execution",status:w.some(h=>h.required&&h.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),l.push({id:"checkpoint-boundary",status:G.errors.length===0?"passed":"failed",message:G.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":G.errors.join(" ")});let ee=$(K(t)),B=[...new Set(x.map(h=>h.projectPath).filter(Boolean))],ae={cardId:e.cardId,scope:e.projectName||B.length===1?"project":"workspace",...e.projectName?{projectName:e.projectName}:{},...B.length===1?{projectPath:B[0]}:{},actionIds:x.map(h=>h.id)},ie=F(a$3.now),te=`repair_${randomUUID().replaceAll("-","")}`,ne=l.some(h=>h.status==="failed")||j.length>0,U=[...j,...l.filter(h=>h.status==="failed").map(h=>h.message)],le=[...new Map(L.map(h=>[`${h.projectPath}:${h.adapterId}`,h])).values()],p=ga({actions:x,adapters:le,preconditions:l,stages:w,decisionOptions:W,maxRisk:A,fallbackReasons:U}),S={schemaVersion:a,transactionId:te,revision:1,createdAt:ie,updatedAt:ie,workspace:{name:t.workspace.name,rootRef:"."},target:ae,state:ne?"decision-required":"awaiting-approval",policy:q,approval:{required:true,status:"pending"},preconditions:l,adapterEvaluations:le,checkpoint:{status:M.length>0?"pending":"unavailable",files:G.entries},stages:w,...ne?{decision:{reason:[...new Set(U)].join(" "),options:[...W],causes:p}}:{},events:[],integrity:{sourceEvidenceHash:ee,planHash:qe({sourceEvidenceHash:ee,target:ae,policy:q,preconditions:l,adapterEvaluations:le,stages:w,checkpointFiles:G.entries})}};I(S,"planned",ne?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$3.now}),a$1(S,c,"Workspace repair transaction");let z=oe(r,te);return await k.ensureDir(z),await Z(Te(r,te),t),await Z(ye(r,te),S),await Z(c$1.join(r,b),S),S}async function Xa(e,a={}){let r=e.proposal.goalId;if(!r)return ca(e,a);let t=c$1.resolve(e.workspacePath);return c$2(t,`.workspai/goals/${r}/repair-proposal`,()=>ca({...e,workspacePath:t},a))}async function ca(e$1,a$3={}){a$1(e$1.proposal,e,"Workspace repair proposal");let r=c$1.resolve(e$1.workspacePath),t=JSON.parse(JSON.stringify(e$1.proposal));if(t.goalId){let p=await l({workspacePath:r,goalId:t.goalId});if(!p.active||p.index.activeGoalId!==t.goalId)throw new Error(`Repair proposal Goal Pack is not active: ${t.goalId}`);if(p.goalPack?.state!=="ready-to-plan")throw new Error(`Repair proposal Goal Pack is not ready for proposal execution: ${p.goalPack?.state??"missing"}`);if((p.active.repairTransactionIds??(p.active.repairTransactionId?[p.active.repairTransactionId]:[])).length>=p.goalPack.policy.maxAttempts)throw new Error(`Goal ${t.goalId} exhausted its repair proposal budget (${p.goalPack.policy.maxAttempts}). Review the latest evidence before creating another Goal Pack.`);if(p.goalPack.scope.kind==="project"||p.goalPack.scope.kind==="project-set"){let z=p.goalPack.scope.projects;if(!t.projectName||!z.includes(t.projectName))throw new Error(p.goalPack.scope.kind==="project"?`Goal-bound repair must declare the exact permitted projectName (${z[0]}).`:`Goal-bound repair must declare a projectName inside the permitted Goal scope (${z.join(", ")}).`)}}let o=e$1.maxRisk??"guarded",s={maxRisk:o,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},d=[],i=[],g=new Set(["manual-repair","cancel"]),n=await k.pathExists(c$1.join(r,".workspai-workspace"))||await k.pathExists(c$1.join(r,".workspai"));d.push({id:"workspace-root",status:n?"passed":"failed",message:n?"Canonical workspace root markers exist.":"Workspace root markers must exist."});let f;try{f=await qa({workspacePath:r,proposal:t});}catch(p){i.push(p instanceof Error?p.message:String(p));}if(f&&(t.projectName||t.projectPath)&&(t.projectPath=c$1.relative(r,f).split(c$1.sep).join("/")),t.projectPath){let p=f??c$1.resolve(r,t.projectPath),S=await k.lstat(p).catch(()=>{});(!S?.isDirectory()||S.isSymbolicLink())&&i.push("The declared project path must be a real canonical registered project directory.");}t.validation=t.validation?.map(p=>({...p,cwd:sa(r,p.cwd,f)}));let m=new Set,b$1=new Set,R=0;for(let p of t.changes){p.path=sa(r,p.path,f),p.path==="."&&i.push(`${p.id} cannot replace the workspace root.`),m.has(p.id)&&i.push(`Duplicate proposal change id: ${p.id}.`),b$1.has(p.path)&&i.push(`Multiple proposal changes target ${p.path}.`),m.add(p.id),b$1.add(p.path),R+=Buffer.byteLength(p.content??"","utf8"),R>$a&&i.push("The model proposal exceeds the 25 MiB source-change limit.");let S=ya(p.path);if(S&&i.push(`${p.path}: ${S}`),H[p.risk]>H[o]&&(i.push(`${p.id} exceeds the approved ${o} risk ceiling.`),g.add(p.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let z=c$1.resolve(r,t.projectPath),h=c$1.resolve(r,p.path);E(z,h)||i.push(`${p.path} escapes the declared project scope.`);}}let x=[...b$1].sort(),A=await ve(r,x,f);i.push(...A.errors);let q=new Map(A.entries.map(p=>[p.path,p]));for(let p of t.changes){let S=q.get(p.path);if(!S||S.beforeHash!==p.expectedBeforeHash){i.push(`${p.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}p.operation==="delete"&&!S.existed&&i.push(`${p.path} cannot be deleted because it does not exist.`),p.operation==="write"&&S.beforeHash!==null&&$(p.content??"")===S.beforeHash&&i.push(`${p.path} is a no-op and cannot prove source progress.`);}d.push({id:"proposal-boundary",status:i.length===0?"passed":"failed",message:i.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(i)].join(" ")});let l$1=new Set;if(t.projectPath)l$1.add(f??c$1.resolve(r,t.projectPath));else for(let p of t.changes)l$1.add(await Va(r,p.path));let u=await Ua({workspacePath:r,proposal:t,projectRoots:[...l$1].sort(),maxRisk:o,policy:s,dependencies:a$3});i.push(...u.blockers);let w=u.stages,T=w.some(p=>p.status!=="skipped"&&["audit","test","build"].includes(p.kind));d.push({id:"validation-coverage",status:T?"passed":"unknown",message:T?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let L=[...new Set([...x,...u.checkpointFiles])].sort(),j=await ve(r,L,f);i.push(...j.errors),d.push({id:"checkpoint-boundary",status:j.errors.length===0?"passed":"failed",message:j.errors.length===0?`${j.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:j.errors.join(" ")});let W=[{id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."},...t.changes.map(p=>({id:`proposal:${p.id}`,kind:"repair",status:H[p.risk]<=H[o]?"pending":"blocked",required:true,risk:p.risk,summary:p.summary,changedPaths:[p.path]})),...w,{id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."},{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];d.push(...await Ne({workspacePath:r,stages:W,toolAvailable:a$3.toolAvailable}));let Q=new Set(W.map(p=>p.id));Q.size!==W.length&&i.push("Repair proposal stage ids must be unique."),d.push({id:"stage-identity",status:Q.size===W.length?"passed":"failed",message:Q.size===W.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let p=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true});if(!t.targetActionIds?.length){let C=p.actions.filter(N=>N.cardId===t.cardId&&(!t.projectName||N.projectName===t.projectName)&&(!t.projectPath||N.projectPath===t.projectPath)).map(N=>N.id).sort();C.length>0&&(t.targetActionIds=C);}let S=new Set(t.targetActionIds??[]),z=p.actions.filter(C=>S.has(C.id)),h=ka(z);h&&d.push(h);}catch{}let M=$(K(t)),G={cardId:t.cardId,scope:t.projectPath||t.projectName?"project":"workspace",...t.projectName?{projectName:t.projectName}:{},...t.projectPath?{projectPath:t.projectPath}:{},...t.blockerSignature?{blockerSignature:t.blockerSignature}:{},actionIds:t.targetActionIds&&t.targetActionIds.length>0?[...new Set(t.targetActionIds)].sort():t.changes.map(p=>`proposal:${p.id}`)},ee=F(a$3.now),B=`repair_${randomUUID().replaceAll("-","")}`,ie=d.some(p=>p.status==="failed")||i.length>0,te=[...i,...d.filter(p=>p.status==="failed"&&p.id!=="proposal-boundary").map(p=>p.message)],ne=ga({adapters:u.adapters,preconditions:d,stages:W,decisionOptions:g,maxRisk:o,fallbackReasons:te});for(let p of t.changes)H[p.risk]<=H[o]||ne.push({kind:"risk-approval",id:`risk:${p.id}`,message:`${p.id} exceeds the approved ${o} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});let U={schemaVersion:a,transactionId:B,revision:1,createdAt:ee,updatedAt:ee,workspace:{name:await La(r),rootRef:"."},target:G,state:ie?"decision-required":"awaiting-approval",policy:s,approval:{required:true,status:"pending"},preconditions:d,adapterEvaluations:u.adapters,checkpoint:{status:"pending",files:j.entries},stages:W,...ie?{decision:{reason:[...new Set(te)].join(" "),options:[...g],causes:ne}}:{},events:[],integrity:{sourceEvidenceHash:M,planHash:qe({sourceEvidenceHash:M,target:G,policy:s,preconditions:d,adapterEvaluations:u.adapters,stages:W,checkpointFiles:j.entries})}};I(U,"planned",ie?"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$3.now}),a$1(U,c,"Workspace repair transaction");let le=oe(r,B);return await k.ensureDir(le),await Z(Te(r,B),t),await Z(ye(r,B),U),await Z(c$1.join(r,b),U),t.goalId&&await p({workspacePath:r,goalId:t.goalId,transactionId:B}),U}async function Wt(e,a={}){let r=await se(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(De(r)!==r.integrity.planHash)return r.approval.status="expired",r.state="decision-required",r.decision=D("The compiled repair plan changed after planning.",["cancel"]),await P(e.workspacePath,r,a.now),r;let t=await Pe(e.workspacePath,e.transactionId);return $(K(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision=D("The persisted source plan changed after planning.",["cancel"]),await P(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:F(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",I(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await P(e.workspacePath,r,a.now),r)}async function Pa(e,a){let r=c$1.join(e,Ce,Ea);await k.ensureDir(c$1.dirname(r));try{let t=await k.stat(r),o=await k.readJson(r).catch(()=>({})),s=typeof o.host=="string"?o.host:void 0,d=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,i=false;if((!s||s===hostname())&&d)try{process.kill(d,0),i=true;}catch(n){i=n!==null&&typeof n=="object"&&"code"in n&&n.code==="EPERM";}let g=!!(s&&s!==hostname());!i&&!g&&Date.now()-t.mtimeMs>Sa&&await k.remove(r);}catch{}try{await k.outputFile(r,`${JSON.stringify({transactionId:a,pid:process.pid,host:hostname(),acquiredAt:new Date().toISOString()})}
|
|
2
|
-
`,{flag:"wx"});}catch{throw new Error("Another workspace repair transaction currently owns the engine lock.")}return async()=>{(await k.readJson(r).catch(async()=>{let o=await k.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await k.remove(r);}}async function Ra(e){let a=e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):void 0,r=await ve(e.workspacePath,e.transaction.checkpoint.files.map(o=>o.path),a);if(r.errors.length>0)throw new Error(r.errors.join(" "));let t=new Map(r.entries.map(o=>[o.path,o]));for(let o of e.transaction.checkpoint.files){let s=t.get(o.path);if(!s||o.existed!==s.existed||o.beforeHash!==s.beforeHash||o.mode!==s.mode)throw new Error(`Checkpoint precondition changed after planning: ${o.path}. Create and approve a fresh plan.`)}}async function Za(e){if(e.transaction.checkpoint.status==="captured")return;await Ra(e);let a=c$1.join(oe(e.workspacePath,e.transaction.transactionId),oa);await k.ensureDir(a);for(let r=0;r<e.transaction.checkpoint.files.length;r+=1){let t=e.transaction.checkpoint.files[r],o=c$1.resolve(e.workspacePath,t.path),s=t.existed?await k.readFile(o):void 0;if(s&&$(s)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let d=`${oa}/${String(r).padStart(4,"0")}.bin`;if(s){let i=c$1.join(oe(e.workspacePath,e.transaction.transactionId),d),g=`${i}.${process.pid}.${randomUUID()}.tmp`;await k.writeFile(g,s,{flag:"wx"});let n=await k.readFile(g);if($(n)!==t.beforeHash)throw await k.remove(g),new Error(`Checkpoint backup verification failed for ${t.path}.`);await k.move(g,i,{overwrite:true}),t.backupRef=d;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=F(e.now),e.transaction.state="checkpointed",I(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function da(e,a){for(let r of a.checkpoint.files){let t=c$1.resolve(e,r.path),o=await k.readFile(t).catch(()=>{});r.afterHash=o?$(o):null;}}function xe(e){return c$1.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function Fe(e,a,r,t=[]){let o=c$1.resolve(e,a.cwd);if(!(E(e,o)||t.some(n=>E(n,o))))throw new Error(`Invocation cwd escapes authorized repair boundaries: ${a.cwd}`);if(a.args.length>100||a.args.some(n=>!n||/[\0\r\n]/.test(n)))throw new Error("Invocation contains invalid arguments.");let d=xe(a.executable),i=c$1.isAbsolute(a.executable),g=/^\.{1,2}[\\/]/.test(a.executable);if(i&&!E(e,a.executable)&&!t.some(n=>E(n,a.executable)))throw new Error(`Invocation executable escapes authorized repair boundaries: ${a.executable}`);if(!i&&!g&&!Ta.has(d))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(n=>/^(?:--force|-f)$/i.test(n)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(n=>/(?:breaking|legacy-peer-deps)/i.test(n)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(d)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${d} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:o,executable:a.executable}}async function We(e){let a=e.projectBoundary?[c$1.resolve(e.projectBoundary)]:[],r=Fe(e.workspacePath,e.invocation,e.policy,a),t=await k.lstat(r.cwd).catch(()=>{});if(!t?.isDirectory()||t.isSymbolicLink()||!await _(e.projectBoundary??e.workspacePath,r.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(c$1.isAbsolute(r.executable)||/^\.{1,2}[\\/]/.test(r.executable)){let d=c$1.isAbsolute(r.executable)?r.executable:c$1.resolve(r.cwd,r.executable);if(!await _(e.projectBoundary??e.workspacePath,d))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let o=Object.fromEntries(Object.entries(process.env).filter(([d])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(d))),s=await execa(r.executable,e.invocation.args,{cwd:r.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:ha,stdin:"ignore",extendEnv:false,env:{...o,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:s.exitCode??null,stdout:s.stdout??"",stderr:s.stderr??""}}function Qa(e){let a=j.find(t=>t.cardId===e);if(!a)throw new Error(`No canonical producer is registered for repair card ${e}.`);let r=a.verifyCommand.trim().split(/\s+/);if(r[0]!=="npx"||r[1]!=="workspai"||r.length<3)throw new Error(`Repair card ${e} publishes an invalid canonical producer command.`);return r.slice(2)}async function et(e){let a=j.find(d=>d.cardId===e.transaction.target.cardId);if(!a)throw new Error(`No canonical producer is registered for repair card ${e.transaction.target.cardId}.`);let r=process.argv[1]?.trim();if(!r||!await k.pathExists(r))throw new Error("The running Workspai CLI entrypoint is unavailable for target verification.");let t=a.scope==="project"&&e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):c$1.resolve(e.workspacePath);if(a.scope==="project"&&!e.transaction.target.projectPath)throw new Error(`Repair card ${a.cardId} requires an explicit project path for exact producer verification.`);if(!await _(e.workspacePath,t))throw new Error("The target producer working directory escapes the workspace boundary.");let o=Object.fromEntries(Object.entries(process.env).filter(([d])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(d))),s=await execa(process.execPath,[r,...Qa(a.cardId)],{cwd:t,shell:false,reject:false,timeout:15*6e4,maxBuffer:ha,stdin:"ignore",extendEnv:false,env:{...o,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:s.exitCode??null,stdout:s.stdout??"",stderr:s.stderr??""}}async function at(e){if(e.dependencies.targetVerify)return e.dependencies.targetVerify({workspacePath:e.workspacePath,transaction:e.transaction});if(e.dependencies.verify)return {status:e.workspaceStatus==="passed"?"passed":"failed",remainingActionIds:e.workspaceStatus==="passed"?[]:[...e.transaction.target.actionIds]};if(e.workspaceStatus==="failed")return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]};try{let a=await a$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),r=new Set(e.transaction.target.actionIds),t=re(e.sourcePlan)&&Array.isArray(e.sourcePlan.targetActionIds)&&e.sourcePlan.targetActionIds.length>0,o=re(e.sourcePlan)?a.actions.filter(s=>t?r.has(s.id):s.cardId===e.transaction.target.cardId&&(!e.transaction.target.projectName||s.projectName===e.transaction.target.projectName)&&(!e.transaction.target.projectPath||s.projectPath===e.transaction.target.projectPath)):a.actions.filter(s=>r.has(s.id));return {status:o.length===0?"passed":"failed",remainingActionIds:o.map(s=>s.id).sort()}}catch{return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]}}}async function tt(e){if(e.dependencies.verify||e.dependencies.targetVerify)return {current:true,missingActionIds:[],semanticDrift:false};let a=e.transaction.target.actionIds.filter(g=>!g.startsWith("proposal:"));if(a.length===0)return {current:true,missingActionIds:[],semanticDrift:false};let r=await a$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),t=new Set(r.actions.map(g=>g.id)),o=a.filter(g=>!t.has(g)),s=e.transaction.preconditions.map(g=>g.id).find(g=>g.startsWith(Se))?.slice(Se.length),d=r.actions.filter(g=>t.has(g.id)&&a.includes(g.id)),i=o.length===0&&!!s&&fa(d)!==s;return {current:o.length===0&&!i,missingActionIds:o,semanticDrift:i}}function J(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
|
|
3
|
-
${e.slice(-a)}`}async function rt(e,a){if(a.type==="file-create")return i({projectPath:e,operation:a});if(a.type==="file-append")return j$1({projectPath:e,operation:a});if(a.type==="file-copy")return k$1({projectPath:e,operation:a});if(a.type==="package-json-script")return h$2({projectPath:e,packageJsonPath:a.path,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return m$1({projectPath:e,operation:a});if(a.type==="env-key-add")return n({projectPath:e,operation:a});if(a.type==="makefile-target")return o({projectPath:e,operation:a})}async function ot(e){let a=c$1.resolve(e.workspacePath,e.change.path),r=e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):e.workspacePath;if(!E(r,a)||!await _(r,a))throw new Error(`Proposal target escaped the canonical repair boundary: ${e.change.path}`);let t=ya(e.change.path);if(t)throw new Error(`${e.change.path}: ${t}`);let o=e.transaction.checkpoint.files.find(m=>m.path===e.change.path);if(!o)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let s=await k.readFile(a).catch(()=>{}),d=s?$(s):null;if(d!==o.beforeHash||d!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let i=await k.lstat(a).catch(()=>{});if(i?.isSymbolicLink()||i&&!i.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!i)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await k.remove(a);return}let g=e.change.content??"";if(Buffer.byteLength(g,"utf8")>ua)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await k.ensureDir(c$1.dirname(a));let n=c$1.join(c$1.dirname(a),`.${c$1.basename(a)}.${process.pid}.${randomUUID()}.repair-tmp`);await k.writeFile(n,g,{encoding:"utf8",flag:"wx"}),await k.move(n,a,{overwrite:true});let f=await k.readFile(a);if($(f)!==$(g))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function pa(e){if(e.stage.status==="passed"||e.stage.status==="skipped")return true;if(e.stage.status==="blocked")return false;e.stage.status="running",e.stage.startedAt=F(e.dependencies.now),I(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now);try{if(e.stage.id==="target-precondition"||e.stage.id==="target-producer-verify"){let a=!!(e.dependencies.verify||e.dependencies.targetVerify||e.dependencies.runInvocation||e.dependencies.toolAvailable||e.dependencies.now),r=await(e.dependencies.runTargetProducer??(a?async()=>({exitCode:0,stdout:"",stderr:""}):et))({workspacePath:e.workspacePath,transaction:e.transaction});if(e.stage.exitCode=r.exitCode,e.stage.stdoutTail=J(r.stdout),e.stage.stderrTail=J(r.stderr),r.exitCode!==0&&r.exitCode!==2)throw new Error(r.stderr||r.stdout||`Exact card producer exited with ${String(r.exitCode)}.`);if(e.stage.id==="target-precondition"){let t=await tt({workspacePath:e.workspacePath,transaction:e.transaction,dependencies:e.dependencies});if(!t.current){let o=t.semanticDrift?"The selected action semantics changed after approval.":`Missing action(s): ${t.missingActionIds.join(", ")}.`;throw new Error(`The approved causal repair target changed before mutation. ${o} Create and approve a fresh plan.`)}}}else if(e.stage.kind==="repair"){let a=e.actions.get(e.stage.id);if(!a)throw new Error(`Persisted repair action is missing: ${e.stage.id}`);if(a.kind==="proposal")await ot({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=Re(a.action);if(r){let t=fe(e.workspacePath,a.action);if(!await _(e.workspacePath,t))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${t}`);await rt(t,r);}else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??We)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:be(e.workspacePath,e.transaction)});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=J(t.stdout),e.stage.stderrTail=J(t.stderr),t.exitCode!==0)throw new Error(t.stderr||t.stdout||`Repair command exited with ${t.exitCode}.`)}else throw new Error("Repair stage has no typed operation or structured invocation.")}}else if(e.stage.invocation){let a=await(e.dependencies.runInvocation??We)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:be(e.workspacePath,e.transaction)});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=J(a.stdout),e.stage.stderrTail=J(a.stderr),a.exitCode!==0)throw new Error(a.stderr||a.stdout||`${e.stage.kind} exited with ${a.exitCode}.`)}return e.stage.status="passed",e.stage.completedAt=F(e.dependencies.now),e.stage.summary=e.stage.id==="target-precondition"?`Exact ${e.transaction.target.cardId} target revalidated before mutation.`:e.stage.id==="target-producer-verify"?`Exact ${e.transaction.target.cardId} producer refreshed after mutation.`:`${e.stage.kind} completed.`,await da(e.workspacePath,e.transaction),I(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=F(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await da(e.workspacePath,e.transaction),I(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now),false}}async function ge(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",I(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now);let r=async s=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision=D(s,["manual-repair","cancel"]),I(e.transaction,"decision",s,{status:"conflicted",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now),false),t=[];for(let s of e.transaction.checkpoint.files){let d=c$1.resolve(e.workspacePath,s.path),i=e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):e.workspacePath;if(!E(i,d)||!await _(i,d))return r(`Rollback refused because ${s.path} escaped the canonical repair boundary.`);let g=await k.lstat(d).catch(()=>{});if(g?.isSymbolicLink()||g&&!g.isFile())return r(`Rollback refused because ${s.path} is no longer a regular file.`);let n=g?await k.readFile(d):void 0,f=n?$(n):null,m=s.afterHash!==void 0&&f===s.afterHash,b=a&&f===s.beforeHash;if(!m&&!b)return r(`Rollback refused because ${s.path} changed outside this transaction.`);if(!s.existed){t.push({entry:s,absolute:d});continue}if(!s.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${s.path}.`);let R=c$1.join(oe(e.workspacePath,e.transaction.transactionId),s.backupRef),x=await k.lstat(R).catch(()=>{});if(!x?.isFile()||x.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${s.path}.`);let A=await k.readFile(R);if($(A)!==s.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${s.path}.`);t.push({entry:s,absolute:d,backup:A});}for(let s of t){if(!s.entry.existed){await k.remove(s.absolute);continue}let d=s.backup;if(d===void 0)throw new Error(`Validated checkpoint backup disappeared for ${s.entry.path}.`);let i=c$1.join(c$1.dirname(s.absolute),`.${c$1.basename(s.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await k.ensureDir(c$1.dirname(s.absolute)),await k.writeFile(i,d,{flag:"wx"}),s.entry.mode!==void 0&&await k.chmod(i,s.entry.mode),await k.move(i,s.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=F(e.dependencies.now);let o=e.transaction.stages.filter(s=>s.kind==="reconcile"&&s.invocation);for(let s of o){let d=s.invocation;if(!d)continue;let i=`rollback:${s.id}`,g=e.transaction.stages.find(m=>m.id===i&&m.kind==="rollback"),n=g??{id:i,kind:"rollback",status:"pending",required:true,risk:s.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:d};g||e.transaction.stages.push(n),n.status="running",n.startedAt=F(e.dependencies.now),delete n.completedAt,delete n.exitCode,delete n.stdoutTail,delete n.stderrTail,I(e.transaction,"rollback",n.summary,{stageId:n.id,status:"running",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now);let f;try{f=await(e.dependencies.runInvocation??We)({workspacePath:e.workspacePath,invocation:d,policy:e.transaction.policy,projectBoundary:be(e.workspacePath,e.transaction)});}catch(m){f={exitCode:null,stdout:"",stderr:m instanceof Error?m.message:String(m)};}if(n.exitCode=f.exitCode,n.stdoutTail=J(f.stdout),n.stderrTail=J(f.stderr),n.completedAt=F(e.dependencies.now),f.exitCode!==0)return n.status="failed",n.summary=f.stderr||f.stdout||`Rollback reconciliation exited with ${f.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision=D(`Source files were restored, but the installed dependency tree could not be reconciled: ${n.summary}`,["manual-repair","cancel"]),I(e.transaction,"decision",e.transaction.decision.reason,{stageId:n.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now),false;n.status="passed",n.summary="Installed dependency tree reconciled with the restored source state.",I(e.transaction,"rollback",n.summary,{stageId:n.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,I(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now),true}async function Ct(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Pa(r,e.transactionId);try{let o=await se({workspacePath:r,transactionId:e.transactionId});if(!["approved","checkpointed","executing","verifying","rollback-required","rolling-back"].includes(o.state))throw new Error(`Repair transaction cannot execute from state ${o.state}.`);if(o.approval.status!=="approved"||o.approval.approvedPlanHash!==o.integrity.planHash)throw new Error("Repair approval is missing, expired, or bound to another plan revision.");if(De(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision=D("The compiled repair plan changed after approval. Create and approve a fresh transaction.",["cancel"]),I(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await P(r,o,a.now),o;let s=await Pe(r,e.transactionId);if($(K(s))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision=D("Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",["cancel"]),I(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await P(r,o,a.now),o;if(o.state==="approved"&&re(s)&&s.goalId){let u=await l({workspacePath:r,goalId:s.goalId}),w=u.active?.repairTransactionIds??(u.active?.repairTransactionId?[u.active.repairTransactionId]:[]);if(u.index.activeGoalId!==s.goalId||!w.includes(o.transactionId))throw new Error(`Goal-bound repair transaction is not linked to the active Goal Pack: ${o.transactionId}`)}let i=(await Ne({workspacePath:r,stages:o.stages,toolAvailable:a.toolAvailable})).find(u=>u.status==="failed");if(i){let u=o.stages.find(w=>w.invocation&&`tool:${w.invocation.cwd}:${w.invocation.executable}`===i.id)?.invocation?.executable;return o.approval.status="expired",o.state="decision-required",o.decision=D(`${i.message} The approved plan cannot execute against a changed toolchain.`,["manual-repair","cancel"],{kind:"missing-executable",id:i.id,message:i.message,...u?{executable:u}:{}}),I(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await P(r,o,a.now),o}if(o.state==="rollback-required"||o.state==="rolling-back"){if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required to resume rollback.");return await ge({workspacePath:r,transaction:o,dependencies:a}),o}let g=new Map(re(s)?s.changes.map(u=>[`proposal:${u.id}`,{kind:"proposal",change:u}]):s.actions.map(u=>[`action:${u.id}`,{kind:"canonical",action:u}]));try{await Ra({workspacePath:r,transaction:o});}catch(u){return o.approval.status="expired",o.state="decision-required",o.decision=D(u instanceof Error?u.message:String(u),["cancel"]),I(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await P(r,o,a.now),o}let n=o.stages.find(u=>u.id==="target-precondition");if(!n)return o.approval.status="expired",o.state="decision-required",o.decision=D("The approved plan has no exact target precondition. Create and approve a fresh transaction.",["cancel"]),await P(r,o,a.now),o;if(!await pa({workspacePath:r,transaction:o,stage:n,actions:g,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision=D(`Target precondition failed before checkpoint: ${n.summary}`,["cancel"]),I(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await P(r,o,a.now),o;try{await Za({workspacePath:r,transaction:o,now:a.now});}catch(u){return o.approval.status="expired",o.state="decision-required",o.decision=D(u instanceof Error?u.message:String(u),["cancel"]),I(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await P(r,o,a.now),o}o.state="executing",await P(r,o,a.now);for(let u of o.stages.filter(w=>w.id!=="target-precondition"&&w.id!=="canonical-verify"&&w.kind!=="rollback"))if(!await pa({workspacePath:r,transaction:o,stage:u,actions:g,dependencies:a})&&u.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=D(`Required stage ${u.id} failed: ${u.summary}`,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await P(r,o,a.now),o.policy.autoRollback&&await ge({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let m=o.stages.find(u=>u.id==="canonical-verify");if(!m)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=D("The approved plan has no canonical verification stage.",o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await P(r,o,a.now),o.policy.autoRollback&&await ge({workspacePath:r,transaction:o,dependencies:a}),o;m.status="running",m.startedAt=F(a.now),I(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:m.id,status:"running",now:a.now}),await P(r,o,a.now);let b;try{b=a.verify?await a.verify(r):await c$3({workspacePath:r,strict:true,agent:"generic"});}catch(u){b={status:"failed",exitCode:1,artifactPath:e$1.intelligenceRun},m.stderrTail=J(u instanceof Error?u.message:String(u));}let R=b.status==="passed"&&b.exitCode===0?"passed":b.status==="failed"||b.exitCode===1?"failed":"blocked",x=await at({workspacePath:r,transaction:o,sourcePlan:s,dependencies:a,workspaceStatus:R}),A=x.status==="passed"&&R!=="failed",q,l$1;if(A&&re(s)&&s.goalId){let u=await a$3(r);if(u.status==="miss")A=false,l$1=`Goal-bound repair could not seal its post-repair Model/Graph source state (${u.reason}).`;else {let w=u.graph.source.inputs?.hash;w?q={modelHash:d(u.model),modelHashSemantics:"workspace-model-structural-v1",graphHash:c$4(u.graph),graphHashSemantics:"canonical-json-v1",graphInputHash:w}:(A=false,l$1="Goal-bound repair could not seal its post-repair Graph input fingerprint.");}}return m.status=A?"passed":"failed",m.completedAt=F(a.now),m.exitCode=b.exitCode,m.summary=A&&R==="passed"?"Selected repair target and canonical workspace verification passed.":A?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":l$1||(x.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${R}.`),o.verification={status:A?"passed":"failed",targetStatus:x.status,workspaceStatus:R,remainingActionIds:x.remainingActionIds,artifact:e$1.intelligenceRun,exitCode:b.exitCode,summary:m.summary,...q?{sourceBinding:q}:{}},I(o,"verification",m.summary,{stageId:m.id,status:m.status,now:a.now}),A?(o.state="closed",delete o.decision,I(o,"closed",m.summary,{status:"passed",now:a.now}),o.integrity.closureHash=va(o),await P(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=D(m.summary,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await P(r,o,a.now),o.policy.autoRollback&&await ge({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function st(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Pa(r,e.transactionId);try{let o=await se({workspacePath:r,transactionId:e.transactionId});if(!["checkpointed","executing","verifying","rollback-required","rolling-back","decision-required","failed"].includes(o.state))throw new Error(`Repair transaction cannot roll back from state ${o.state}.`);if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required for rollback.");return await ge({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function Tt(e,a={}){let r=await se(e);if(["closed","rolled-back","cancelled"].includes(r.state))return r;if(r.checkpoint.status==="captured")throw new Error("Rollback a mutated transaction before cancelling it.");return r.state="cancelled",r.approval.status=r.approval.status==="approved"?"expired":r.approval.status,I(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await P(e.workspacePath,r,a.now),r}async function Nt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await se({workspacePath:r,transactionId:e.transactionId});if(t.state!=="decision-required"||!t.decision)throw new Error(`Repair transaction is not awaiting a decision: ${t.state}`);if(!t.decision.options.includes(e.decision))throw new Error(`Decision ${e.decision} is not available. Allowed: ${t.decision.options.join(", ")}.`);if(e.decision==="rollback")return st({workspacePath:r,transactionId:e.transactionId},a);if(e.decision==="cancel"||e.decision==="manual-repair"){if(t.checkpoint.status==="captured")throw new Error("A mutated transaction must be rolled back before control is released.");return t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,I(t,"decision",e.decision==="manual-repair"?"The user chose manual repair; this transaction released source ownership without mutation.":"The user cancelled the decision-required transaction.",{status:e.decision,now:a.now}),await P(r,t,a.now),t}if(t.checkpoint.status==="captured")throw new Error("Repair policy cannot change after a checkpoint has been captured. Roll back first.");let o=await Pe(r,e.transactionId);t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,I(t,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await P(r,t,a.now);let s={maxRisk:e.decision==="approve-invasive"?"invasive":e.decision==="approve-guarded"&&t.policy.maxRisk==="safe"?"guarded":t.policy.maxRisk,allowForce:t.policy.allowForce||e.decision==="allow-force",allowBreaking:t.policy.allowBreaking||e.decision==="allow-breaking",autoRollback:t.policy.autoRollback};if(re(o))return Xa({workspacePath:r,proposal:o,...s},a);let d=t.target.actionIds.map(i=>i.startsWith("action:")?i.slice(7):i);return Ya({workspacePath:r,cardId:t.target.cardId,...d.length===1?{actionId:d[0]}:{},projectName:t.target.projectName,...s},a)}async function qt(e){let a=c$1.join(e,Ce,"transactions"),r=await k.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>se({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,s)=>s.updatedAt.localeCompare(o.updatedAt))}export{Wt as approveWorkspaceRepair,St as assertClosedGoalRepairTransactionCurrent,Tt as cancelWorkspaceRepair,Nt as decideWorkspaceRepair,Qa as exactCardProducerArgs,Ct as executeWorkspaceRepair,$t as inspectWorkspaceRepairCapabilities,qt as listWorkspaceRepairTransactions,Ya as planWorkspaceRepair,Xa as planWorkspaceRepairProposal,se as readWorkspaceRepairTransaction,st as rollbackWorkspaceRepair};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{a as runWorkspaceStage}from'./chunk-HQWDW2BV.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-W6FHVXNL.js';
|
|
File without changes
|