workspai 0.75.2 → 0.76.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/contracts/agent-framework-capabilities.v1.json +2 -2
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +12 -0
- package/contracts/create-planner-capabilities.v1.json +24 -0
- package/contracts/extension-cli-compatibility.v1.json +4 -2
- package/contracts/published-contract-catalog.v1.json +10 -0
- package/contracts/runtime-command-surface.v1.json +3 -1
- package/contracts/workspace-intelligence/agent-framework-admission-candidate.v2.json +217 -0
- package/contracts/workspace-intelligence/agent-framework-conformance-report.v2.json +274 -0
- package/contracts/workspace-intelligence-architecture.v1.json +5 -3
- package/dist/analyze-QVRVJB7I.js +1 -0
- package/dist/autopilot-release-DOGIETAT.js +1 -0
- package/dist/capabilities-command-FYBUVHZ7.js +1 -0
- package/dist/{chunk-ADHX7D3F.js → chunk-23CNBYIW.js} +1 -1
- package/dist/{chunk-IKBE3HOH.js → chunk-2I2A55RE.js} +1 -1
- package/dist/{chunk-4JXJRIJM.js → chunk-4BBFEHPL.js} +1 -1
- package/dist/{chunk-VHMDWRDG.js → chunk-4BPZJR4Z.js} +4 -4
- package/dist/{chunk-KDVNRNDU.js → chunk-4MXKXHLW.js} +1 -1
- package/dist/{chunk-JKAAKE4Z.js → chunk-4R44E7HN.js} +1 -1
- package/dist/chunk-5S6IZ6PY.js +2 -0
- package/dist/chunk-6BO4QHKA.js +1 -0
- package/dist/{chunk-VWBWDDU2.js → chunk-AGI46TSQ.js} +1 -1
- package/dist/{chunk-GDOO2YZW.js → chunk-BZLDCASY.js} +1 -1
- package/dist/{chunk-OA2YJN22.js → chunk-DWDYLKVW.js} +1 -1
- package/dist/{chunk-P36TACKN.js → chunk-FBF767WP.js} +1 -1
- package/dist/{chunk-PFAGXI3G.js → chunk-FD2ZGGCQ.js} +1 -1
- package/dist/chunk-H4YHIOCT.js +7 -0
- package/dist/{chunk-ZI54C2AO.js → chunk-HRGIHWYH.js} +1 -1
- package/dist/{chunk-LFY7KTPD.js → chunk-IKNWNGLY.js} +1 -1
- package/dist/{chunk-ZGVODK5C.js → chunk-KO4DM2AV.js} +1 -1
- package/dist/{chunk-FNVWDXK2.js → chunk-KW35SWG6.js} +5 -5
- package/dist/{chunk-EP7SUMAX.js → chunk-L6VNI4DN.js} +1 -1
- package/dist/chunk-NSC4VWV2.js +1 -0
- package/dist/chunk-P5LI5DL3.js +1 -0
- package/dist/chunk-PSQPKK6H.js +97 -0
- package/dist/chunk-PUH3TSPC.js +1 -0
- package/dist/chunk-QFDTKOYS.js +2649 -0
- package/dist/chunk-QIPW3G2H.js +1 -0
- package/dist/chunk-QVFIR64T.js +10 -0
- package/dist/{chunk-FZWLWFR4.js → chunk-R3Z4LY3O.js} +1 -1
- package/dist/chunk-RKFTUIZ4.js +4 -0
- package/dist/{chunk-COOVCORC.js → chunk-SVO2GGTV.js} +1 -1
- package/dist/{chunk-5K4O3TAW.js → chunk-TFFNHWXY.js} +1 -1
- package/dist/chunk-TJ3MDZMC.js +6 -0
- package/dist/{chunk-WXUCAVFT.js → chunk-UOTOJJI4.js} +8 -8
- package/dist/chunk-VODNLROY.js +1 -0
- package/dist/{chunk-WHBKKJ7L.js → chunk-X7MDTBX5.js} +1 -1
- package/dist/chunk-YLLCZMKP.js +2 -0
- package/dist/{chunk-K52IQX3J.js → chunk-Z2M2XCIB.js} +1 -1
- package/dist/{chunk-DTNOF3MP.js → chunk-ZXQC36NJ.js} +1 -1
- package/dist/{create-ZFSFWAW3.js → create-ZRUQ3KNZ.js} +1 -1
- package/dist/{doctor-4KL4XUCS.js → doctor-7V7LJLHX.js} +1 -1
- package/dist/{goal-lifecycle-EXQZD7IA.js → goal-lifecycle-EM4DUJCR.js} +1 -1
- package/dist/{goal-pack-DKJU2DEP.js → goal-pack-YMWZHAH6.js} +1 -1
- package/dist/index.d.ts +12 -6
- package/dist/index.js +251 -250
- package/dist/{pipeline-4GVAOCEN.js → pipeline-6MBH3MU2.js} +1 -1
- package/dist/platform-capabilities-RWOWND5Q.js +1 -0
- package/dist/{project-agent-entry-7QKNEEXP.js → project-agent-entry-ZXAE2MAJ.js} +1 -1
- package/dist/{project-intelligence-lens-IHRYCLNU.js → project-intelligence-lens-NBTPOK2R.js} +1 -1
- package/dist/{project-test-coverage-3P5FH6E5.js → project-test-coverage-HOZC72EK.js} +1 -1
- package/dist/proof-carrying-change-WJFAKK3C.js +1 -0
- package/dist/{pythonRapidkitExec-UMFLDIYR.js → pythonRapidkitExec-S35OEIEF.js} +1 -1
- package/dist/{verified-goal-XI4RQESU.js → verified-goal-B7EX2PBE.js} +1 -1
- package/dist/{workspace-EYXAKMVI.js → workspace-EBPYCSEM.js} +1 -1
- package/dist/{workspace-agent-sync-SN55KT6N.js → workspace-agent-sync-Y4F6FBBC.js} +1 -1
- package/dist/{workspace-context-PW6ESEHH.js → workspace-context-Y7F7GJCQ.js} +1 -1
- package/dist/{workspace-contract-FPLFL4G3.js → workspace-contract-XJMWMVQE.js} +1 -1
- package/dist/{workspace-explain-TVQ5IF5D.js → workspace-explain-T2J5ZLY7.js} +1 -1
- package/dist/{workspace-foundation-DWIJPZRH.js → workspace-foundation-2UP6IMTH.js} +1 -1
- package/dist/{workspace-graph-stream-RUTNWLQB.js → workspace-graph-stream-MZVL3OCX.js} +1 -1
- package/dist/{workspace-intelligence-4CA2CSPZ.js → workspace-intelligence-FZRQIFFM.js} +1 -1
- package/dist/{workspace-intelligence-runner-VM5SXXAT.js → workspace-intelligence-runner-IXT62JG7.js} +1 -1
- package/dist/{workspace-knowledge-graph-JXN2ZOAF.js → workspace-knowledge-graph-EFC4TUDZ.js} +1 -1
- package/dist/workspace-knowledge-graph-snapshot-QIMF7TCF.js +1 -0
- package/dist/{workspace-mcp-serve-4WN4CSD7.js → workspace-mcp-serve-C42UUU7W.js} +1 -1
- package/dist/{workspace-model-D4IECQML.js → workspace-model-72SJ6WXT.js} +1 -1
- package/dist/{workspace-onboarding-6XWDKLM5.js → workspace-onboarding-TFDAIHTS.js} +1 -1
- package/dist/{workspace-registry-summary-Y3ET36NH.js → workspace-registry-summary-ZNTXSUI4.js} +1 -1
- package/dist/{workspace-repair-engine-HBUXRHDY.js → workspace-repair-engine-542TAL3Z.js} +1 -1
- package/dist/workspace-run-NAPJYNSZ.js +1 -0
- package/dist/{workspace-verify-OOAZ3NMZ.js → workspace-verify-UXKENOQU.js} +1 -1
- package/dist/{workspace-watch-BNM5B6HU.js → workspace-watch-DV5AHLOK.js} +1 -1
- package/docs/README.md +2 -2
- package/docs/agent-framework-adapters.md +164 -39
- package/docs/ci-workflows.md +29 -22
- package/docs/commands-reference.md +17 -8
- package/docs/creating-workspaces-and-projects.md +4 -2
- package/docs/doctor-command.md +6 -4
- package/docs/native-kit-baselines.md +2 -1
- package/docs/workspace-run.md +3 -1
- package/package.json +3 -1
- package/scripts/enterprise-package-smoke.mjs +98 -5
- package/dist/analyze-6UEBC5OJ.js +0 -1
- package/dist/autopilot-release-H5TO6NYY.js +0 -1
- package/dist/capabilities-command-VK3LQLP2.js +0 -1
- package/dist/chunk-3N27P3KO.js +0 -7
- package/dist/chunk-3RNWBFRP.js +0 -4
- package/dist/chunk-66O62XNJ.js +0 -97
- package/dist/chunk-7NKM6EHE.js +0 -7
- package/dist/chunk-BR6QIYQS.js +0 -1
- package/dist/chunk-DFREJHG7.js +0 -1
- package/dist/chunk-E42IFQFR.js +0 -6
- package/dist/chunk-EWD6QTAM.js +0 -2
- package/dist/chunk-G5UCEXP6.js +0 -1
- package/dist/chunk-LARREYZN.js +0 -1
- package/dist/chunk-RGNCL5OB.js +0 -1
- package/dist/chunk-SZHRPELL.js +0 -1
- package/dist/chunk-VXFIMEC6.js +0 -2
- package/dist/chunk-X7OI24LO.js +0 -418
- package/dist/platform-capabilities-DB4BZPTD.js +0 -1
- package/dist/proof-carrying-change-O37XUPIZ.js +0 -1
- package/dist/workspace-knowledge-graph-snapshot-KBNUXA64.js +0 -1
- package/dist/workspace-run-VN7KV4BU.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{b as AUTOPILOT_RELEASE_ALIAS_FILENAME,a as AUTOPILOT_RELEASE_LAST_RUN_FILENAME,c as runAutopilotRelease}from'./chunk-EP7SUMAX.js';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{b as runDoctorCapabilities}from'./chunk-JKAAKE4Z.js';
|
package/dist/chunk-3N27P3KO.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import {d,b,e}from'./chunk-BR6QIYQS.js';import {a}from'./chunk-NMXGSVMD.js';import {d as d$3}from'./chunk-S5KTATOU.js';import {B,q as q$1,A,u as u$1,z,D as D$1}from'./chunk-E42IFQFR.js';import {d as d$2,c as c$1}from'./chunk-ROOPODG6.js';import {k,m,g as g$1,f}from'./chunk-7NKM6EHE.js';import {g}from'./chunk-BLEIUQL6.js';import {e as e$1,g as g$2}from'./chunk-RGNCL5OB.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {c,d as d$1}from'./chunk-25AWHAB5.js';import {u,q,t as t$1}from'./chunk-VQZ5PI5J.js';import {p,t}from'./chunk-ODK4LCEL.js';import Q from'fs';import y from'path';import D from'chalk';import {execa}from'execa';var yt={"python-fastapi":{runtime:"python",framework:"FastAPI",markers:["pyproject.toml","fastapi"],commands:{init:"python -m pip install -e .",test:"pytest",build:"python -m build",start:"uvicorn main:app --reload"},errorPatterns:{setup:["ModuleNotFoundError","No module named","pip: command not found"],"test-failure":["FAILED","ERROR","test session started"],dependency:["ImportError","missing.*dependency"],runtime:["TypeError","AttributeError","ValueError"],timeout:["timeout","Timeout","timed out"],unknown:[]},healthCheck:{stage:"start",type:"http",value:"http://localhost:8000/docs"},validation:{command:"python -m pip list | grep fastapi",error:"FastAPI not installed"}},"python-django":{runtime:"python",framework:"Django",markers:["manage.py","django"],commands:{init:"python manage.py migrate",test:"python manage.py test",build:"python manage.py collectstatic --noinput",start:"python manage.py runserver 0.0.0.0:8000"},errorPatterns:{setup:["ModuleNotFoundError","ProgrammingError.*migrate"],"test-failure":["FAILED","ERROR","Ran.*test"],dependency:["ImportError","missing.*dependency"],runtime:["DatabaseError","ImproperlyConfigured"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"node-nestjs":{runtime:"node",framework:"NestJS",markers:["package.json","@nestjs/core"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm run start"},errorPatterns:{setup:["npm ERR!","ENOENT","not found"],"test-failure":["Tests.*failed","FAIL","fail.*test"],dependency:["Cannot find module","ERR_MODULE_NOT_FOUND"],runtime:["TypeError","Error: ","ReferenceError"],timeout:["timeout","TIMEOUT"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3}},"node-express":{runtime:"node",framework:"Express",markers:["package.json","express"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm start"},errorPatterns:{setup:["npm ERR!","ENOENT"],"test-failure":["failed","FAIL"],dependency:["Cannot find module"],runtime:["Error","TypeError"],timeout:["timeout"],unknown:[]}},"go-fiber":{runtime:"go",framework:"Fiber",markers:["go.mod","fiber"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found","cannot find","go mod tidy"],"test-failure":["FAIL","--- FAIL"],dependency:["missing.*module"],runtime:["panic","fatal","Error"],timeout:["timeout","context deadline"],unknown:[]},dependencies:["init"]},"go-gin":{runtime:"go",framework:"Gin",markers:["go.mod","gin-gonic"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found"],"test-failure":["FAIL"],dependency:["missing.*module"],runtime:["panic"],timeout:["timeout"],unknown:[]}},"java-springboot":{runtime:"java",framework:"Spring Boot",markers:["pom.xml","build.gradle","spring-boot"],commands:{init:"mvn dependency:go-offline",test:"mvn test",build:"mvn package -DskipTests",start:"mvn spring-boot:run"},errorPatterns:{setup:["\\[ERROR\\]","BUILD FAILURE","missing dependencies"],"test-failure":["\\[ERROR\\] Tests run:","BUILD FAILURE"],dependency:["missing.*dependency"],runtime:["Exception","Error","NullPointerException"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8080}},"php-laravel":{runtime:"php",framework:"Laravel",markers:["composer.json","artisan","app/Models"],commands:{init:"composer install && php artisan migrate:fresh --seed",test:"php artisan test",build:"php artisan config:cache && php artisan route:cache && php artisan view:cache",start:"php artisan serve --host=0.0.0.0 --port=8000"},errorPatterns:{setup:["Composer.*lock","Fatal error","Class.*not found"],"test-failure":["FAILED","Tests.*failed"],dependency:["Class.*not found","require.*failed"],runtime:["Fatal error","Exception","Error"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"php-symfony":{runtime:"php",framework:"Symfony",markers:["composer.json","symfony.lock","bin/console"],commands:{init:"composer install && php bin/console doctrine:database:create",test:"php bin/phpunit",build:"php bin/console cache:clear --env=prod",start:"symfony serve --no-tls"},errorPatterns:{setup:["Composer.*error","Fatal error"],"test-failure":["FAILED","failure"],dependency:["Class.*not found"],runtime:["Fatal error","Exception"],timeout:["timeout"],unknown:[]},dependencies:["init"]},"rust-actix":{runtime:"rust",framework:"Actix-web",markers:["Cargo.toml","actix"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find","failed.*download"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E","thread.*panicked"],timeout:["timeout"],unknown:[]},validation:{command:"cargo --version",error:"Rust/Cargo not installed"}},"rust-axum":{runtime:"rust",framework:"Axum",markers:["Cargo.toml","axum"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"rust-rocket":{runtime:"rust",framework:"Rocket",markers:["Cargo.toml","rocket"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["FAILED"],dependency:["can.t find"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"dotnet-aspnetcore":{runtime:"dotnet",framework:"ASP.NET Core",markers:[".csproj",".sln","Program.cs"],commands:{init:"dotnet restore",test:"dotnet test",build:"dotnet build -c Release",start:"dotnet run"},errorPatterns:{setup:["error CS","CSPROJ.*not found","NuGet.*restore"],"test-failure":["Failed:.*test","FAILED"],dependency:["error NU1101"],runtime:["error CS","Exception"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:5e3}},"elixir-phoenix":{runtime:"elixir",framework:"Phoenix",markers:["mix.exs","phoenix"],commands:{init:"mix setup",test:"mix test",build:"mix compile --all-warnings",start:"mix phx.server"},errorPatterns:{setup:["\\*\\* \\(.*Error\\)","Mix.InstallError"],"test-failure":["\\d+\\sfailed","FAILED"],dependency:["dependencies are not available"],runtime:["\\*\\* \\(","RuntimeError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:4e3},dependencies:["init"]},"ruby-rails":{runtime:"ruby",framework:"Rails",markers:["Gemfile","config/application.rb","bin/rails"],commands:{init:"bundle install && rails db:prepare",test:"rails test",build:"rails assets:precompile",start:"rails server --binding=0.0.0.0 --port=3000"},errorPatterns:{setup:["Bundler::.*Error","Gem::.*Error"],"test-failure":["failures,","error,","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","Exception","NoMethodError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3},dependencies:["init"]},"ruby-sinatra":{runtime:"ruby",framework:"Sinatra",markers:["Gemfile","app.rb","sinatra"],commands:{init:"bundle install",test:"rspec",build:`echo "Sinatra apps don't require build"`,start:"ruby app.rb"},errorPatterns:{setup:["Bundler.*Error","Gem.*Error"],"test-failure":["failure","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","NoMethodError"],timeout:["timeout"],unknown:[]}}},ht={init:{python:["pip install -e .","poetry install","pip install -r requirements.txt"],node:["npm install","pnpm install","yarn install"],go:["go mod download && go mod tidy","go get ./..."],java:["mvn dependency:go-offline","gradle dependencies"],php:["composer install"],rust:["cargo fetch"],dotnet:["dotnet restore"],c:["cmake -S . -B build"],cpp:["cmake -S . -B build"],elixir:["mix deps.get"],ruby:["bundle install"],clojure:["clojure -P"],scala:["sbt update"],kotlin:["./gradlew dependencies","gradle dependencies"],deno:[],bun:["bun install"],"jvm-generic":["mvn dependency:go-offline","gradle dependencies"],unknown:[]},test:{python:["pytest","python -m unittest","python -m pytest"],node:["npm test","npm run test"],go:["go test ./...","make test"],java:["mvn test","gradle test"],php:["php artisan test","phpunit","pest"],rust:["cargo test"],dotnet:["dotnet test"],c:["ctest --test-dir build --output-on-failure"],cpp:["ctest --test-dir build --output-on-failure"],elixir:["mix test"],ruby:["rspec","ruby -m minitest"],clojure:["clojure -X:test"],scala:["sbt test"],kotlin:["./gradlew test","gradle test"],deno:["deno task test","deno test"],bun:["bun test","bun run test"],"jvm-generic":["mvn test","gradle test"],unknown:[]},build:{python:["python -m build","python setup.py build"],node:["npm run build"],go:["go build -o app .","go build ./..."],java:["mvn package -DskipTests","gradle build -x test"],php:['echo "PHP build: typically no build step"'],rust:["cargo build --release"],dotnet:["dotnet build -c Release"],c:["cmake --build build"],cpp:["cmake --build build"],elixir:["mix compile"],ruby:["gem build *.gemspec"],clojure:[],scala:["sbt compile"],kotlin:["./gradlew build","gradle build"],deno:["deno task build"],bun:["bun run build"],"jvm-generic":["mvn package -DskipTests","gradle build"],unknown:[]},start:{python:["python app.py","python main.py","uvicorn main:app --reload"],node:["npm start","node index.js","node src/index.js"],go:["./app","go run main.go","go run ./..."],java:["mvn spring-boot:run","gradle bootRun","java -jar target/*.jar"],php:["php -S 0.0.0.0:8000","php artisan serve"],rust:["cargo run --release","./target/release/app"],dotnet:["dotnet run"],c:[],cpp:[],elixir:["mix phx.server","iex -S mix"],ruby:["rails server","ruby app.rb","bundle exec puma"],clojure:["clojure -M:run"],scala:["sbt run"],kotlin:["./gradlew run","gradle run"],deno:["deno task start","deno task dev"],bun:["bun run start","bun run dev"],"jvm-generic":["java -jar *.jar","gradle run"],unknown:[]}};function de(e,r){if(r){let t=r.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=f(r),o=`${e}-${n==="gofiber"?"fiber":n==="gogin"?"gin":n==="dotnet"?"aspnetcore":n!=="unknown"?n:t==="fiber"?"fiber":t==="aspnetcore"||t==="asp-net-core"?"aspnetcore":t}`;return yt[o]}}function Je(e,r,t){if(r){let n=de(e,r);if(n&&n.commands[t])return n.commands[t]}if(["init","test","build","start"].includes(t)){let n=ht[t]?.[e]??[];return n.length>0?n[0]:void 0}}var kt={test:"test",build:"build",start:"start"};function le(e){if(e.stage==="init")return e.runtime==="node"?A(e.projectPath):Je(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let r=kt[e.stage];if(r){let t=u$1(e.projectPath,r,{framework:e.framework});if(t)return z(e.projectPath,t.scriptName)}}return Je(e.runtime,e.framework,e.stage)}function bt(e){let r=k(e).map(t=>t==="python"?"python":t==="node"||t==="bun"?"node":t==="go"?"go":t==="java"?"java":t==="php"?"php":t==="rust"?"rust":t==="dotnet"?"dotnet":t==="elixir"?"elixir":t==="ruby"?"ruby":t==="clojure"||t==="scala"||t==="kotlin"?"jvm-generic":null).filter(t=>t!==null).filter((t,n,s)=>s.indexOf(t)===n);return {primary:r.length>0?r[0]:"unknown",secondary:r.slice(1)}}function Ze(e){return bt(e).primary}function Qe(e,r,t){if(!e)return "unknown";r||(r={timeout:["timed out","timeout","deadline exceeded","SocketTimeoutException"],dependency:["cannot find module","import.*error","Could not find a package configuration file provided by","CMAKE_PREFIX_PATH","failed to fetch","error while requesting resource","unable to (?:resolve|connect)","could not resolve host","network (?:is )?unreachable","ECONNREFUSED","ENOTFOUND"],setup:["ModuleNotFoundError","No module named","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],runtime:["Exception","Error:","panic","TypeError"],unknown:[]});for(let[n,s]of Object.entries(r))if(!(n==="test-failure"&&t&&t!=="test")){for(let o of s)if(new RegExp(o,"i").test(e))return n}return "unknown"}async function re(e,r){let t=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(t))return {valid:true};if(t.includes("/")||t.includes("\\")){let s=y.isAbsolute(t)?t:y.resolve(r??process.cwd(),t);try{return await Q.promises.access(s,process.platform==="win32"?Q.constants.F_OK:Q.constants.X_OK),{valid:true}}catch{return {valid:false,reason:`Command '${t}' not found or not executable in '${r??process.cwd()}'`}}}try{let s=process.platform==="win32"?"where":"which";if((await execa(s,[t],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${t}' not found or not executable`}}function et(e,r,t){if(!r)return e;let n=typeof r=="object"&&!Array.isArray(r)&&("dev"in r||"staging"in r||"prod"in r||"default"in r)&&!Object.keys(r).some(s=>["init","test","build","start"].includes(s))?r:{};return t&&typeof n[t]=="string"?n[t]:typeof n.default=="string"?n.default:e}async function tt(e,r){if(!e)return {healthy:true};switch(e.type){case "port":{let t=e.value;try{let n=await import('net');return new Promise(s=>{let o=new n.Socket,i=5e3;o.setTimeout(i),o.on("connect",()=>{o.destroy(),s({healthy:true,reason:`Port ${t} is listening`});}),o.on("timeout",()=>{o.destroy(),s({healthy:false,reason:`Port ${t} timeout after ${i}ms`});}),o.on("error",l=>{o.destroy(),s({healthy:false,reason:`Port ${t} error: ${String(l)}`});}),o.connect(t,"localhost");})}catch(n){return {healthy:false,reason:`Port check error: ${n instanceof Error?n.message:String(n)}`}}}case "http":{let t=e.value,n;try{let s=new AbortController;n=setTimeout(()=>s.abort(),5e3);let o=await fetch(t,{method:"GET",signal:s.signal});return {healthy:o.status===200,reason:`HTTP ${o.status}`,metadata:{status:o.status}}}catch(s){return {healthy:false,reason:`HTTP check error: ${s instanceof Error?s.message:String(s)}`}}finally{n&&clearTimeout(n);}}case "log":{let t=e.value;if(!r)return {healthy:true};try{let n=[y.join(r,".workspai","last-run.log"),y.join(r,".rapidkit","last-run.log")].find(s=>Q.existsSync(s));if(n){let s=Q.readFileSync(n,"utf-8"),o=new RegExp(t,"i");return {healthy:o.test(s),reason:o.test(s)?"Log pattern found":"Log pattern not found"}}return {healthy:true,reason:"No log file to check"}}catch(n){return {healthy:false,reason:`Log check error: ${n instanceof Error?n.message:String(n)}`}}}case "command":{let t=e.value;try{let n=await execa(t,[],{cwd:r,reject:false,shell:true});return {healthy:n.exitCode===0,reason:n.exitCode===0?"Health check passed":"Health check failed",metadata:{exitCode:n.exitCode}}}catch(n){return {healthy:false,reason:`Command check error: ${n instanceof Error?n.message:String(n)}`}}}default:return {healthy:true}}}var rt={init:"init",test:"test",build:"build",start:"start"};function wt(e){return e in rt?rt[e]:null}function xt(e,r){let n=q$1(e)?.contextJson?.commands;if(!n||typeof n!="object"||Array.isArray(n))return;let s=n[r];if(typeof s=="string"&&s.trim().length>0)return s.trim();if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s,i=o.default??o.dev;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}function nt(e,r,t=D$1(e)){let n=wt(r);if(!n)return xt(e,r)?{supported:true}:{supported:false,reason:`Workspace stage "${r}" is not part of the Workspai fleet contract.`};if(!t.projectRoot)return {supported:false,reason:"No Workspai project metadata was detected for this target."};let s=t.commandMap[n];if(!s||s.status!=="supported"){let o=t.runtimeSupportTier==="observed"||t.frameworkSupportTier==="observed";return {supported:false,reason:s?.reason??`Command "${n}" is not supported for this project runtime/framework.`,shouldFail:!o}}return {supported:true}}var vt=new Set(["init","test","build","start"]),Rt=new Set([".git","node_modules",".workspai",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function Y(e){try{return await Q.promises.access(e,Q.constants.F_OK),true}catch{return false}}function ot(e,r){let t=y.relative(y.resolve(e),y.resolve(r));return t===""||!t.startsWith(`..${y.sep}`)&&t!==".."&&!y.isAbsolute(t)}function St(e){let r=y.resolve(e.projectPath,e.unit.root);return !e.selectedProjectPaths.some(t=>y.resolve(t)===y.resolve(e.projectPath)?false:ot(e.projectPath,t)&&ot(t,r))}async function Ct(e){for(let r of e)if(await Y(r))return true;return false}async function Et(e,r,t){if(r==="python"){let i=[y.join(e,".workspai","cli.py"),y.join(e,".rapidkit","cli.py")];for(let l of i)if(await Y(l))return {valid:true};return {valid:false,reason:"Project-local .workspai/cli.py is missing. Run `workspai init` in this project first."}}let s={go:"go",rust:"cargo",dotnet:"dotnet",php:"php"}[r];if(s)return re(s,e);let o=t.trim().split(/\s+/)[0];if(o&&["npm","npx","pnpm","yarn"].includes(o)){let i=e$1(o);if((await execa(i.command,[...i.prefixArgs,"--version"],{reject:false,env:g$2()})).exitCode===0)return {valid:true}}return re(t,e)}async function pe(e){let r=await Q.promises.readFile(e,"utf-8");return JSON.parse(r)}function K(e){return e.replace(/\\/g,"/")}function jt(e){let r=e?.trim();return r?r.startsWith("project:")?r.slice(8).trim()||null:r:null}async function Pt(e){let r=y.join(e,p.model);if(await Y(r))try{let n=((await pe(r)).projects??[]).map(s=>typeof s.path=="string"?d$2(e,s.path):null).filter(s=>!!s).filter((s,o,i)=>i.indexOf(s)===o).filter(s=>Q.existsSync(s));if(n.length>0)return n.sort()}catch{}return a(e,{skipDirs:Rt,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t,n)=>await Ct([...u(t,"context.json"),...u(t,"project.json")])?true:y.resolve(t)===y.resolve(n)?false:k(t).length>0})}async function ct(e){for(let r of [y.join(".workspai","project.json"),y.join(".workspai","context.json"),y.join(".rapidkit","project.json"),y.join(".rapidkit","context.json")]){let t=y.join(e,r);if(await Y(t))try{let n=await pe(t),s=n.name??n.projectName??n.slug;if(typeof s=="string"&&s.trim())return s.trim()}catch{}}return null}async function At(e,r,t){let n=jt(t);if(!n)return {projects:r,normalizedScope:null};let s=K(n).toLowerCase(),o=[];for(let i of r){let l=await ct(i);c$1({workspacePath:e,projectPath:i,declaredName:l}).map(m=>K(m).toLowerCase()).includes(s)&&o.push(i);}if(o.length===0)throw new Error(`Workspace run scope did not match any project: ${t}`);return {projects:o,normalizedScope:n}}async function Ft(e,r,t){let n=await execa("git",["diff","--name-only",`${t}...HEAD`],{cwd:e,reject:false,env:a$1()});if(n.exitCode!==0)return new Set(r);let s=n.stdout.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0).map(i=>K(i));if(s.length===0)return new Set;let o=new Set;for(let i of r){let l=K(y.relative(e,i));if(!l||l===".")continue;let c=`${l}/`;s.some(m=>m===l||m.startsWith(c))&&o.add(i);}return o}async function Tt(e,r,t$1){let n=await g(e,t.workspaceContract)??q(e,"workspace.contract.json");if(await Y(n))try{let u=await Ot(e,r,t$1,n);if(u.graphStatus!=="missing")return u}catch{return {expanded:t$1,graphStatus:"invalid",expansionDepth:0}}let s=await g(e,".workspai/workspace-dependency-graph.json")??q(e,"workspace-dependency-graph.json");if(!await Y(s))return {expanded:t$1,graphStatus:"missing",expansionDepth:0};let o;try{o=await pe(s);}catch{return {expanded:t$1,graphStatus:"invalid",expansionDepth:0}}let i=new Set(r.map(u=>y.resolve(u))),l=new Map;if(!o||typeof o!="object"||Array.isArray(o))return {expanded:t$1,graphStatus:"invalid",expansionDepth:0};let c=Array.isArray(o.projects)?o.projects:[];for(let u of c){if(!u||typeof u!="object"||Array.isArray(u))continue;let p=u,d=typeof p.path=="string"?p.path:"",w=y.resolve(e,d);if(!i.has(w))continue;let x=Array.isArray(p.dependsOn)?p.dependsOn.filter(C=>typeof C=="string"):[];for(let C of x){let v=y.resolve(e,C);i.has(v)&&(l.has(v)||l.set(v,new Set),l.get(v)?.add(w));}}let m=d$3(l,t$1);return {expanded:m.reached,graphStatus:"loaded",expansionDepth:m.added}}async function Ot(e,r,t,n){let s=await pe(n);if(!s||typeof s!="object"||Array.isArray(s))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let o=s,i=Array.isArray(o.projects)?o.projects:null;if(!i)return {expanded:t,graphStatus:"invalid",expansionDepth:0};let l=new Map,c=new Map;for(let w of r){let x=K(y.relative(e,w));c.set(x,y.resolve(w));}let m=new Map,u=new Map,p=new Map;for(let w of i){if(!w||typeof w!="object"||Array.isArray(w))continue;let x=w,C=typeof x.slug=="string"?x.slug:"",v=typeof x.relativePath=="string"?K(x.relativePath):C,h=c.get(v);!C||!h||l.set(C,h);}for(let w of i){if(!w||typeof w!="object"||Array.isArray(w))continue;let x=w,C=typeof x.slug=="string"?x.slug:"",v=l.get(C);if(!v)continue;let h=x.contracts&&typeof x.contracts=="object"&&!Array.isArray(x.contracts)?x.contracts:{},R=Array.isArray(h.dependsOn)?h.dependsOn.filter(S=>typeof S=="string"):[],M=Array.isArray(h.publishes)?h.publishes.filter(S=>typeof S=="string"):[],_=Array.isArray(h.consumes)?h.consumes.filter(S=>typeof S=="string"):[];for(let S of R){let P=l.get(S);P&&(p.has(P)||p.set(P,new Set),p.get(P)?.add(v));}for(let S of M)m.has(S)||m.set(S,new Set),m.get(S)?.add(v);for(let S of _)u.has(S)||u.set(S,new Set),u.get(S)?.add(v);}for(let[w,x]of m.entries()){let C=u.get(w);if(C)for(let v of x){p.has(v)||p.set(v,new Set);for(let h of C)h!==v&&p.get(v)?.add(h);}}let d=d$3(p,t);return {expanded:d.reached,graphStatus:"loaded",expansionDepth:d.added}}async function Dt(e,r){if(typeof r=="boolean")return r;let t=t$1(e,"policies.yml").find(o=>Q.existsSync(o))??q(e,"policies.yml");if(!await Y(t))return true;let n="";try{n=await Q.promises.readFile(t,"utf-8");}catch{return true}let s=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return s?s[1]==="true":true}function It(e,r){let t=process.env.RAPIDKIT_WORKSPACE_RUN_STAGE_TIMEOUT_MS;if(t){let n=Number.parseInt(t,10);if(Number.isFinite(n)&&n>0)return n}return e!=="init"?9e4:r==="python"||r==="java"||r==="jvm-generic"||r==="dotnet"||r==="rust"?6e5:3e5}function $t(e){let r=e.trim();if(!r||/[&|;<>()$`"'\n\r]/.test(r))return null;let[t,...n]=r.split(/\s+/);return !t||/^[A-Za-z_][A-Za-z0-9_]*=/.test(t)||![t,...n].every(s=>/^[A-Za-z0-9_./:@%+,=\\-]+$/.test(s))?null:{file:t,args:n}}function st(e,r){let t=Number.parseInt(process.env[e]??"",10);return Number.isFinite(t)&&t>0?t:r}function xe(e){return new Promise(r=>setTimeout(r,e))}async function Nt(e){let r=process.argv[1];if(e.useRapidkitWrapper&&!r)return {exitCode:1,stdout:"",stderr:"Workspai entrypoint is unavailable for startup verification.",healthStatus:{healthy:false,reason:"Workspai entrypoint is unavailable."}};let t=e.useRapidkitWrapper&&r?execa(process.execPath,[r,"start"],{cwd:e.projectPath,reject:false,timeout:e.timeoutMs,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}}):execa(e.finalCommand,[],{cwd:e.projectPath,reject:false,shell:true,timeout:e.timeoutMs}),n=Promise.resolve(t).then(u=>({kind:"exit",result:u}),u=>({kind:"error",error:u})),s=st("WORKSPAI_WORKSPACE_RUN_STARTUP_GRACE_MS",2e3),o=await Promise.race([n,xe(s).then(()=>({kind:"alive"}))]);if(o.kind==="error"){let u=typeof o.error=="object"&&o.error!==null&&"timedOut"in o.error&&!!o.error.timedOut;return {exitCode:u?124:1,stdout:"",stderr:o.error instanceof Error?o.error.message:String(o.error),timedOut:u,healthStatus:{healthy:false,reason:"The start command failed before readiness."}}}if(o.kind==="exit"){let u=Number(o.result.exitCode??0);return {exitCode:u,stdout:String(o.result.stdout??""),stderr:String(o.result.stderr??""),healthStatus:{healthy:u===0,reason:u===0?"The start command completed successfully.":`The start command exited with code ${u} before readiness.`}}}let i=de(e.runtime,e.framework)?.healthCheck,l=i?{healthy:false,reason:"The configured health check has not passed yet."}:{healthy:true,reason:`The service remained alive for ${s}ms (bounded startup smoke).`};if(i){let u=st("WORKSPAI_WORKSPACE_RUN_STARTUP_HEALTH_TIMEOUT_MS",15e3),p=Date.now()+u;for(;Date.now()<p;){let d=await tt(i,e.projectPath);if(l={healthy:d.healthy,reason:d.reason},d.healthy)break;if((await Promise.race([n,xe(350).then(()=>({kind:"alive"}))])).kind!=="alive"){l={healthy:false,reason:"The service exited before its configured health check passed."};break}}}try{t.kill?.("SIGTERM",{forceKillAfterDelay:1e3});}catch{try{t.kill?.();}catch{}}let c=await Promise.race([n,xe(2e3).then(()=>({kind:"alive"}))]),m=c.kind==="exit"?c.result:void 0;return {exitCode:l.healthy?0:1,stdout:String(m?.stdout??""),stderr:String(m?.stderr??""),healthStatus:l}}async function Re(e,r,t,n=false){let s=process.argv[1];if(!s)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};let o=false,i,l;try{let c=execa(process.execPath,[s,...e],{cwd:r,reject:false,detached:process.platform!=="win32",env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});t&&t>0&&(l=setTimeout(()=>{o=true;let u=c.pid;if(!u){c.kill("SIGTERM");return}if(process.platform==="win32"){execa("taskkill",["/pid",String(u),"/T","/F"],{reject:false});return}try{process.kill(-u,"SIGTERM");}catch{c.kill("SIGTERM");}i=setTimeout(()=>{try{process.kill(-u,"SIGKILL");}catch{}},1e3),i.unref();},t),l.unref()),n&&(c.stdout?.on("data",u=>process.stdout.write(u)),c.stderr?.on("data",u=>process.stderr.write(u)));let m=await c;return {exitCode:o?124:Number(m.exitCode??1),stdout:m.stdout,stderr:o?`${m.stderr??""}${m.stderr?`
|
|
2
|
-
`:""}Stage timed out after ${t}ms`:m.stderr}}catch(c){let m=o||typeof c=="object"&&c!==null&&"timedOut"in c&&!!c.timedOut;return {exitCode:m?124:1,stdout:typeof c=="object"&&c!==null&&"stdout"in c?String(c.stdout??""):"",stderr:m?`Stage timed out after ${t}ms`:typeof c=="object"&&c!==null&&"stderr"in c?String(c.stderr??""):c instanceof Error?c.message:String(c)}}finally{l&&clearTimeout(l),i&&clearTimeout(i);}}function dt(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"||e==="rust"||e==="php"}function Wt(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}function Mt(e,r=8){if(e.length<=r)return e.join(`
|
|
3
|
-
`);let t=lt(e),n=t?e.lastIndexOf(t):-1,s=new Set([0,1]);if(n>=0)for(let o=Math.max(0,n-2);o<=n+2;o+=1)o<e.length&&s.add(o);for(let o=e.length-1;o>=0&&s.size<r;o-=1)s.add(o);return [...s].sort((o,i)=>o-i).slice(0,r).map(o=>e[o]).join(`
|
|
4
|
-
`)}function lt(e){let r=/(?:\bnot found\b|\bno such\b|\bmissing\b|\bfailed\b|\berror\b|\bexception\b|\bcannot\b|\bdenied\b|\btimeout\b|\btimed out\b|\benoent\b|\beacces\b|\beperm\b)/i;return [...e].reverse().find(t=>r.test(t))??e.at(-1)}async function _t(e){let r=process.cwd();try{process.chdir(e);let{handleInitCommand:t}=await import('./index.js');return {exitCode:await t(["init"]),stdout:"",stderr:""}}finally{process.chdir(r);}}async function ve(e){let r=p=>{let d=g$1(p);return d==="node"||d==="bun"?"node":d==="python"?"python":d==="go"?"go":d==="java"?"java":d==="php"?"php":d==="ruby"?"ruby":d==="rust"?"rust":d==="dotnet"?"dotnet":d==="elixir"?"elixir":d==="clojure"||d==="scala"||d==="kotlin"?"jvm-generic":Ze(e)},t=p=>{if(!p)return;let d=f(p);if(new Set(["fastapi","django","flask","nestjs","express","fastify","koa","gofiber","gogin","echo","springboot","laravel","symfony","rails","sinatra","dotnet","actix","axum","rocket","phoenix"]).has(d))return d},n=q$1(e),s=n?.detection??m(e,n?.projectJson??null),o=n?.contextJson,i=r(s.runtime),l=t(s.key),c={},m$1=new Set(["init","test","build","start"]);if(o?.commands&&typeof o.commands=="object")for(let[p,d]of Object.entries(o.commands))typeof d=="string"&&m$1.has(p)&&(c[p]=d);let u;if(o?.commandEnvironments&&typeof o.commandEnvironments=="object"){let p=o.commandEnvironments;u={dev:typeof p.dev=="string"?p.dev:void 0,staging:typeof p.staging=="string"?p.staging:void 0,prod:typeof p.prod=="string"?p.prod:void 0,default:typeof p.default=="string"?p.default:void 0};}return {runtime:i,framework:l,commandOverrides:Object.keys(c).length>0?c:void 0,environmentCommandVariants:u,environment:typeof o?.environment=="string"?o.environment:void 0}}async function at(e,r,t,n,s,o,i,l=false){let c=!s?.[r]&&dt(t),m;if(s&&s[r]?m=s[r]:c?m=`rapidkit ${r}`:m=le({projectPath:e,runtime:t,framework:n,stage:r}),!m)return {exitCode:127,command:`<stage not supported for ${t}>`,message:`No stage command found for runtime '${t}' and framework '${n||"unknown"}'`,errorCategory:"runtime"};let u=et(m,o,i);if(!u)return {exitCode:127,command:m,message:"Failed to resolve stage command",errorCategory:"runtime"};let p=le({projectPath:e,runtime:t,framework:n,stage:r});if(c){if(p){let b=c?await Et(e,t,p):await re(p,e);if(!b.valid)return {exitCode:127,command:u,message:b.reason||"Command not available",errorCategory:"setup"}}}else {let b=await re(u,e);if(!b.valid)return {exitCode:127,command:u,message:b.reason||"Command not available",errorCategory:"setup"}}let d=0,w="",x="",C,v=false,h,R=It(r,t),M=Date.now();try{let b=r==="start"?await Nt({projectPath:e,finalCommand:u,useRapidkitWrapper:c,runtime:t,framework:n,timeoutMs:R}):c?r==="init"&&Wt()?await _t(e):await Re([r],e,R,l):await(async()=>{let $=$t(u);return $?execa($.file,$.args,{cwd:e,reject:false,timeout:R,forceKillAfterDelay:1e3}):execa(u,[],{cwd:e,reject:false,shell:true,timeout:R,forceKillAfterDelay:1e3})})();if(v=!!(typeof b=="object"&&b!==null&&"timedOut"in b&&b.timedOut),d=v?124:Number(b.exitCode??0),w=b.stdout,x=b.stderr,h=r==="start"?b.healthStatus:void 0,d!==0){let $=`${w}
|
|
5
|
-
${x}`,me=Date.now()-M,ee=Qe($,void 0,r);C=v||d===124||d===143&&me>=Math.floor(R*.8)||ee==="timeout"?"timeout":ee;}}catch(b){let $=typeof b=="object"&&b!==null&&"timedOut"in b&&!!b.timedOut;return {exitCode:$?124:1,command:u,message:$?`Stage timed out after ${R}ms`:b instanceof Error?b.message:"Command execution failed",errorCategory:$?"timeout":"runtime"}}let _=`${w}
|
|
6
|
-
${x}`.split(/\r?\n/).map(b=>b.trim()).filter(Boolean),S=Mt(_),P=lt(_),I=Date.now()-M;if(r==="test"&&t==="go"&&d!==0&&/(?:matched no packages|no packages to test)/i.test(_.join(`
|
|
7
|
-
`)))return {exitCode:0,command:u,skipped:true,message:"No Go packages matched; test stage is not applicable to this runtime unit."};let z=v||d===124||d===143&&I>=Math.floor(R*.8),V=d===0?void 0:z?"timeout":C,J=d===0||!V?void 0:{category:V,exitCode:d,command:u,timedOut:z,timeoutMs:R,...S?{outputExcerpt:S}:{}};return {exitCode:d,command:u,errorCategory:V,healthStatus:h,failureDiagnostic:J,message:z?`Stage timed out after ${R}ms`:d!==0?P?`Stage failed with exit code ${d}: ${P}`:`Stage failed with exit code ${d}`:void 0}}function it(e){try{return JSON.parse(e)}catch{return null}}function Lt(e){switch(e){case "dotnet":return "Install .NET 8+ SDK, then rerun `npx workspai setup dotnet` or `npx workspai init`.";case "go":return "Install Go 1.21+, then rerun `npx workspai setup go` or `npx workspai init`.";case "java":case "jvm-generic":return "Install Java 21+ and Maven/Gradle, then rerun `npx workspai setup java` or `npx workspai init`.";case "node":return "Install Node.js LTS and npm/pnpm/yarn, then rerun `npx workspai setup node` or `npx workspai init`.";case "python":return "Install Python 3.10+ and pip/Poetry, then rerun `npx workspai setup python` or `npx workspai init`.";default:return null}}async function Gt(e){let r=[],t=await Re(["doctor","workspace","--json"],e);if(t.exitCode!==0)r.push({gate:"doctor-workspace",status:"fail",summary:"doctor workspace command failed"});else {let o=it(t.stdout)?.healthScore,i=Number(o?.errors??0);Number.isFinite(i)&&i>0?r.push({gate:"doctor-workspace",status:"fail",summary:`doctor workspace reports ${i} error(s)`}):r.push({gate:"doctor-workspace",status:"pass",summary:"doctor workspace passed"});}let n=await Re(["readiness","--json"],e);if(n.exitCode!==0)r.push({gate:"readiness",status:"fail",summary:"readiness command failed"});else {let s=it(n.stdout),o=String(s?.overallStatus??"").toLowerCase();o==="fail"?r.push({gate:"readiness",status:"fail",summary:"readiness overall status is fail"}):o==="warn"?r.push({gate:"readiness",status:"warn",summary:"readiness overall status is warn"}):r.push({gate:"readiness",status:"pass",summary:"readiness overall status is pass"});}return r}var Bt=new Set(["dev","stop"]);function Kt(e){let r=e.trim();return !r||Bt.has(r.toLowerCase())?false:vt.has(r)?true:/^[a-z][a-z0-9_-]*$/i.test(r)}function ut(e,r,t){let n=K(y.relative(t,r));return (Array.isArray(e.projects)?e.projects:[]).some(o=>{if(!o||typeof o!="object")return false;let i=o,l=[i.relativePath,i.path].filter(c=>typeof c=="string"&&c.length>0).map(c=>K(c));return i.status==="passed"&&(l.includes(n)||l.some(c=>c.endsWith(`/${n}`)))})}function Ut(e,r){return de(e,r)?.dependencies??[]}function zt(e,r){let t=Math.max(1,Math.min(4,r)),n=Number(e??t);return Number.isFinite(n)?Math.max(1,Math.min(16,Math.trunc(n))):t}async function Er(e$1){if(!Kt(e$1.stage))throw new Error(`Unsupported workspace run stage: ${e$1.stage}`);let r=Date.now(),t=y.resolve(e$1.workspacePath);c({blockId:"workspace.run.resolve",status:"running",message:"Resolving workspace project fleet",component:"workspace-run"});let n=await d(t),s=await Pt(t),{projects:o,normalizedScope:i}=await At(t,s,e$1.scope),l=e$1.affected===true,c$1=e$1.blastRadius===true,m=e$1.since?.trim()||"HEAD~1",u=l?await Ft(t,o,m):new Set(o),p,d$2="not-applicable",w=0,x="all";if(l&&c$1){let g=await Tt(t,s,u);p=g.expanded,d$2=g.graphStatus,w=g.expansionDepth,x="affected+blast-radius";}else l?(p=u,x="affected"):(p=u,x="all");c({blockId:"workspace.run.resolve",status:"succeeded",message:`Resolved ${o.length} project(s)`,component:"workspace-run",attributes:{projects:o.length,selectionMode:x}}),c({blockId:"workspace.run.gates",status:"running",message:"Evaluating workspace run gates",component:"workspace-run"});let C=e$1.stage==="init"||e$1.planOnly===true?false:await Dt(t,e$1.enforceGates),v=C?await Gt(t):[{gate:"doctor-workspace",status:"skipped",summary:"workspace run gates disabled"},{gate:"readiness",status:"skipped",summary:"workspace run gates disabled"}],h=v.find(g=>g.status==="fail");c({blockId:"workspace.run.gates",status:h?"blocked":"succeeded",message:h?`Blocked by ${h.gate}`:"Workspace run gates passed",component:"workspace-run",attributes:{gates:v}});let R=o.filter(g=>p.has(g)),M=e$1.continueOnError===true||e$1.stage==="init",_=e$1.parallel===true,S=zt(e$1.maxWorkers,R.length),P=R.length,I=0;c({blockId:"workspace.run.execute",status:h?"blocked":"running",message:h?`Execution blocked by ${h.gate}`:`Executing ${e$1.stage} across ${P} project(s)`,component:"workspace-run",progress:{completed:0,total:P},attributes:{stage:e$1.stage,parallel:_,maxWorkers:S}}),e$1.json||console.log(D.gray(`Workspace run (${e$1.stage}) started: ${P} target(s), ${_?`parallel x${S}`:"sequential"}`));let U=new Map;for(let g of s){let k=K(y.relative(t,g)),a=await ct(g),L=o.includes(g),E=L&&p.has(g);U.set(g,{path:g,relativePath:k,projectName:a??(y.basename(k)||y.basename(g)),selected:E,affected:E,status:"skipped",exitCode:null,durationMs:0,reason:E?void 0:L?"not affected":"outside scope",framework:void 0,runtimeDetected:void 0,executionCommand:void 0});}if(h)for(let g of R){let k=U.get(g);k&&(k.status="skipped",k.reason=`blocked by ${h.gate}`);}else {let g=async k=>{let a=U.get(k);if(!a)return;let L=K(y.relative(t,k));e$1.json||console.log(D.gray(`\u23F3 [${I}/${P}] ${e$1.stage} ${L}`)),a.selected=true,a.affected=true;let E=Date.now(),N=B(k),T=e$1.runtime?.trim().toLowerCase(),O=N.units.filter(f=>St({projectPath:k,unit:f,selectedProjectPaths:R})).filter(f=>!T||f.runtime===T).map(f=>({unit:f,stage:f.stages.find(j=>j.stage===e$1.stage)})).filter(f=>!!f.stage),G=O.map(({unit:f,stage:j})=>({unitId:f.id,runtime:f.runtime,role:f.role,root:f.root,manifest:f.manifest,stage:j.stage,command:j.command,status:"planned",exitCode:null,durationMs:0}));if(a.runtimeExecutions=G,!N.polyglot&&!T&&G.length===1&&O[0]?.unit.root==="."){let f=await ve(k);a.framework=f.framework,a.runtimeDetected=f.runtime;let j=f.commandOverrides?.[e$1.stage],W=j||(dt(f.runtime)?`rapidkit ${e$1.stage}`:le({projectPath:k,runtime:f.runtime,framework:f.framework,stage:e$1.stage}));if(W){let F=G[0];G.splice(0,G.length,{...F,unitId:`project:${f.runtime}`,root:".",manifest:O.map(({unit:ne})=>ne.manifest).join(", "),command:W});}}if(e$1.planOnly){a.runtimeDetected||(a.runtimeDetected=O[0]?.unit.runtime),a.status="skipped",a.reason=O.length>0?`plan only: ${O.length} runtime unit(s)`:T?`no ${T} runtime unit supports stage "${e$1.stage}"`:`no runtime unit supports stage "${e$1.stage}"`,a.durationMs=Date.now()-E,I+=1;return}if(N.polyglot||T||O.length>1||O.length===1&&O[0]?.unit.root!=="."){if(O.length===0){a.status="failed",a.reason=T?`No ${T} runtime unit supports stage "${e$1.stage}"`:`No runtime unit supports stage "${e$1.stage}"`,a.errorCategory="setup",a.errorMessage=a.reason,a.exitCode=127,a.durationMs=Date.now()-E,I+=1;return}let f;for(let F=0;F<O.length;F+=1){let{unit:ne,stage:Ee}=O[F],Z=G[F],je=y.resolve(k,ne.root),gt=Date.now(),he=await ve(je),H=await at(je,e$1.stage,ne.runtime,he.framework,{[e$1.stage]:Ee.command},he.environmentCommandVariants,he.environment,!e$1.json);if(Z.durationMs=Date.now()-gt,Z.exitCode=H.exitCode,Z.status=H.skipped?"skipped":H.exitCode===0?"passed":"failed",Z.reason=H.message,Z.errorCategory=H.errorCategory,Z.failureDiagnostic=H.failureDiagnostic,H.exitCode!==0&&!f&&(f=H.message??Ee.command),H.exitCode!==0&&!M){for(let Pe of G.slice(F+1))Pe.status="skipped",Pe.reason="stopped after runtime-unit failure";break}}let j=G.find(F=>F.status==="failed");a.runtimeDetected=O[0]?.unit.runtime,a.executionCommand=G.filter(F=>F.status!=="skipped").map(F=>`[${F.runtime}:${F.root}] ${F.command}`).join(" && "),a.durationMs=Date.now()-E;let W=G.find(F=>F.status==="passed");a.exitCode=j?.exitCode??0,a.status=j?"failed":W?"passed":"skipped",a.reason=j?f??"runtime-unit stage failed":W?void 0:"No applicable runtime unit executed the requested stage",a.errorCategory=j?j.errorCategory??"runtime":void 0,a.errorMessage=a.reason,a.failureDiagnostic=j?.failureDiagnostic,I+=1;return}let{runtime:fe,framework:ge,commandOverrides:pt,environmentCommandVariants:mt,environment:ft}=await ve(k);a.runtimeDetected=fe,a.framework=ge;let ye=nt(k,e$1.stage);if(!ye.supported){a.status=ye.shouldFail===false?"skipped":"failed",a.reason=ye.reason??`stage "${e$1.stage}" unsupported for project`,a.durationMs=Date.now()-E,a.exitCode=a.status==="failed"?127:null,a.status==="failed"&&(a.errorCategory="setup",a.errorMessage=a.reason),I+=1;return}if(e$1.reusePassed&&n){let f=n.stages[e$1.stage]??n.stages[e$1.stage];if(f&&ut(f,k,t)){a.status="passed",a.reason="reused passed result from workspace-run-last.json",a.durationMs=Date.now()-E,a.exitCode=0,I+=1,e$1.json||console.log(D.gray(`\u21BA reused passed cache for ${L}`));return}}let Ce=Ut(fe,ge).filter(f=>f!==e$1.stage);if(Ce.length>0&&n){let f=Ce.find(j=>{let W=n.stages[j];return !W||!ut(W,k,t)});if(f){a.status="skipped",a.reason=`dependency stage "${f}" not satisfied in workspace-run-last.json`,a.durationMs=Date.now()-E,a.exitCode=null,I+=1;return}}let A=await at(k,e$1.stage,fe,ge,pt,mt,ft,!e$1.json);a.executionCommand=A.command,a.errorCategory=A.errorCategory,a.healthStatus=A.healthStatus,a.failureDiagnostic=A.failureDiagnostic,a.durationMs=Date.now()-E,a.exitCode=A.exitCode;let q=a.runtimeExecutions?.[0];if(q&&(q.command=A.command,q.status=A.skipped?"skipped":A.exitCode===0?"passed":"failed",q.exitCode=A.exitCode,q.durationMs=a.durationMs,q.reason=A.message,q.errorCategory=A.errorCategory,q.failureDiagnostic=A.failureDiagnostic),A.skipped?(a.status="skipped",a.reason=A.message):A.exitCode===0?(a.status="passed",a.reason=void 0):(a.status="failed",a.reason=A.message||"stage command failed",a.errorMessage=A.message),I+=1,!e$1.json){let f=P>0?Math.round(I/P*100):100,j=a.status==="passed"?D.green("\u2705"):D.red("\u274C");if(console.log(D.gray(`${j} [${I}/${P}] (${f}%) ${L} ${a.durationMs}ms`)),a.status==="failed"){a.reason&&console.log(D.red(` Reason: ${a.reason}`)),a.executionCommand&&console.log(D.gray(` Command: ${a.executionCommand}`));let W=Lt(a.runtimeDetected);W&&a.errorCategory==="setup"&&console.log(D.gray(` Hint: ${W}`));}}};if(_&&R.length>1){let k=0,a=false,L=new Array(S).fill(null).map(async()=>{for(;k<R.length;){if(a&&!M)return;let E=k;k+=1;let N=R[E];await g(N),U.get(N)?.status==="failed"&&(a=true);}});if(await Promise.all(L),!M&&a){let E=false;for(let N of R){let T=U.get(N);if(T){if(T.status==="failed"){E=true;continue}E&&T.status==="skipped"&&(T.reason=T.reason||"stopped after failure");}}}}else for(let k of R){await g(k);let a=U.get(k);if(!M&&a?.status==="failed"){let L=R.slice(R.indexOf(k)+1);for(let E of L){let N=U.get(E);N&&(N.status="skipped",N.reason="stopped after failure");}break}}}let z=[];for(let g of s){let k=U.get(g);k&&z.push(k);}let V=z.filter(g=>g.status==="passed").length,J=z.filter(g=>g.status==="failed").length,b$1=z.filter(g=>g.status==="skipped").length;c({blockId:"workspace.run.execute",status:J>0?"failed":h?"blocked":"succeeded",message:`Workspace run finished: ${V} passed, ${J} failed, ${b$1} skipped`,component:"workspace-run",progress:{completed:P,total:P,percent:100},attributes:{passed:V,failed:J,skipped:b$1,stage:e$1.stage}});let $=e$1.strict===true,me=J>0||$&&v.some(g=>g.status==="fail"||g.status==="warn")?1:0,ee={schemaVersion:"1.0",workspacePath:t,stage:e$1.stage,generatedAt:new Date().toISOString(),durationMs:Date.now()-r,options:{affected:l,blastRadius:c$1,since:l?m:null,parallel:_,maxWorkers:S,continueOnError:M,strict:$,enforceGates:C,scope:i,reusePassed:e$1.reusePassed===true,planOnly:e$1.planOnly===true,runtime:e$1.runtime?.trim()||null},selection:{mode:x,since:l?m:null,scope:i,graphStatus:d$2,expansionDepth:w},gates:{enforced:C,results:v,blocked:!!h,blockingGate:h?.gate},summary:{projectCount:s.length,selectedCount:R.length,passed:V,failed:J,skipped:b$1,exitCode:me},projects:z,enterpriseControls:{jsonReady:true,evidencePath:b}},Se=y.join(t,b);c({blockId:"workspace.run.publish",status:"running",message:"Publishing workspace run evidence",component:"workspace.run"});try{await e(t,ee),c({blockId:"workspace.run.publish",status:"succeeded",message:"Workspace run evidence published",component:"workspace.run"}),d$1({workspacePath:t,relativePath:b,blockId:"workspace.run.publish"});}catch(g){throw c({blockId:"workspace.run.publish",status:"failed",message:g instanceof Error?g.message:"Workspace run evidence publish failed",component:"workspace.run"}),g}return e$1.json||(h&&(console.log(D.red(`\u274C Workspace run blocked by ${h.gate}`)),console.log(D.gray(` ${h.summary}`))),console.log(D.cyan(`Workspace run (${e$1.stage}) => passed: ${V}, failed: ${J}, skipped: ${b$1}`)),console.log(D.gray(`Report: ${Se}`))),ee}export{It as a,Er as b};
|
package/dist/chunk-3RNWBFRP.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-FIK343LI.js';import {c as c$1}from'./chunk-KDVNRNDU.js';import {l,q}from'./chunk-G5UCEXP6.js';import {f,g,h as h$2}from'./chunk-SZHRPELL.js';import {a as a$3}from'./chunk-VWBWDDU2.js';import {i,h as h$1,d,b as b$1,a as a$2,c as c$2,k as k$2}from'./chunk-BLEIUQL6.js';import {b as b$3}from'./chunk-VN2MKTQO.js';import {a}from'./chunk-AFIFZTOY.js';import {a as a$4}from'./chunk-XWKGZRHN.js';import {c,d as d$1}from'./chunk-EWZZUQBR.js';import {b as b$2}from'./chunk-25AWHAB5.js';import {h,i as i$1,m,k as k$1,n,o,g as g$1,l as l$1,j,s,e,f as f$1}from'./chunk-ODK4LCEL.js';import {a as a$5}from'./chunk-FB7SCXAZ.js';import {randomUUID,createHash}from'crypto';import P from'path';import T from'fs-extra';var rt=new Set(["committed","rejected","aborted","superseded"]);function p(e,t){if(!e)throw new Error(`Decision protocol violation: ${t}`)}function nt(e){return [...new Set(e)].sort()}function Ge(e,t){return t.digestCanonical(e.effects.map(a=>({id:a.id,status:a.status,key:a.idempotencyKey})))}function ze(e,t,a){p(!e.some(r=>r.id===t),`${a} receipt '${t}' already exists`);}function it(e,t){ze(e.effects,t.id,"effect");let a=e.effects.find(r=>r.idempotencyKey===t.idempotencyKey);return p(!a,`effect idempotency key '${t.idempotencyKey}' was already recorded by '${a?.id}'`),[...e.effects,t]}function st(e,t,a){return ze(e.verifications,t.id,"verification"),p(t.target.effectHeadDigest===Ge(e,a),`verification '${t.id}' does not bind the current effect head`),[...e.verifications,t]}function ot(e){return e.requiredCriteria.every(t=>{let a=e.verifications.filter(r=>r.criterionId===t);return a.length>0&&a.at(-1)?.status==="passed"})}function ct(e$1,t,a){if(t.kind==="created"){p(e$1===null,"created must be the first event");let w=t.payload.references?.[0];p(w,"created must bind an intent artifact");let u=t.payload.references?.filter(I=>I.role==="success-criterion").map(I=>I.artifact)??[];return {schemaVersion:e,id:t.transactionId,purpose:"proof-carrying-change",createdAt:t.occurredAt,updatedAt:t.occurredAt,state:"draft",generation:1,eventCount:t.sequence,eventHeadDigest:t.digest,intent:w,requiredCriteria:nt(u),scope:null,evidence:[],plans:[],authorization:null,effects:[],verifications:[],blockers:[]}}p(e$1,`${t.kind} cannot occur before created`),p(!rt.has(e$1.state),`${t.kind} cannot follow terminal state ${e$1.state}`);let r=e$1.state,n=e$1.scope,i=e$1.evidence,d=e$1.plans,f=e$1.authorization,l=e$1.effects,s=e$1.verifications,o=e$1.blockers,h=e$1.terminalReason;switch(t.kind){case "scope-bound":p(e$1.state==="draft"||e$1.state==="scoped","scope-bound requires draft or scoped state"),p(t.payload.scope,"scope-bound requires scope"),n=t.payload.scope,r="scoped";break;case "evidence-attached":p(e$1.state==="scoped"||e$1.state==="evidence-ready","evidence-attached requires scoped state"),p((t.payload.references?.length??0)>0,"evidence-attached requires references"),i=[...i,...t.payload.references??[]],r="evidence-ready";break;case "plan-attached":p(e$1.state==="evidence-ready","plan-attached requires evidence-ready state"),p((t.payload.references?.length??0)>0,"plan-attached requires references"),d=[...d,...t.payload.references??[]];break;case "authorized":p(e$1.state==="evidence-ready","authorization requires evidence-ready state"),p(t.payload.authorization,"authorized requires a bounded authorization grant"),f=t.payload.authorization,r="authorized";break;case "effect-requested":p(e$1.state==="authorized"||e$1.state==="executing","effect-requested requires authorization"),r="executing";break;case "effect-recorded":p(e$1.state==="authorized"||e$1.state==="executing","effect-recorded requires authorization"),p(t.payload.effect,"effect-recorded requires a receipt"),p(f?.effectClasses.includes(t.payload.effect.effectClass),`effect class '${t.payload.effect.effectClass}' is outside the authorization grant`),l=it(e$1,t.payload.effect),r=t.payload.effect.status==="succeeded"?"executing":"blocked",t.payload.effect.status!=="succeeded"&&(o=[...o,{code:t.payload.effect.status==="uncertain"?"decision.effect.uncertain":"decision.effect.failed",actionable:true,details:t.payload.effect.summary}]);break;case "effect-uncertain":p(e$1.state==="authorized"||e$1.state==="executing","effect-uncertain requires an active execution"),r="blocked",o=[...o,t.payload.blocker??{code:"decision.effect.uncertain",actionable:true}];break;case "verification-started":p(e$1.state==="authorized"||e$1.state==="executing","verification-started requires authorized or executing state"),r="verifying";break;case "verification-recorded":{p(e$1.state==="verifying","verification-recorded requires verifying state"),p(t.payload.verification,"verification-recorded requires a receipt"),s=st(e$1,t.payload.verification,a),r=t.payload.verification.status==="failed"?"blocked":t.payload.verification.status==="inconclusive"?"awaiting-human":"verifying";break}case "human-required":r="awaiting-human";break;case "blocked":p(t.payload.blocker,"blocked requires a structured blocker"),o=[...o,t.payload.blocker],r="blocked";break;case "resumed":p(e$1.state==="blocked"||e$1.state==="awaiting-human","resumed requires a paused state"),p(t.payload.resumeTo,"resumed requires an explicit target state"),r=t.payload.resumeTo,o=[];break;case "committed":p(e$1.state==="verifying","commit requires verifying state"),p(ot(e$1),"every required criterion needs a latest passing receipt"),p(!e$1.effects.some(w=>w.status!=="succeeded"),"all effects must be certainly successful"),r="committed",h=t.payload.reason??t.payload.summary;break;case "rejected":case "aborted":case "superseded":r=t.kind,h=t.payload.reason??t.payload.summary;break;default:throw new Error(`Decision protocol violation: unsupported event ${t.kind}`)}return {...e$1,updatedAt:t.occurredAt,state:r,generation:e$1.generation+1,eventCount:t.sequence,eventHeadDigest:t.digest,scope:n,evidence:i,plans:d,authorization:f,effects:l,verifications:s,blockers:o,...h?{terminalReason:h}:{}}}function qe(e,t,a,r){let n=(t?.sequence??0)+1,i={schemaVersion:f$1,transactionId:e,sequence:n,kind:a.kind,occurredAt:a.occurredAt,actor:a.actor,previousEventDigest:t?.digest??null,payload:a.payload};return {...i,digest:r.digestCanonical(i)}}function L(e,t){p(e.length>0,"at least one event is required");let a=null,r=null;for(let n of e){p(n.schemaVersion===f$1,`unsupported event schema ${n.schemaVersion}`),p(n.sequence===(r?.sequence??0)+1,`event sequence ${n.sequence} is not contiguous`),p(n.previousEventDigest===(r?.digest??null),`event ${n.sequence} has an invalid previous digest`);let{digest:i,...d}=n;p(n.digest===t.digestCanonical(d),`event ${n.sequence} digest is invalid`),p(!r||n.transactionId===r.transactionId,"events cross transaction boundaries"),a=ct(a,n,t),r=n;}return a}function ne(e,t,a){return {schemaVersion:g$1,transactionId:e.id,generatedAt:t,generation:e.generation,eventCount:e.eventCount,eventHeadDigest:e.eventHeadDigest,state:e.state,transactionDigest:a.digestCanonical(e)}}function U(e,t){return Ge(e,t)}var G={digestCanonical:c};function lt(e){let t=e.trim();if(!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(t))throw new Error(`Invalid decision transaction id: ${e}`);return t}function N(e){let a=`.workspai/decisions/${lt(e)}`;return {directory:a,transaction:`${a}/transaction.json`,checkpoint:`${a}/checkpoint.json`,events:`${a}/events.jsonl`,lock:`${a}.lock`}}function ft(e,t){return e.split(/\r?\n/).filter(r=>r.trim().length>0).map((r,n)=>{try{return JSON.parse(r)}catch(i){throw new Error(`Decision event log is corrupt at ${t}:${n+1}: ${i.message}`)}})}async function Ne(e,t){let a=N(t),r=await b$1(e,a.events);return r?ft(await T.readFile(r,"utf8"),r):[]}function We(e,t){let a=N(t);return {directory:a$2(e,a.directory),transaction:a$2(e,a.transaction),checkpoint:a$2(e,a.checkpoint),events:a$2(e,a.events)}}async function gt(e,t,a$1,r){let n=N(t.id),i=ne(t,r,G);for(let[d,f]of a$1.entries())a(f,"contracts/workspace-intelligence/decision-event.v1.json",`Decision event ${d+1}`);return b$3(n.transaction,t),b$3(n.checkpoint,i),await k$2(e,n.events,`${a$1.map(d=>JSON.stringify(d)).join(`
|
|
2
|
-
`)}
|
|
3
|
-
`),await h$1(e,n.transaction,t),await h$1(e,n.checkpoint,i),{transaction:t,checkpoint:i,events:a$1,paths:We(e,t.id)}}async function Me(e){let t=N(e.transactionId),a=a$2(e.workspacePath,t.lock);return a$4(a,async()=>{let r=await Ne(e.workspacePath,e.transactionId),n=r.at(-1)??null;if((n?.digest??null)!==e.expectedHeadDigest)throw new Error(`Decision transaction head changed: expected ${e.expectedHeadDigest??"<empty>"}, observed ${n?.digest??"<empty>"}`);r.length>0&&L(r,G);let i=qe(e.transactionId,n,e.event,G),d=[...r,i],f=L(d,G);return gt(e.workspacePath,f,d,e.event.occurredAt)},{purpose:`decision:${e.transactionId}`,timeoutMs:3e4,staleMs:6e4})}async function Be(e,t){let a=await Ne(e,t);if(a.length===0)throw new Error(`Decision transaction not found: ${t}`);let r=L(a,G),n=ne(r,r.updatedAt,G);return {transaction:r,checkpoint:n,events:a,paths:We(e,t)}}function W(e){return N(e).directory}var oe={digestCanonical:c},pt="workspai.deleted-artifact-tombstone.v1";function ut(e){let t=e.trim();if(!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(t))throw new Error(`Invalid proof-carrying change id: ${e}`);return t}function E(e){let a=`.workspai/changes/${ut(e)}`;return {directory:a,lease:`${a}/lease.json`,prediction:`${a}/predicted-overlay.json`,actualOverlay:`${a}/actual-overlay.json`,surprises:`${a}/architecture-surprises.json`,workspaceVerification:`${a}/verification/workspace-verify.json`,capsule:`${a}/capsule.json`,privateBaselineGraph:`${a}/private/baseline-graph.json`}}function mt(e,t){return {kind:e,id:t}}function x(e){return {role:e.role,artifact:e.artifact,schemaVersion:e.schemaVersion,digest:{algorithm:"sha256",semantics:e.semantics??"canonical-json-v1",value:e.value}}}async function A(e,t){let a=await b$1(e,t);return a?await T.readJson(a):null}async function Fe(e,t){let a=await d(e,C(t));return !a||!(await T.stat(a).catch(()=>null))?.isFile()?null:createHash("sha256").update(await T.readFile(a)).digest("hex")}async function yt(e,t){let a=new Map;await Promise.all(t.proofs.map(async n=>{let i=C(n.artifact),d=a.get(i);d||(d=Fe(e,i),a.set(i,d)),await d;}));let r=Object.fromEntries((await Promise.all([...a.entries()].map(async([n,i])=>[n,await i]))).filter(n=>typeof n[1]=="string"));return {...t,pccArtifactContentHashes:r}}async function wt(e){let a=(await A(e,s.workspaceContract.artifactPath))?.workspace?.name;if(typeof a=="string"&&a.trim())return a.trim();let r=await A(e,".workspai/workspace.json"),n=r?.workspace_name??r?.name;return typeof n=="string"&&n.trim()?n.trim():P.basename(e)}async function ce(e,t){let a=await c$2(e,t.artifact);if(!a)return false;if(t.digest.semantics==="raw-bytes-v1"){let i=await T.readFile(a);return createHash("sha256").update(i).digest("hex")===t.digest.value}let r=await T.readJson(a).catch(()=>null);return r?(t.digest.semantics==="workspace-model-structural-v1"?d$1(r):c(r))===t.digest.value:false}function Je(e){return c({schemaVersion:pt,artifact:C(e),deleted:true})}function vt(e){let t=C(e.artifact);if(!t||t==="."||t===".."||t.startsWith("../"))throw new Error(`Deleted artifact identity must be a contained relative path: ${e.artifact}`);return {artifact:t,observedAt:e.observedAt??new Date().toISOString(),digest:{algorithm:"sha256",semantics:"deletion-tombstone-v1",value:Je(t)}}}async function Ye(e,t){if(t.digest.algorithm!=="sha256"||t.digest.semantics!=="deletion-tombstone-v1"||t.digest.value!==Je(t.artifact))return false;let a=await d(e,t.artifact);return a!==null&&!await T.pathExists(a)}async function kt(e,t){let a=await A(e,E(t).lease);if(!a||a.schemaVersion!==h)throw new Error(`Architecture lease is missing or unsupported for ${t}.`);if(a.changeId!==t)throw new Error(`Architecture lease binding failed for ${t}.`);return a}async function J(e){let t=await a$3(e);if(t.status==="miss")throw new Error(`A current canonical Model and Graph are required (${t.reason}). Run workspai workspace intelligence run --for-agent generic --strict --json.`);return t}function Ct(e,t,a){return c({modelHash:e,graphHash:t,inputHash:a})}function Y(e){let t=d$1(e.model),a=c(e.graph),r=e.graph.source.inputs?.hash;if(!r)throw new Error("The canonical Graph has no live input fingerprint.");return {modelHash:t,graphHash:a,inputHash:r,generation:Ct(t,a,r)}}async function de(e,t){let a=await J(e),r=Y(a);if(r.generation!==t.generation)throw new Error(`Architecture lease ${t.changeId} is stale. Expected generation ${t.generation}, observed ${r.generation}. Abort or begin a new change from current evidence.`);return a}function v(e,t,a,r,n=new Date().toISOString()){return {kind:e,payload:t,occurredAt:n,actor:mt(a,r)}}async function k(e,t,a,r){return Me({workspacePath:e,transactionId:a,expectedHeadDigest:t?.transaction.eventHeadDigest??null,event:r})}function b(e,t,a){return `${e}\0${t}\0${a}`}function It(e){let t=[];for(let[a,r]of [["entity",e.entities],["relation",e.relations],["proof",e.proofs]])t.push(...r.added.map(n=>({operation:"add",targetKind:a,targetId:n.id}))),t.push(...r.removed.map(n=>({operation:"remove",targetKind:a,targetId:n.id}))),t.push(...r.changed.map(n=>({operation:"change",targetKind:a,targetId:n.id})));return t.push(...e.changedArtifacts.map(a=>({operation:"change",targetKind:"artifact",targetId:a}))),t.sort((a,r)=>b(a.operation,a.targetKind,a.targetId).localeCompare(b(r.operation,r.targetKind,r.targetId)))}function Pt(e,t){let a=new Set(t.filter(s=>s.targetKind==="artifact").map(s=>C(s.targetId)));if(a.size===0)return new Set;let r=new Set,n=new Set,i=(s,o)=>{a.has(C(o.artifact))&&(n.add(o.id),r.add(b(s,"proof",o.id)));};e.proofs.added.forEach(s=>i("add",s)),e.proofs.removed.forEach(s=>i("remove",s)),e.proofs.changed.forEach(s=>{let o=s.after??s.before;o&&i("change",o);});let d=new Set,f=(s,o)=>{o.proofIds.some(h=>n.has(h))&&(d.add(o.id),r.add(b(s,"entity",o.id)));};e.entities.added.forEach(s=>f("add",s)),e.entities.removed.forEach(s=>f("remove",s)),e.entities.changed.forEach(s=>{let o=s.after??s.before;o&&f("change",o);});let l=(s,o)=>{!o.proofIds.some(h=>n.has(h))&&!d.has(o.from)&&!d.has(o.to)||r.add(b(s,"relation",o.id));};return e.relations.added.forEach(s=>l("add",s)),e.relations.removed.forEach(s=>l("remove",s)),e.relations.changed.forEach(s=>{let o=s.after??s.before;o&&l("change",o);}),r}function bt(e){let t=e.prediction?.operations.map(o=>({operation:o.operation,targetKind:o.targetKind,targetId:o.targetId}))??[],a=It(e.actual),r=new Set(t.map(o=>b(o.operation,o.targetKind,o.targetId))),n=new Set(a.map(o=>b(o.operation,o.targetKind,o.targetId))),i=Pt(e.actual,t),d=a.filter(o=>r.has(b(o.operation,o.targetKind,o.targetId))||i.has(b(o.operation,o.targetKind,o.targetId))),f=a.filter(o=>!r.has(b(o.operation,o.targetKind,o.targetId))&&!i.has(b(o.operation,o.targetKind,o.targetId))),l=t.filter(o=>!n.has(b(o.operation,o.targetKind,o.targetId))),s=e.prediction?f.length===0&&l.length===0&&i.size===0?"exact":f.length===0?"within-expectation":"surprising":"no-prediction";return {schemaVersion:j,changeId:e.changeId,generatedAt:e.generatedAt,prediction:e.predictionReference,actual:e.actualReference,matched:d,unpredicted:f,missing:l,summary:{predicted:t.length,actual:a.length,matched:d.length,unpredicted:f.length,missing:l.length,verdict:s}}}async function ie(e){let t=await A(e.workspacePath,e.relativePath);return t?x({role:e.role,artifact:e.relativePath,schemaVersion:e.schemaVersion,value:c(t)}):null}function At(e){let{integrity:t,...a}=e;return a}async function le(e){let t=E(e.lease.changeId),[a,r,n]=await Promise.all([ie({workspacePath:e.workspacePath,relativePath:t.prediction,role:"prediction",schemaVersion:i$1}),ie({workspacePath:e.workspacePath,relativePath:t.actualOverlay,role:"actual-architecture-overlay",schemaVersion:a$5}),ie({workspacePath:e.workspacePath,relativePath:t.surprises,role:"architecture-surprises",schemaVersion:j})]),i=x({role:"decision-transaction",artifact:`${W(e.lease.changeId)}/transaction.json`,schemaVersion:e.record.transaction.schemaVersion,value:c(e.record.transaction)}),d=e.record.transaction.effects.flatMap(g=>g.artifacts),f=e.record.transaction.effects.flatMap(g=>g.deletedArtifacts??[]),l=e.record.transaction.verifications.flatMap(g=>g.artifacts),s=await A(e.workspacePath,t.actualOverlay),o=s?!se(s):false,h=[{id:"intent-bound",status:"passed",summary:"The transaction is hash-bound to its immutable Goal Pack."},{id:"baseline-pinned",status:"passed",summary:"The architecture lease pins exact Model, Graph, and live-input identities."},{id:"effects-receipted",status:e.record.transaction.effects.length>0&&e.record.transaction.effects.every(g=>g.status==="succeeded")||e.record.transaction.effects.length===0&&o?"passed":e.record.transaction.effects.length===0?"pending":"failed",summary:e.record.transaction.effects.length===0&&o?"Fresh Graph observation proves this was a no-effect change.":`${e.record.transaction.effects.length} typed effect receipt(s) are bound to the transaction ledger.`},{id:"architecture-reobserved",status:r?"passed":"pending",summary:r?"The actual architecture delta was derived from a fresh canonical Graph.":"No post-effect architecture overlay has been observed yet."},{id:"independently-verified",status:e.record.transaction.state==="committed"?"passed":e.record.transaction.verifications.some(g=>g.status==="failed")?"failed":"pending",summary:`${e.record.transaction.verifications.length} independent verification receipt(s) are recorded.`}],w=await A(e.workspacePath,t.surprises),u=[...e.record.transaction.effects.length===0&&s&&se(s)?["No typed effect receipt explains the observed architecture generation."]:[],...w?.summary.unpredicted?[`${w.summary.unpredicted} actual architecture operation(s) were not predicted.`]:[],...e.record.transaction.blockers.map(g=>g.details??g.code)],I=e.record.transaction.state==="committed"?"sealed":e.record.transaction.state==="aborted"?"aborted":e.record.transaction.state==="blocked"||e.record.transaction.state==="awaiting-human"?"blocked":e.record.transaction.state==="verifying"&&e.record.transaction.verifications.some(g=>g.status==="passed")?"verified":"open",c$1={schemaVersion:k$1,changeId:e.lease.changeId,goalId:e.lease.goalId,generatedAt:e.record.transaction.updatedAt,status:I,workspace:e.lease.workspace,scope:e.lease.scope,decision:{transaction:i,eventHeadDigest:e.record.transaction.eventHeadDigest,effectHeadDigest:U(e.record.transaction,oe),state:e.record.transaction.state,generation:e.record.transaction.generation},intent:e.record.transaction.intent,baseline:e.lease.baseline,prediction:a,actualOverlay:r,surpriseReport:n,effects:d,deletedArtifacts:f,verification:l,assurances:h,remainingUncertainty:[...new Set(u)]};return {...c$1,integrity:{algorithm:"sha256",semantics:"canonical-json-v1",capsuleDigest:c(c$1)}}}async function S(e,t,a){let r=await le({workspacePath:e,lease:t,record:a});return await h$1(e,E(t.changeId).capsule,r),r}function V(e){let t=E(e.lease.changeId),a$1={schemaVersion:l$1,operation:e.operation,changeId:e.lease.changeId,state:e.record.transaction.state,capsule:e.capsule,artifacts:{lease:t.lease,prediction:e.capsule.prediction?.artifact??null,actualOverlay:e.capsule.actualOverlay?.artifact??null,surpriseReport:e.capsule.surpriseReport?.artifact??null,transaction:`${W(e.lease.changeId)}/transaction.json`,events:`${W(e.lease.changeId)}/events.jsonl`,capsule:t.capsule},nextActions:e.nextActions};return a(a$1,"contracts/workspace-intelligence/change-operation-result.v1.json","Proof-Carrying Change operation result"),b$2({kind:"operation.completed",status:e.record.transaction.state==="blocked"||e.record.transaction.state==="awaiting-human"?"blocked":e.record.transaction.state==="aborted"?"cancelled":"succeeded",component:"proof-carrying-change",correlationId:e.lease.changeId,message:`${e.operation}: ${e.record.transaction.state}`,evidenceBindings:[{kind:"artifact",ref:t.capsule,role:"output",provenance:"authoritative"},{kind:"artifact",ref:`${W(e.lease.changeId)}/transaction.json`,role:"subject",provenance:"authoritative"}],attributes:{operation:e.operation,changeId:e.lease.changeId,goalId:e.lease.goalId,decisionState:e.record.transaction.state,assurancePassed:e.capsule.assurances.filter(r=>r.status==="passed").length,assuranceTotal:e.capsule.assurances.length}}),a$1}async function R(e,t){let a=await kt(e,t),r=await Be(e,t);return {lease:a,record:r}}async function sa(e){let t=P.resolve(e.workspacePath),a=await l({workspacePath:t,goalId:e.goalId,validateBindings:true}),r=a.goalPack;if(!r||!a.active)throw new Error("No active Goal Pack is available, or the named Goal is not active.");if(r.state!=="ready-to-plan")throw new Error(`Goal ${r.id} cannot begin a change while its state is ${r.state}.`);let n=await J(t),i$1=Y(n);if(i$1.modelHash!==r.sourceBinding.model.hash||(r.sourceBinding.graph.inputHash?i$1.inputHash!==r.sourceBinding.graph.inputHash:i$1.graphHash!==r.sourceBinding.graph.hash))throw new Error(`Goal ${r.id} is no longer bound to the current architecture generation.`);let d=`change-${r.intent.category}-${randomUUID().replace(/-/g,"").slice(0,16)}`,f=E(d),l$1=new Date().toISOString(),s=await yt(t,n.graph),o=c(s),h$1={schemaVersion:h,changeId:d,goalId:r.id,createdAt:l$1,workspace:r.workspace,scope:{kind:r.scope.kind,projects:[...r.scope.projects]},baseline:{model:x({role:"baseline-model",artifact:r.sourceBinding.model.artifact,schemaVersion:r.sourceBinding.model.schemaVersion,value:r.sourceBinding.model.hash,semantics:"workspace-model-structural-v1"}),graph:{...x({role:"baseline-graph",artifact:r.sourceBinding.graph.artifact,schemaVersion:r.sourceBinding.graph.schemaVersion,value:i$1.graphHash}),inputHash:i$1.inputHash}},generation:i$1.generation,semantics:"optimistic-generation-guard",privateMaterialization:{artifact:f.privateBaselineGraph,role:"hash-bound-baseline-cache",portable:false,authoritative:false,digest:{algorithm:"sha256",semantics:"canonical-json-v1",value:o}}};await i(t,f.lease,[{relativePath:f.privateBaselineGraph,payload:s},{relativePath:f.lease,payload:h$1}]);let w=e.actorKind??"cli",u=e.actorId??"workspai-change",I=x({role:"intent",artifact:a.active.goalPack,schemaVersion:r.schemaVersion,value:c(r)}),c$1=r.successCriteria.map(j=>x({role:"success-criterion",artifact:j.id,schemaVersion:"workspai.goal-success-criterion.v1",value:c(j)})),g=await k(t,null,d,v("created",{summary:`Begin proof-carrying change for ${r.id}.`,references:[I,...c$1]},w,u,l$1));g=await k(t,g,d,v("scope-bound",{summary:"Bind immutable Goal scope.",scope:h$1.scope},w,u)),g=await k(t,g,d,v("evidence-attached",{summary:"Attach exact architecture generation and lease.",references:[h$1.baseline.model,{role:h$1.baseline.graph.role,artifact:h$1.baseline.graph.artifact,schemaVersion:h$1.baseline.graph.schemaVersion,digest:h$1.baseline.graph.digest},x({role:"architecture-lease",artifact:f.lease,schemaVersion:h$1.schemaVersion,value:c(h$1)})]},w,u)),await q({workspacePath:t,goalId:r.id,changeId:d});let D=await S(t,h$1,g);return V({operation:"begin",lease:h$1,record:g,capsule:D,nextActions:[`workspai change predict --change ${d} --file <prediction.json> --json`,`workspai change authorize --change ${d} --effects filesystem,command --json`]})}async function oa(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId);if(await de(e.workspacePath,t),a.transaction.state!=="evidence-ready")throw new Error(`Prediction requires evidence-ready state, observed ${a.transaction.state}.`);let r={...e.prediction,schemaVersion:i$1,changeId:e.changeId,goalId:t.goalId,baselineGeneration:t.generation,nonCanonical:true,proofEligible:false,operations:[...e.prediction.operations].sort((f,l)=>b(f.operation,f.targetKind,f.targetId).localeCompare(b(l.operation,l.targetKind,l.targetId)))};await h$1(e.workspacePath,E(e.changeId).prediction,r);let n=x({role:"noncanonical-prediction",artifact:E(e.changeId).prediction,schemaVersion:r.schemaVersion,value:c(r)}),i=await k(e.workspacePath,a,e.changeId,v("plan-attached",{summary:"Attach an explicitly noncanonical architecture prediction.",references:[n]},e.actorKind??"agent",e.actorId??"workspai-agent")),d=await S(e.workspacePath,t,i);return V({operation:"predict",lease:t,record:i,capsule:d,nextActions:[`workspai change authorize --change ${e.changeId} --effects filesystem,command --json`]})}async function ca(e){let{lease:t,record:a$1}=await R(e.workspacePath,e.changeId);if(await de(e.workspacePath,t),a$1.transaction.state!=="evidence-ready")throw new Error(`Plan attachment requires evidence-ready state, observed ${a$1.transaction.state}.`);let r=e.role.trim().toLowerCase();if(!/^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$/.test(r))throw new Error(`Invalid proof-carrying plan role: ${e.role}`);if(!e.schemaVersion.trim())throw new Error("Plan schema version is required.");let n=e.contractPath.replace(/\\/g,"/");if(!n.startsWith("contracts/")||n.split("/").some(l=>l===".."||l==="."))throw new Error(`Plan contract path must resolve inside the published contract root: ${e.contractPath}`);if(!e.payload||typeof e.payload!="object"||e.payload.schemaVersion!==e.schemaVersion)throw new Error("Plan payload schema version does not match its PCC reference.");a(e.payload,n,`${r} plan`);let i=c(e.payload),d=`${E(e.changeId).directory}/plans/${r}-${i}.json`;await h$1(e.workspacePath,d,e.payload);let f=await k(e.workspacePath,a$1,e.changeId,v("plan-attached",{summary:`Attach ${r} execution plan.`,references:[x({role:r,artifact:d,schemaVersion:e.schemaVersion,value:i})]},e.actorKind??"cli",e.actorId??"workspai-plan"));return await S(e.workspacePath,t,f),{changeId:e.changeId,state:f.transaction.state,artifact:d,digest:i}}async function da(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId);if(await de(e.workspacePath,t),e.effectClasses.length===0)throw new Error("Authorization requires at least one effect class.");let r=await k(e.workspacePath,a,e.changeId,v("authorized",{summary:`Authorize bounded effect classes: ${e.effectClasses.join(", ")}.`,authorization:{grantedBy:e.grantedBy,grant:"bounded-effects",effectClasses:[...new Set(e.effectClasses)].sort()}},e.actorKind??"human",e.grantedBy)),n=await S(e.workspacePath,t,r);return V({operation:"authorize",lease:t,record:r,capsule:n,nextActions:[`workspai change effect record --change ${e.changeId} --file <effect-receipt.json> --json`,`workspai change verify --change ${e.changeId} --json`]})}async function la(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId);if(a.transaction.state!=="blocked"&&a.transaction.state!=="awaiting-human")throw new Error(`Resume requires blocked or awaiting-human state, observed ${a.transaction.state}.`);let r=await k(e.workspacePath,a,e.changeId,v("resumed",{summary:e.reason,reason:e.reason,resumeTo:e.resumeTo},"human",e.actorId)),n=await S(e.workspacePath,t,r);return V({operation:"resume",lease:t,record:r,capsule:n,nextActions:e.resumeTo==="verifying"?[`workspai change verification record --change ${e.changeId} --file <verification-receipt.json> --json`]:[`workspai change effect record --change ${e.changeId} --file <effect-receipt.json> --json`]})}async function fa(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId),r=new Set(e.receipt.artifacts.map(f=>C(f.artifact))),n=(e.receipt.deletedArtifacts??[]).map(f=>C(f.artifact));if(new Set(n).size!==n.length)throw new Error("Effect receipt contains duplicate deleted-artifact identities.");if(n.some(f=>r.has(f)))throw new Error("An effect artifact cannot be both present and deleted in one receipt.");if(n.length>0&&e.receipt.status!=="succeeded")throw new Error("Only a succeeded effect may carry deleted-artifact tombstones.");for(let f of e.receipt.artifacts)if(!await ce(e.workspacePath,f))throw new Error(`Effect artifact is missing or corrupt: ${f.artifact}`);for(let f of e.receipt.deletedArtifacts??[])if(!await Ye(e.workspacePath,f))throw new Error(`Deleted effect artifact is present, outside the governed scope, or has an invalid tombstone: ${f.artifact}`);let i=await k(e.workspacePath,a,e.changeId,v("effect-recorded",{summary:e.receipt.summary,effect:e.receipt},e.actorKind??"agent",e.actorId??"workspai-agent")),d=await S(e.workspacePath,t,i);return V({operation:"effect-record",lease:t,record:i,capsule:d,nextActions:i.transaction.state==="blocked"?[`workspai change status --change ${e.changeId} --json`]:[`workspai change verify --change ${e.changeId} --json`]})}async function ga(e){let t=P.resolve(e.workspacePath),{lease:a,record:r}=await R(t,e.changeId);if(!r.transaction.requiredCriteria.includes(e.receipt.criterionId))throw new Error(`Verification criterion '${e.receipt.criterionId}' is outside the immutable Goal contract.`);let n=await J(t),i=E(e.changeId),[d,f]=await Promise.all([A(t,i.actualOverlay),A(t,i.surprises)]),l=r.transaction.verifications.some(c=>c.criterionId==="workspace-verify"&&c.status==="passed");if(!d||!f||!l)throw new Error("Domain verification can be admitted only after change verify re-observes the Graph and records a passing Workspace Verify receipt.");let s=Y(n),o=U(r.transaction,oe);if(e.receipt.target.modelHash!==s.modelHash||e.receipt.target.graphHash!==s.graphHash||e.receipt.target.effectHeadDigest!==o)throw new Error("Verification receipt does not target the current Model, Graph, and effect head.");for(let c of e.receipt.artifacts)if(!await ce(t,c))throw new Error(`Verification artifact is missing or corrupt: ${c.artifact}`);let h=e.actorKind??"ci",w=e.actorId??"workspai-verifier",u=r;if(u.transaction.state==="blocked"){if(!u.transaction.blockers.every(g=>g.code==="change.verification.criteria_missing"))throw new Error("The change is blocked by a condition that a verification receipt cannot resume.");u=await k(t,u,e.changeId,v("resumed",{summary:"Resume to admit a missing verification receipt.",resumeTo:"verifying"},h,w));}else if(u.transaction.state!=="verifying")throw new Error(`Verification receipt requires verifying or criteria-blocked state; observed ${u.transaction.state}.`);u=await k(t,u,e.changeId,v("verification-recorded",{summary:e.receipt.summary,verification:e.receipt},h,w)),u.transaction.state==="verifying"&&u.transaction.requiredCriteria.every(g=>u.transaction.verifications.filter(j=>j.criterionId===g).at(-1)?.status==="passed")&&(u=await k(t,u,e.changeId,v("committed",{summary:"Seal the independently verified proof-carrying change."},h,w)));let I=await S(t,a,u);return V({operation:"verification-record",lease:a,record:u,capsule:I,nextActions:u.transaction.state==="committed"?[`workspai change capsule validate --change ${e.changeId} --json`]:[`workspai change status --change ${e.changeId} --json`]})}function F(e,t,a,r="verification"){return x({role:r,artifact:e,schemaVersion:t,value:c(a)})}function se(e){return e.summary.entityAdds+e.summary.entityRemovals+e.summary.entityChanges+e.summary.relationAdds+e.summary.relationRemovals+e.summary.relationChanges+e.summary.proofAdds+e.summary.proofRemovals+e.summary.proofChanges>0}function C(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Et(e){if(e.scope.kind==="workspace")return e.overlay;let t=new Set(e.scope.projects),a=c=>!!(c.projectId&&t.has(c.projectId)),r={added:e.overlay.entities.added.filter(a),removed:e.overlay.entities.removed.filter(a),changed:e.overlay.entities.changed.filter(c=>a(c.after??c.before??{}))},n=c=>e.scopedEntityIds.has(c.from)||e.scopedEntityIds.has(c.to),i={added:e.overlay.relations.added.filter(n),removed:e.overlay.relations.removed.filter(n),changed:e.overlay.relations.changed.filter(c=>{let g=c.after??c.before;return !!(g&&n(g))})},d=new Set([...r.added.flatMap(c=>c.proofIds),...r.removed.flatMap(c=>c.proofIds),...r.changed.flatMap(c=>[...c.before?.proofIds??[],...c.after?.proofIds??[]]),...i.added.flatMap(c=>c.proofIds),...i.removed.flatMap(c=>c.proofIds),...i.changed.flatMap(c=>[...c.before?.proofIds??[],...c.after?.proofIds??[]])]),f=c=>{let g=C(c);return e.projectPrefixes.includes(".")?true:e.projectPrefixes.some(D=>g===D||g.startsWith(`${D}/`))},l=c=>d.has(c.id)||f(c.artifact),s={added:e.overlay.proofs.added.filter(l),removed:e.overlay.proofs.removed.filter(l),changed:e.overlay.proofs.changed.filter(c=>{let g=c.after??c.before;return !!(g&&l(g))})},o=e.overlay.impactedEntityIds.filter(c=>e.scopedEntityIds.has(c)),h=e.overlay.changedArtifacts.filter(f),w=r.removed.length+i.removed.length+s.removed.length,u=w+r.added.length+r.changed.length+i.added.length+i.changed.length+s.added.length+s.changed.length,I=u===0?"none":w>0||o.length>=10?"high":o.length>=5||u>=5?"medium":"low";return {...e.overlay,entities:r,relations:i,proofs:s,impactedEntityIds:o,changedArtifacts:h,summary:{entityAdds:r.added.length,entityRemovals:r.removed.length,entityChanges:r.changed.length,relationAdds:i.added.length,relationRemovals:i.removed.length,relationChanges:i.changed.length,proofAdds:s.added.length,proofRemovals:s.removed.length,proofChanges:s.changed.length,impactedEntities:o.length,changedArtifacts:h.length,risk:I}}}function Le(e){let t=P.normalize(P.resolve(e));return process.platform==="win32"?t.toLowerCase():t}async function Dt(e){let t=new Set(e.receiptedArtifacts.map(C)),a=new Set;for(let n of t){let i=await d(e.workspacePath,n);i&&a.add(Le(i));}let r=[];for(let n of e.changedArtifacts){let i=C(n);if(t.has(i))continue;let d$1=await d(e.workspacePath,i);d$1&&a.has(Le(d$1))||r.push(n);}return r}function Rt(e){let t=C(e.artifact);return e.receiptedArtifacts.has(t)||e.scope.kind==="workspace"||e.projectPrefixes.includes(".")?true:e.projectPrefixes.some(a=>t===a||t.startsWith(`${a}/`))}async function $t(e){let t=C(e.artifact),a=f=>{let l=f.proofs.filter(s=>C(s.artifact)===t);return l.length===0?[]:l.some(s=>!s.contentHash)?null:[...new Set(l.map(s=>s.contentHash))].sort()},r=a(e.baseline),n=a(e.head),i=await Fe(e.workspacePath,t),d=e.baseline.pccArtifactContentHashes?.[t];return d?i===null||i!==d:r&&r.length>0?i===null||!r.includes(i):r&&r.length===0?i!==null||!!n?.length:r===null||n===null?true:c(r)!==c(n)}async function ha(e){let t=P.resolve(e.workspacePath),{lease:a,record:r}=await R(t,e.changeId);if(r.transaction.state!=="authorized"&&r.transaction.state!=="executing")throw new Error(`Verification requires authorized or executing state, observed ${r.transaction.state}.`);e.refresh!==false&&await c$1({workspacePath:t,strict:false,agent:"generic"});let n=await J(t),i=await A(t,a.privateMaterialization.artifact);if(!i||c(i)!==a.privateMaterialization.digest.value)throw new Error(`The hash-bound baseline materialization is missing or corrupt for ${e.changeId}.`);let d=new Date().toISOString(),f$1=n.model.projects.filter(y=>a.scope.projects.includes(y.name)).map(y=>C(y.path).replace(/\/$/u,"")).filter(Boolean),l=Et({overlay:a$1(i,n.graph,new Date(d)),scope:a.scope,projectPrefixes:f$1,scopedEntityIds:new Set([...i.entities,...n.graph.entities].filter(y=>y.projectId&&a.scope.projects.includes(y.projectId)).map(y=>y.id))}),s=E(e.changeId);await h$1(t,s.actualOverlay,l);let o=F(s.actualOverlay,l.schemaVersion,l,"actual-architecture-overlay"),h=await A(t,s.prediction),w=h?F(s.prediction,h.schemaVersion,h,"noncanonical-prediction"):null,u=bt({changeId:e.changeId,generatedAt:d,prediction:h,predictionReference:w,actual:l,actualReference:o});await h$1(t,s.surprises,u);let I=F(s.surprises,u.schemaVersion,u,"architecture-surprises"),c$2=r,g$1=e.actorKind??"cli",D=e.actorId??"workspai-change-verify";if(se(l)&&c$2.transaction.effects.length===0){c$2=await k(t,c$2,e.changeId,v("blocked",{summary:"Observed architecture change has no typed effect receipt.",blocker:{code:"change.effect_receipt.missing",actionable:true,details:"Record the actual mutation effect before verification can claim causality."}},g$1,D));let y=await S(t,a,c$2);return V({operation:"verify",lease:a,record:c$2,capsule:y,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Record missing effect receipt" --json`]})}let j=c$2.transaction.effects.filter(y=>y.status==="succeeded").flatMap(y=>[...y.artifacts.map(H=>H.artifact),...(y.deletedArtifacts??[]).map(H=>H.artifact)]),Xe=new Set(j.map(C)),Qe=(await Promise.all(l.changedArtifacts.map(async y=>({artifact:y,contentChanged:await $t({workspacePath:t,artifact:y,baseline:i,head:n.graph})})))).filter(({artifact:y,contentChanged:H})=>H&&Rt({artifact:y,scope:a.scope,projectPrefixes:f$1,receiptedArtifacts:Xe})).map(({artifact:y})=>y),ge=await Dt({workspacePath:t,changedArtifacts:Qe,receiptedArtifacts:j});if(ge.length>0){c$2=await k(t,c$2,e.changeId,v("blocked",{summary:"Observed architecture artifacts are not covered by typed effect receipts.",blocker:{code:"change.effect_receipt.coverage_missing",actionable:true,details:`Uncovered artifacts: ${ge.slice(0,20).join(", ")}`}},g$1,D));let y=await S(t,a,c$2);return V({operation:"verify",lease:a,record:c$2,capsule:y,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Cover observed artifacts" --json`]})}c$2=await k(t,c$2,e.changeId,v("verification-started",{summary:"Begin independent post-effect verification."},g$1,D));let Ze=await f({workspacePath:t}),et=await g(Ze,t),he=P.relative(t,et).split(P.sep).join("/"),X=await A(t,he);if(!X)throw new Error(`Workspace Verify evidence was not persisted at ${he}.`);await h$1(t,s.workspaceVerification,X);let M=await A(t,s.workspaceVerification);if(!M)throw new Error(`Change-scoped Workspace Verify evidence was not persisted at ${s.workspaceVerification}.`);let K=h$2(X,{strict:e.strict===true}),pe=Y(n),ue={id:`verify-workspace-${c({generatedAt:d,verify:M,gate:K}).slice(0,16)}`,criterionId:"workspace-verify",status:K.passed?"passed":"failed",summary:K.passed?`Workspace Verify passed in ${K.mode} mode.`:`Workspace Verify blocked in ${K.mode} mode: ${K.reasons.join("; ")}`,target:{modelHash:pe.modelHash,graphHash:pe.graphHash,effectHeadDigest:U(c$2.transaction,oe)},artifacts:[F(s.workspaceVerification,M.schemaVersion,M),o,I],observedAt:d};if(c$2=await k(t,c$2,e.changeId,v("verification-recorded",{summary:ue.summary,verification:ue},g$1,D)),c$2.transaction.state==="verifying"){let y=c$2.transaction.requiredCriteria.filter(H=>c$2.transaction.verifications.filter(at=>at.criterionId===H).at(-1)?.status!=="passed");y.length>0?c$2=await k(t,c$2,e.changeId,v("blocked",{summary:"Required outcome verification is incomplete.",blocker:{code:"change.verification.criteria_missing",actionable:true,details:`Missing passing receipts: ${y.join(", ")}`}},g$1,D)):c$2=await k(t,c$2,e.changeId,v("committed",{summary:"Seal the independently verified proof-carrying change."},g$1,D));}let tt=await S(t,a,c$2);return V({operation:"verify",lease:a,record:c$2,capsule:tt,nextActions:c$2.transaction.state==="committed"?[`workspai change capsule validate --change ${e.changeId} --json`]:[`workspai change status --change ${e.changeId} --json`]})}async function pa(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId),r=await le({workspacePath:e.workspacePath,lease:t,record:a});return V({operation:e.operation??"status",lease:t,record:a,capsule:r,nextActions:a.transaction.state==="evidence-ready"?[`workspai change authorize --change ${e.changeId} --effects filesystem,command --json`]:a.transaction.state==="authorized"||a.transaction.state==="executing"?[`workspai change verify --change ${e.changeId} --json`]:[]})}async function ua(e){let t=P.resolve(e.workspacePath),a$1=await b$1(t,".workspai/changes","directory"),n=(a$1?await T.readdir(a$1,{withFileTypes:true}):[]).filter(l=>l.isDirectory()&&/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(l.name)).map(l=>l.name).sort(),i=[],d=null;for(let l of n)try{let{lease:s,record:o}=await R(t,l);d??=s.workspace.name;let h=await le({workspacePath:t,lease:s,record:o}),w=await fe({workspacePath:t,changeId:l}),u=o.transaction.blockers.map(c=>c.details??c.code),I=h.status==="blocked"?h.assurances.filter(c=>c.status==="failed").map(c=>`${c.id}: ${c.summary}`):[];i.push({changeId:l,goalId:s.goalId,state:o.transaction.state,status:h.status,createdAt:o.transaction.createdAt,updatedAt:o.transaction.updatedAt,scope:s.scope,assurance:{passed:h.assurances.filter(c=>c.status==="passed").length,total:h.assurances.length},blockers:[...new Set([...u,...I])],capsuleArtifact:E(l).capsule,valid:w.valid,errors:w.errors});}catch(s){i.push({changeId:l,goalId:null,state:null,status:"invalid",createdAt:null,updatedAt:null,scope:null,assurance:{passed:0,total:5},blockers:[],capsuleArtifact:E(l).capsule,valid:false,errors:[s instanceof Error?s.message:String(s)]});}i.sort((l,s)=>(s.updatedAt??"").localeCompare(l.updatedAt??"")||l.changeId.localeCompare(s.changeId));let f={schemaVersion:m,generatedAt:new Date().toISOString(),workspace:{name:d??await wt(t)},changes:i,summary:{total:i.length,open:i.filter(l=>l.status==="open"||l.status==="verified").length,blocked:i.filter(l=>l.status==="blocked").length,sealed:i.filter(l=>l.status==="sealed").length,aborted:i.filter(l=>l.status==="aborted").length,invalid:i.filter(l=>!l.valid).length}};return a(f,"contracts/workspace-intelligence/proof-carrying-change-list.v1.json","Proof-Carrying Change list"),f}async function ma(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId),r=await k(e.workspacePath,a,e.changeId,v("aborted",{summary:e.reason,reason:e.reason},"human",e.actorId)),n=await S(e.workspacePath,t,r);return V({operation:"abort",lease:t,record:r,capsule:n,nextActions:[]})}async function fe(e){let t=E(e.changeId),a$1=await A(e.workspacePath,t.capsule);if(!a$1)throw new Error(`Proof-carrying change capsule not found: ${e.changeId}`);let r=[];a$1.schemaVersion!==k$1&&r.push(`Unsupported capsule schema: ${a$1.schemaVersion}`),a$1.changeId!==e.changeId&&r.push("Capsule change binding does not match."),c(At(a$1))!==a$1.integrity.capsuleDigest&&r.push("Capsule integrity digest does not match its canonical content.");let{lease:n$1,record:i}=await R(e.workspacePath,e.changeId),d=i.transaction.evidence.find(s=>s.role==="architecture-lease");(!d||d.digest.value!==c(n$1))&&r.push("Architecture lease does not match the decision-ledger evidence binding."),(n$1.goalId!==a$1.goalId||n$1.generation!==c({modelHash:n$1.baseline.model.digest.value,graphHash:n$1.baseline.graph.digest.value,inputHash:n$1.baseline.graph.inputHash}))&&r.push("Architecture lease identity or generation binding is invalid."),i.transaction.eventHeadDigest!==a$1.decision.eventHeadDigest&&r.push("Capsule does not bind the current decision event head."),c(i.transaction)!==a$1.decision.transaction.digest.value&&r.push("Decision transaction projection digest does not match the capsule.");let f=await A(e.workspacePath,n$1.privateMaterialization.artifact);(!f||c(f)!==n$1.privateMaterialization.digest.value)&&r.push("Hash-bound baseline materialization is missing or corrupt.");for(let s of [a$1.intent,a$1.decision.transaction,a$1.prediction,a$1.actualOverlay,a$1.surpriseReport,...a$1.effects,...a$1.verification].filter(o=>!!o))await ce(e.workspacePath,s)||r.push(`Referenced artifact is missing or corrupt: ${s.artifact}`);for(let s of a$1.deletedArtifacts??[])await Ye(e.workspacePath,s)||r.push(`Deleted artifact tombstone is invalid or the artifact exists again: ${s.artifact}`);let l={schemaVersion:n,changeId:e.changeId,validatedAt:new Date().toISOString(),valid:r.length===0,errors:r,capsule:a$1};return a(l,"contracts/workspace-intelligence/proof-carrying-change-capsule-validation.v1.json","Proof-Carrying Change capsule validation"),l}async function ya(e){let t=await fe(e);if(!t.valid)throw new Error(`Cannot export an invalid capsule: ${t.errors.join("; ")}`);let a$1=P.resolve(e.workspacePath),r=P.resolve(a$1,e.outputPath),n=P.relative(a$1,r);if(n===".."||n.startsWith(`..${P.sep}`)||P.isAbsolute(n))throw new Error("Capsule export path must remain inside the workspace.");let i=n.split(P.sep).join("/"),d=await h$1(a$1,i,t.capsule),f={schemaVersion:o,changeId:e.changeId,outputPath:d,validation:t};return a(f,"contracts/workspace-intelligence/proof-carrying-change-capsule-export.v1.json","Proof-Carrying Change capsule export"),f}function wa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Prediction input must be a JSON object.");let t=e;if(!Array.isArray(t.operations)||!Array.isArray(t.assumptions))throw new Error("Prediction input requires operations[] and assumptions[].");let a=new Set(["add","remove","change"]),r=new Set(["entity","relation","proof","artifact"]),n=new Set(["high","medium","low"]);for(let d of t.operations)if(!d||!a.has(d.operation)||!r.has(d.targetKind)||typeof d.targetId!="string"||d.targetId.trim().length===0||typeof d.rationale!="string"||!n.has(d.confidence))throw new Error("Prediction contains an invalid operation.");let i=t.predictedRisk;if(!i||!["none","low","medium","high"].includes(i))throw new Error("Prediction requires predictedRisk: none, low, medium, or high.");return {schemaVersion:i$1,changeId:t.changeId??"change-placeholder",goalId:t.goalId??"goal-placeholder",generatedAt:t.generatedAt??new Date().toISOString(),baselineGeneration:t.baselineGeneration??"pending-binding",nonCanonical:true,proofEligible:false,operations:t.operations,assumptions:t.assumptions.filter(d=>typeof d=="string"),predictedRisk:i}}function va(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Effect receipt input must be a JSON object.");let t=e;if(typeof t.id!="string"||!["filesystem","command","configuration","dependency","external"].includes(String(t.effectClass))||!["succeeded","failed","uncertain"].includes(String(t.status))||typeof t.summary!="string"||typeof t.observedAt!="string"||typeof t.idempotencyKey!="string"||!Array.isArray(t.artifacts))throw new Error("Effect receipt is missing required typed fields.");if(t.deletedArtifacts!==void 0&&(!Array.isArray(t.deletedArtifacts)||t.deletedArtifacts.some(r=>!r||typeof r.artifact!="string"||r.observedAt!==void 0&&typeof r.observedAt!="string"||r.digest!==void 0&&(r.digest.algorithm!=="sha256"||r.digest.semantics!=="deletion-tombstone-v1"||typeof r.digest.value!="string"))))throw new Error("Effect receipt contains an invalid deleted-artifact tombstone.");let a=t;return {...a,...a.deletedArtifacts?{deletedArtifacts:a.deletedArtifacts.map(r=>r.digest?r:vt({artifact:r.artifact,observedAt:r.observedAt??a.observedAt}))}:{}}}function ka(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Verification receipt input must be a JSON object.");let t=e;if(typeof t.id!="string"||typeof t.criterionId!="string"||!["passed","failed","inconclusive"].includes(String(t.status))||typeof t.summary!="string"||typeof t.observedAt!="string"||!t.target||typeof t.target.modelHash!="string"||typeof t.target.graphHash!="string"||typeof t.target.effectHeadDigest!="string"||!Array.isArray(t.artifacts))throw new Error("Verification receipt is missing required typed fields.");return t}function Ca(e,t){return e.decision.eventHeadDigest===t.eventHeadDigest&&e.decision.transaction.digest.value===c(t)}async function Ia(e){let t=await fe({workspacePath:e.workspacePath,changeId:e.changeId});if(!t.valid)throw new Error(`Proof-carrying change ${e.changeId} failed capsule validation.`);let{lease:a,record:r}=await R(e.workspacePath,e.changeId);if(a.goalId!==e.goalId||r.transaction.state!=="committed"||t.capsule.status!=="sealed")throw new Error(`Proof-carrying change ${e.changeId} is not a sealed change for ${e.goalId}.`);let n=[...r.transaction.verifications].reverse().find(i=>i.status==="passed");if(!n)throw new Error(`Proof-carrying change ${e.changeId} has no passing verification receipt.`);return {modelHash:n.target.modelHash,graphHash:n.target.graphHash}}
|
|
4
|
-
export{Be as a,vt as b,sa as c,oa as d,ca as e,da as f,la as g,fa as h,ga as i,Dt as j,ha as k,pa as l,ua as m,ma as n,fe as o,ya as p,wa as q,va as r,ka as s,Ca as t,Ia as u};
|