workspai 0.52.2 → 0.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/contracts/artifact-remediation-plan.v1.json +1 -0
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +36 -0
- package/contracts/extension-cli-compatibility.v1.json +24 -2
- package/contracts/pipeline-last-run.v1.json +6 -1
- package/contracts/published-contract-catalog.v1.json +113 -2
- package/contracts/runtime-command-surface.v1.json +216 -5
- package/contracts/studio-card-repair-capabilities.v1.json +378 -0
- package/contracts/workspace-intelligence/workspace-repair-proposal.v1.json +78 -0
- package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +249 -0
- package/contracts/workspace-intelligence-chain.v1.json +6 -0
- package/contracts/workspace-repair-capabilities.v1.json +316 -0
- package/dist/analyze-AAZEJ4FC.js +1 -0
- package/dist/artifact-remediation-plan-CJSPCMWA.js +1 -0
- package/dist/autopilot-release-LZWNQQLY.js +1 -0
- package/dist/chunk-27AXFTKW.js +1 -0
- package/dist/{chunk-OTDGTAZJ.js → chunk-2FJW6GSW.js} +1 -1
- package/dist/chunk-3DONU3DU.js +1 -0
- package/dist/chunk-44VJHNZB.js +1 -0
- package/dist/chunk-5XDPQ3CB.js +1 -0
- package/dist/chunk-7AR5PDLD.js +1 -0
- package/dist/chunk-7KKP7RNB.js +3 -0
- package/dist/chunk-AMB42V2F.js +1 -0
- package/dist/chunk-BYVTHIC3.js +2 -0
- package/dist/chunk-E5YYVFM2.js +1 -0
- package/dist/{chunk-6PBSAAS5.js → chunk-EBKYSDCX.js} +1 -1
- package/dist/chunk-FQLB4BIC.js +7 -0
- package/dist/{chunk-ICLYL3N5.js → chunk-FZCYTRBQ.js} +1 -1
- package/dist/{chunk-ZVOEPWQM.js → chunk-GDU7VP6G.js} +1 -1
- package/dist/chunk-H7P7SSUW.js +75 -0
- package/dist/chunk-HOVJUP7K.js +8 -0
- package/dist/{chunk-MZFSINY7.js → chunk-HRN5J6PW.js} +12 -12
- package/dist/chunk-HY3RMPW5.js +10 -0
- package/dist/chunk-KFKZOPZC.js +1 -0
- package/dist/{chunk-HPWLSLMC.js → chunk-KVUYAYTY.js} +1 -1
- package/dist/chunk-MQ73VS4E.js +2 -0
- package/dist/{chunk-2OIBHUVH.js → chunk-MRFN5ZQP.js} +1 -1
- package/dist/{chunk-4UVGTFOX.js → chunk-NYHVCFBT.js} +1 -1
- package/dist/{chunk-IO54DFWR.js → chunk-OLX6LX77.js} +1 -1
- package/dist/chunk-OUBBBC7T.js +36 -0
- package/dist/{chunk-WJY7ZXVJ.js → chunk-P7K5RHJC.js} +1 -1
- package/dist/chunk-QZ7PNMVP.js +1 -0
- package/dist/chunk-RA24WQLF.js +1 -0
- package/dist/chunk-RMXXK64P.js +4 -0
- package/dist/{chunk-PTTZPDLX.js → chunk-S7Z4DP3P.js} +1 -1
- package/dist/chunk-SJLUE6AY.js +1 -0
- package/dist/chunk-SUV7Y2FH.js +3 -0
- package/dist/chunk-T6JI7GYZ.js +88 -0
- package/dist/chunk-USMLRNZ7.js +5 -0
- package/dist/chunk-WD2XDMGB.js +1 -0
- package/dist/chunk-WIO6L24E.js +2 -0
- package/dist/{chunk-QURMI7ID.js → chunk-WZA5ISAQ.js} +1 -1
- package/dist/chunk-XVRJVKOX.js +1 -0
- package/dist/{create-ESK3CQPK.js → create-R6A7EHQZ.js} +1 -1
- package/dist/{doctor-MYRJ5BFF.js → doctor-KNIYGDM7.js} +1 -1
- package/dist/index.d.ts +92 -23
- package/dist/index.js +246 -244
- package/dist/pipeline-PVCLAQDI.js +5 -0
- package/dist/{project-intelligence-lens-Q4SZDI2N.js → project-intelligence-lens-ZOAWXYC5.js} +1 -1
- package/dist/project-test-coverage-44ZPCOPV.js +1 -0
- package/dist/{verified-goal-23HZPMRK.js → verified-goal-MCSNMA3P.js} +1 -1
- package/dist/{workspace-LSOZM2CG.js → workspace-B53XH35L.js} +1 -1
- package/dist/{workspace-agent-sync-RZBQXCNJ.js → workspace-agent-sync-446AXPHJ.js} +1 -1
- package/dist/{workspace-archive-ZOWQXWJ6.js → workspace-archive-VHUPOBAV.js} +1 -1
- package/dist/{workspace-context-IYJKO5BN.js → workspace-context-XSECHC7O.js} +1 -1
- package/dist/{workspace-contract-AZFISDLS.js → workspace-contract-AYFTZIKM.js} +1 -1
- package/dist/workspace-explain-SZI2WAAD.js +1 -0
- package/dist/workspace-explain-contract-N2XQHAPM.js +1 -0
- package/dist/{workspace-feedback-LIHEWTNV.js → workspace-feedback-WXE7NVMV.js} +1 -1
- package/dist/{workspace-foundation-H5UTAUXQ.js → workspace-foundation-FFNCK5ZD.js} +1 -1
- package/dist/{workspace-graph-stream-KUDOZE73.js → workspace-graph-stream-AJPS45FD.js} +1 -1
- package/dist/{workspace-history-HULG5EFN.js → workspace-history-YY7YRDOH.js} +1 -1
- package/dist/{workspace-intelligence-A4UE4DZK.js → workspace-intelligence-FWRB47EJ.js} +1 -1
- package/dist/{workspace-intelligence-evaluation-AOLGHYHC.js → workspace-intelligence-evaluation-UP2K3L35.js} +1 -1
- package/dist/{workspace-intelligence-runner-VYGSASDP.js → workspace-intelligence-runner-JNCQLUH7.js} +1 -1
- package/dist/workspace-intelligence-runtime-registry-MRSF7RTT.js +1 -0
- package/dist/{workspace-knowledge-graph-LEM6X5CM.js → workspace-knowledge-graph-BMMM2FUE.js} +1 -1
- package/dist/{workspace-mcp-serve-N2QPR7VJ.js → workspace-mcp-serve-COA4FMCA.js} +1 -1
- package/dist/{workspace-model-FJXX3NET.js → workspace-model-MNJOGBPP.js} +1 -1
- package/dist/{workspace-onboarding-IKFISWWY.js → workspace-onboarding-2B7CYZ5H.js} +1 -1
- package/dist/{workspace-readme-E2M35RJH.js → workspace-readme-4S6PJ74A.js} +1 -1
- package/dist/{workspace-registry-summary-HOQ3OBNT.js → workspace-registry-summary-GPJEL7K7.js} +1 -1
- package/dist/workspace-repair-engine-SRWECKZO.js +3 -0
- package/dist/workspace-run-3U77TMKX.js +1 -0
- package/dist/{workspace-verify-32AWCJQG.js → workspace-verify-C6HWHRLJ.js} +1 -1
- package/dist/{workspace-watch-4WVNB26E.js → workspace-watch-DLPHLF5R.js} +1 -1
- package/docs/README.md +2 -0
- package/docs/commands-reference.md +10 -8
- package/docs/contracts/ARTIFACT_CATALOG.md +27 -22
- package/docs/contracts/README.md +3 -0
- package/docs/contracts/RUNTIME_ACCEPTANCE_MATRIX.md +20 -11
- package/docs/doctor-command.md +10 -4
- package/docs/workspace-intelligence-runner.md +2 -1
- package/docs/workspace-knowledge-graph.md +6 -1
- package/docs/workspace-operations.md +3 -1
- package/docs/workspace-repair-engine.md +113 -0
- package/docs/workspace-run.md +17 -14
- package/package.json +3 -2
- package/scripts/enterprise-package-smoke.mjs +9 -6
- package/dist/analyze-J7VNZMDH.js +0 -1
- package/dist/artifact-remediation-plan-2UKY4TKO.js +0 -3
- package/dist/autopilot-release-34H5BSI2.js +0 -1
- package/dist/chunk-23JDMHSD.js +0 -86
- package/dist/chunk-2E6WGUN6.js +0 -1
- package/dist/chunk-3D3PFPP5.js +0 -1
- package/dist/chunk-4D7DIGAB.js +0 -1
- package/dist/chunk-5XJRCP3D.js +0 -36
- package/dist/chunk-62K2H72S.js +0 -1
- package/dist/chunk-7MQZQ4UU.js +0 -1
- package/dist/chunk-AL237TSJ.js +0 -7
- package/dist/chunk-AYHNNPPH.js +0 -8
- package/dist/chunk-B4CPDK6J.js +0 -2
- package/dist/chunk-CZC5P2MF.js +0 -1
- package/dist/chunk-DZ4VKAXB.js +0 -75
- package/dist/chunk-FUPHQOJB.js +0 -1
- package/dist/chunk-GHB6QMQH.js +0 -1
- package/dist/chunk-JIUWK4ML.js +0 -1
- package/dist/chunk-KHEJO3JU.js +0 -4
- package/dist/chunk-LOCPNNSK.js +0 -1
- package/dist/chunk-LPCL4U4L.js +0 -1
- package/dist/chunk-MBRU3VWJ.js +0 -2
- package/dist/chunk-P4OSLAVD.js +0 -3
- package/dist/chunk-Q6CUJ3WF.js +0 -10
- package/dist/chunk-SQTV2OYU.js +0 -4
- package/dist/chunk-ULR66OJR.js +0 -2
- package/dist/chunk-XHRHNVCZ.js +0 -1
- package/dist/pipeline-FOZ46ELQ.js +0 -5
- package/dist/project-test-coverage-A677ZLW3.js +0 -1
- package/dist/workspace-explain-26UGV7L4.js +0 -1
- package/dist/workspace-explain-contract-GIWPCCEF.js +0 -1
- package/dist/workspace-intelligence-runtime-registry-YOQ5GFFJ.js +0 -1
- package/dist/workspace-run-GUW4EOYB.js +0 -1
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import {a as a$3}from'./chunk-KVUYAYTY.js';import {c}from'./chunk-HOVJUP7K.js';import {q}from'./chunk-T6JI7GYZ.js';import {c as c$1}from'./chunk-FPJNWPKU.js';import {a as a$4}from'./chunk-RMXXK64P.js';import {f,e as e$1}from'./chunk-T3GJ7YVG.js';import {a}from'./chunk-MRFN5ZQP.js';import {g}from'./chunk-HRN5J6PW.js';import {d,a as a$2,e as e$2}from'./chunk-WIO6L24E.js';import {a as a$1,e,d as d$1}from'./chunk-44VJHNZB.js';import c$2 from'chalk';import h from'path';import I from'fs-extra';function O(s){return s===0?"pass":s===2?"warn":"fail"}async function G(s){try{let r=I.readJsonSync(s),i=r.policyProfile,o=(Array.isArray(r.projects)?r.projects:[]).flatMap(u=>{let l=u,m=typeof l.name=="string"?l.name:"project",f=Array.isArray(l.issues)?l.issues.filter(p=>typeof p=="string"):[],P=(Array.isArray(l.probes)?l.probes:[]).flatMap(p=>{let g=p;if(g.status!=="fail"&&g.status!=="warn")return [];let y=typeof g.reason=="string"?g.reason.trim():"";return y?[`${m}: ${y}`]:[]});return [...f.map(p=>`${m}: ${p}`),...P]});return {policyProfile:typeof i?.name=="string"?i.name:void 0,blockers:[...new Set(o)].slice(0,12)}}catch{return {blockers:[]}}}function L(s){return s.some(r=>r.status==="fail")?"blocked":s.some(r=>r.status==="warn")?"needs-attention":"ready"}function _(s,r){if(r)return 3;let i=s.some(o=>o.status==="fail"),t=s.some(o=>o.status==="warn");return i?1:t?2:0}function V(s,r){return s===2&&!r?0:s}async function K(s){let r=await g(s,true),i=false;try{let{syncWorkspaceContract:t}=await import('./workspace-contract-AYFTZIKM.js');await t({workspacePath:s}),i=true;}catch{i=false;}return {sync:r,contractSynced:i}}async function J(s={}){let r=h.resolve(s.workspacePath??process.cwd()),i=a(r);if(!i)throw new Error("No Workspai workspace found in current directory or parents");let t=[],o=[],u=false,l,m,f$1,k=Date.now();try{let{sync:e,contractSynced:a}=await K(i),n=e.workspaceFound&&(e.added.length>0||e.skipped>=0)||e.workspaceFound?"pass":"warn";t.push({name:"sync",status:n,durationMs:Date.now()-k,summary:e.workspaceFound?`registry sync complete (${e.added.length} added, ${e.skipped} existing)${a?", contract synced":""}`:"workspace not registered in global registry; contract sync attempted"}),e.workspaceFound||o.push("workspace registry entry missing \u2014 run workspai create workspace or register manually");}catch(e){u=true,t.push({name:"sync",status:"fail",durationMs:Date.now()-k,summary:`sync failed: ${e instanceof Error?e.message:String(e)}`}),o.push("workspace sync stage failed");}let P=Date.now();try{let e=await q({workspace:true,json:true,quiet:true,strict:s.strict===true,ci:s.strict!==true}),a=O(e),n=await d(i,a$1.doctor)??a$2(i,a$1.doctor),d$1=await G(n);t.push({name:"doctor",status:a,durationMs:Date.now()-P,summary:a==="pass"?"doctor workspace passed":a==="warn"?"doctor workspace reported warnings":"doctor workspace did not pass",exitCode:e,evidencePath:n,policyProfile:d$1.policyProfile,blockers:d$1.blockers}),a==="fail"?o.push(...d$1.blockers.length>0?d$1.blockers.map(j=>`doctor: ${j}`):["doctor workspace gate failed"]):a==="warn"&&o.push("doctor workspace reported warnings");}catch(e){u=true,t.push({name:"doctor",status:"fail",durationMs:Date.now()-P,summary:`doctor failed: ${e instanceof Error?e.message:String(e)}`}),o.push("doctor workspace stage failed");}if(s.skipAnalyze)t.push({name:"analyze",status:"skipped",durationMs:0,summary:"analyze stage skipped"});else {let e=Date.now();try{let a=await a$3({workspacePath:i,json:true,strict:s.strict===true});l=h.isAbsolute(a.enterpriseControls.evidencePath)?a.enterpriseControls.evidencePath:h.join(i,a.enterpriseControls.evidencePath);let n=a.summary.verdict==="blocked"?"fail":a.summary.verdict==="needs-attention"?"warn":"pass";t.push({name:"analyze",status:n,durationMs:Date.now()-e,summary:`analyze verdict: ${a.summary.verdict} (score ${a.summary.score}/100)`,evidencePath:l}),n==="fail"?o.push("analyze reported blocked verdict"):n==="warn"&&o.push("analyze reported needs-attention verdict");}catch(a){u=true,t.push({name:"analyze",status:"fail",durationMs:Date.now()-e,summary:`analyze failed: ${a instanceof Error?a.message:String(a)}`}),o.push("analyze stage failed");}}let p=Date.now();try{let e=await a$4({startPath:i,writeReport:true,skipVerify:s.skipVerify===true});m=e.evidencePath;let a=e.overallStatus==="pass"?"pass":e.overallStatus==="warn"?"warn":"fail";t.push({name:"readiness",status:a,durationMs:Date.now()-p,summary:`readiness overall: ${e.overallStatus}`,evidencePath:e.evidencePath}),a==="fail"?o.push(...e.blockingReasons.map(n=>`readiness: ${n}`)):a==="warn"&&o.push(...e.gates.filter(n=>n.status==="warn").map(n=>`readiness warn: ${n.gate}: ${n.summary}`));}catch(e){u=true,t.push({name:"readiness",status:"fail",durationMs:Date.now()-p,summary:`readiness failed: ${e instanceof Error?e.message:String(e)}`}),o.push("readiness stage failed");}if(s.skipAutopilot)t.push({name:"autopilot",status:"skipped",durationMs:0,summary:"autopilot stage skipped"});else {let e=Date.now(),a=s.autopilotMode??"audit";try{let n=await c({workspacePath:i,mode:a,json:true,skipPipelineStages:true});f$1=n.artifacts.reportPath;let d=n.summary.verdict==="approved"?"pass":n.summary.verdict==="partial"?"warn":"fail";t.push({name:"autopilot",status:d,durationMs:Date.now()-e,summary:`autopilot ${a}: ${n.summary.verdict}`,exitCode:n.summary.exitCode,evidencePath:f$1}),d!=="pass"&&o.push(...n.blockingReasons.slice(0,5));}catch(n){u=true,t.push({name:"autopilot",status:"fail",durationMs:Date.now()-e,summary:`autopilot failed: ${n instanceof Error?n.message:String(n)}`}),o.push("autopilot release stage failed");}}let g=L(t),y=_(t,u),N=h.join(i,e.pipelineLastRun),w={schemaVersion:d$1.pipelineLastRun.schemaVersion,generatedAt:new Date().toISOString(),workspacePath:i,summary:{verdict:g,exitCode:y,stagesPassed:t.filter(e=>e.status==="pass").length,stagesWarn:t.filter(e=>e.status==="warn").length,stagesFailed:t.filter(e=>e.status==="fail").length},stages:t,blockingReasons:[...new Set(o)],artifacts:{reportPath:N,analyzeEvidencePath:l,readinessEvidencePath:m,autopilotEvidencePath:f$1}};if(s.writeReport!==false){let e$3=f(w,{commandId:"workspacePipeline",exitCode:y,generatedAt:w.generatedAt,blockers:w.blockingReasons,runId:e$1()});await e$2(i,e.pipelineLastRun,e$3);}if(s.writeReport!==false&&s.noAgentSync!==true&&process.env.RAPIDKIT_NO_AGENT_SYNC!=="1"&&s.agentSync!==false)try{let{syncWorkspaceAgentGrounding:e}=await import('./workspace-agent-sync-446AXPHJ.js'),a=await e({workspacePath:i,write:true,refreshContext:true,strict:false});w.agentGrounding={indexPath:a.indexPath,writtenFiles:a.writtenFiles,blockers:a.blockers};}catch{}return w}async function ce(s){let r;try{r=await J(s);}catch(t){let o=t instanceof Error?t.message:String(t);s.json?console.log(JSON.stringify(c$1({operation:"pipeline",code:"pipeline.failed",message:o}),null,2)):console.log(c$2.red(`Pipeline failed: ${o}`)),process.exit(1);}if(s.json)console.log(JSON.stringify(r,null,2));else {console.log(c$2.bold.cyan(`
|
|
2
|
+
\u{1F517} Workspai Governance Pipeline
|
|
3
|
+
`)),console.log(c$2.bold(`Workspace: ${c$2.cyan(h.basename(r.workspacePath))}`)),console.log(c$2.gray(`Path: ${r.workspacePath}`)),console.log(c$2.white(`Verdict: ${r.summary.verdict} Exit: ${r.summary.exitCode} (${r.summary.stagesPassed} pass / ${r.summary.stagesWarn} warn / ${r.summary.stagesFailed} fail)`));for(let t of r.stages){let o=t.status==="pass"?c$2.green("PASS"):t.status==="warn"?c$2.yellow("WARN"):t.status==="skipped"?c$2.gray("SKIP"):c$2.red("FAIL");console.log(` - ${t.name}: ${o} ${t.summary}`);}if(r.blockingReasons.length>0){console.log(c$2.bold(`
|
|
4
|
+
Blocking reasons:`));for(let t of r.blockingReasons.slice(0,8))console.log(c$2.gray(` \u2022 ${t}`));}console.log(c$2.gray(`
|
|
5
|
+
Evidence: ${r.artifacts.reportPath}`)),r.agentGrounding?.writtenFiles.length&&console.log(c$2.gray(`Agent grounding: ${r.agentGrounding.writtenFiles.length} file(s) synced (INDEX + AGENTS.md + Copilot/Cursor/Claude hooks)`));}let i=V(r.summary.exitCode,s.strict===true);i!==0&&process.exit(i);}export{V as pipelineProcessExitCode,J as runPipeline,ce as runPipelineCommand};
|
package/dist/{project-intelligence-lens-Q4SZDI2N.js → project-intelligence-lens-ZOAWXYC5.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as PROJECT_CONTEXT_AGENT_SCHEMA_VERSION,b as PROJECT_GROUNDING_MODE_VALUES,d as WORKSPAI_PROJECT_GROUNDING_END,c as WORKSPAI_PROJECT_GROUNDING_START,e as buildProjectContextAgent,h as resolveWorkspaceProjectLensTargets,f as syncProjectIntelligenceLens,g as syncWorkspaceProjectLenses}from'./chunk-
|
|
1
|
+
export{a as PROJECT_CONTEXT_AGENT_SCHEMA_VERSION,b as PROJECT_GROUNDING_MODE_VALUES,d as WORKSPAI_PROJECT_GROUNDING_END,c as WORKSPAI_PROJECT_GROUNDING_START,e as buildProjectContextAgent,h as resolveWorkspaceProjectLensTargets,f as syncProjectIntelligenceLens,g as syncWorkspaceProjectLenses}from'./chunk-H7P7SSUW.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{b as PROJECT_TEST_COVERAGE_ARTIFACT,a as PROJECT_TEST_COVERAGE_SCHEMA,c as collectProjectTestCoverage}from'./chunk-SJLUE6AY.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {c}from'./chunk-JIUWK4ML.js';import {a as a$3}from'./chunk-SQTV2OYU.js';import {c as c$1}from'./chunk-4D7DIGAB.js';import {a as a$2}from'./chunk-KHEJO3JU.js';import {p}from'./chunk-FUPHQOJB.js';import {a as a$4}from'./chunk-GR6442P7.js';import {e,d}from'./chunk-MBRU3VWJ.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {a,b}from'./chunk-62K2H72S.js';import {createHash}from'crypto';import l from'path';import y from'fs-extra';var W="workspai.verified-goal.v1",x=b.verifiedGoalStatus,C=a.verifiedGoalStatus,J="contracts/workspace-intelligence/verified-goal.v1.json",G="contracts/workspace-intelligence/verified-goal-status.v1.json";function A(e){return Array.isArray(e)?`[${e.map(A).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[a])=>t.localeCompare(a)).map(([t,a])=>`${JSON.stringify(t)}:${A(a)}`).join(",")}}`:JSON.stringify(e)}function H(e){return createHash("sha256").update(A(e)).digest("hex")}var te=["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","Pipfile","Pipfile.lock","poetry.lock","uv.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","packages.lock.json","Directory.Packages.props","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deps.edn","project.clj","build.sbt"],ae=new Set(te.map(e=>e.toLowerCase())),se=new Set([".git",".hg",".svn",".workspai",".venv","venv",".tox",".mypy_cache",".pytest_cache","__pycache__","node_modules","vendor","pods","dist","build","out","target","bin","obj","coverage",".coverage",".next",".nuxt",".svelte-kit"]),F=1e5;function ne(e){return ae.has(e.toLowerCase())||/\.(?:csproj|fsproj|vbproj)$/i.test(e)}async function re(e){let t=[e],a=[],s=0;for(;t.length>0;){let o=t.shift();if(o===void 0)break;let i=await y.readdir(o,{withFileTypes:true});if(i.sort((n,r)=>n.name.localeCompare(r.name)),s+=i.length,s>F)throw new Error(`Dependency safety baseline exceeded ${F} filesystem entries under ${e}. Narrow the project boundary before creating this goal.`);for(let n of i){let r=l.join(o,n.name);if(n.isDirectory()){!se.has(n.name.toLowerCase())&&!a$4(n.name)&&t.push(r);continue}n.isFile()&&ne(n.name)&&a.push(r);}}return a}function ie(e){return /^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/i.test(e)?"node":/^(?:pyproject\.toml|requirements\.txt|Pipfile(?:\.lock)?|poetry\.lock|uv\.lock)$/i.test(e)?"python":/^go\.(?:mod|sum)$/i.test(e)?"go":/^Cargo\.(?:toml|lock)$/i.test(e)?"rust":/^(?:pom\.xml|build\.gradle(?:\.kts)?|gradle\.lockfile)$/i.test(e)?"jvm":/^(?:Directory\.Packages\.props|packages\.lock\.json)$/i.test(e)?"dotnet":/^composer\.(?:json|lock)$/i.test(e)?"php":/^Gemfile(?:\.lock)?$/i.test(e)?"ruby":/^mix\.(?:exs|lock)$/i.test(e)?"elixir":/^(?:deps\.edn|project\.clj)$/i.test(e)?"clojure":/^build\.sbt$/i.test(e)?"scala":/\.(?:csproj|fsproj|vbproj)$/i.test(e)?"dotnet":"unknown"}function K(e){try{let t=JSON.parse(e),a={};for(let s of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let o=t[s];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let[i,n]of Object.entries(o))typeof n=="string"&&(a[`${s}:${i}`]=n);}return a}catch{return}}async function U(e,t){let s=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(i=>t.kind==="workspace"||i.name===t.projectName||l.resolve(e,i.path)===l.resolve(t.projectPath??"")),o=new Map;for(let i of s){let n=l.resolve(e,i.path),r=await re(n);for(let c of r){let p=l.basename(c),f=await y.readFile(c,"utf8"),d=l.relative(e,c).split(l.sep).join("/");o.set(d,{path:d,ecosystem:ie(p),sha256:createHash("sha256").update(f).digest("hex"),...p==="package.json"?{dependencies:K(f)??{}}:{}});}}return {manifests:[...o.values()].sort((i,n)=>i.path.localeCompare(n.path))}}function O(e){let a=e.replace(/^(?:workspace:|npm:[^@]+@)/,"").match(/(?:^|[^\d])(\d+)(?:\.\d+)?(?:\.\d+)?/);return a?Number(a[1]):null}function S(e){return /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|poetry\.lock|uv\.lock|Pipfile\.lock|go\.sum|Cargo\.lock|gradle\.lockfile|packages\.lock\.json|composer\.lock|Gemfile\.lock|mix\.lock)$/i.test(e)}async function oe(e){let t=e.dependencySafetyBaseline;if(!t)return k({id:"change-policy",label:"Change safety policy",status:"missing",expected:"dependency manifest safety baseline",actual:"baseline unavailable"});let a=[],s=await U(e.workspace.path,e.scope),o=new Map(s.manifests.map(r=>[r.path,r])),i=new Map(t.manifests.map(r=>[r.path,r])),n=new Set;for(let r of t.manifests){let c=o.get(r.path);(!c||c.sha256!==r.sha256)&&n.add(r.path);}for(let r of s.manifests)i.has(r.path)||n.add(r.path);for(let r of s.manifests)!i.has(r.path)&&!S(r.path)&&a.push(`${r.path} was added after the safety baseline`);for(let r of t.manifests){let c=o.get(r.path);if(!c){a.push(`${r.path} was removed`);continue}if(c.sha256===r.sha256)continue;if(r.dependencies){let d=await y.readFile(l.join(e.workspace.path,r.path),"utf8"),m=K(d);if(!m){a.push(`${r.path} is not valid dependency JSON`);continue}for(let[u,g]of Object.entries(r.dependencies)){let h=m[u];if(!h){a.push(`${u.replace(/^[^:]+:/,"")} was removed`);continue}if(h===g)continue;let $=O(g),R=O(h);($===null||R===null||$!==R||/(?:latest|\*)/i.test(h))&&a.push(`${u.replace(/^[^:]+:/,"")} changed outside its proven major range (${g} \u2192 ${h})`);}continue}if(S(r.path))continue;let p=l.posix.dirname(r.path);[...o.values()].some(d=>{let m=l.posix.dirname(d.path);return d.ecosystem===r.ecosystem&&(m===p||p.startsWith(`${m}/`))&&S(d.path)&&n.has(d.path)})||a.push(`${r.path} changed without a matching reconciled ${r.ecosystem} lockfile`);}return k({id:"change-policy",label:"Change safety policy",status:a.length===0?"passed":"blocked",expected:"no force, removal, unbounded, or major dependency changes",actual:a.length===0?"manifest changes are within proven bounds":a.join("; ")})}function E(e,t){if(!/^[a-z0-9][a-z0-9._-]{7,95}$/i.test(t))throw new Error(`Invalid verified goal id: ${t}`);let a=l.join(e,".workspai","goals",t);return {directory:a,goal:l.join(a,"goal.json"),status:l.join(a,"status.json"),latestReport:l.join(e,C)}}function ce(e){return {workspacePath:l.resolve(e.workspace.path),kind:e.kind,scope:e.scope,target:e.criteria.kind==="test-coverage"?e.criteria.minimumPercent:null,constraints:e.constraints}}async function V(e,t){await y.ensureDir(l.dirname(e));let a=`${e}.${process.pid}.${Date.now()}.tmp`;await y.writeJson(a,t,{spaces:2}),await y.rename(a,e);}async function le(e,t){let a=t?.trim();if(!a||a==="workspace")return {scope:{kind:"workspace"}};let s=a.startsWith("project:")?a.slice(8).trim():a;if(!s)throw new Error("Project goal scope must name a project.");let i=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(c=>{let p=l.resolve(e,c.path);return c.name===s||c.path===s||p===l.resolve(s)});if(i.length!==1)throw new Error(i.length===0?`Project goal scope was not found: ${s}`:`Project goal scope is ambiguous: ${s}`);let n=i[0],r=l.resolve(e,n.path);return {project:n,scope:{kind:"project",projectName:n.name,projectPath:r}}}function z(e,t,a){return e===null?"unavailable":a==="minimum"?e>=t?"satisfied":"unsatisfied":e<=t?"satisfied":"unsatisfied"}async function Y(e){if(!e)return null;try{let t=await y.readJson(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function de(e){return Array.isArray(e.projects)?e.projects.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):e.project&&typeof e.project=="object"&&!Array.isArray(e.project)?[e.project]:[]}function ue(e){let t=e.dependencyAudit;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}async function X(e,t){let a$1=await d(e,a.doctor),s=await Y(a$1);if(!s)return {measuredAt:new Date().toISOString(),value:null,target:0,unit:"blocking-vulnerabilities",status:"unavailable",evidencePaths:[],message:"Fresh Doctor dependency evidence is not available."};let o=de(s).filter(c=>{if(t.kind==="workspace")return true;let p=typeof c.name=="string"?c.name:typeof c.projectName=="string"?c.projectName:"",f=typeof c.path=="string"?l.resolve(c.path):typeof c.projectPath=="string"?l.resolve(c.projectPath):"";return p===t.projectName||t.projectPath!==void 0&&f===l.resolve(t.projectPath)}),i=o.map(ue).filter(c=>c!==null),n=i.map(c=>c.blockingFindingCount).filter(c=>Number.isInteger(c)&&Number(c)>=0),r=o.length>0&&n.length===o.length?n.reduce((c,p)=>c+p,0):null;return {measuredAt:(()=>{let c=i.map(p=>p.generatedAt).filter(p=>typeof p=="string").sort();return c[c.length-1]??new Date().toISOString()})(),value:r,target:0,unit:"blocking-vulnerabilities",status:z(r,0,"maximum"),evidencePaths:a$1?[a$1]:[],message:r===null?"Doctor did not publish complete dependency audit counts for the selected scope.":`${r} blocking dependency vulnerability finding(s) remain.`}}async function Q(e){let t=await a$2({startPath:e,writeReport:false}),a=t.gates.filter(o=>o.status==="pass").length,s=t.gates.length;return {measuredAt:t.generatedAt,value:a,target:s,unit:"gates",status:t.overallStatus==="pass"?"satisfied":"unsatisfied",evidencePaths:[...new Set(t.gates.map(o=>o.evidencePath).filter(o=>typeof o=="string"))],message:t.overallStatus==="pass"?"All release readiness gates pass.":`${s-a} release readiness gate(s) still require work.`}}async function B(e){let t=await c$1({projectPath:e.projectPath,target:e.target,run:e.run}),s=t.metrics[t.target.metric]?.percent??null;return {executionStatus:t.status,measurement:{measuredAt:t.generatedAt,value:s,target:e.target,unit:"percent",status:z(s,e.target,"minimum"),evidencePaths:[t.artifactPaths.project],message:t.status==="failed"?"The runtime-native coverage test command failed.":s===null?"Machine-readable coverage evidence is unavailable.":`${t.target.metric} coverage is ${s}% (target ${e.target}%).`}}}async function Z(e){if(e.scope.kind==="project"){if(!e.scope.projectPath)throw new Error("Coverage goal project scope does not have a project path.");return B({projectPath:e.scope.projectPath,target:e.target,run:e.run})}let t=await p({workspacePath:e.workspacePath,includeAbsolutePaths:true});if(t.projects.length===0)return {executionStatus:"unavailable",measurement:{measuredAt:new Date().toISOString(),value:null,target:e.target,unit:"percent",status:"unavailable",evidencePaths:[],message:"The workspace does not contain a registered project to measure."}};let a=[];for(let d of t.projects)a.push({projectName:d.name,result:await B({projectPath:l.resolve(e.workspacePath,d.path),target:e.target,run:e.run})});let s=a.filter(d=>d.result.executionStatus==="failed"),o=a.filter(d=>d.result.measurement.status==="unavailable"),i=a.filter(d=>d.result.measurement.status==="unsatisfied"),n=a.map(d=>d.result.measurement.value).filter(d=>d!==null),r=n.length===a.length&&n.length>0?Math.min(...n):null,c=s.length>0?"failed":o.length>0?"unavailable":i.length>0?"below-target":"passed",p$1=a.map(d=>d.result.measurement.measuredAt).sort(),f=[...s.map(d=>`${d.projectName}: coverage command failed`),...o.map(d=>`${d.projectName}: coverage unavailable`),...i.map(d=>`${d.projectName}: ${d.result.measurement.value??"unknown"}%`)];return {executionStatus:c,measurement:{measuredAt:p$1[p$1.length-1]??new Date().toISOString(),value:r,target:e.target,unit:"percent",status:c==="passed"?"satisfied":c==="below-target"?"unsatisfied":"unavailable",evidencePaths:[...new Set(a.flatMap(d=>d.result.measurement.evidencePaths))],message:c==="passed"?`Every registered project has at least ${e.target}% test coverage.`:`Workspace coverage is not verified: ${f.join("; ")}.`}}}function pe(e){let t=e.scope.kind==="project"?`project ${e.scope.projectName??"selected project"}`:"workspace";return e.kind==="release-readiness"?`Prepare the ${t} for release.`:e.kind==="dependency-security"?`Resolve blocking dependency vulnerabilities in the ${t} without unsafe changes.`:`Raise ${t} test coverage to ${e.target??80}% without breaking its build.`}function ge(e,t){return e==="release-readiness"?{kind:e,readiness:"pass",workspaceVerify:"ready"}:e==="dependency-security"?{kind:e,maximumBlockingVulnerabilities:0,requireFreshAudit:true}:{kind:e,metric:"auto",minimumPercent:t}}async function fe(e){return e.kind==="release-readiness"?Q(e.workspacePath):e.kind==="dependency-security"?X(e.workspacePath,e.scope):(await Z({workspacePath:e.workspacePath,scope:e.scope,target:e.target,run:false})).measurement}async function Ge(e$1){let t=l.resolve(e$1.workspacePath),a=Math.max(0,Math.min(100,Math.round(e$1.target??80))),{scope:s}=await le(t,e$1.scope),o={workspacePath:l.resolve(t),kind:e$1.kind,scope:s,target:e$1.kind==="test-coverage"?a:null,constraints:{allowBreakingChanges:e$1.allowBreakingChanges===true,allowForce:e$1.allowForce===true,requireBuild:e$1.requireBuild!==false,requireTests:e$1.requireTests!==false}},i=H(o),n=`goal-${e$1.kind}-${i.slice(0,16)}`,r=E(t,n);if(await y.pathExists(r.goal)){let{goal:m,status:u}=await ee(t,n);if(m.fingerprint===i)return {goal:m,status:u,resumed:u.state!=="verified"}}let c=new Date().toISOString(),p=await fe({workspacePath:t,kind:e$1.kind,scope:s,target:a}),f={schemaVersion:W,id:n,fingerprint:i,createdAt:c,updatedAt:c,workspace:{name:l.basename(t),path:t},scope:s,kind:e$1.kind,summary:pe({kind:e$1.kind,scope:s,target:a}),constraints:o.constraints,criteria:ge(e$1.kind,a),baseline:p,...e$1.kind==="dependency-security"?{dependencySafetyBaseline:await U(t,s)}:{},artifactPaths:{goal:r.goal,status:r.status,latestReport:r.latestReport}},d={schemaVersion:x,goalId:n,goalFingerprint:i,workspacePath:t,updatedAt:c,state:"planned",attempt:0,progress:p,checks:[],blockingReasons:[],evidencePaths:p.evidencePaths,nextActions:e$1.kind==="test-coverage"?["Add focused tests for the lowest-coverage source paths.","Run verified goal checks."]:e$1.kind==="dependency-security"?["Inspect the fresh project dependency audit.","Apply only compatible non-force dependency repairs.","Reconcile the lockfile, test, build, and verify again."]:["Inspect the current remediation plan and failing release gates.","Repair the next causal blocker, then verify again."],artifactPath:r.status};return a$1(f,J,"Verified goal"),a$1(d,G,"Verified goal status"),await V(r.goal,f),await V(r.status,d),await e(t,C,d),{goal:f,status:d,resumed:false}}async function ee(e,t){let a=E(l.resolve(e),t),s=await y.readJson(a.goal),o=await y.readJson(a.status);a$1(s,J,"Verified goal"),a$1(o,G,"Verified goal status");let i=l.resolve(e),n=l.resolve(s.artifactPaths.goal)===l.resolve(a.goal)&&l.resolve(s.artifactPaths.status)===l.resolve(a.status)&&l.resolve(s.artifactPaths.latestReport)===l.resolve(a.latestReport);if(s.schemaVersion!==W||o.schemaVersion!==x||s.id!==o.goalId||s.fingerprint!==o.goalFingerprint||s.fingerprint!==H(ce(s))||l.resolve(s.workspace.path)!==i||l.resolve(o.workspacePath)!==i||!n)throw new Error(`Verified goal artifacts are inconsistent: ${t}`);return {goal:s,status:o}}function k(e){return {...e,message:e.message??`${e.label}: ${e.actual}; expected ${e.expected}.`}}async function q(e){let t=[],a=e.goal.scope.kind==="project"&&e.goal.scope.projectName?`project:${e.goal.scope.projectName}`:void 0;for(let s of ["test","build"]){if(s==="test"&&e.includeTests===false)continue;if(!(s==="test"?e.goal.constraints.requireTests:e.goal.constraints.requireBuild)){t.push(k({id:s,label:`${s} validation`,status:"skipped",expected:"not required",actual:"skipped by goal contract"}));continue}if(!e.run){t.push(k({id:s,label:`${s} validation`,status:"missing",expected:"fresh passed evidence",actual:"execution disabled"}));continue}let i=await a$3({workspacePath:e.goal.workspace.path,stage:s,scope:a,parallel:false,continueOnError:false,strict:true,json:true,enforceGates:false});if(t.push(k({id:s,label:`${s} validation`,status:i.summary.exitCode===0?"passed":"failed",expected:"exit 0",actual:`exit ${i.summary.exitCode}`,evidencePath:l.join(e.goal.workspace.path,".workspai","reports","workspace-run-last.json")})),i.summary.exitCode!==0)break}return t}async function Ee(e$1){let t=l.resolve(e$1.workspacePath),{goal:a$2,status:s}=await ee(t,e$1.goalId),o=e$1.run!==false,i=[],n;if(o&&e$1.runIntelligence!==false){let u=await c({workspacePath:t,strict:true,agent:"generic"}),g=u.exitCode===0||u.exitCode===2,h=a$2.kind==="release-readiness";i.push(k({id:"workspace-intelligence-chain",label:"Workspace Intelligence chain",status:u.exitCode===0||u.exitCode===2&&!h?"passed":u.exitCode===2?"blocked":"failed",expected:"passed",actual:u.exitCode===2&&g&&!h?`${u.status}; canonical evidence refreshed for goal-scoped verification`:u.status,evidencePath:l.join(t,a.intelligenceRun)}));}if(a$2.kind==="release-readiness"){n=await Q(t),i.push(k({id:"release-readiness",label:"Release readiness",status:n.status==="satisfied"?"passed":"blocked",expected:"all gates pass",actual:n.message,evidencePath:l.join(t,a.readiness)}));let u=await d(t,a.verify),g=await Y(u),h=g?.summary&&typeof g.summary=="object"&&!Array.isArray(g.summary)?String(g.summary.verdict??"missing"):"missing";i.push(k({id:"workspace-verify",label:"Workspace verification",status:h==="ready"?"passed":h==="missing"?"missing":"blocked",expected:"ready",actual:h,evidencePath:l.join(t,a.verify)}));}else if(a$2.kind==="dependency-security")n=await X(t,a$2.scope),i.push(k({id:"dependency-audit",label:"Dependency security audit",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:"0 blocking vulnerabilities",actual:n.message,evidencePath:n.evidencePaths[0]})),i.push(a$2.constraints.allowBreakingChanges||a$2.constraints.allowForce?k({id:"change-policy",label:"Change safety policy",status:"blocked",expected:"breaking and force changes disabled",actual:`allowBreakingChanges=${a$2.constraints.allowBreakingChanges}, allowForce=${a$2.constraints.allowForce}`}):await oe(a$2)),n.status==="satisfied"&&i.push(...await q({goal:a$2,run:o}));else {let u=a$2.criteria.kind==="test-coverage"?a$2.criteria.minimumPercent:a$2.baseline.target;if(u===null)throw new Error("Coverage goal does not have a valid target.");let g=await Z({workspacePath:t,scope:a$2.scope,target:u,run:o});n=g.measurement,i.push(k({id:"coverage",label:"Test coverage",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:`at least ${u}%`,actual:n.message,evidencePath:n.evidencePaths[0]})),i.push(k({id:"test",label:"Coverage test execution",status:g.executionStatus==="failed"?"failed":g.executionStatus==="unavailable"?"missing":"passed",expected:"runtime-native coverage test command completed",actual:g.executionStatus==="failed"?"coverage test command failed":g.executionStatus==="unavailable"?"coverage execution evidence unavailable":"coverage evidence produced by the test runner",evidencePath:n.evidencePaths[0]})),n.status==="satisfied"&&i.push(...await q({goal:a$2,run:o,includeTests:false}));}let r=i.filter(u=>u.status==="blocked"||u.status==="failed"||u.status==="missing").map(u=>u.message),c$1=[...new Set([...n.evidencePaths,...i.map(u=>u.evidencePath).filter(u=>typeof u=="string")])],p=n.status==="satisfied"&&i.every(u=>u.status==="passed"||u.status==="skipped"),f=E(t,a$2.id),d$1=p?[]:a$2.kind==="test-coverage"?["Inspect low-coverage files from the coverage artifact.","Add focused tests and verify again."]:a$2.kind==="dependency-security"?["Use fresh audit candidates and compatible package-manager repairs.","Reconcile lockfiles before running verified goal checks again."]:["Repair the first blocking readiness gate and verify the goal again."],m={schemaVersion:x,goalId:a$2.id,goalFingerprint:a$2.fingerprint,workspacePath:t,updatedAt:new Date().toISOString(),state:p?"verified":i.some(u=>u.status==="failed")?"failed":"blocked",attempt:s.attempt+1,progress:n,checks:i,blockingReasons:r,evidencePaths:c$1,nextActions:d$1,artifactPath:f.status};return a$1(m,G,"Verified goal status"),await V(f.status,m),await e(t,C,m),m}export{C as VERIFIED_GOAL_LAST_RUN_REPORT_PATH,W as VERIFIED_GOAL_SCHEMA_VERSION,x as VERIFIED_GOAL_STATUS_SCHEMA_VERSION,Ge as planVerifiedGoal,ee as readVerifiedGoal,Ee as verifyVerifiedGoal};
|
|
1
|
+
import {c}from'./chunk-27AXFTKW.js';import {a as a$3}from'./chunk-USMLRNZ7.js';import {c as c$1}from'./chunk-SJLUE6AY.js';import {a as a$2}from'./chunk-RMXXK64P.js';import {p}from'./chunk-7AR5PDLD.js';import {a as a$4}from'./chunk-GR6442P7.js';import {e,d}from'./chunk-WIO6L24E.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {a,b}from'./chunk-44VJHNZB.js';import {createHash}from'crypto';import l from'path';import y from'fs-extra';var W="workspai.verified-goal.v1",x=b.verifiedGoalStatus,C=a.verifiedGoalStatus,J="contracts/workspace-intelligence/verified-goal.v1.json",G="contracts/workspace-intelligence/verified-goal-status.v1.json";function A(e){return Array.isArray(e)?`[${e.map(A).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[a])=>t.localeCompare(a)).map(([t,a])=>`${JSON.stringify(t)}:${A(a)}`).join(",")}}`:JSON.stringify(e)}function H(e){return createHash("sha256").update(A(e)).digest("hex")}var te=["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","Pipfile","Pipfile.lock","poetry.lock","uv.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","packages.lock.json","Directory.Packages.props","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deps.edn","project.clj","build.sbt"],ae=new Set(te.map(e=>e.toLowerCase())),se=new Set([".git",".hg",".svn",".workspai",".venv","venv",".tox",".mypy_cache",".pytest_cache","__pycache__","node_modules","vendor","pods","dist","build","out","target","bin","obj","coverage",".coverage",".next",".nuxt",".svelte-kit"]),F=1e5;function ne(e){return ae.has(e.toLowerCase())||/\.(?:csproj|fsproj|vbproj)$/i.test(e)}async function re(e){let t=[e],a=[],s=0;for(;t.length>0;){let o=t.shift();if(o===void 0)break;let i=await y.readdir(o,{withFileTypes:true});if(i.sort((n,r)=>n.name.localeCompare(r.name)),s+=i.length,s>F)throw new Error(`Dependency safety baseline exceeded ${F} filesystem entries under ${e}. Narrow the project boundary before creating this goal.`);for(let n of i){let r=l.join(o,n.name);if(n.isDirectory()){!se.has(n.name.toLowerCase())&&!a$4(n.name)&&t.push(r);continue}n.isFile()&&ne(n.name)&&a.push(r);}}return a}function ie(e){return /^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/i.test(e)?"node":/^(?:pyproject\.toml|requirements\.txt|Pipfile(?:\.lock)?|poetry\.lock|uv\.lock)$/i.test(e)?"python":/^go\.(?:mod|sum)$/i.test(e)?"go":/^Cargo\.(?:toml|lock)$/i.test(e)?"rust":/^(?:pom\.xml|build\.gradle(?:\.kts)?|gradle\.lockfile)$/i.test(e)?"jvm":/^(?:Directory\.Packages\.props|packages\.lock\.json)$/i.test(e)?"dotnet":/^composer\.(?:json|lock)$/i.test(e)?"php":/^Gemfile(?:\.lock)?$/i.test(e)?"ruby":/^mix\.(?:exs|lock)$/i.test(e)?"elixir":/^(?:deps\.edn|project\.clj)$/i.test(e)?"clojure":/^build\.sbt$/i.test(e)?"scala":/\.(?:csproj|fsproj|vbproj)$/i.test(e)?"dotnet":"unknown"}function K(e){try{let t=JSON.parse(e),a={};for(let s of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let o=t[s];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let[i,n]of Object.entries(o))typeof n=="string"&&(a[`${s}:${i}`]=n);}return a}catch{return}}async function U(e,t){let s=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(i=>t.kind==="workspace"||i.name===t.projectName||l.resolve(e,i.path)===l.resolve(t.projectPath??"")),o=new Map;for(let i of s){let n=l.resolve(e,i.path),r=await re(n);for(let c of r){let p=l.basename(c),f=await y.readFile(c,"utf8"),d=l.relative(e,c).split(l.sep).join("/");o.set(d,{path:d,ecosystem:ie(p),sha256:createHash("sha256").update(f).digest("hex"),...p==="package.json"?{dependencies:K(f)??{}}:{}});}}return {manifests:[...o.values()].sort((i,n)=>i.path.localeCompare(n.path))}}function O(e){let a=e.replace(/^(?:workspace:|npm:[^@]+@)/,"").match(/(?:^|[^\d])(\d+)(?:\.\d+)?(?:\.\d+)?/);return a?Number(a[1]):null}function S(e){return /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|poetry\.lock|uv\.lock|Pipfile\.lock|go\.sum|Cargo\.lock|gradle\.lockfile|packages\.lock\.json|composer\.lock|Gemfile\.lock|mix\.lock)$/i.test(e)}async function oe(e){let t=e.dependencySafetyBaseline;if(!t)return k({id:"change-policy",label:"Change safety policy",status:"missing",expected:"dependency manifest safety baseline",actual:"baseline unavailable"});let a=[],s=await U(e.workspace.path,e.scope),o=new Map(s.manifests.map(r=>[r.path,r])),i=new Map(t.manifests.map(r=>[r.path,r])),n=new Set;for(let r of t.manifests){let c=o.get(r.path);(!c||c.sha256!==r.sha256)&&n.add(r.path);}for(let r of s.manifests)i.has(r.path)||n.add(r.path);for(let r of s.manifests)!i.has(r.path)&&!S(r.path)&&a.push(`${r.path} was added after the safety baseline`);for(let r of t.manifests){let c=o.get(r.path);if(!c){a.push(`${r.path} was removed`);continue}if(c.sha256===r.sha256)continue;if(r.dependencies){let d=await y.readFile(l.join(e.workspace.path,r.path),"utf8"),m=K(d);if(!m){a.push(`${r.path} is not valid dependency JSON`);continue}for(let[u,g]of Object.entries(r.dependencies)){let h=m[u];if(!h){a.push(`${u.replace(/^[^:]+:/,"")} was removed`);continue}if(h===g)continue;let $=O(g),R=O(h);($===null||R===null||$!==R||/(?:latest|\*)/i.test(h))&&a.push(`${u.replace(/^[^:]+:/,"")} changed outside its proven major range (${g} \u2192 ${h})`);}continue}if(S(r.path))continue;let p=l.posix.dirname(r.path);[...o.values()].some(d=>{let m=l.posix.dirname(d.path);return d.ecosystem===r.ecosystem&&(m===p||p.startsWith(`${m}/`))&&S(d.path)&&n.has(d.path)})||a.push(`${r.path} changed without a matching reconciled ${r.ecosystem} lockfile`);}return k({id:"change-policy",label:"Change safety policy",status:a.length===0?"passed":"blocked",expected:"no force, removal, unbounded, or major dependency changes",actual:a.length===0?"manifest changes are within proven bounds":a.join("; ")})}function E(e,t){if(!/^[a-z0-9][a-z0-9._-]{7,95}$/i.test(t))throw new Error(`Invalid verified goal id: ${t}`);let a=l.join(e,".workspai","goals",t);return {directory:a,goal:l.join(a,"goal.json"),status:l.join(a,"status.json"),latestReport:l.join(e,C)}}function ce(e){return {workspacePath:l.resolve(e.workspace.path),kind:e.kind,scope:e.scope,target:e.criteria.kind==="test-coverage"?e.criteria.minimumPercent:null,constraints:e.constraints}}async function V(e,t){await y.ensureDir(l.dirname(e));let a=`${e}.${process.pid}.${Date.now()}.tmp`;await y.writeJson(a,t,{spaces:2}),await y.rename(a,e);}async function le(e,t){let a=t?.trim();if(!a||a==="workspace")return {scope:{kind:"workspace"}};let s=a.startsWith("project:")?a.slice(8).trim():a;if(!s)throw new Error("Project goal scope must name a project.");let i=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(c=>{let p=l.resolve(e,c.path);return c.name===s||c.path===s||p===l.resolve(s)});if(i.length!==1)throw new Error(i.length===0?`Project goal scope was not found: ${s}`:`Project goal scope is ambiguous: ${s}`);let n=i[0],r=l.resolve(e,n.path);return {project:n,scope:{kind:"project",projectName:n.name,projectPath:r}}}function z(e,t,a){return e===null?"unavailable":a==="minimum"?e>=t?"satisfied":"unsatisfied":e<=t?"satisfied":"unsatisfied"}async function Y(e){if(!e)return null;try{let t=await y.readJson(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function de(e){return Array.isArray(e.projects)?e.projects.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):e.project&&typeof e.project=="object"&&!Array.isArray(e.project)?[e.project]:[]}function ue(e){let t=e.dependencyAudit;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}async function X(e,t){let a$1=await d(e,a.doctor),s=await Y(a$1);if(!s)return {measuredAt:new Date().toISOString(),value:null,target:0,unit:"blocking-vulnerabilities",status:"unavailable",evidencePaths:[],message:"Fresh Doctor dependency evidence is not available."};let o=de(s).filter(c=>{if(t.kind==="workspace")return true;let p=typeof c.name=="string"?c.name:typeof c.projectName=="string"?c.projectName:"",f=typeof c.path=="string"?l.resolve(c.path):typeof c.projectPath=="string"?l.resolve(c.projectPath):"";return p===t.projectName||t.projectPath!==void 0&&f===l.resolve(t.projectPath)}),i=o.map(ue).filter(c=>c!==null),n=i.map(c=>c.blockingFindingCount).filter(c=>Number.isInteger(c)&&Number(c)>=0),r=o.length>0&&n.length===o.length?n.reduce((c,p)=>c+p,0):null;return {measuredAt:(()=>{let c=i.map(p=>p.generatedAt).filter(p=>typeof p=="string").sort();return c[c.length-1]??new Date().toISOString()})(),value:r,target:0,unit:"blocking-vulnerabilities",status:z(r,0,"maximum"),evidencePaths:a$1?[a$1]:[],message:r===null?"Doctor did not publish complete dependency audit counts for the selected scope.":`${r} blocking dependency vulnerability finding(s) remain.`}}async function Q(e){let t=await a$2({startPath:e,writeReport:false}),a=t.gates.filter(o=>o.status==="pass").length,s=t.gates.length;return {measuredAt:t.generatedAt,value:a,target:s,unit:"gates",status:t.overallStatus==="pass"?"satisfied":"unsatisfied",evidencePaths:[...new Set(t.gates.map(o=>o.evidencePath).filter(o=>typeof o=="string"))],message:t.overallStatus==="pass"?"All release readiness gates pass.":`${s-a} release readiness gate(s) still require work.`}}async function B(e){let t=await c$1({projectPath:e.projectPath,target:e.target,run:e.run}),s=t.metrics[t.target.metric]?.percent??null;return {executionStatus:t.status,measurement:{measuredAt:t.generatedAt,value:s,target:e.target,unit:"percent",status:z(s,e.target,"minimum"),evidencePaths:[t.artifactPaths.project],message:t.status==="failed"?"The runtime-native coverage test command failed.":s===null?"Machine-readable coverage evidence is unavailable.":`${t.target.metric} coverage is ${s}% (target ${e.target}%).`}}}async function Z(e){if(e.scope.kind==="project"){if(!e.scope.projectPath)throw new Error("Coverage goal project scope does not have a project path.");return B({projectPath:e.scope.projectPath,target:e.target,run:e.run})}let t=await p({workspacePath:e.workspacePath,includeAbsolutePaths:true});if(t.projects.length===0)return {executionStatus:"unavailable",measurement:{measuredAt:new Date().toISOString(),value:null,target:e.target,unit:"percent",status:"unavailable",evidencePaths:[],message:"The workspace does not contain a registered project to measure."}};let a=[];for(let d of t.projects)a.push({projectName:d.name,result:await B({projectPath:l.resolve(e.workspacePath,d.path),target:e.target,run:e.run})});let s=a.filter(d=>d.result.executionStatus==="failed"),o=a.filter(d=>d.result.measurement.status==="unavailable"),i=a.filter(d=>d.result.measurement.status==="unsatisfied"),n=a.map(d=>d.result.measurement.value).filter(d=>d!==null),r=n.length===a.length&&n.length>0?Math.min(...n):null,c=s.length>0?"failed":o.length>0?"unavailable":i.length>0?"below-target":"passed",p$1=a.map(d=>d.result.measurement.measuredAt).sort(),f=[...s.map(d=>`${d.projectName}: coverage command failed`),...o.map(d=>`${d.projectName}: coverage unavailable`),...i.map(d=>`${d.projectName}: ${d.result.measurement.value??"unknown"}%`)];return {executionStatus:c,measurement:{measuredAt:p$1[p$1.length-1]??new Date().toISOString(),value:r,target:e.target,unit:"percent",status:c==="passed"?"satisfied":c==="below-target"?"unsatisfied":"unavailable",evidencePaths:[...new Set(a.flatMap(d=>d.result.measurement.evidencePaths))],message:c==="passed"?`Every registered project has at least ${e.target}% test coverage.`:`Workspace coverage is not verified: ${f.join("; ")}.`}}}function pe(e){let t=e.scope.kind==="project"?`project ${e.scope.projectName??"selected project"}`:"workspace";return e.kind==="release-readiness"?`Prepare the ${t} for release.`:e.kind==="dependency-security"?`Resolve blocking dependency vulnerabilities in the ${t} without unsafe changes.`:`Raise ${t} test coverage to ${e.target??80}% without breaking its build.`}function ge(e,t){return e==="release-readiness"?{kind:e,readiness:"pass",workspaceVerify:"ready"}:e==="dependency-security"?{kind:e,maximumBlockingVulnerabilities:0,requireFreshAudit:true}:{kind:e,metric:"auto",minimumPercent:t}}async function fe(e){return e.kind==="release-readiness"?Q(e.workspacePath):e.kind==="dependency-security"?X(e.workspacePath,e.scope):(await Z({workspacePath:e.workspacePath,scope:e.scope,target:e.target,run:false})).measurement}async function Ge(e$1){let t=l.resolve(e$1.workspacePath),a=Math.max(0,Math.min(100,Math.round(e$1.target??80))),{scope:s}=await le(t,e$1.scope),o={workspacePath:l.resolve(t),kind:e$1.kind,scope:s,target:e$1.kind==="test-coverage"?a:null,constraints:{allowBreakingChanges:e$1.allowBreakingChanges===true,allowForce:e$1.allowForce===true,requireBuild:e$1.requireBuild!==false,requireTests:e$1.requireTests!==false}},i=H(o),n=`goal-${e$1.kind}-${i.slice(0,16)}`,r=E(t,n);if(await y.pathExists(r.goal)){let{goal:m,status:u}=await ee(t,n);if(m.fingerprint===i)return {goal:m,status:u,resumed:u.state!=="verified"}}let c=new Date().toISOString(),p=await fe({workspacePath:t,kind:e$1.kind,scope:s,target:a}),f={schemaVersion:W,id:n,fingerprint:i,createdAt:c,updatedAt:c,workspace:{name:l.basename(t),path:t},scope:s,kind:e$1.kind,summary:pe({kind:e$1.kind,scope:s,target:a}),constraints:o.constraints,criteria:ge(e$1.kind,a),baseline:p,...e$1.kind==="dependency-security"?{dependencySafetyBaseline:await U(t,s)}:{},artifactPaths:{goal:r.goal,status:r.status,latestReport:r.latestReport}},d={schemaVersion:x,goalId:n,goalFingerprint:i,workspacePath:t,updatedAt:c,state:"planned",attempt:0,progress:p,checks:[],blockingReasons:[],evidencePaths:p.evidencePaths,nextActions:e$1.kind==="test-coverage"?["Add focused tests for the lowest-coverage source paths.","Run verified goal checks."]:e$1.kind==="dependency-security"?["Inspect the fresh project dependency audit.","Apply only compatible non-force dependency repairs.","Reconcile the lockfile, test, build, and verify again."]:["Inspect the current remediation plan and failing release gates.","Repair the next causal blocker, then verify again."],artifactPath:r.status};return a$1(f,J,"Verified goal"),a$1(d,G,"Verified goal status"),await V(r.goal,f),await V(r.status,d),await e(t,C,d),{goal:f,status:d,resumed:false}}async function ee(e,t){let a=E(l.resolve(e),t),s=await y.readJson(a.goal),o=await y.readJson(a.status);a$1(s,J,"Verified goal"),a$1(o,G,"Verified goal status");let i=l.resolve(e),n=l.resolve(s.artifactPaths.goal)===l.resolve(a.goal)&&l.resolve(s.artifactPaths.status)===l.resolve(a.status)&&l.resolve(s.artifactPaths.latestReport)===l.resolve(a.latestReport);if(s.schemaVersion!==W||o.schemaVersion!==x||s.id!==o.goalId||s.fingerprint!==o.goalFingerprint||s.fingerprint!==H(ce(s))||l.resolve(s.workspace.path)!==i||l.resolve(o.workspacePath)!==i||!n)throw new Error(`Verified goal artifacts are inconsistent: ${t}`);return {goal:s,status:o}}function k(e){return {...e,message:e.message??`${e.label}: ${e.actual}; expected ${e.expected}.`}}async function q(e){let t=[],a=e.goal.scope.kind==="project"&&e.goal.scope.projectName?`project:${e.goal.scope.projectName}`:void 0;for(let s of ["test","build"]){if(s==="test"&&e.includeTests===false)continue;if(!(s==="test"?e.goal.constraints.requireTests:e.goal.constraints.requireBuild)){t.push(k({id:s,label:`${s} validation`,status:"skipped",expected:"not required",actual:"skipped by goal contract"}));continue}if(!e.run){t.push(k({id:s,label:`${s} validation`,status:"missing",expected:"fresh passed evidence",actual:"execution disabled"}));continue}let i=await a$3({workspacePath:e.goal.workspace.path,stage:s,scope:a,parallel:false,continueOnError:false,strict:true,json:true,enforceGates:false});if(t.push(k({id:s,label:`${s} validation`,status:i.summary.exitCode===0?"passed":"failed",expected:"exit 0",actual:`exit ${i.summary.exitCode}`,evidencePath:l.join(e.goal.workspace.path,".workspai","reports","workspace-run-last.json")})),i.summary.exitCode!==0)break}return t}async function Ee(e$1){let t=l.resolve(e$1.workspacePath),{goal:a$2,status:s}=await ee(t,e$1.goalId),o=e$1.run!==false,i=[],n;if(o&&e$1.runIntelligence!==false){let u=await c({workspacePath:t,strict:true,agent:"generic"}),g=u.exitCode===0||u.exitCode===2,h=a$2.kind==="release-readiness";i.push(k({id:"workspace-intelligence-chain",label:"Workspace Intelligence chain",status:u.exitCode===0||u.exitCode===2&&!h?"passed":u.exitCode===2?"blocked":"failed",expected:"passed",actual:u.exitCode===2&&g&&!h?`${u.status}; canonical evidence refreshed for goal-scoped verification`:u.status,evidencePath:l.join(t,a.intelligenceRun)}));}if(a$2.kind==="release-readiness"){n=await Q(t),i.push(k({id:"release-readiness",label:"Release readiness",status:n.status==="satisfied"?"passed":"blocked",expected:"all gates pass",actual:n.message,evidencePath:l.join(t,a.readiness)}));let u=await d(t,a.verify),g=await Y(u),h=g?.summary&&typeof g.summary=="object"&&!Array.isArray(g.summary)?String(g.summary.verdict??"missing"):"missing";i.push(k({id:"workspace-verify",label:"Workspace verification",status:h==="ready"?"passed":h==="missing"?"missing":"blocked",expected:"ready",actual:h,evidencePath:l.join(t,a.verify)}));}else if(a$2.kind==="dependency-security")n=await X(t,a$2.scope),i.push(k({id:"dependency-audit",label:"Dependency security audit",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:"0 blocking vulnerabilities",actual:n.message,evidencePath:n.evidencePaths[0]})),i.push(a$2.constraints.allowBreakingChanges||a$2.constraints.allowForce?k({id:"change-policy",label:"Change safety policy",status:"blocked",expected:"breaking and force changes disabled",actual:`allowBreakingChanges=${a$2.constraints.allowBreakingChanges}, allowForce=${a$2.constraints.allowForce}`}):await oe(a$2)),n.status==="satisfied"&&i.push(...await q({goal:a$2,run:o}));else {let u=a$2.criteria.kind==="test-coverage"?a$2.criteria.minimumPercent:a$2.baseline.target;if(u===null)throw new Error("Coverage goal does not have a valid target.");let g=await Z({workspacePath:t,scope:a$2.scope,target:u,run:o});n=g.measurement,i.push(k({id:"coverage",label:"Test coverage",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:`at least ${u}%`,actual:n.message,evidencePath:n.evidencePaths[0]})),i.push(k({id:"test",label:"Coverage test execution",status:g.executionStatus==="failed"?"failed":g.executionStatus==="unavailable"?"missing":"passed",expected:"runtime-native coverage test command completed",actual:g.executionStatus==="failed"?"coverage test command failed":g.executionStatus==="unavailable"?"coverage execution evidence unavailable":"coverage evidence produced by the test runner",evidencePath:n.evidencePaths[0]})),n.status==="satisfied"&&i.push(...await q({goal:a$2,run:o,includeTests:false}));}let r=i.filter(u=>u.status==="blocked"||u.status==="failed"||u.status==="missing").map(u=>u.message),c$1=[...new Set([...n.evidencePaths,...i.map(u=>u.evidencePath).filter(u=>typeof u=="string")])],p=n.status==="satisfied"&&i.every(u=>u.status==="passed"||u.status==="skipped"),f=E(t,a$2.id),d$1=p?[]:a$2.kind==="test-coverage"?["Inspect low-coverage files from the coverage artifact.","Add focused tests and verify again."]:a$2.kind==="dependency-security"?["Use fresh audit candidates and compatible package-manager repairs.","Reconcile lockfiles before running verified goal checks again."]:["Repair the first blocking readiness gate and verify the goal again."],m={schemaVersion:x,goalId:a$2.id,goalFingerprint:a$2.fingerprint,workspacePath:t,updatedAt:new Date().toISOString(),state:p?"verified":i.some(u=>u.status==="failed")?"failed":"blocked",attempt:s.attempt+1,progress:n,checks:i,blockingReasons:r,evidencePaths:c$1,nextActions:d$1,artifactPath:f.status};return a$1(m,G,"Verified goal status"),await V(f.status,m),await e(t,C,m),m}export{C as VERIFIED_GOAL_LAST_RUN_REPORT_PATH,W as VERIFIED_GOAL_SCHEMA_VERSION,x as VERIFIED_GOAL_STATUS_SCHEMA_VERSION,Ge as planVerifiedGoal,ee as readVerifiedGoal,Ee as verifyVerifiedGoal};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{c as captureWorkspaceRegistrationStrict,k as createProject,j as createWorkspace,m as createWorkspaceShareBundle,l as listWorkspaces,a as normalizeWorkspaceEntry,i as registerProjectInWorkspace,h as registerProjectInWorkspaceStrict,f as registerWorkspace,b as registerWorkspaceStrict,d as restoreWorkspaceRegistrationStrict,g as syncWorkspaceProjects,e as unregisterWorkspaceStrict}from'./chunk-
|
|
1
|
+
export{c as captureWorkspaceRegistrationStrict,k as createProject,j as createWorkspace,m as createWorkspaceShareBundle,l as listWorkspaces,a as normalizeWorkspaceEntry,i as registerProjectInWorkspace,h as registerProjectInWorkspaceStrict,f as registerWorkspace,b as registerWorkspaceStrict,d as restoreWorkspaceRegistrationStrict,g as syncWorkspaceProjects,e as unregisterWorkspaceStrict}from'./chunk-HRN5J6PW.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{g as AGENT_CUSTOMIZATION_PACK_REPORT_PATH,e as AGENT_CUSTOMIZATION_PACK_SCHEMA,f as AGENT_REPORTS_INDEX_PATH,d as AGENT_REPORTS_INDEX_SCHEMA,h as AGENT_REPORT_CATALOG,i as buildCanonicalAgentReportReadOrder,j as buildWorkspaceAgentReportsIndex,k as parseAgentGroundingTargets,l as syncWorkspaceAgentGrounding}from'./chunk-
|
|
1
|
+
export{g as AGENT_CUSTOMIZATION_PACK_REPORT_PATH,e as AGENT_CUSTOMIZATION_PACK_SCHEMA,f as AGENT_REPORTS_INDEX_PATH,d as AGENT_REPORTS_INDEX_SCHEMA,h as AGENT_REPORT_CATALOG,i as buildCanonicalAgentReportReadOrder,j as buildWorkspaceAgentReportsIndex,k as parseAgentGroundingTargets,l as syncWorkspaceAgentGrounding}from'./chunk-OUBBBC7T.js';export{f as AGENT_GROUNDING_DOC_PATH,g as LEGACY_AGENT_GROUNDING_DOC_PATH,A as LEGACY_COPILOT_GROUNDING_SKILL_PATH,m as LEGACY_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,C as LEGACY_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,i as LEGACY_CURSOR_GROUNDING_RULE_PATH,E as LEGACY_MCP_DESIGN_REPORT_PATH,G as LEGACY_VSCODE_AGENT_HOOKS_PATH,z as WORKSPAI_COPILOT_GROUNDING_SKILL_PATH,l as WORKSPAI_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,B as WORKSPAI_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,h as WORKSPAI_CURSOR_GROUNDING_RULE_PATH,D as WORKSPAI_MCP_DESIGN_REPORT_PATH,F as WORKSPAI_VSCODE_AGENT_HOOKS_PATH}from'./chunk-AMB42V2F.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{f as WORKSPACE_ARCHIVE_KIND,e as WORKSPACE_ARCHIVE_MANIFEST_PATH,h as assertSafeRemoteArchiveUrl,o as doctorWorkspaceArchive,l as exportWorkspaceArchive,p as hydrateWorkspaceArchive,m as inspectWorkspaceArchive,g as isPrivateAddress,j as isSafeArchiveEntryName,i as sanitizeWorkspaceArchiveName,k as shouldExcludeWorkspaceArchivePath,n as verifyWorkspaceArchive}from'./chunk-
|
|
1
|
+
export{f as WORKSPACE_ARCHIVE_KIND,e as WORKSPACE_ARCHIVE_MANIFEST_PATH,h as assertSafeRemoteArchiveUrl,o as doctorWorkspaceArchive,l as exportWorkspaceArchive,p as hydrateWorkspaceArchive,m as inspectWorkspaceArchive,g as isPrivateAddress,j as isSafeArchiveEntryName,i as sanitizeWorkspaceArchiveName,k as shouldExcludeWorkspaceArchivePath,n as verifyWorkspaceArchive}from'./chunk-HY3RMPW5.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{b as WORKSPACE_CONTEXT_AGENT_REPORT_PATH,a as WORKSPACE_CONTEXT_SCHEMA_VERSION,c as buildWorkspaceAgentContext,d as writeWorkspaceAgentContext}from'./chunk-
|
|
1
|
+
export{b as WORKSPACE_CONTEXT_AGENT_REPORT_PATH,a as WORKSPACE_CONTEXT_SCHEMA_VERSION,c as buildWorkspaceAgentContext,d as writeWorkspaceAgentContext}from'./chunk-P7K5RHJC.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{g as WORKSPACE_CONTRACT_PATH,i as WORKSPACE_CONTRACT_SCHEMA_VERSION,h as WORKSPACE_CONTRACT_VERIFY_REPORT_PATH,j as WORKSPACE_CONTRACT_VERIFY_SCHEMA_VERSION,k as WorkspaceContractVerificationError,m as buildWorkspaceContract,q as buildWorkspaceContractGraph,l as discoverProjectJsonFiles,p as readWorkspaceContract,o as syncWorkspaceContract,r as verifyWorkspaceContract,n as writeWorkspaceContract,s as writeWorkspaceContractVerifyEvidence}from'./chunk-
|
|
1
|
+
export{g as WORKSPACE_CONTRACT_PATH,i as WORKSPACE_CONTRACT_SCHEMA_VERSION,h as WORKSPACE_CONTRACT_VERIFY_REPORT_PATH,j as WORKSPACE_CONTRACT_VERIFY_SCHEMA_VERSION,k as WorkspaceContractVerificationError,m as buildWorkspaceContract,q as buildWorkspaceContractGraph,l as discoverProjectJsonFiles,p as readWorkspaceContract,o as syncWorkspaceContract,r as verifyWorkspaceContract,n as writeWorkspaceContract,s as writeWorkspaceContractVerifyEvidence}from'./chunk-MQ73VS4E.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{b as buildWorkspaceExplain,a as resolveWorkspaceExplainArtifactPath,c as writeWorkspaceExplainReport}from'./chunk-WZA5ISAQ.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-AMB42V2F.js';export{e as WORKSPACE_MODEL_DIFF_REPORT_PATH}from'./chunk-S7Z4DP3P.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as WORKSPACE_EXPLAIN_SCHEMA_VERSION,b as WORKSPACE_EXPLAIN_TARGETS,e as isWorkspaceExplainReport,c as parseWorkspaceExplainTarget,d as resolveWorkspaceTraceTarget}from'./chunk-EBKYSDCX.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-AMB42V2F.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b}from'./chunk-ICGWHIMK.js';import {b as b$1,f,j}from'./chunk-
|
|
1
|
+
import {b}from'./chunk-ICGWHIMK.js';import {b as b$1,f,j}from'./chunk-GDU7VP6G.js';import o from'path';async function m(r){let t=o.resolve(r.workspacePath),n=b(r.payload);if(!n)return {ok:false,error:"Invalid agent-action-outcome payload",historyPath:o.join(t,b$1)};let c=f(n),p=o.join(t,b$1);return await j(t,c,{retention:r.retention}),{ok:true,entry:c,historyPath:p}}function l(r){let t=r.trim();if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function h(){let r=[];for await(let t of process.stdin)r.push(typeof t=="string"?Buffer.from(t):t);return Buffer.concat(r).toString("utf8")}export{l as parseFeedbackStdinPayload,h as readStdinAll,m as recordWorkspaceFeedback};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b}from'./chunk-
|
|
1
|
+
import {b}from'./chunk-OLX6LX77.js';import {a}from'./chunk-Y5YAP4F3.js';import c from'path';import u from'fs-extra';async function W(t,r){let o=await a(t),d=o?.name||c.basename(t),n,i=c.join(t,".python-version");if(await u.pathExists(i)){let a=(await u.readFile(i,"utf-8")).trim();a&&(n=a);}let e=r?.profile||"polyglot",m=e==="python-only"||e==="polyglot"||e==="enterprise",f=r?.installMethod||o?.metadata?.npm?.installMethod||(m?"poetry":"venv"),s=await b(t,{workspaceName:d,installMethod:f,pythonVersion:n,profile:e,writeMarker:true,writeGitignore:true,onlyIfMissing:!r?.force}),{publishWorkspaceRegistrySummary:y}=await import('./workspace-registry-summary-GPJEL7K7.js');return await y(t),{workspacePath:t,created:s,status:s.length>0?"passed":"skipped"}}export{W as ensureWorkspaceFoundation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {c}from'./chunk-
|
|
1
|
+
import {c}from'./chunk-7KKP7RNB.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-AFIFZTOY.js';import g from'crypto';import H from'path';var M="workspace-graph-stream.v1";function w(o){return c$1({...o,generatedAt:"<ignored>",proofs:o.proofs.map(s=>({...s,observedAt:"<ignored>"}))})}function f(o){return "observedAt"in o?{...o,observedAt:"<ignored>"}:o}function u(o,s){let e=new Map(o.map(r=>[r.id,r])),a=new Map(s.map(r=>[r.id,r])),i=s.filter(r=>!e.has(r.id)),p=s.filter(r=>{let t=e.get(r.id);return t?c$1(f(t))!==c$1(f(r)):false}),d=o.filter(r=>!a.has(r.id)).map(r=>r.id);return {added:i,updated:p,removed:d}}function E(o,s){let e=new Map(o.map(a=>[a.id,a]));return s.filter(a=>{let i=e.get(a.id);return !i||c$1(i)!==c$1(a)})}function I(o){return a(o,"contracts/workspace-intelligence/workspace-graph-stream.v1.json","Workspace graph stream event"),o}var R=class{previous=null;revision=0;generation=0;workspaceId;sessionId;now;nextCorrelationId;constructor(s){this.workspaceId=`workspace:${g.createHash("sha256").update(H.resolve(s.workspacePath)).digest("hex")}`,this.sessionId=s.sessionId??g.randomUUID(),this.now=s.now??(()=>new Date),this.nextCorrelationId=s.correlationId??(()=>g.randomUUID());}publish(s,e){c(e,s);let a=this.now().toISOString(),i=d(s),p=w(e),d$1=this.nextCorrelationId(),r={schemaVersion:M,workspaceId:this.workspaceId,sessionId:this.sessionId,generation:this.generation,modelHash:i,graphHash:p,generatedAt:a,causationId:d$1,correlationId:d$1};if(!this.previous){let S=I({...r,type:"graph.snapshot",revision:this.revision,payload:{graph:e,reason:"initial"}});return this.previous=e,S}let t=this.previous,W=this.revision,b=t.source.hash,y=w(t);this.revision+=1,this.generation+=1;let c$2=u(t.entities,e.entities),h=u(t.relations,e.relations),l=u(t.proofs,e.proofs),G=c$1(t.quality)!==c$1(e.quality),A=I({...r,generation:this.generation,type:"graph.delta",baseRevision:W,baseModelHash:b,baseGraphHash:y,revision:this.revision,payload:{entitiesAdded:c$2.added,entitiesUpdated:c$2.updated,entitiesRemoved:c$2.removed,relationsAdded:h.added,relationsUpdated:h.updated,relationsRemoved:h.removed,proofsAdded:l.added,proofsUpdated:l.updated,proofsRemoved:l.removed,providersUpdated:E(t.providers,e.providers),quality:G?e.quality:null,diagnostics:e.diagnostics}});return this.previous=e,A}};export{M as WORKSPACE_GRAPH_STREAM_SCHEMA_VERSION,R as WorkspaceGraphStreamPublisher};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{c as DEFAULT_HISTORY_RETENTION,b as WORKSPACE_HISTORY_PATH,a as WORKSPACE_HISTORY_SCHEMA_VERSION,i as appendHistoryEntry,f as historyEntryFromAgentAction,g as historyEntryFromDoctorFixResult,e as historyEntryFromVerify,d as normalizeHistoryEntry,h as readWorkspaceHistory,j as recordWorkspaceHistory}from'./chunk-
|
|
1
|
+
export{c as DEFAULT_HISTORY_RETENTION,b as WORKSPACE_HISTORY_PATH,a as WORKSPACE_HISTORY_SCHEMA_VERSION,i as appendHistoryEntry,f as historyEntryFromAgentAction,g as historyEntryFromDoctorFixResult,e as historyEntryFromVerify,d as normalizeHistoryEntry,h as readWorkspaceHistory,j as recordWorkspaceHistory}from'./chunk-GDU7VP6G.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{g as WORKSPACE_IMPACT_REPORT_PATH,f as WORKSPACE_IMPACT_SCHEMA_VERSION,e as WORKSPACE_MODEL_DIFF_REPORT_PATH,c as WORKSPACE_MODEL_DIFF_SCHEMA_VERSION,d as WORKSPACE_MODEL_SNAPSHOT_REPORT_PATH,b as WORKSPACE_MODEL_SNAPSHOT_SCHEMA_VERSION,p as buildWorkspaceImpact,k as buildWorkspaceModelSnapshot,m as diffWorkspaceModel,i as isGitDiffSource,h as migrateLegacyWorkspaceModelSnapshot,j as parseGitDiffRef,o as workspaceVerificationPlan,q as writeWorkspaceImpact,n as writeWorkspaceModelDiff,l as writeWorkspaceModelSnapshot}from'./chunk-
|
|
1
|
+
export{g as WORKSPACE_IMPACT_REPORT_PATH,f as WORKSPACE_IMPACT_SCHEMA_VERSION,e as WORKSPACE_MODEL_DIFF_REPORT_PATH,c as WORKSPACE_MODEL_DIFF_SCHEMA_VERSION,d as WORKSPACE_MODEL_SNAPSHOT_REPORT_PATH,b as WORKSPACE_MODEL_SNAPSHOT_SCHEMA_VERSION,p as buildWorkspaceImpact,k as buildWorkspaceModelSnapshot,m as diffWorkspaceModel,i as isGitDiffSource,h as migrateLegacyWorkspaceModelSnapshot,j as parseGitDiffRef,o as workspaceVerificationPlan,q as writeWorkspaceImpact,n as writeWorkspaceModelDiff,l as writeWorkspaceModelSnapshot}from'./chunk-S7Z4DP3P.js';export{d as hashWorkspaceModel}from'./chunk-EWZZUQBR.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$2,b as b$1,c,d as d$1}from'./chunk-
|
|
1
|
+
import {a as a$2,b as b$1,c,d as d$1}from'./chunk-NYHVCFBT.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {a}from'./chunk-44VJHNZB.js';import d from'crypto';import s from'path';import {open,unlink,stat}from'fs/promises';import u from'fs-extra';var k=a.evaluationLive,O=a.evaluationLastRun,W="contracts/workspace-intelligence/model-usage-event.v1.json",E="contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",P="contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json",_=3e4,N=100,b=25;function C(){return {modelCalls:0,toolCalls:0,tokenSources:{providerReported:0,tokenizerCounted:0,estimated:0,unavailable:0},tokens:{input:0,output:0,cachedInput:0,reasoning:0,observedTotal:0},latencyMs:0,costs:[],outcome:{status:"unknown",verified:false,blockersResolved:0},efficiency:{tokensPerVerifiedOutcome:null,noProgressDecisions:0,repeatedArtifactReads:0}}}function m(t){return t??0}function S(t){let e=C(),a=new Map,n=new Map;for(let o of t){if(o.kind==="model-call"){e.modelCalls+=1;let r={"provider-reported":"providerReported","tokenizer-counted":"tokenizerCounted",estimated:"estimated",unavailable:"unavailable"}[o.modelCall.source];if(e.tokenSources[r]+=1,e.tokens.input+=m(o.modelCall.inputTokens),e.tokens.output+=m(o.modelCall.outputTokens),e.tokens.cachedInput+=m(o.modelCall.cachedInputTokens),e.tokens.reasoning+=m(o.modelCall.reasoningTokens),e.latencyMs+=o.modelCall.latencyMs??0,o.modelCall.cost){let i=o.modelCall.cost.currency.toUpperCase(),l=n.get(i)??{currency:i,amount:0,providerReported:0,estimated:0};l.amount+=o.modelCall.cost.amount,o.modelCall.cost.source==="provider-reported"?l.providerReported+=o.modelCall.cost.amount:l.estimated+=o.modelCall.cost.amount,n.set(i,l);}continue}if(o.kind==="tool-call"){e.toolCalls+=1,e.latencyMs+=o.toolCall.durationMs??0,!o.toolCall.changedSource&&o.toolCall.result==="passed"&&(e.efficiency.noProgressDecisions+=1),o.toolCall.artifact&&a.set(o.toolCall.artifact,(a.get(o.toolCall.artifact)??0)+1);continue}o.kind==="outcome"&&(e.outcome={status:o.outcome.status,verified:o.outcome.verified,blockersResolved:o.outcome.blockersResolved});}return e.tokens.observedTotal=e.tokens.input+e.tokens.output,e.costs=[...n.values()].map(o=>({...o,amount:Number(o.amount.toFixed(8)),providerReported:Number(o.providerReported.toFixed(8)),estimated:Number(o.estimated.toFixed(8))})).sort((o,r)=>o.currency.localeCompare(r.currency)),e.efficiency.repeatedArtifactReads=[...a.values()].reduce((o,r)=>o+Math.max(0,r-1),0),e.efficiency.tokensPerVerifiedOutcome=e.outcome.verified&&e.outcome.status==="passed"?e.tokens.observedTotal:null,e}function x(t,e=new Date){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Evaluation event must be a JSON object.");let a=t,n={...a,schemaVersion:a$2,eventId:typeof a.eventId=="string"&&a.eventId.trim()?a.eventId.trim():d.randomUUID(),recordedAt:typeof a.recordedAt=="string"&&a.recordedAt.trim()?a.recordedAt:e.toISOString()};a$1(n,W,"workspace evaluation event");let o={"model-call":"modelCall","tool-call":"toolCall",outcome:"outcome",milestone:"milestone"}[n.kind],r=["modelCall","toolCall","outcome","milestone"].filter(i=>a[i]!==void 0);if(r.length!==1||r[0]!==o)throw new Error(`Evaluation event kind ${n.kind} requires only ${o}.`);if(n.kind==="model-call"&&n.modelCall.source!=="unavailable"&&n.modelCall.inputTokens===null&&n.modelCall.outputTokens===null)throw new Error("Measured model calls require at least one input or output token count.");return n}function J(t){let e=t.now??new Date,a=s.resolve(t.workspacePath),n={schemaVersion:b$1,runId:t.runId??d.randomUUID(),sessionId:t.sessionId??d.randomUUID(),status:"live",startedAt:e.toISOString(),updatedAt:e.toISOString(),workspace:{name:t.workspaceName?.trim()||s.basename(a),path:a},configuration:{taskId:t.taskId.trim(),strategy:t.strategy??"workspace-intelligence",...t.provider?{provider:t.provider}:{},...t.model?{model:t.model}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.baselineRunId?{baselineRunId:t.baselineRunId}:{}},methodology:{id:"provider-usage-and-verified-outcome.v1",claimBoundary:"Provider-reported and tokenizer-counted values are measured; estimated values remain explicitly labelled. Verified task success is required before reporting tokens per successful outcome."},events:[],summary:C()};return a$1(n,E,"workspace evaluation"),n}async function L(t,e){await u.ensureDir(s.dirname(t));let a=`${t}.${process.pid}.${d.randomUUID()}.tmp`;try{await u.writeJson(a,e,{spaces:2}),await u.rename(a,t);}finally{await u.remove(a).catch(()=>{});}}async function A(t,e){let a=s.join(s.resolve(t),`${k}.lock`);await u.ensureDir(s.dirname(a));for(let n=0;n<N;n+=1)try{let o=await open(a,"wx");try{return await o.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await o.close(),await unlink(a).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let i=await stat(a).catch(()=>null);if(i&&Date.now()-i.mtimeMs>_){await unlink(a).catch(()=>{});continue}await new Promise(l=>setTimeout(l,b));}throw new Error("Timed out waiting for the workspace evaluation writer lock.")}async function v(t,e,a=k){let n=s.join(s.resolve(t),a);return a$1(e,E,a),await L(n,e),n}async function T(t,e=k){let a=s.isAbsolute(e)?e:s.join(s.resolve(t),e),n=await u.readJson(a);return a$1(n,E,a),n}async function G(t){return A(t.workspacePath,async()=>{let e=await T(t.workspacePath);if(e.status!=="live")throw new Error(`Evaluation ${e.runId} is ${e.status}; initialize a new run.`);let a=x(t.payload,t.now);if(e.events.some(o=>o.eventId===a.eventId))return e;let n={...e,updatedAt:(t.now??new Date).toISOString(),events:[...e.events,a],summary:S([...e.events,a])};return await v(t.workspacePath,n),n})}async function H(t){return A(t.workspacePath,async()=>{let e=await T(t.workspacePath),a=(t.now??new Date).toISOString(),n={...e,status:t.status??"completed",updatedAt:a,completedAt:a,summary:S(e.events)},o=await v(t.workspacePath,n,O);return await v(t.workspacePath,n),{report:n,outputPath:o}})}function q(t,e){let a=t.summary.tokens.observedTotal,n=e.summary.tokens.observedTotal,o=a-n,r={schemaVersion:c,generatedAt:new Date().toISOString(),taskAligned:t.configuration.taskId===e.configuration.taskId,current:{runId:t.runId,strategy:t.configuration.strategy,tokens:a,verified:t.summary.outcome.verified,status:t.summary.outcome.status},baseline:{runId:e.runId,strategy:e.configuration.strategy,tokens:n,verified:e.summary.outcome.verified,status:e.summary.outcome.status},delta:{tokens:o,reductionPercent:n===0?null:Number((-o/n*100).toFixed(2)),modelCalls:t.summary.modelCalls-e.summary.modelCalls,toolCalls:t.summary.toolCalls-e.summary.toolCalls,latencyMs:Number((t.summary.latencyMs-e.summary.latencyMs).toFixed(2))},comparableOutcome:t.summary.outcome.verified&&e.summary.outcome.verified&&t.summary.outcome.status===e.summary.outcome.status};return a$1(r,P,"workspace evaluation comparison"),r}function B(){if(d$1.length!==4)throw new Error("Model usage source taxonomy is incomplete.")}export{O as WORKSPACE_EVALUATION_LAST_RUN_PATH,k as WORKSPACE_EVALUATION_LIVE_PATH,G as appendWorkspaceEvaluationEvent,B as assertWorkspaceEvaluationSourceTaxonomy,q as compareWorkspaceEvaluations,J as createWorkspaceEvaluation,H as finalizeWorkspaceEvaluation,x as normalizeWorkspaceEvaluationEvent,T as readWorkspaceEvaluation,S as summarizeWorkspaceEvaluation,v as writeWorkspaceEvaluation};
|
package/dist/{workspace-intelligence-runner-VYGSASDP.js → workspace-intelligence-runner-JNCQLUH7.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-
|
|
1
|
+
export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-27AXFTKW.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{f as WORKSPACE_INTELLIGENCE_ADDITIONAL_PRODUCERS,a as WORKSPACE_INTELLIGENCE_ARTIFACTS,b as WORKSPACE_INTELLIGENCE_ARTIFACT_SCHEMAS,c as WORKSPACE_INTELLIGENCE_ARTIFACT_SCHEMA_CONTRACTS,g as WORKSPACE_INTELLIGENCE_COMMAND_SIGNATURES,k as WORKSPACE_INTELLIGENCE_PREFLIGHT_ARTIFACTS,j as WORKSPACE_INTELLIGENCE_PREFLIGHT_IDS,h as WORKSPACE_INTELLIGENCE_ROOT_COMMANDS,l as WORKSPACE_INTELLIGENCE_RUNTIME_STEPS,i as WORKSPACE_INTELLIGENCE_STEP_IDS,e as WORKSPACE_SUPPLEMENTAL_ARTIFACTS,d as WORKSPACE_SUPPLEMENTAL_ARTIFACT_CONTRACTS,m as workspaceIntelligenceRuntimeStep}from'./chunk-44VJHNZB.js';
|
package/dist/{workspace-knowledge-graph-LEM6X5CM.js → workspace-knowledge-graph-BMMM2FUE.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{b as WORKSPACE_KNOWLEDGE_GRAPH_REPORT_PATH,c as assertWorkspaceKnowledgeGraphSourceBinding,d as buildWorkspaceKnowledgeGraph,e as knowledgeEntityId}from'./chunk-
|
|
1
|
+
export{b as WORKSPACE_KNOWLEDGE_GRAPH_REPORT_PATH,c as assertWorkspaceKnowledgeGraphSourceBinding,d as buildWorkspaceKnowledgeGraph,e as knowledgeEntityId}from'./chunk-7KKP7RNB.js';
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {b}from'./chunk-
|
|
1
|
+
import {b}from'./chunk-WZA5ISAQ.js';import {c as c$1,e}from'./chunk-EBKYSDCX.js';import {d,c as c$2,f,e as e$1}from'./chunk-PS5F4DCT.js';import {c as c$4,b as b$2}from'./chunk-AMB42V2F.js';import {b as b$1}from'./chunk-P7K5RHJC.js';import {d as d$2}from'./chunk-XVRJVKOX.js';import {c as c$3}from'./chunk-7KKP7RNB.js';import {k}from'./chunk-7AR5PDLD.js';import {h}from'./chunk-MQ73VS4E.js';import {d as d$1}from'./chunk-WIO6L24E.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {a as a$1,c}from'./chunk-44VJHNZB.js';import {v}from'./chunk-MOSXTVPU.js';import u from'path';import N from'readline';import g from'fs-extra';var L=a$1.agentIndex,q=new Map(Object.keys(a$1).flatMap(e=>{let t=c[e];return t?[[a$1[e],t]]:[]}));function M(e,t){return e.kind!==t.kind?false:e.kind==="project"&&t.kind==="project"?e.project.toLowerCase()===t.project.toLowerCase():e.kind==="blocker"&&t.kind==="blocker"?e.blockerId===t.blockerId:e.kind==="trace"&&t.kind==="trace"?e.diffRef===t.diffRef:true}var J=[{name:"getWorkspaceModel",description:"Read workspace-model.json",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceKnowledgeGraph",description:"Read the current proof-backed workspace knowledge graph artifact",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceEvaluation",description:"Read the live or finalized provenance-aware model usage and verified-outcome report",inputSchema:{type:"object",properties:{live:{type:"boolean",description:"Read the live report instead of the finalized last-run report"}}}},{name:"queryWorkspaceEntities",description:"List workspace knowledge entities, optionally filtered by kind",inputSchema:{type:"object",properties:{kind:{type:"string",description:"Optional entity kind"}}}},{name:"searchWorkspaceGraph",description:"Return bounded, proof-carrying workspace context matching a text query",inputSchema:{type:"object",properties:{query:{type:"string",description:"Text, path, symbol, service, or concept to find"},kind:{type:"string",description:"Optional entity kind filter"},limit:{type:"integer",minimum:1,maximum:100,default:12}},required:["query"]}},{name:"getWorkspaceGraphEvidence",description:"Resolve portable evidence for a knowledge graph entity or relation",inputSchema:{type:"object",properties:{query:{type:"string"}},required:["query"]}},{name:"findWorkspaceGraphPath",description:"Find a shortest proof-carrying path between two workspace entities",inputSchema:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"]}},{name:"getEvidenceIndex",description:"Read agent reports INDEX.json",inputSchema:{type:"object",properties:{}}},{name:"getBlockers",description:"Aggregate blocking reasons from verify, explain, and contract-verify reports",inputSchema:{type:"object",properties:{}}},{name:"getSafeCommands",description:"Read safe commands from workspace-context-agent.json",inputSchema:{type:"object",properties:{}}},{name:"getProjectContext",description:"Read scoped project context from workspace-context-agent.json",inputSchema:{type:"object",properties:{project:{type:"string",description:"Optional project name; defaults to active scope"}}}},{name:"getArtifact",description:"Read one workspace-relative artifact path",inputSchema:{type:"object",properties:{relativePath:{type:"string"}},required:["relativePath"]}},{name:"listOperationalSkills",description:"Read workspace-skills-index.json",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceExplain",description:"Build or read workspace explain report",inputSchema:{type:"object",properties:{target:{type:"string",description:"release-blocked | project:<name> | blocker:<id> | trace:<diffRef> | <project>"}}}}];function H(e){let t=e.trim().replace(/\\/g,"/");return t.length>0&&!u.isAbsolute(t)&&!t.split("/").includes("..")&&(t.startsWith(".workspai/")||t.startsWith(".rapidkit/"))}async function a(e,t){if(!H(t))throw new Error(`Unsafe artifact path: ${t}`);let r=await d$1(e,t)??u.join(e,t);if(!await g.pathExists(r))return null;let n=await g.readJson(r),o=v(t),c=q.get(o);if(c&&a$2(n,c,`MCP artifact ${o}`),o===a$1.knowledgeGraph){let p=u.join(e,k);if(!await g.pathExists(p))throw new Error("Workspace knowledge graph cannot be consumed without its source model.");let l=await g.readJson(p);c$3(n,l);}return n}async function F(e$1){let t=[],r=new Set,o=((await a(e$1,d$2))?.blockingReasons??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(o.length>0){t.push({artifact:d$2,reasons:o});for(let i of o)r.add(i);}let c=await a(e$1,c$4);if(e(c)){let i=(c.blockingReasons??[]).filter(s=>typeof s=="string"&&s.trim().length>0);if(i.length>0){t.push({artifact:c$4,reasons:i});for(let s of i)r.add(s);}}let p=await a(e$1,h),l=(p?.violations??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(l.length>0||String(p?.status??"").toLowerCase()==="failed"){let i=l.length>0?l:["Workspace contract verification failed"];t.push({artifact:h,reasons:i});for(let s of i)r.add(s);}return {blockingReasons:[...r],sources:t}}async function I(e$2,t,r){switch(t){case "getWorkspaceModel":return a(e$2,k);case "getWorkspaceKnowledgeGraph":return a(e$2,a$1.knowledgeGraph);case "getWorkspaceEvaluation":return a(e$2,r.live===true?a$1.evaluationLive:a$1.evaluationLastRun);case "queryWorkspaceEntities":{let n=await a(e$2,a$1.knowledgeGraph);if(!n)return null;let o=String(r.kind??"").trim();return {schemaVersion:n.schemaVersion,generatedAt:n.generatedAt,entities:e$1(n,o||void 0)}}case "searchWorkspaceGraph":{let n=await a(e$2,a$1.knowledgeGraph);if(!n)return null;let o=typeof r.limit=="number"?r.limit:Number(r.limit??12);return f(n,{query:String(r.query??""),...typeof r.kind=="string"&&r.kind.trim()?{kind:r.kind.trim()}:{},limit:Number.isFinite(o)?o:12})}case "getWorkspaceGraphEvidence":{let n=await a(e$2,a$1.knowledgeGraph);return n?c$2(n,String(r.query??"")):null}case "findWorkspaceGraphPath":{let n=await a(e$2,a$1.knowledgeGraph);return n?d(n,String(r.from??""),String(r.to??"")):null}case "getEvidenceIndex":return a(e$2,L);case "getBlockers":return F(e$2);case "getSafeCommands":return {safeCommands:(await a(e$2,b$1))?.safeCommands??[]};case "getProjectContext":{let n=await a(e$2,b$1);if(!n)return null;let o=String(r.project??"").trim(),c=n.scope?.activeProject??void 0,p=o||c,l=Array.isArray(n.projects)?n.projects:[],i=p&&l.find(s=>typeof s.name=="string"&&s.name.toLowerCase()===p.toLowerCase());return {workspace:n.workspace??null,scope:n.scope??null,validation:n.validation??null,project:i??null,safeCommands:n.safeCommands??[]}}case "getArtifact":{let n=String(r.relativePath??"").trim();return a(e$2,n)}case "listOperationalSkills":return a(e$2,b$2);case "getWorkspaceExplain":{let n=String(r.target??"release-blocked").trim(),o=c$1(n);if(!o)throw new Error(`Invalid explain target: ${n}`);let c=await a(e$2,c$4);return e(c)&&M(c.target,o)?c:b({workspacePath:e$2,target:o})}default:throw new Error(`Unknown tool: ${t}`)}}function R(e,t){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:e??null,result:t})}
|
|
2
2
|
`);}function E(e,t){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:e??null,error:{code:-32e3,message:t}})}
|
|
3
3
|
`);}async function ce(e){let t=u.resolve(e.workspacePath),r=N.createInterface({input:process.stdin,terminal:false});for await(let n of r){let o=n.trim();if(!o)continue;let c;try{c=JSON.parse(o);}catch{E(null,"Invalid JSON-RPC request");continue}let{id:p,method:l,params:i}=c;try{if(l==="initialize"){R(p,{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"workspai-workspace-mcp",version:"0.1.0"}});continue}if(l==="notifications/initialized")continue;if(l==="tools/list"){R(p,{tools:J.map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema}))});continue}if(l==="tools/call"){let s=String(i?.name??""),K=i?.arguments&&typeof i.arguments=="object"?i.arguments:{},S=await I(t,s,K);R(p,{content:[{type:"text",text:JSON.stringify(S,null,2)}],isError:S==null});continue}E(p,`Unsupported method: ${l??"unknown"}`);}catch(s){E(p,s instanceof Error?s.message:String(s));}}}async function pe(e,t,r={}){return I(u.resolve(e),t,r)}export{J as WORKSPACE_MCP_READ_TOOLS,pe as invokeMcpToolForTest,ce as runWorkspaceMcpServe};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{k as WORKSPACE_MODEL_REPORT_PATH,j as WORKSPACE_MODEL_SCHEMA_VERSION,p as buildWorkspaceModel,q as buildWorkspaceModelCached,o as buildWorkspaceModelFacts,r as buildWorkspaceModelIncremental,m as createWorkspaceModelBuildProvenance,n as validateWorkspaceModelStrict,l as workspaceModelProjectTopology,s as writeWorkspaceModel}from'./chunk-
|
|
1
|
+
export{k as WORKSPACE_MODEL_REPORT_PATH,j as WORKSPACE_MODEL_SCHEMA_VERSION,p as buildWorkspaceModel,q as buildWorkspaceModelCached,o as buildWorkspaceModelFacts,r as buildWorkspaceModelIncremental,m as createWorkspaceModelBuildProvenance,n as validateWorkspaceModelStrict,l as workspaceModelProjectTopology,s as writeWorkspaceModel}from'./chunk-7AR5PDLD.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{b as finalizeWorkspaceOnboarding,a as syncWorkspaceConsumerArtifacts}from'./chunk-
|
|
1
|
+
export{b as finalizeWorkspaceOnboarding,a as syncWorkspaceConsumerArtifacts}from'./chunk-2FJW6GSW.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-
|
|
1
|
+
import {b as b$1}from'./chunk-RA24WQLF.js';import {g as g$1}from'./chunk-WIO6L24E.js';import g from'path';import i from'fs-extra';var l="README.md",h="<!-- workspai:workspace-intelligence:start -->",c="<!-- workspai:workspace-intelligence:end -->",m={minimal:"A lightweight workspace boundary that adds runtimes only when you need them.","node-only":"A Node.js-focused workspace with shared evidence and agent grounding.","python-only":"A Python-focused workspace with shared evidence and agent grounding.","go-only":"A Go-focused workspace with shared evidence and agent grounding.","java-only":"A Java-focused workspace with shared evidence and agent grounding.","dotnet-only":"A .NET-focused workspace with shared evidence and agent grounding.",polyglot:"A multi-runtime workspace for projects that share contracts, evidence, and agents.",enterprise:"A governed multi-runtime workspace with the complete evidence, policy, and agent surface."};function w(e){return e?.trim()||"minimal"}async function u(e){let n=g.join(e,".workspai","workspace.json");return await i.pathExists(n)?await i.readJson(n).catch(()=>({})):{}}function f(e){let n=e.engine;if(!n)return;if(n.python_core?.status==="skipped")return "Optional Python engine: not installed";if(n.python_version)return `Optional Python engine: Python ${n.python_version} via ${n.install_method||"local environment"}`}function y(e){let n=w(e.profile),r=b$1().presentations.standard.nodes.map(s=>s.label).join(" \u2192 "),a=e.projectCount===1?"project":"projects",t=m[n]??"A governed workspace with shared evidence for developers, tools, CI, IDEs, and AI agents.";return `${h}
|
|
2
2
|
# ${e.workspaceName}
|
|
3
3
|
|
|
4
4
|
This is a **Workspai Workspace Intelligence** workspace. It gives every registered project one shared, evidence-backed view for developers, CI, IDEs, and AI agents.
|
package/dist/{workspace-registry-summary-HOQ3OBNT.js → workspace-registry-summary-GPJEL7K7.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH,b as WORKSPACE_REGISTRY_SUMMARY_SCHEMA_VERSION,f as buildWorkspaceRegistrySummary,g as formatWorkspaceRegistrySyncSummary,e as publishWorkspaceRegistrySummary,d as readWorkspaceRegistrySummary,c as resolveWorkspaceRegisteredProjects}from'./chunk-
|
|
1
|
+
export{a as WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH,b as WORKSPACE_REGISTRY_SUMMARY_SCHEMA_VERSION,f as buildWorkspaceRegistrySummary,g as formatWorkspaceRegistrySyncSummary,e as publishWorkspaceRegistrySummary,d as readWorkspaceRegistrySummary,c as resolveWorkspaceRegisteredProjects}from'./chunk-3DONU3DU.js';
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {c as c$2}from'./chunk-27AXFTKW.js';import {a as a$2}from'./chunk-SUV7Y2FH.js';import {d,h as h$1,i,j as j$1,g as g$1,l,m,n}from'./chunk-T6JI7GYZ.js';import {a,c,h,b as b$1,e,g,d as d$1}from'./chunk-E5YYVFM2.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {a as a$3}from'./chunk-44VJHNZB.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import c$1 from'path';import {execa}from'execa';import u from'fs-extra';var pe=".workspai/repair",ze="transaction.json",Xe="source-plan.json",We="checkpoint",Ye="engine.lock",Fe=5*1024*1024,Ze=25*1024*1024,Qe=25*1024*1024,ea=4*1024*1024,aa=900*1e3,ta=new Set(["package.json","pyproject.toml","requirements.txt","go.mod","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","pom.xml","build.gradle","build.gradle.kts"]),ra=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","requirements-dev.txt","uv.lock","poetry.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deno.json","deno.jsonc","deno.lock","Directory.Packages.props","packages.lock.json","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile"]),_={safe:0,guarded:1,invasive:2},oa=new Set(["node","npm","npx","pnpm","yarn","bun","deno","python","python3","py","pip","pip3","poetry","uv","pytest","pip-audit","govulncheck","go","cargo","composer","bundle","bundle-audit","dotnet","mvn","mvnw","gradle","gradlew","mix","make"]);function A(e){return (e?.()??new Date).toISOString()}function j(e){return createHash("sha256").update(e).digest("hex")}function L(e){return Array.isArray(e)?`[${e.map(L).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,a])=>a!==void 0).sort(([a],[t])=>a.localeCompare(t)).map(([a,t])=>`${JSON.stringify(a)}:${L(t)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}function $(e,a){let t=c$1.relative(c$1.resolve(e),c$1.resolve(a));return t===""||!t.startsWith("..")&&!c$1.isAbsolute(t)}async function G(e,a){let t=await u.realpath(e).catch(()=>c$1.resolve(e)),r=c$1.resolve(a);for(;!await u.pathExists(r);){let i=c$1.dirname(r);if(i===r)return false;r=i;}let o=await u.realpath(r).catch(()=>c$1.resolve(r));return $(t,o)}function S(e,a){let t=c$1.isAbsolute(a)?c$1.resolve(a):c$1.resolve(e,a);if(!$(e,t))throw new Error(`Repair path escapes workspace boundary: ${a}`);return c$1.relative(e,t).split(c$1.sep).join("/")||"."}function V(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return c$1.join(e,pe,"transactions",a)}function ie(e,a){return c$1.join(V(e,a),ze)}function le(e,a){return c$1.join(V(e,a),Xe)}async function M(e,a){await u.ensureDir(c$1.dirname(e));let t=`${e}.${process.pid}.${randomUUID()}.tmp`;await u.writeJson(t,a,{spaces:2}),await u.move(t,e,{overwrite:true});}function P(e,a,t,r={}){e.events.push({sequence:e.events.length+1,at:A(r.now),type:a,...r.stageId?{stageId:r.stageId}:{},...r.status?{status:r.status}:{},message:t});}async function y(e,a,t){a.revision+=1,a.updatedAt=A(t),a$1(a,c,"Workspace repair transaction"),await M(ie(e,a.transactionId),a),await M(c$1.join(e,b$1),a);}async function z(e){let a$2=await u.readJson(ie(e.workspacePath,e.transactionId));if(a$2.schemaVersion!==a)throw new Error(`Unsupported repair transaction schema: ${a$2.schemaVersion}`);return a$1(a$2,c,"Workspace repair transaction"),a$2}async function ue(e,a){return await u.readJson(le(e,a))}function Ne(e){return e.schemaVersion===d$1}function ae(e,a){let t=a.scope==="project"&&a.projectPath?a.projectPath:".",r=c$1.isAbsolute(t)?c$1.resolve(t):c$1.resolve(e,t);if(!$(e,r))throw new Error(`Repair project scope escapes workspace: ${t}`);return r}function v(e){return {cwd:S(e.workspacePath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function Se(e){return u.readFile(e,"utf8").catch(()=>"")}async function sa(e){return u.readJson(e).catch(()=>({}))}function Ce(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}function ia(e){let a=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(r=>r.toLowerCase()):[""],t=c$1.extname(e).length>0;return (process.env.PATH??"").split(c$1.delimiter).filter(Boolean).flatMap(r=>t?[c$1.join(r,e)]:a.map(o=>c$1.join(r,`${e}${o}`)))}function Te(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function De(e){let a=c$1.resolve(e.workspacePath,e.invocation.cwd);if(e.toolAvailable)return e.toolAvailable(e.invocation.executable,a);let t=e.invocation.executable;if(c$1.isAbsolute(t)||/^\.{1,2}[\\/]/.test(t)){let r=c$1.isAbsolute(t)?t:c$1.resolve(a,t),o=await u.stat(r).catch(()=>{});return Te(o)}for(let r of ia(t)){let o=await u.stat(r).catch(()=>{});if(Te(o))return true}return false}async function he(e){let a=e.stages.filter(o=>o.required&&o.status!=="skipped"&&o.invocation).map(o=>o.invocation),t=new Map;for(let o of a)t.set(`${o.cwd}\0${o.executable}`,o);let r=[];for(let o of t.values()){let i=await De({workspacePath:e.workspacePath,invocation:o,toolAvailable:e.toolAvailable});r.push({id:`tool:${o.cwd}:${o.executable}`,status:i?"passed":"failed",message:i?`Required repair executable is available: ${o.executable} (${o.cwd}).`:`Required repair executable is unavailable: ${o.executable} (${o.cwd}). Install or configure it, then create a fresh plan.`});}return r}function K(e,a,t){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:t}}function b(e){return {id:e.id,kind:e.kind,status:e.invocation?"pending":e.required===false?"skipped":"blocked",required:e.required??true,risk:e.risk??"safe",summary:e.summary,...e.invocation?{invocation:e.invocation}:{}}}function na(e,a,t){let r=t.strategy?.find(o=>o.kind==="verify"&&o.invocation)?.invocation;if(r)return v({workspacePath:e,projectPath:a,executable:r.executable,args:r.args,purpose:"audit"})}async function ca(e){let a=ae(e.workspacePath,e.action),t=S(e.workspacePath,a),r=async l=>u.pathExists(c$1.join(a,l)),o=new Set,i=[],d=[],s=l=>`${t}:${e.adapterId}:${l}`,p=l=>l.forEach(w=>o.add(S(e.workspacePath,c$1.join(a,w)))),n=l=>{i.push(l),l.required&&l.status==="blocked"&&d.push(l.summary);},g$1=na(e.workspacePath,a,e.action),m=()=>{let l=g.find(w=>w.id===e.adapterId);if(!l)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:i,checkpointFiles:[...o],blockers:d,adapters:[{adapterId:l.id,ecosystem:l.ecosystem,projectPath:t,manifests:l.manifests,support:l.support,status:d.length>0?"partial":"ready",requiredExecutables:[...new Set(i.filter(w=>w.required&&w.invocation).map(w=>w.invocation.executable))],missingExecutables:[],message:d.length>0?[...new Set(d)].join(" "):`${l.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await r("package.json")){let l=await sa(c$1.join(a,"package.json")),w=l.scripts&&typeof l.scripts=="object"&&!Array.isArray(l.scripts)?l.scripts:{},R=await r("bun.lock")||await r("bun.lockb")?"bun":await r("pnpm-lock.yaml")?"pnpm":await r("yarn.lock")?"yarn":"npm",I=R==="bun"?await r("bun.lock")?"bun.lock":"bun.lockb":R==="pnpm"?"pnpm-lock.yaml":R==="yarn"?"yarn.lock":await r("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";p(["package.json",I]),n(b({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${R} manifest, lockfile, and installed tree.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:R,args:["install"],purpose:"reconcile"})}));let C=v(R==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:R==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:R==="yarn"?{workspacePath:e.workspacePath,projectPath:a,executable:"yarn",args:["npm","audit","--json","--severity","moderate"],purpose:"audit"}:{workspacePath:e.workspacePath,projectPath:a,executable:"bun",args:["audit","--json"],purpose:"audit"});return n(b({id:s("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:g$1??C})),n(typeof w.test=="string"&&w.test.trim()?b({id:s("test"),kind:"test",summary:"Run the declared project test contract.",invocation:Ce({workspacePath:e.workspacePath,projectPath:a,manager:R,script:"test",purpose:"test"})}):K(s("test"),"test","No test script is declared.")),n(typeof w.build=="string"&&w.build.trim()?b({id:s("build"),kind:"build",summary:"Run the declared project build contract.",invocation:Ce({workspacePath:e.workspacePath,projectPath:a,manager:R,script:"build",purpose:"build"})}):K(s("build"),"build","No build script is declared.")),m()}if(e.adapterId==="python"&&(await r("pyproject.toml")||await r("requirements.txt"))){p(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let l=process.platform==="win32"?"python":"python3",w=c$1.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");await u.pathExists(w)&&(l=w);let R=await r("uv.lock")?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):await r("poetry.lock")?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await r("requirements.txt")&&$(e.workspacePath,l)?v({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):void 0;n(b({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:R})),n(b({id:s("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:g$1}));let I=await Se(c$1.join(a,"pyproject.toml")),C=await r("tests")||/\[tool\.pytest/i.test(I);return n(C?b({id:s("test"),kind:"test",summary:"Run the Python test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["-m","pytest"],purpose:"test"})}):K(s("test"),"test","No Python test surface is declared.")),n(/\[build-system\]/i.test(I)?b({id:s("build"),kind:"build",summary:"Build the declared Python package.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["-m","build"],purpose:"build"})}):K(s("build"),"build","No Python build contract is declared.")),m()}let f=[{adapterId:"go",manifest:"go.mod",files:["go.mod","go.sum"],reconcile:["go",["mod","tidy"]],audit:["govulncheck",["-json","./..."]],test:["go",["test","./..."]],build:["go",["build","./..."]]},{adapterId:"rust",manifest:"Cargo.toml",files:["Cargo.toml","Cargo.lock"],reconcile:["cargo",["check"]],audit:["cargo",["audit","--json"]],test:["cargo",["test"]],build:["cargo",["build"]]},{adapterId:"php-composer",manifest:"composer.json",files:["composer.json","composer.lock"],reconcile:["composer",["install","--no-interaction"]],audit:["composer",["audit","--format=json"]],test:["composer",["run-script","test"]],build:["composer",["run-script","build"]]},{adapterId:"ruby-bundler",manifest:"Gemfile",files:["Gemfile","Gemfile.lock"],reconcile:["bundle",["install"]],audit:["bundle-audit",["check","--format","json"]],test:["bundle",["exec","rake","test"]],build:["bundle",["exec","rake","build"]]},{adapterId:"elixir-mix",manifest:"mix.exs",files:["mix.exs","mix.lock"],reconcile:["mix",["deps.get"]],audit:["mix",["hex.audit"]],test:["mix",["test"]],build:["mix",["compile","--warnings-as-errors"]]},{adapterId:"deno",manifest:"deno.json",alternateManifest:"deno.jsonc",files:["deno.json","deno.lock"],reconcile:["deno",["install"]],audit:["deno",["audit"]],test:["deno",["task","test"]],build:["deno",["task","build"]]}];for(let l of f){if(l.adapterId!==e.adapterId)continue;let w=await r(l.manifest)?l.manifest:l.alternateManifest&&await r(l.alternateManifest)?l.alternateManifest:void 0;if(!w)continue;p(l.files),n(b({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${w} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l.reconcile[0],args:l.reconcile[1],purpose:"reconcile"})})),n(b({id:s("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:g$1??(l.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:l.audit[0],args:l.audit[1],purpose:"audit"}):void 0)}));let R=await Se(c$1.join(a,w)),I=l.manifest==="composer.json"||l.adapterId==="deno"?/["']test["']\s*:/.test(R):l.manifest==="Gemfile"?await r("Rakefile"):true,C=l.manifest==="composer.json"||l.manifest==="deno.json"?/["']build["']\s*:/.test(R):l.manifest==="Gemfile"?(await u.readdir(a)).some(T=>T.endsWith(".gemspec")):true;return n(I?b({id:s("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l.test[0],args:l.test[1],purpose:"test"})}):K(s("test"),"test","No test contract is declared.")),n(C?b({id:s("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l.build[0],args:l.build[1],purpose:"build"})}):K(s("build"),"build","No build contract is declared.")),m()}let E=await u.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&E.some(l=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(l)))return p(["Directory.Packages.props","packages.lock.json",...E.filter(l=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(l))]),n(b({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),n(b({id:s("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:g$1??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),n(b({id:s("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),n(b({id:s("build"),kind:"build",summary:"Build the .NET project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["build","--no-restore"],purpose:"build"})})),m();let x=await r("mvnw")?"./mvnw":"mvn";if(e.adapterId==="jvm-maven"&&await r("pom.xml"))return p(["pom.xml"]),n(b({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:x,args:["dependency:resolve"],purpose:"reconcile"})})),n(b({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:g$1})),n(b({id:s("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:x,args:["test"],purpose:"test"})})),n(b({id:s("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:x,args:["package","-DskipTests"],purpose:"build"})})),m();let F=await r("build.gradle.kts")?"build.gradle.kts":await r("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&F){let l=await r("gradlew")?"./gradlew":"gradle";return p([F,"gradle.lockfile","gradle/libs.versions.toml"]),n(b({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["dependencies"],purpose:"reconcile"})})),n(b({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:g$1})),n(b({id:s("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["test"],purpose:"test"})})),n(b({id:s("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["build","-x","test"],purpose:"build"})})),m()}return d.push(`The ${e.adapterId} repair adapter no longer matches the source at ${t}; refresh evidence and create a fresh plan.`),n(b({id:s("reconcile"),kind:"reconcile",required:true,summary:d[0]})),m()}async function Oe(e){let a=i=>u.pathExists(c$1.join(e,i)),t=await u.readdir(e).catch(()=>[]),r=[];await a("package.json")&&r.push("node"),(await a("pyproject.toml")||await a("requirements.txt"))&&r.push("python"),await a("go.mod")&&r.push("go"),await a("Cargo.toml")&&r.push("rust"),await a("composer.json")&&r.push("php-composer"),await a("Gemfile")&&r.push("ruby-bundler"),await a("mix.exs")&&r.push("elixir-mix"),(await a("deno.json")||await a("deno.jsonc"))&&r.push("deno"),t.some(i=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(i))&&r.push("dotnet"),await a("pom.xml")&&r.push("jvm-maven"),(await a("build.gradle.kts")||await a("build.gradle"))&&r.push("jvm-gradle");let o=new Map(g.map((i,d)=>[i.id,d]));return [...new Set(r)].sort((i,d)=>(o.get(i)??999)-(o.get(d)??999))}function da(e){let a=e?.trim().toLowerCase();if(a){if(["npm","pnpm","yarn","bun","node","javascript","typescript"].includes(a))return "node";if(["python","pip","poetry","uv"].includes(a))return "python";if(["go","gomod","go-modules"].includes(a))return "go";if(["rust","cargo"].includes(a))return "rust";if(["php","composer"].includes(a))return "php-composer";if(["ruby","bundler","bundle"].includes(a))return "ruby-bundler";if(["elixir","mix"].includes(a))return "elixir-mix";if(a==="deno")return "deno";if(["dotnet",".net","nuget"].includes(a))return "dotnet";if(["maven","jvm-maven"].includes(a))return "jvm-maven";if(["gradle","jvm-gradle"].includes(a))return "jvm-gradle"}}async function _e(e,a={}){let t=ae(e.workspacePath,e.action),r=S(e.workspacePath,t),o=await Oe(t),i=da(e.action.transaction?.ecosystem),d=i?[i]:o;if(i&&!o.includes(i)){let p=`Doctor declared the ${i} repair adapter for ${r}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[b({id:`${r}:${i}:reconcile`,kind:"reconcile",required:true,summary:p})],checkpointFiles:[],blockers:[p],adapters:[{adapterId:i,ecosystem:g.find(n=>n.id===i)?.ecosystem??i,projectPath:r,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:p}]}}if(d.length===0){let p=`No deterministic dependency transaction adapter exists for ${r}.`;return {stages:[b({id:`${r}:unsupported:reconcile`,kind:"reconcile",required:true,summary:p})],checkpointFiles:[],blockers:[p],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:r,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:p}]}}let s={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let p of d){let n=await ca({...e,adapterId:p});s.stages.push(...n.stages),s.checkpointFiles.push(...n.checkpointFiles),s.blockers.push(...n.blockers),s.adapters.push(...n.adapters);}s.stages=[...new Map(s.stages.map(p=>[p.id,p])).values()],s.checkpointFiles=[...new Set(s.checkpointFiles)].sort(),s.blockers=[...new Set(s.blockers)];for(let p of s.adapters){let n=s.stages.filter(m=>m.id.startsWith(`${p.projectPath}:${p.adapterId}:`)),g=[];for(let m of n)!m.required||!m.invocation||await De({workspacePath:e.workspacePath,invocation:m.invocation,toolAvailable:a.toolAvailable})||g.push(m.invocation.executable);p.missingExecutables=[...new Set(g)],p.missingExecutables.length>0&&(p.status="partial",p.message=`Required executable(s) unavailable: ${p.missingExecutables.join(", ")}.`);}if(d.length===1){let p=`:${d[0]}:`;for(let n of s.stages)n.id=n.id.replace(p,":");}return s}async function Ha(e={}){let a=h();if(!e.workspacePath&&!e.projectPath)return a;let t=c$1.resolve(e.workspacePath??process.cwd()),r=c$1.resolve(t,e.projectPath??".");if(!$(t,r))throw new Error("Repair capability inspection project path escapes the workspace.");return {...a,inspection:{projectPath:S(t,r),detectedAdapters:await Oe(r)}}}function ke(e){if(e.command){let a=d(e.command);if(a)return a}if(e.operation?.type==="file-create")return e.operation}async function pa(e){let a=new Set(e.dependencyFiles);for(let t of e.actions){for(let d of t.files)a.add(S(e.workspacePath,d));let r=ke(t);if(!r)continue;let o=ae(e.workspacePath,t),i="path"in r?r.path:void 0;i&&a.add(S(e.workspacePath,c$1.resolve(o,i)));}return [...a].filter(t=>t!==".").sort()}function la(e,a){if(!a.invocation)return;let t=ae(e,a);return v({workspacePath:e,projectPath:t,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function ge(e){return j(L({sourceEvidenceHash:e.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],stages:e.stages.map(a=>({id:a.id,kind:a.kind,required:a.required,risk:a.risk,...a.invocation?{invocation:a.invocation}:{}})),checkpointFiles:e.checkpointFiles.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,...a.mode!==void 0?{mode:a.mode}:{}}))}))}function Me(e){return ge({sourceEvidenceHash:e.integrity.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations,stages:e.stages.filter(a=>a.kind!=="rollback"),checkpointFiles:e.checkpoint.files})}async function se(e,a){let t=[],r=[],o=0;for(let i of a){let d=c$1.resolve(e,i);if(!$(e,d)){r.push(`Checkpoint path escapes workspace: ${i}`);continue}if(!await G(e,d)){r.push(`Checkpoint path resolves through a link outside the workspace: ${i}`);continue}let s=await u.lstat(d).catch(()=>{});if(s?.isSymbolicLink()){r.push(`Checkpoint refuses symbolic link mutation: ${i}`);continue}if(s&&!s.isFile()){r.push(`Checkpoint target is not a regular file: ${i}`);continue}if(s&&s.size>Fe){r.push(`Checkpoint file exceeds 5 MiB: ${i}`);continue}if(o+=s?.size??0,o>Ze){r.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let p=s?await u.readFile(d):void 0;t.push({path:i,existed:!!s,beforeHash:p?j(p):null,...s?{mode:s.mode}:{}});}return {entries:t,errors:r}}function He(e){let a=e.replaceAll("\\","/"),t=a.split("/"),r=t.at(-1)??a;if(a===".workspai-workspace"||a.startsWith(".workspai/"))return "Canonical workspace state and evidence cannot be edited through a model proposal.";if(a===".git"||a.startsWith(".git/"))return "Git internals cannot be edited through a model proposal.";if(t.includes("node_modules"))return "Installed dependency trees cannot be edited through a model proposal.";if(/^\.env(?:\.|$)/i.test(r)&&!/^\.env\.(?:example|sample|template)$/i.test(r))return "Secret-bearing environment files cannot be edited through a model proposal.";if(/\.(?:pem|key|p12|pfx|jks|keystore)$/i.test(r))return "Private key and credential containers cannot be edited through a model proposal."}async function ua(e){let a=await u.readJson(c$1.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():c$1.basename(e)}function ha(e){return ta.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function ka(e,a){let t=c$1.resolve(e,a),r=c$1.dirname(t);for(;$(e,r);){if((await u.readdir(r).catch(()=>[])).some(ha))return r;if(c$1.resolve(r)===c$1.resolve(e))break;r=c$1.dirname(r);}return e}function ga(e,a,t){return t.some(r=>{let o=c$1.resolve(e,r.path);if(!$(a,o))return false;let i=c$1.basename(o);return ra.has(i)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(i)})}function ma(e){let a=S(e.workspacePath,e.projectPath);return {id:`proposal:${e.proposal.cardId}:${a}`,artifactKind:"workspace-repair-proposal",cardId:e.proposal.cardId,title:"Validate model-proposed repair",order:1,phase:"source-repair",scope:a==="."?"workspace":"project",...e.proposal.projectName?{projectName:e.proposal.projectName}:{},...a!=="."?{projectPath:a}:{},status:"ready",mode:"edit-file",risk:"guarded",requiresApproval:true,blocker:"",summary:e.proposal.rationale,verifyCommand:"workspai workspace intelligence run --for-agent generic --strict --json",cwd:a==="."?"workspace":"project",files:e.proposal.changes.map(t=>t.path),rollback:{available:true,strategy:"idempotent"},notes:["Source changes are applied only by the CLI Repair Engine after hash-bound approval."]}}function fa(e,a){let t=Le(a.executable),[r="",o=""]=a.args;if(a.args.some(s=>/^(?:-e|--eval|-c|--command|-command)$/i.test(s)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let i=["npm","pnpm","yarn","bun"].includes(t);if(!(i&&e.kind==="audit"&&a.args.some(s=>/audit/i.test(s))||i&&["test","build"].includes(e.kind)&&(r==="run"||r===e.kind||o===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(t)||["python","python3","py"].includes(t)&&r==="-m"&&["pytest","unittest","build","pip_audit"].includes(o.replaceAll("-","_"))||t==="poetry"&&["run","check"].includes(r)||t==="uv"&&r==="run"||t==="go"&&["test","build","vet"].includes(r)||t==="cargo"&&["test","build","check","audit"].includes(r)||t==="composer"&&["audit","run-script","validate"].includes(r)||t==="bundle"&&r==="exec"&&o==="rake"||t==="dotnet"&&["test","build"].includes(r)||["mvn","mvnw","gradle","gradlew"].includes(t)&&a.args.some(s=>/^(?:test|build|check|verify|package)$/i.test(s))||t==="mix"&&(r==="test"||r==="compile"||r==="hex.audit"&&e.kind==="audit")||t==="deno"&&(r==="test"||r==="task"&&["test","build"].includes(o))))throw new Error(`Validation ${e.id} must use a runtime-native audit, test, or build command; arbitrary executables are not accepted from a model.`)}async function wa(e){let a=[],t=new Set,r=[],o=[],i=new Set,d=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let s of e.proposal.validation??[]){let p=c$1.resolve(e.workspacePath,s.cwd),n=S(e.workspacePath,p),g=await u.lstat(p).catch(()=>{});if(!g?.isDirectory()||g.isSymbolicLink()||!await G(e.workspacePath,p)){r.push(`Validation ${s.id} requires a real directory inside the workspace.`);continue}if(d&&!$(d,p)){r.push(`Validation ${s.id} escapes the declared project scope.`);continue}if(_[s.risk]>_[e.maxRisk]){r.push(`Validation ${s.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let m=v({workspacePath:e.workspacePath,projectPath:p,executable:s.executable,args:s.args,purpose:s.kind,timeoutMs:s.timeoutMs});try{me(e.workspacePath,m,e.policy),fa(s,m);}catch(f){r.push(f instanceof Error?f.message:String(f));continue}a.push(b({id:`validation:${s.id}`,kind:s.kind,risk:s.risk,required:s.required,summary:s.summary,invocation:m})),i.add(`${n}:${s.kind}`);}for(let s of e.projectRoots){let p=ma({workspacePath:e.workspacePath,projectPath:s,proposal:e.proposal}),n=await _e({workspacePath:e.workspacePath,action:p},e.dependencies);o.push(...n.adapters);let g=ga(e.workspacePath,s,e.proposal.changes);if(g){for(let f of n.checkpointFiles)t.add(f);r.push(...n.blockers);}let m=S(e.workspacePath,s);for(let f of n.stages)!g&&!["test","build"].includes(f.kind)||i.has(`${m}:${f.kind}`)||a.push(f);}return {stages:[...new Map(a.map(s=>[s.id,s])).values()],checkpointFiles:[...t],blockers:[...new Set(r)],adapters:[...new Map(o.map(s=>[`${s.projectPath}:${s.adapterId}`,s])).values()]}}async function ba(e,a$3={}){let t=c$1.resolve(e.workspacePath),r=await a$2({workspacePath:t,includeAbsolutePaths:false,ciMode:true}),o=r.actions.filter(k=>k.cardId===e.cardId).filter(k=>!e.actionId||k.id===e.actionId).filter(k=>!e.projectName||k.projectName===e.projectName).sort((k,O)=>k.order-O.order||k.id.localeCompare(O.id)),i=e.maxRisk??"guarded",d={maxRisk:i,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},s=[{id:"workspace-root",status:await u.pathExists(c$1.join(t,".workspai-workspace"))||await u.pathExists(c$1.join(t,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:o.length>0?"passed":"failed",message:o.length>0?`${o.length} governed action(s) selected.`:"No governed remediation action matches this target."}],p=[],n=[],g=[],m=[],f=new Set(["manual-repair","cancel"]);for(let k of o){let O=ke(k),N=la(t,k);if(_[k.risk]<=_[i]||(m.push(`${k.id} exceeds the approved ${i} risk ceiling.`),f.add(k.risk==="invasive"?"approve-invasive":"approve-guarded")),(k.status==="blocked"||k.status==="guidance-only")&&m.push(`${k.id} is ${k.status}: ${k.blocker}`),!O&&!N&&m.push(`${k.id} has no typed operation or structured invocation.`),N)try{me(t,N,d);}catch(D){let H=D instanceof Error?D.message:String(D);m.push(H),/Force-based/.test(H)&&f.add("allow-force"),/Breaking dependency/.test(H)&&f.add("allow-breaking");}if(p.push({id:`action:${k.id}`,kind:"repair",status:O||N?"pending":"blocked",required:true,risk:k.risk,summary:k.summary,...N?{invocation:N}:{}}),k.transaction?.kind==="dependency-security"){let D=await _e({workspacePath:t,action:k},a$3);p.push(...D.stages),n.push(...D.checkpointFiles),m.push(...D.blockers),g.push(...D.adapters);}}let E=[...new Map(p.map(k=>[k.id,k])).values()];p.splice(0,p.length,...E),p.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),s.push(...await he({workspacePath:t,stages:p,toolAvailable:a$3.toolAvailable}));let x=await pa({workspacePath:t,actions:o,dependencyFiles:n}),F=await se(t,x);s.push({id:"rollback-coverage",status:o.some(k=>k.mode==="edit-file"||k.mode==="run-command")&&x.length===0?"failed":"passed",message:x.length>0?`${x.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),s.push({id:"structured-execution",status:p.some(k=>k.required&&k.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),s.push({id:"checkpoint-boundary",status:F.errors.length===0?"passed":"failed",message:F.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":F.errors.join(" ")});let l=j(L(r)),w={cardId:e.cardId,scope:o.some(k=>k.scope==="project")?"project":"workspace",...e.projectName?{projectName:e.projectName}:{},...o.length===1&&o[0].projectPath?{projectPath:o[0].projectPath}:{},actionIds:o.map(k=>k.id)},R=A(a$3.now),I=`repair_${randomUUID().replaceAll("-","")}`,C=s.some(k=>k.status==="failed")||m.length>0,T=[...m,...s.filter(k=>k.status==="failed").map(k=>k.message)],W={schemaVersion:a,transactionId:I,revision:1,createdAt:R,updatedAt:R,workspace:{name:r.workspace.name,rootRef:"."},target:w,state:C?"decision-required":"awaiting-approval",policy:d,approval:{required:true,status:"pending"},preconditions:s,adapterEvaluations:[...new Map(g.map(k=>[`${k.projectPath}:${k.adapterId}`,k])).values()],checkpoint:{status:x.length>0?"pending":"unavailable",files:F.entries},stages:p,...C?{decision:{reason:[...new Set(T)].join(" "),options:[...f]}}:{},events:[],integrity:{sourceEvidenceHash:l,planHash:ge({sourceEvidenceHash:l,target:w,policy:d,preconditions:s,adapterEvaluations:[...new Map(g.map(k=>[`${k.projectPath}:${k.adapterId}`,k])).values()],stages:p,checkpointFiles:F.entries})}};P(W,"planned",C?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$3.now}),a$1(W,c,"Workspace repair transaction");let X=V(t,I);return await u.ensureDir(X),await M(le(t,I),r),await M(ie(t,I),W),await M(c$1.join(t,b$1),W),W}async function va(e$1,a$2={}){a$1(e$1.proposal,e,"Workspace repair proposal");let t=c$1.resolve(e$1.workspacePath),r=JSON.parse(JSON.stringify(e$1.proposal)),o=e$1.maxRisk??"guarded",i={maxRisk:o,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},d=[],s=[],p=new Set(["manual-repair","cancel"]),n=await u.pathExists(c$1.join(t,".workspai-workspace"))||await u.pathExists(c$1.join(t,".workspai"));if(d.push({id:"workspace-root",status:n?"passed":"failed",message:n?"Canonical workspace root markers exist.":"Workspace root markers must exist."}),r.projectPath){r.projectPath=S(t,r.projectPath);let h=c$1.resolve(t,r.projectPath),q=await u.lstat(h).catch(()=>{});(!q?.isDirectory()||q.isSymbolicLink())&&s.push("The declared project path must be a real directory inside the workspace.");}r.validation=r.validation?.map(h=>({...h,cwd:S(t,h.cwd)}));let g=new Set,m=new Set,f=0;for(let h of r.changes){h.path=S(t,h.path),h.path==="."&&s.push(`${h.id} cannot replace the workspace root.`),g.has(h.id)&&s.push(`Duplicate proposal change id: ${h.id}.`),m.has(h.path)&&s.push(`Multiple proposal changes target ${h.path}.`),g.add(h.id),m.add(h.path),f+=Buffer.byteLength(h.content??"","utf8"),f>Qe&&s.push("The model proposal exceeds the 25 MiB source-change limit.");let q=He(h.path);if(q&&s.push(`${h.path}: ${q}`),_[h.risk]>_[o]&&(s.push(`${h.id} exceeds the approved ${o} risk ceiling.`),p.add(h.risk==="invasive"?"approve-invasive":"approve-guarded")),r.projectPath){let Je=c$1.resolve(t,r.projectPath),Ke=c$1.resolve(t,h.path);$(Je,Ke)||s.push(`${h.path} escapes the declared project scope.`);}}let E=[...m].sort(),x=await se(t,E);s.push(...x.errors);let F=new Map(x.entries.map(h=>[h.path,h]));for(let h of r.changes){let q=F.get(h.path);if(!q||q.beforeHash!==h.expectedBeforeHash){s.push(`${h.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}h.operation==="delete"&&!q.existed&&s.push(`${h.path} cannot be deleted because it does not exist.`),h.operation==="write"&&q.beforeHash!==null&&j(h.content??"")===q.beforeHash&&s.push(`${h.path} is a no-op and cannot prove source progress.`);}d.push({id:"proposal-boundary",status:s.length===0?"passed":"failed",message:s.length===0?`${r.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(s)].join(" ")});let l=new Set;if(r.projectPath)l.add(c$1.resolve(t,r.projectPath));else for(let h of r.changes)l.add(await ka(t,h.path));let w=await wa({workspacePath:t,proposal:r,projectRoots:[...l].sort(),maxRisk:o,policy:i,dependencies:a$2});s.push(...w.blockers);let R=w.stages,I=R.some(h=>h.status!=="skipped"&&["audit","test","build"].includes(h.kind));d.push({id:"validation-coverage",status:I?"passed":"unknown",message:I?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let C=[...new Set([...E,...w.checkpointFiles])].sort(),T=await se(t,C);s.push(...T.errors),d.push({id:"checkpoint-boundary",status:T.errors.length===0?"passed":"failed",message:T.errors.length===0?`${T.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:T.errors.join(" ")});let W=[...r.changes.map(h=>({id:`proposal:${h.id}`,kind:"repair",status:_[h.risk]<=_[o]?"pending":"blocked",required:true,risk:h.risk,summary:h.summary,changedPaths:[h.path]})),...R,{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];d.push(...await he({workspacePath:t,stages:W,toolAvailable:a$2.toolAvailable}));let X=new Set(W.map(h=>h.id));X.size!==W.length&&s.push("Repair proposal stage ids must be unique."),d.push({id:"stage-identity",status:X.size===W.length?"passed":"failed",message:X.size===W.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});let k=j(L(r)),O={cardId:r.cardId,scope:r.projectPath||r.projectName?"project":"workspace",...r.projectName?{projectName:r.projectName}:{},...r.projectPath?{projectPath:r.projectPath}:{},actionIds:r.changes.map(h=>`proposal:${h.id}`)},N=A(a$2.now),Y=`repair_${randomUUID().replaceAll("-","")}`,H=d.some(h=>h.status==="failed")||s.length>0,Z={schemaVersion:a,transactionId:Y,revision:1,createdAt:N,updatedAt:N,workspace:{name:await ua(t),rootRef:"."},target:O,state:H?"decision-required":"awaiting-approval",policy:i,approval:{required:true,status:"pending"},preconditions:d,adapterEvaluations:w.adapters,checkpoint:{status:"pending",files:T.entries},stages:W,...H?{decision:{reason:[...new Set([...s,...d.filter(h=>h.status==="failed").map(h=>h.message)])].join(" "),options:[...p]}}:{},events:[],integrity:{sourceEvidenceHash:k,planHash:ge({sourceEvidenceHash:k,target:O,policy:i,preconditions:d,adapterEvaluations:w.adapters,stages:W,checkpointFiles:T.entries})}};P(Z,"planned",H?"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$2.now}),a$1(Z,c,"Workspace repair transaction");let Ve=V(t,Y);return await u.ensureDir(Ve),await M(le(t,Y),r),await M(ie(t,Y),Z),await M(c$1.join(t,b$1),Z),Z}async function Ba(e,a={}){let t=await z(e);if(t.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${t.state}`);if(Me(t)!==t.integrity.planHash)return t.approval.status="expired",t.state="decision-required",t.decision={reason:"The compiled repair plan changed after planning.",options:["cancel"]},await y(e.workspacePath,t,a.now),t;let r=await ue(e.workspacePath,e.transactionId);return j(L(r))!==t.integrity.sourceEvidenceHash?(t.approval.status="expired",t.state="decision-required",t.decision={reason:"The persisted source plan changed after planning.",options:["cancel"]},await y(e.workspacePath,t,a.now),t):(t.approval={required:true,status:"approved",approvedAt:A(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:t.integrity.planHash},t.state="approved",P(t,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await y(e.workspacePath,t,a.now),t)}async function Be(e,a){let t=c$1.join(e,pe,Ye);await u.ensureDir(c$1.dirname(t));try{let r=await u.stat(t),o=await u.readJson(t).catch(()=>({})),i=typeof o.host=="string"?o.host:void 0,d=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,s=false;if((!i||i===hostname())&&d)try{process.kill(d,0),s=true;}catch(n){s=n!==null&&typeof n=="object"&&"code"in n&&n.code==="EPERM";}let p=!!(i&&i!==hostname());!s&&!p&&Date.now()-r.mtimeMs>aa&&await u.remove(t);}catch{}try{await u.outputFile(t,`${JSON.stringify({transactionId:a,pid:process.pid,host:hostname(),acquiredAt:new Date().toISOString()})}
|
|
2
|
+
`,{flag:"wx"});}catch{throw new Error("Another workspace repair transaction currently owns the engine lock.")}return async()=>{(await u.readJson(t).catch(async()=>{let o=await u.readFile(t,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await u.remove(t);}}async function ya(e){if(e.transaction.checkpoint.status==="captured")return;let a=await se(e.workspacePath,e.transaction.checkpoint.files.map(o=>o.path));if(a.errors.length>0)throw new Error(a.errors.join(" "));let t=new Map(a.entries.map(o=>[o.path,o]));for(let o of e.transaction.checkpoint.files){let i=t.get(o.path);if(!i||o.existed!==i.existed||o.beforeHash!==i.beforeHash||o.mode!==i.mode)throw new Error(`Checkpoint precondition changed after planning: ${o.path}. Create and approve a fresh plan.`)}let r=c$1.join(V(e.workspacePath,e.transaction.transactionId),We);await u.ensureDir(r);for(let o=0;o<e.transaction.checkpoint.files.length;o+=1){let i=e.transaction.checkpoint.files[o],d=c$1.resolve(e.workspacePath,i.path),s=i.existed?await u.readFile(d):void 0;if(s&&j(s)!==i.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${i.path}. Create and approve a fresh plan.`);let p=`${We}/${String(o).padStart(4,"0")}.bin`;if(s){let n=c$1.join(V(e.workspacePath,e.transaction.transactionId),p),g=`${n}.${process.pid}.${randomUUID()}.tmp`;await u.writeFile(g,s,{flag:"wx"});let m=await u.readFile(g);if(j(m)!==i.beforeHash)throw await u.remove(g),new Error(`Checkpoint backup verification failed for ${i.path}.`);await u.move(g,n,{overwrite:true}),i.backupRef=p;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=A(e.now),e.transaction.state="checkpointed",P(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function qe(e,a){for(let t of a.checkpoint.files){let r=c$1.resolve(e,t.path),o=await u.readFile(r).catch(()=>{});t.afterHash=o?j(o):null;}}function Le(e){return c$1.basename(e).toLowerCase().replace(/\.(?:cmd|exe)$/i,"")}function me(e,a,t){let r=c$1.resolve(e,a.cwd);if(!$(e,r))throw new Error(`Invocation cwd escapes workspace: ${a.cwd}`);if(a.args.length>100||a.args.some(s=>!s||/[\0\r\n]/.test(s)))throw new Error("Invocation contains invalid arguments.");let o=Le(a.executable),i=c$1.isAbsolute(a.executable),d=/^\.{1,2}[\\/]/.test(a.executable);if(i&&!$(e,a.executable))throw new Error(`Invocation executable escapes workspace: ${a.executable}`);if(!i&&!d&&!oa.has(o))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!t.allowForce&&a.args.some(s=>/^(?:--force|-f)$/i.test(s)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!t.allowBreaking&&a.args.some(s=>/(?:breaking|legacy-peer-deps)/i.test(s)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(o)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${o} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:r,executable:a.executable}}async function de(e){let a=me(e.workspacePath,e.invocation,e.policy),t=await u.lstat(a.cwd).catch(()=>{});if(!t?.isDirectory()||t.isSymbolicLink()||!await G(e.workspacePath,a.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(c$1.isAbsolute(a.executable)||/^\.{1,2}[\\/]/.test(a.executable)){let i=c$1.isAbsolute(a.executable)?a.executable:c$1.resolve(a.cwd,a.executable);if(!await G(e.workspacePath,i))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let r=Object.fromEntries(Object.entries(process.env).filter(([i])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(i))),o=await execa(a.executable,e.invocation.args,{cwd:a.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:ea,stdin:"ignore",extendEnv:false,env:{...r,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:o.exitCode??null,stdout:o.stdout??"",stderr:o.stderr??""}}function B(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
|
|
3
|
+
${e.slice(-a)}`}async function Pa(e,a){if(a.type==="file-create")return h$1({projectPath:e,operation:a});if(a.type==="file-append")return i({projectPath:e,operation:a});if(a.type==="file-copy")return j$1({projectPath:e,operation:a});if(a.type==="package-json-script")return g$1({projectPath:e,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return l({projectPath:e,operation:a});if(a.type==="env-key-add")return m({projectPath:e,operation:a});if(a.type==="makefile-target")return n({projectPath:e,operation:a})}async function Ra(e){let a=c$1.resolve(e.workspacePath,e.change.path);if(!$(e.workspacePath,a)||!await G(e.workspacePath,a))throw new Error(`Proposal target escaped the canonical workspace boundary: ${e.change.path}`);let t=He(e.change.path);if(t)throw new Error(`${e.change.path}: ${t}`);let r=e.transaction.checkpoint.files.find(g=>g.path===e.change.path);if(!r)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let o=await u.readFile(a).catch(()=>{}),i=o?j(o):null;if(i!==r.beforeHash||i!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let d=await u.lstat(a).catch(()=>{});if(d?.isSymbolicLink()||d&&!d.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!d)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await u.remove(a);return}let s=e.change.content??"";if(Buffer.byteLength(s,"utf8")>Fe)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await u.ensureDir(c$1.dirname(a));let p=c$1.join(c$1.dirname(a),`.${c$1.basename(a)}.${process.pid}.${randomUUID()}.repair-tmp`);await u.writeFile(p,s,{encoding:"utf8",flag:"wx"}),await u.move(p,a,{overwrite:true});let n=await u.readFile(a);if(j(n)!==j(s))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function xa(e){if(e.stage.status==="passed"||e.stage.status==="skipped")return true;if(e.stage.status==="blocked")return false;e.stage.status="running",e.stage.startedAt=A(e.dependencies.now),P(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await y(e.workspacePath,e.transaction,e.dependencies.now);try{if(e.stage.kind==="repair"){let a=e.actions.get(e.stage.id);if(!a)throw new Error(`Persisted repair action is missing: ${e.stage.id}`);if(a.kind==="proposal")await Ra({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let t=ke(a.action);if(t)await Pa(ae(e.workspacePath,a.action),t);else if(e.stage.invocation){let r=await(e.dependencies.runInvocation??de)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy});if(e.stage.exitCode=r.exitCode,e.stage.stdoutTail=B(r.stdout),e.stage.stderrTail=B(r.stderr),r.exitCode!==0)throw new Error(r.stderr||r.stdout||`Repair command exited with ${r.exitCode}.`)}else throw new Error("Repair stage has no typed operation or structured invocation.")}}else if(e.stage.invocation){let a=await(e.dependencies.runInvocation??de)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=B(a.stdout),e.stage.stderrTail=B(a.stderr),a.exitCode!==0)throw new Error(a.stderr||a.stdout||`${e.stage.kind} exited with ${a.exitCode}.`)}return e.stage.status="passed",e.stage.completedAt=A(e.dependencies.now),e.stage.summary=`${e.stage.kind} completed.`,await qe(e.workspacePath,e.transaction),P(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await y(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=A(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await qe(e.workspacePath,e.transaction),P(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await y(e.workspacePath,e.transaction,e.dependencies.now),false}}async function ee(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",P(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await y(e.workspacePath,e.transaction,e.dependencies.now);let t=async i=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision={reason:i,options:["manual-repair","cancel"]},P(e.transaction,"decision",i,{status:"conflicted",now:e.dependencies.now}),await y(e.workspacePath,e.transaction,e.dependencies.now),false),r=[];for(let i of e.transaction.checkpoint.files){let d=c$1.resolve(e.workspacePath,i.path);if(!$(e.workspacePath,d)||!await G(e.workspacePath,d))return t(`Rollback refused because ${i.path} escaped the workspace boundary.`);let s=await u.lstat(d).catch(()=>{});if(s?.isSymbolicLink()||s&&!s.isFile())return t(`Rollback refused because ${i.path} is no longer a regular file.`);let p=s?await u.readFile(d):void 0,n=p?j(p):null,g=i.afterHash!==void 0&&n===i.afterHash,m=a&&n===i.beforeHash;if(!g&&!m)return t(`Rollback refused because ${i.path} changed outside this transaction.`);if(!i.existed){r.push({entry:i,absolute:d});continue}if(!i.backupRef)return t(`Rollback refused because the checkpoint backup is missing for ${i.path}.`);let f=c$1.join(V(e.workspacePath,e.transaction.transactionId),i.backupRef),E=await u.lstat(f).catch(()=>{});if(!E?.isFile()||E.isSymbolicLink())return t(`Rollback refused because the checkpoint backup is invalid for ${i.path}.`);let x=await u.readFile(f);if(j(x)!==i.beforeHash)return t(`Rollback refused because the checkpoint backup hash is invalid for ${i.path}.`);r.push({entry:i,absolute:d,backup:x});}for(let i of r){if(!i.entry.existed){await u.remove(i.absolute);continue}let d=i.backup;if(d===void 0)throw new Error(`Validated checkpoint backup disappeared for ${i.entry.path}.`);let s=c$1.join(c$1.dirname(i.absolute),`.${c$1.basename(i.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await u.ensureDir(c$1.dirname(i.absolute)),await u.writeFile(s,d,{flag:"wx"}),i.entry.mode!==void 0&&await u.chmod(s,i.entry.mode),await u.move(s,i.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=A(e.dependencies.now);let o=e.transaction.stages.filter(i=>i.kind==="reconcile"&&i.invocation);for(let i of o){let d=i.invocation;if(!d)continue;let s=`rollback:${i.id}`,p=e.transaction.stages.find(m=>m.id===s&&m.kind==="rollback"),n=p??{id:s,kind:"rollback",status:"pending",required:true,risk:i.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:d};p||e.transaction.stages.push(n),n.status="running",n.startedAt=A(e.dependencies.now),delete n.completedAt,delete n.exitCode,delete n.stdoutTail,delete n.stderrTail,P(e.transaction,"rollback",n.summary,{stageId:n.id,status:"running",now:e.dependencies.now}),await y(e.workspacePath,e.transaction,e.dependencies.now);let g;try{g=await(e.dependencies.runInvocation??de)({workspacePath:e.workspacePath,invocation:d,policy:e.transaction.policy});}catch(m){g={exitCode:null,stdout:"",stderr:m instanceof Error?m.message:String(m)};}if(n.exitCode=g.exitCode,n.stdoutTail=B(g.stdout),n.stderrTail=B(g.stderr),n.completedAt=A(e.dependencies.now),g.exitCode!==0)return n.status="failed",n.summary=g.stderr||g.stdout||`Rollback reconciliation exited with ${g.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision={reason:`Source files were restored, but the installed dependency tree could not be reconciled: ${n.summary}`,options:["manual-repair","cancel"]},P(e.transaction,"decision",e.transaction.decision.reason,{stageId:n.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await y(e.workspacePath,e.transaction,e.dependencies.now),false;n.status="passed",n.summary="Installed dependency tree reconciled with the restored source state.",P(e.transaction,"rollback",n.summary,{stageId:n.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,P(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await y(e.workspacePath,e.transaction,e.dependencies.now),true}async function La(e,a={}){let t=c$1.resolve(e.workspacePath),r=await Be(t,e.transactionId);try{let o=await z({workspacePath:t,transactionId:e.transactionId});if(!["approved","checkpointed","executing","verifying","rollback-required","rolling-back"].includes(o.state))throw new Error(`Repair transaction cannot execute from state ${o.state}.`);if(o.approval.status!=="approved"||o.approval.approvedPlanHash!==o.integrity.planHash)throw new Error("Repair approval is missing, expired, or bound to another plan revision.");if(Me(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision={reason:"The compiled repair plan changed after approval. Create and approve a fresh transaction.",options:["cancel"]},P(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await y(t,o,a.now),o;let i=await ue(t,e.transactionId);if(j(L(i))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision={reason:"Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",options:["cancel"]},P(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await y(t,o,a.now),o;let s=(await he({workspacePath:t,stages:o.stages,toolAvailable:a.toolAvailable})).find(f=>f.status==="failed");if(s)return o.approval.status="expired",o.state="decision-required",o.decision={reason:`${s.message} The approved plan cannot execute against a changed toolchain.`,options:["manual-repair","cancel"]},P(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await y(t,o,a.now),o;if(o.state==="rollback-required"||o.state==="rolling-back"){if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required to resume rollback.");return await ee({workspacePath:t,transaction:o,dependencies:a}),o}let p=new Map(Ne(i)?i.changes.map(f=>[`proposal:${f.id}`,{kind:"proposal",change:f}]):i.actions.map(f=>[`action:${f.id}`,{kind:"canonical",action:f}]));try{await ya({workspacePath:t,transaction:o,now:a.now});}catch(f){return o.approval.status="expired",o.state="decision-required",o.decision={reason:f instanceof Error?f.message:String(f),options:["cancel"]},P(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await y(t,o,a.now),o}o.state="executing",await y(t,o,a.now);for(let f of o.stages.filter(E=>E.kind!=="verify"&&E.kind!=="rollback"))if(!await xa({workspacePath:t,transaction:o,stage:f,actions:p,dependencies:a})&&f.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision={reason:`Required stage ${f.id} failed: ${f.summary}`,options:o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]},await y(t,o,a.now),o.policy.autoRollback&&await ee({workspacePath:t,transaction:o,dependencies:a}),o;o.state="verifying";let n=o.stages.find(f=>f.kind==="verify");if(!n)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision={reason:"The approved plan has no canonical verification stage.",options:o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]},await y(t,o,a.now),o.policy.autoRollback&&await ee({workspacePath:t,transaction:o,dependencies:a}),o;n.status="running",n.startedAt=A(a.now),P(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:n.id,status:"running",now:a.now}),await y(t,o,a.now);let g;try{g=a.verify?await a.verify(t):await c$2({workspacePath:t,strict:true,agent:"generic"});}catch(f){g={status:"failed",exitCode:1,artifactPath:a$3.intelligenceRun},n.stderrTail=B(f instanceof Error?f.message:String(f));}let m=g.exitCode===0&&g.status==="passed";return n.status=m?"passed":"failed",n.completedAt=A(a.now),n.exitCode=g.exitCode,n.summary=m?"Canonical verification passed.":`Canonical verification remained ${g.status}.`,o.verification={status:m?"passed":"failed",artifact:a$3.intelligenceRun,exitCode:g.exitCode,summary:n.summary},P(o,"verification",n.summary,{stageId:n.id,status:n.status,now:a.now}),m?(o.state="closed",delete o.decision,P(o,"closed","Repair closed only after canonical verification passed.",{status:"passed",now:a.now}),await y(t,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision={reason:n.summary,options:o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]},await y(t,o,a.now),o.policy.autoRollback&&await ee({workspacePath:t,transaction:o,dependencies:a}),o)}finally{await r();}}async function ja(e,a={}){let t=c$1.resolve(e.workspacePath),r=await Be(t,e.transactionId);try{let o=await z({workspacePath:t,transactionId:e.transactionId});if(!["checkpointed","executing","verifying","rollback-required","rolling-back","decision-required","failed"].includes(o.state))throw new Error(`Repair transaction cannot roll back from state ${o.state}.`);if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required for rollback.");return await ee({workspacePath:t,transaction:o,dependencies:a}),o}finally{await r();}}async function Va(e,a={}){let t=await z(e);if(["closed","rolled-back","cancelled"].includes(t.state))return t;if(t.checkpoint.status==="captured")throw new Error("Rollback a mutated transaction before cancelling it.");return t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,P(t,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await y(e.workspacePath,t,a.now),t}async function Ja(e,a={}){let t=c$1.resolve(e.workspacePath),r=await z({workspacePath:t,transactionId:e.transactionId});if(r.state!=="decision-required"||!r.decision)throw new Error(`Repair transaction is not awaiting a decision: ${r.state}`);if(!r.decision.options.includes(e.decision))throw new Error(`Decision ${e.decision} is not available. Allowed: ${r.decision.options.join(", ")}.`);if(e.decision==="rollback")return ja({workspacePath:t,transactionId:e.transactionId},a);if(e.decision==="cancel"||e.decision==="manual-repair"){if(r.checkpoint.status==="captured")throw new Error("A mutated transaction must be rolled back before control is released.");return r.state="cancelled",r.approval.status=r.approval.status==="approved"?"expired":r.approval.status,P(r,"decision",e.decision==="manual-repair"?"The user chose manual repair; this transaction released source ownership without mutation.":"The user cancelled the decision-required transaction.",{status:e.decision,now:a.now}),await y(t,r,a.now),r}if(r.checkpoint.status==="captured")throw new Error("Repair policy cannot change after a checkpoint has been captured. Roll back first.");let o=await ue(t,e.transactionId);r.state="cancelled",r.approval.status=r.approval.status==="approved"?"expired":r.approval.status,P(r,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await y(t,r,a.now);let i={maxRisk:e.decision==="approve-invasive"?"invasive":e.decision==="approve-guarded"&&r.policy.maxRisk==="safe"?"guarded":r.policy.maxRisk,allowForce:r.policy.allowForce||e.decision==="allow-force",allowBreaking:r.policy.allowBreaking||e.decision==="allow-breaking",autoRollback:r.policy.autoRollback};if(Ne(o))return va({workspacePath:t,proposal:o,...i},a);let d=r.target.actionIds.map(s=>s.startsWith("action:")?s.slice(7):s);return ba({workspacePath:t,cardId:r.target.cardId,...d.length===1?{actionId:d[0]}:{},projectName:r.target.projectName,...i},a)}async function Ka(e){let a=c$1.join(e,pe,"transactions"),t=await u.readdir(a).catch(()=>[]);return (await Promise.all(t.map(o=>z({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))}export{Ba as approveWorkspaceRepair,Va as cancelWorkspaceRepair,Ja as decideWorkspaceRepair,La as executeWorkspaceRepair,Ha as inspectWorkspaceRepairCapabilities,Ka as listWorkspaceRepairTransactions,ba as planWorkspaceRepair,va as planWorkspaceRepairProposal,z as readWorkspaceRepairTransaction,ja as rollbackWorkspaceRepair};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as runWorkspaceStage}from'./chunk-USMLRNZ7.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-WD2XDMGB.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{d as WORKSPACE_VERIFY_REPORT_PATH,c as WORKSPACE_VERIFY_SCHEMA_VERSION,f as buildWorkspaceVerify,e as computeAffectedSubgraphGate,h as evaluateWorkspaceVerifyGate,i as workspaceVerifyExitCode,g as writeWorkspaceVerify}from'./chunk-
|
|
1
|
+
export{d as WORKSPACE_VERIFY_REPORT_PATH,c as WORKSPACE_VERIFY_SCHEMA_VERSION,f as buildWorkspaceVerify,e as computeAffectedSubgraphGate,h as evaluateWorkspaceVerifyGate,i as workspaceVerifyExitCode,g as writeWorkspaceVerify}from'./chunk-XVRJVKOX.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-FZCYTRBQ.js';import {f as f$1,r,l}from'./chunk-7AR5PDLD.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import y from'fs';var b="workspace-watch-event.v1";function R(e){return a$2(e,"contracts/workspace-watch-event.v1.json","Workspace watch event"),e}function g(e){return `${e.from}\0${e.to}\0${e.kind}`}function f(e){return (l(e)?.edges??[]).map(o=>({from:o.from,to:o.to,kind:o.kind}))}function m(e){let r=[...a(e).entries()].sort((a,n)=>a[0].localeCompare(n[0])).map(([a,n])=>({id:a,hash:n})),c=f(e).map(g).sort((a,n)=>a.localeCompare(n));return f$1({projects:r,edges:c})}function C(e,o){let r=a(o),c=e?a(e):new Map,a$1=[],n=[];for(let[t,s]of r.entries())c.has(t)?c.get(t)!==s&&a$1.push(t):n.push(t);let d=[];for(let t of c.keys())r.has(t)||d.push(t);let i=new Map(e?f(e).map(t=>[g(t),t]):[]),l=new Map(f(o).map(t=>[g(t),t])),p=[];for(let[t,s]of l.entries())i.has(t)||p.push(s);let h=[];for(let[t,s]of i.entries())l.has(t)||h.push(s);let u=(t,s)=>g(t).localeCompare(g(s));return a$1.sort((t,s)=>t.localeCompare(s)),n.sort((t,s)=>t.localeCompare(s)),d.sort((t,s)=>t.localeCompare(s)),p.sort(u),h.sort(u),{changedProjects:a$1,addedProjects:n,removedProjects:d,edgesAdded:p,edgesRemoved:h}}var k=class{model=null;sequence=0;rebuild;now;constructor(o,r$1){this.rebuild=r$1?.rebuild??(()=>r({...o})),this.now=r$1?.now??(()=>new Date);}get currentModel(){return this.model}async start(){let o=Date.now(),{model:r}=await this.rebuild();return this.model=r,this.buildEvent("ready","initial",null,r,Date.now()-o)}async pulse(){let o=Date.now(),r=this.model,{model:c,mode:a}=await this.rebuild(),n=this.buildEvent(this.hasStructuralChange(r,c)?"changed":"unchanged",a,r,c,Date.now()-o);return this.model=c,n}hasStructuralChange(o,r){return o?m(o)!==m(r):true}buildEvent(o,r,c,a,n){let d=C(c,a),i=m(a),l=c?m(c)!==i:true;return R({schemaVersion:b,kind:o,sequence:this.sequence++,timestamp:this.now().toISOString(),mode:r,modelHash:i,modelHashChanged:l,changedProjects:d.changedProjects,addedProjects:d.addedProjects,removedProjects:d.removedProjects,graph:{nodeCount:a.graph?.nodes.length??0,edgeCount:a.graph?.edges.length??0,edgesAdded:d.edgesAdded,edgesRemoved:d.edgesRemoved},durationMs:n})}},S=new Set([".git",".hg",".svn","node_modules",".venv","venv","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),j=new Set(["reports","cache","tmp",".cache"]);function O(e){if(!e)return false;let o=e.split(/[\\/]/).filter(Boolean);if(o.some(r=>S.has(r)||a$1(r)))return false;for(let r=0;r<o.length-1;r+=1)if((o[r]===".workspai"||o[r]===".rapidkit")&&j.has(o[r+1]))return false;return true}async function N(e){let o=new k(e.buildOptions,e.engineOptions),r=await o.start();if(e.emit(r),o.currentModel&&await e.onModel?.(o.currentModel,r),e.once)return;let c=e.debounceMs??250,a=e.selfWriteSuppressionMs??Math.max(400,c+150),n=null,d=false,i=false,l=0,p=async()=>{if(d){i=true;return}d=true;try{let t=await o.pulse();e.emit(t),o.currentModel&&await e.onModel?.(o.currentModel,t);}catch(t){e.emit(R({schemaVersion:b,kind:"error",sequence:-1,timestamp:new Date().toISOString(),mode:"full",modelHash:o.currentModel?m(o.currentModel):"",modelHashChanged:false,changedProjects:[],addedProjects:[],removedProjects:[],graph:{nodeCount:0,edgeCount:0,edgesAdded:[],edgesRemoved:[]},durationMs:0,error:t instanceof Error?t.message:String(t)}));}finally{d=false,l=Date.now()+a,i&&(i=false,p());}},h=t=>{O(t)&&(d||Date.now()<l||(n&&clearTimeout(n),n=setTimeout(()=>{n=null,p();},c)));};e.onProgress?.(`Watching ${e.workspacePath} for changes (Ctrl+C to stop).`);let u=y.watch(e.workspacePath,{recursive:true},(t,s)=>{typeof s=="string"?h(s):s&&h(Buffer.from(s).toString("utf8"));});await new Promise(t=>{let s=()=>{n&&clearTimeout(n),u.close(),t();};if(e.signal){if(e.signal.aborted){s();return}e.signal.addEventListener("abort",s,{once:true});}u.on("error",()=>s());});}export{b as WORKSPACE_WATCH_EVENT_SCHEMA_VERSION,k as WorkspaceWatchEngine,m as computeWatchModelHash,C as diffWatchModels,O as isWatchRelevantPath,N as runWorkspaceWatch};
|