workspai 0.72.1 → 0.74.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/contracts/runtime-command-surface.v1.json +7 -3
- package/dist/analyze-IA33T6MY.js +1 -0
- package/dist/{artifact-remediation-plan-WDK5ISRU.js → artifact-remediation-plan-OVTQM7HN.js} +1 -1
- package/dist/autopilot-release-T327V7QK.js +1 -0
- package/dist/chunk-252EKOR6.js +2 -0
- package/dist/{chunk-U3RX7KDY.js → chunk-4JJDDL3X.js} +1 -1
- package/dist/chunk-5EVBOUYW.js +3 -0
- package/dist/chunk-5Y4YRYZI.js +12 -0
- package/dist/{chunk-4PDEWMOG.js → chunk-773WUMFU.js} +15 -15
- package/dist/{chunk-JPPZDLY3.js → chunk-BTJPTJLT.js} +2 -2
- package/dist/{chunk-WMC2H7MJ.js → chunk-C43NXRRE.js} +1 -1
- package/dist/chunk-D6BL7ARI.js +2 -0
- package/dist/chunk-DLLHUG2Q.js +9 -0
- package/dist/chunk-DPC5DKH6.js +2 -0
- package/dist/{chunk-S66NO5BX.js → chunk-DTLLIA2C.js} +1 -1
- package/dist/{chunk-SS7X2YF5.js → chunk-FYR4FD7K.js} +1 -1
- package/dist/chunk-G6ADWA2B.js +2 -0
- package/dist/chunk-H333GKL4.js +3 -0
- package/dist/{chunk-T6LCDLJ7.js → chunk-H5DRKXXC.js} +1 -1
- package/dist/{chunk-KVPTZMEV.js → chunk-HAZGSAKP.js} +1 -1
- package/dist/{chunk-FYIPYGMW.js → chunk-IQFXLJIM.js} +1 -1
- package/dist/{chunk-JQINCVK5.js → chunk-IUOMBLRR.js} +1 -1
- package/dist/chunk-K3FXRBER.js +4 -0
- package/dist/{chunk-2RF75G5T.js → chunk-KCIET26G.js} +1 -1
- package/dist/chunk-LEEOZRWR.js +7 -0
- package/dist/{chunk-RQKDJVX3.js → chunk-NCZJUPG5.js} +49 -49
- package/dist/{chunk-IX5Z6EK6.js → chunk-ND5YAC4T.js} +1 -1
- package/dist/{chunk-62YBFWHY.js → chunk-RPM67N7A.js} +1 -1
- package/dist/chunk-SAZXL36B.js +157 -0
- package/dist/chunk-SVGUAVMG.js +1 -0
- package/dist/chunk-TBOIXIQA.js +1 -0
- package/dist/chunk-TGDXD4CD.js +1 -0
- package/dist/{chunk-ISGLADQI.js → chunk-TVSMNF5G.js} +1 -1
- package/dist/{chunk-TDQ2PRHV.js → chunk-UHT2SW7O.js} +1 -1
- package/dist/chunk-VLKX5U4H.js +13 -0
- package/dist/chunk-XF65LQ6M.js +1 -0
- package/dist/chunk-YYELANJO.js +7 -0
- package/dist/chunk-ZKYH44ER.js +1 -0
- package/dist/{chunk-N2PAAQKI.js → chunk-ZNKZ2KXR.js} +1 -1
- package/dist/chunk-ZS7JHATN.js +1 -0
- package/dist/{create-FOPYAWAR.js → create-EKA2QG5R.js} +1 -1
- package/dist/doctor-BXSNADVR.js +1 -0
- package/dist/{goal-lifecycle-ZH7AQIOX.js → goal-lifecycle-XXWNMIAD.js} +1 -1
- package/dist/{goal-pack-OP453Q6U.js → goal-pack-NTHYLISY.js} +1 -1
- package/dist/index.js +158 -158
- package/dist/pipeline-JLOC2SUT.js +5 -0
- package/dist/{project-agent-entry-QGPM7CU7.js → project-agent-entry-ZNUHGCVC.js} +1 -1
- package/dist/{project-intelligence-lens-U7PLWYXX.js → project-intelligence-lens-W72OUEDW.js} +1 -1
- package/dist/{project-test-coverage-4BGDDBBL.js → project-test-coverage-5PXAHBYQ.js} +1 -1
- package/dist/{proof-carrying-change-6LQ6JO5J.js → proof-carrying-change-WLUPMUO7.js} +1 -1
- package/dist/verified-goal-6O2JZOOR.js +1 -0
- package/dist/{workspace-3K2YGPU7.js → workspace-XTIGVLGH.js} +1 -1
- package/dist/{workspace-agent-sync-TFQNKRD3.js → workspace-agent-sync-TN6QDNBR.js} +1 -1
- package/dist/{workspace-context-ZDXF6S7S.js → workspace-context-Y3TNY2XZ.js} +1 -1
- package/dist/{workspace-contract-E7GVWM7W.js → workspace-contract-GRZY7WRD.js} +1 -1
- package/dist/{workspace-explain-YB66UFAS.js → workspace-explain-KUYHJFLY.js} +1 -1
- package/dist/{workspace-foundation-J62BMOQS.js → workspace-foundation-ZBUJTR56.js} +1 -1
- package/dist/{workspace-graph-stream-SJUCBPS4.js → workspace-graph-stream-KC2XUAE4.js} +1 -1
- package/dist/workspace-graph-token-efficiency-YHXFGH3Z.js +1 -0
- package/dist/{workspace-intelligence-3IAAM3H3.js → workspace-intelligence-26YT6KMN.js} +1 -1
- package/dist/{workspace-intelligence-benchmark-UCGDKMDF.js → workspace-intelligence-benchmark-QFVTUBDO.js} +1 -1
- package/dist/{workspace-intelligence-evaluation-QDSOOUHH.js → workspace-intelligence-evaluation-4AB4BBRP.js} +1 -1
- package/dist/{workspace-intelligence-runner-OELXKX3D.js → workspace-intelligence-runner-HVYKHCTX.js} +1 -1
- package/dist/{workspace-knowledge-graph-WNQMNAVL.js → workspace-knowledge-graph-RL3I2FHY.js} +1 -1
- package/dist/{workspace-knowledge-graph-query-3GPXGWYN.js → workspace-knowledge-graph-query-TT2KK3SF.js} +1 -1
- package/dist/workspace-knowledge-graph-snapshot-JEJMRQZL.js +1 -0
- package/dist/workspace-marker-7U3NYRPJ.js +1 -0
- package/dist/{workspace-mcp-serve-X7ZYJA3X.js → workspace-mcp-serve-2FGRXJG4.js} +1 -1
- package/dist/{workspace-model-5FA2636K.js → workspace-model-2ODVOWDQ.js} +1 -1
- package/dist/{workspace-onboarding-CZSQDNKO.js → workspace-onboarding-BY6RUBBH.js} +1 -1
- package/dist/{workspace-python-engine-state-BE4A3BL5.js → workspace-python-engine-state-VCOLSEWV.js} +2 -2
- package/dist/{workspace-registry-summary-WKENOFEA.js → workspace-registry-summary-VKTJ7PHV.js} +1 -1
- package/dist/workspace-repair-engine-RBM7NCGI.js +3 -0
- package/dist/workspace-run-JCA5WPCR.js +1 -0
- package/dist/{workspace-verify-37QL2JYE.js → workspace-verify-NFJ7RKKT.js} +1 -1
- package/dist/{workspace-watch-P5X6TAFK.js → workspace-watch-3DBBB6IP.js} +1 -1
- package/docs/SECURITY.md +16 -59
- package/docs/ci-workflows.md +43 -11
- package/package.json +2 -2
- package/dist/analyze-5ENZTHOT.js +0 -1
- package/dist/autopilot-release-QMZSHOLF.js +0 -1
- package/dist/chunk-2LIVMG5C.js +0 -2
- package/dist/chunk-4AW5QP5J.js +0 -5
- package/dist/chunk-5NL53T5C.js +0 -1
- package/dist/chunk-6WOFOOM7.js +0 -7
- package/dist/chunk-BVWDG66W.js +0 -1
- package/dist/chunk-CQBM6BBP.js +0 -2
- package/dist/chunk-CY4QZ3PE.js +0 -3
- package/dist/chunk-I7P6XQJI.js +0 -1
- package/dist/chunk-L4WG3NI7.js +0 -4
- package/dist/chunk-L5ZD2GD3.js +0 -2
- package/dist/chunk-LLEKVSMX.js +0 -9
- package/dist/chunk-LLSY6L7E.js +0 -157
- package/dist/chunk-NSH7TTSV.js +0 -1
- package/dist/chunk-QVUVJU56.js +0 -2
- package/dist/chunk-QYXX6G5O.js +0 -12
- package/dist/chunk-SATPH22S.js +0 -3
- package/dist/chunk-T6KHOIEY.js +0 -13
- package/dist/chunk-UNXG3ZFV.js +0 -1
- package/dist/chunk-WPZUKU2B.js +0 -2
- package/dist/chunk-X5ZNFXFI.js +0 -1
- package/dist/doctor-Z3Z5L67W.js +0 -1
- package/dist/pipeline-LPZHMO7S.js +0 -5
- package/dist/verified-goal-JIRVX7KO.js +0 -1
- package/dist/workspace-graph-token-efficiency-BTIS6JXL.js +0 -1
- package/dist/workspace-knowledge-graph-snapshot-MTFTCVFF.js +0 -1
- package/dist/workspace-marker-XGAWZZDX.js +0 -1
- package/dist/workspace-repair-engine-RXHJX4CQ.js +0 -3
- package/dist/workspace-run-IDRHBKEB.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b,c,d as d$1}from'./chunk-SS7X2YF5.js';import {a as a$3}from'./chunk-X7FYEKLI.js';import {c as c$2}from'./chunk-37SWTS2B.js';import {c as c$1,d as d$4}from'./chunk-N4B2M44I.js';import {a as a$1,b as b$1}from'./chunk-PYCJWW4B.js';import {p as p$1,a,o,g as g$1,d as d$3,f}from'./chunk-QVUVJU56.js';import {q as q$1,m as m$1,d as d$5}from'./chunk-BVWDG66W.js';import {d as d$2}from'./chunk-WPZUKU2B.js';import {g,h}from'./chunk-FE5R6EUV.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {d}from'./chunk-EWZZUQBR.js';import {q,p,t,r,s}from'./chunk-ODK4LCEL.js';import m from'path';import v from'fs-extra';var fe="rapidkit-blocker-resolution-v1";function pe(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return d$5({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function we(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function me(e){let t=we(e.reason),r=pe({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",...e.sourceCommand?{}:{studioActionId:"run-analyze"}}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:fe,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?e.sourceCommand?`Run the source command once: ${e.sourceCommand}, then verify.`:"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function Re(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function Ce(e){return e.length===0||e.every(t=>Re(t))}function ge(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&Ce(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function tt(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var ye=q.verify,G=p.verify;function Ae(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ke(e){let t=await v.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$2(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$2(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let o=s.transitiveImpact.reduce((u,d)=>Math.max(u,d.distance??0),0);s.summary.blastRadius.maxDistance!==o&&i.push("blastRadius.maxDistance does not match transitive impact distances");let k=m$1(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==k&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function Ee(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Se(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function We(e,t){if(e.id==="workspace.doctor")return m.join(t,p.doctor);if(e.id==="workspace.contract.verify")return m.join(t,p.contractVerify);if(e.id==="workspace.readiness")return m.join(t,p.readiness);if(e.id==="workspace.analyze")return m.join(t,".workspai","reports","analyze-last-run.json");if(e.id==="workspace.pipeline")return m.join(t,".workspai","reports","pipeline-last-run.json");if(e.id==="workspace.doctor-fix")return m.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e.id.startsWith("project.")&&e.id.includes("."))return m.join(t,".workspai","reports","workspace-run-last.json")}function C(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function je(e){if(!c$1(e,"workspace"))return {status:"fail",message:"Doctor evidence contract is missing or unsupported."};try{d$4(e);}catch(s){return {status:"fail",message:`Doctor evidence semantic validation failed: ${s instanceof Error?s.message:String(s)}`}}let t=a$3(e);return t.hasSystemErrors||t.blockingFindings>0?{status:"fail",message:`Doctor evidence reports ${t.blockingFindings} canonical blocking finding(s).`}:t.advisoryFindings+t.unknownFindings+t.contradictionCount+t.missingDiagnosisProjects>0||t.staleEvidence||t.unknownFreshness||t.minimumDiagnosisCompleteness<100?{status:"warn",message:`Doctor evidence needs attention (${t.advisoryFindings} advisory, ${t.unknownFindings} unknown, ${t.contradictionCount} contradictory; ${t.minimumDiagnosisCompleteness}% complete).`}:{status:"pass",message:"Canonical Doctor evidence is complete, fresh, and healthy."}}function xe(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function Pe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Ie(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function Ve(e){let t=e.schemaVersion===s.doctorFixResult.schemaVersion?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s$1=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s$1.length>0)return {status:"fail",message:`Doctor fix result reports ${s$1.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function Fe(e,t$1){let r=await g(e,t.doctorRemediationPlan);if(!r)return false;try{let s=C(await v.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let o=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!o||!t$1)return true;let k=Date.parse(o),u=Date.parse(t$1);return !Number.isFinite(k)||!Number.isFinite(u)?true:k>=u}catch{return false}}function $e(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Oe(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function De(e,t,r){let s=$e(t),i=c$2(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let o=i.stage;if(s&&o!==s)return {status:"missing",message:`Workspace run evidence is for stage "${o}", expected "${s}".`};let k=Array.isArray(i.projects)?i.projects:[],u=t.project?.toLowerCase();if(!u)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=k.find(g=>{let c=C(g);if(!c)return false;let n=typeof c.projectName=="string"?c.projectName.toLowerCase():"",a=["projectPath","relativePath","path"].map(f=>c[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return n===u||a.some(f=>f.endsWith(`/${u}`)||f===u)});if(d){let g=R(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(g)return {status:"fail",message:g};let c=C(d),n=typeof c?.status=="string"?c.status:"unknown";return n==="failed"?{status:"fail",message:`Workspace run evidence failed for ${t.project}.`}:n==="passed"?{status:"pass",message:`Workspace run evidence passed for ${t.project}.`}:n==="skipped"?{status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}:{status:"warn",message:`Workspace run evidence status is ${n} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function R(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function Be(e){if(e.id==="workspace.doctor")return r.doctor;if(e.id==="workspace.readiness")return r.readiness;if(e.id==="workspace.contract.verify")return r.contractVerify;if(e.id==="workspace.analyze")return r.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function _e(e,t,r,s$1){let i=We(e,t),o=i?m.relative(t,i).split(m.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let k=i?await g(t,o??""):null;if(!i||!k)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:o,message:o?`Missing evidence report: ${o}`:"No evidence mapping exists for this command."};let u;try{u=await v.readJson(k);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=C(u);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:"Evidence report is not a JSON object."};let g$1=Be(e);if(g$1)try{a$2(d,g$1,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=R(d.generatedAt,s$1,"Doctor evidence");n?c={status:"fail",message:n}:c=je(d);}else if(e.id==="workspace.readiness"){let n=R(d.generatedAt,s$1,"Release readiness evidence");n?c={status:"fail",message:n}:c=xe(d);}else if(e.id==="workspace.contract.verify"){let n=R(d.generatedAt,s$1,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=Pe(d);}else if(e.id==="workspace.analyze"){let n=R(d.generatedAt,s$1,"Analyze evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.pipeline"){let n=R(d.generatedAt,s$1,"Pipeline evidence");n?c={status:"fail",message:n}:c=Oe(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion===s.doctorFixResult.schemaVersion?d:d.fixResult,a=C(n),f=typeof a?.generatedAt=="string"?a.generatedAt:void 0,y=R(f,s$1,"Doctor fix result");y?c={status:"fail",message:y}:await Fe(t,f)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=Ve(d);}else if(e.id.startsWith("project."))c=De(d,e,s$1);else {let n=R(d.generatedAt,s$1,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:o,message:c.message}}function Ne(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,o=e.filter(n=>n.status==="missing").length,k=e.filter(n=>n.status==="skipped").length,u=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,g="ready",c=0;return u.length>0||t.blockingReasons.length>0?(g="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(g="needs-attention",c=1),{verdict:g,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:o,stepsSkipped:k}}function He(e,t){let r=x(e.affectedProjects.map(a=>a.project?.name).filter(a=>typeof a=="string")),s=new Set(r.map(a=>a.toLowerCase())),i=x(e.transitiveImpact.map(a=>a.project?.name).filter(a=>typeof a=="string").filter(a=>!s.has(a.toLowerCase()))),o=new Map;for(let a of t){if(a.scope!=="project"||!a.project)continue;let f=a.project.toLowerCase(),y=o.get(f)??[];y.push(a),o.set(f,y);}let k=[],u=[],d=[],g=[],c=false,n=(a,f)=>{let y=o.get(a.toLowerCase())??[];if(y.length===0){d.push(a);return}let P=y.filter(p=>p.status==="fail"),b=P.filter(p=>p.required),I=y.filter(p=>p.status==="missing"),E=I.filter(p=>p.required),V=y.some(p=>p.status==="pass"||p.status==="warn");if(b.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has failed verification evidence (${b.map(p=>p.id).join(", ")}).`);return}if(P.length>0){u.push(a),c=true;return}if(E.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has missing required verification evidence (${E.map(p=>p.id).join(", ")}).`);return}if(I.length>0){u.push(a),c=true;return}if(V){k.push(a);return}d.push(a);};for(let a of r)n(a,"directly-changed");for(let a of i)n(a,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:x(k),uncovered:x(u),unverifiable:x(d)},blockingReasons:g,needsAttention:c}}function x(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function Me(e){let t=m.resolve(e.workspacePath);if(e.fromImpactPath){let o=Ae(t,e.fromImpactPath);return {impact:await ke(o),fromImpactRef:m.relative(t,o).split(m.sep).join("/"),impactFromDisk:true}}let r=m.join(t,g$1);if(await v.pathExists(r))return {impact:await ke(r),fromImpactRef:g$1,impactFromDisk:true};let s=m.join(t,d$3);if(await v.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$3,scope:e.scope,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),fromImpactRef:d$3,impactFromDisk:false};let i=await q$1({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {impact:{schemaVersion:f,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",diffRef:p.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:m$1(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:q.diff,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",toRef:p.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function Te(e,t){if(t)return e.generatedAt}async function bt(e){let t=m.resolve(e.workspacePath),{impact:r,fromImpactRef:s,impactFromDisk:i}=await Me(e),o$1=r.diff.currentModel,k=i?await q$1({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):o$1,u=[];if(i){let l=await p$1({workspacePath:t,fromPath:r.diff.fromRef,diff:r.diff,scope:e.scope,now:e.now}),W=[r.affectedProjects,r.transitiveImpact,r.verificationPlan],A=[l.affectedProjects,l.transitiveImpact,l.verificationPlan];JSON.stringify(W)!==JSON.stringify(A)&&u.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(k)!==r.diff.toHash&&u.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r.diff.git;if(i&&d$2?.available){let l=a(t,{ref:d$2.ref}),W=r.diff.changes.filter(h=>h.type.startsWith("git.")).map(h=>`${h.type}:${h.target.replace(/^git:/,"")}`).sort(),A=[...l.changedFiles.map(h=>`git.file.changed:${h}`),...l.untrackedFiles.map(h=>`git.untracked:${h}`),...l.deletedFiles.map(h=>`git.deleted:${h}`)].sort();(!l.available||l.commit!==d$2.commit||JSON.stringify(A)!==JSON.stringify(W))&&u.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let g=Te(r,i),c$1=Ee([...o(),...r.verificationPlan]).filter(l=>Se(e.scope,l)),n=[];for(let l of c$1)n.push(await _e(l,t,o$1.contracts.exists===true,g));let a$2=He(r,n),f=a$1(m$1(o$1)??{nodes:[],edges:[]}),y=b(o$1),P=await Ke(t),b$2=c(y,P?.freshness?.projectHashes),I={verdict:b$2.verdict,baseline:b$2.baseline,changed:b$2.changed,added:b$2.added,removed:b$2.removed,projectHashes:d$1(y)},E=b$1(f),V=o$1.policies?.mode??"warn",p=await Le(o$1,t),B=qe(V,p),S=Ne(n,{blockingReasons:[...a$2.blockingReasons,...E,...B.blockingReasons,...u],needsAttention:a$2.needsAttention||B.needsAttention}),he=n.filter(l=>l.status==="missing"&&l.evidencePath).map(l=>l.evidencePath),_=[...n.filter(l=>l.required&&(l.status==="fail"||l.status==="missing")).map(l=>`${l.id}: ${l.message}`),...a$2.blockingReasons,...E,...B.blockingReasons,...u],ve=p.filter(l=>l.severity==="error").length,be=o$1.summary?.projectCount??o$1.projects.length,U=ge({projectCount:be,verdict:S.verdict,exitCode:S.exitCode,blockingReasons:_,policyErrorCount:ve});S.verdict=U.verdict,S.exitCode=U.exitCode;let Y=Array.from(new Set(_.map(l=>l.trim()).filter(Boolean))).slice(0,12).map((l,W)=>{let A=n.find(h=>l.startsWith(`${h.id}:`));return me({reason:l,blockerId:`blocker-${W+1}`,sourceCommand:A?.command.display,sourceArtifact:A?.evidencePath,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:G})});return {schemaVersion:ye,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r.summary.changed,risk:r.summary.risk,affectedProjects:r.summary.affectedProjects,recommendedCommands:r.summary.recommendedCommands},summary:S,steps:n,missingEvidence:he,blockingReasons:_,...Y.length>0?{resolutionHints:Y}:{},verificationPlan:c$1,affectedSubgraph:a$2.subgraph,graphIntegrity:f,freshness:I,policyMode:V,policyViolations:p}}async function Le(e,t){let r=[];for(let i of e.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await g(t,p.contractVerify);try{if(s&&await v.pathExists(s)){let i=await v.readJson(s);if(Array.isArray(i.violations))for(let o of i.violations)typeof o=="string"&&o.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:o});}}catch{}return r.sort((i,o)=>i.source!==o.source?i.source.localeCompare(o.source):i.code!==o.code?i.code.localeCompare(o.code):i.message.localeCompare(o.message))}function qe(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function Ke(e){let t=m.join(e,G);try{if(!await v.pathExists(t))return null;let r=await v.readJson(t);return r&&r.schemaVersion===ye?r:null}catch{return null}}async function wt(e,t){return h(t,G,d$2(e))}function ze(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function Rt(e,t){return ze(e,t).exitCode}export{fe as a,tt as b,ye as c,G as d,He as e,bt as f,wt as g,ze as h,Rt as i};
|
|
1
|
+
import {b,c,d as d$1}from'./chunk-FYR4FD7K.js';import {a as a$3}from'./chunk-X7FYEKLI.js';import {c as c$2}from'./chunk-37SWTS2B.js';import {c as c$1,d as d$4}from'./chunk-N4B2M44I.js';import {a as a$1,b as b$1}from'./chunk-PYCJWW4B.js';import {p as p$1,a,o,g as g$1,d as d$3,f}from'./chunk-D6BL7ARI.js';import {q as q$1,m as m$1,d as d$5}from'./chunk-TGDXD4CD.js';import {d as d$2}from'./chunk-G6ADWA2B.js';import {g,h}from'./chunk-FE5R6EUV.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {d}from'./chunk-EWZZUQBR.js';import {q,p,t,r,s}from'./chunk-ODK4LCEL.js';import m from'path';import v from'fs-extra';var fe="rapidkit-blocker-resolution-v1";function pe(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return d$5({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function we(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function me(e){let t=we(e.reason),r=pe({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",...e.sourceCommand?{}:{studioActionId:"run-analyze"}}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:fe,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?e.sourceCommand?`Run the source command once: ${e.sourceCommand}, then verify.`:"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function Re(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function Ce(e){return e.length===0||e.every(t=>Re(t))}function ge(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&Ce(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function tt(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var ye=q.verify,G=p.verify;function Ae(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ke(e){let t=await v.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$2(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$2(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let o=s.transitiveImpact.reduce((u,d)=>Math.max(u,d.distance??0),0);s.summary.blastRadius.maxDistance!==o&&i.push("blastRadius.maxDistance does not match transitive impact distances");let k=m$1(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==k&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function Ee(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Se(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function We(e,t){if(e.id==="workspace.doctor")return m.join(t,p.doctor);if(e.id==="workspace.contract.verify")return m.join(t,p.contractVerify);if(e.id==="workspace.readiness")return m.join(t,p.readiness);if(e.id==="workspace.analyze")return m.join(t,".workspai","reports","analyze-last-run.json");if(e.id==="workspace.pipeline")return m.join(t,".workspai","reports","pipeline-last-run.json");if(e.id==="workspace.doctor-fix")return m.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e.id.startsWith("project.")&&e.id.includes("."))return m.join(t,".workspai","reports","workspace-run-last.json")}function C(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function je(e){if(!c$1(e,"workspace"))return {status:"fail",message:"Doctor evidence contract is missing or unsupported."};try{d$4(e);}catch(s){return {status:"fail",message:`Doctor evidence semantic validation failed: ${s instanceof Error?s.message:String(s)}`}}let t=a$3(e);return t.hasSystemErrors||t.blockingFindings>0?{status:"fail",message:`Doctor evidence reports ${t.blockingFindings} canonical blocking finding(s).`}:t.advisoryFindings+t.unknownFindings+t.contradictionCount+t.missingDiagnosisProjects>0||t.staleEvidence||t.unknownFreshness||t.minimumDiagnosisCompleteness<100?{status:"warn",message:`Doctor evidence needs attention (${t.advisoryFindings} advisory, ${t.unknownFindings} unknown, ${t.contradictionCount} contradictory; ${t.minimumDiagnosisCompleteness}% complete).`}:{status:"pass",message:"Canonical Doctor evidence is complete, fresh, and healthy."}}function xe(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function Pe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Ie(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function Ve(e){let t=e.schemaVersion===s.doctorFixResult.schemaVersion?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s$1=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s$1.length>0)return {status:"fail",message:`Doctor fix result reports ${s$1.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function Fe(e,t$1){let r=await g(e,t.doctorRemediationPlan);if(!r)return false;try{let s=C(await v.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let o=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!o||!t$1)return true;let k=Date.parse(o),u=Date.parse(t$1);return !Number.isFinite(k)||!Number.isFinite(u)?true:k>=u}catch{return false}}function $e(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Oe(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function De(e,t,r){let s=$e(t),i=c$2(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let o=i.stage;if(s&&o!==s)return {status:"missing",message:`Workspace run evidence is for stage "${o}", expected "${s}".`};let k=Array.isArray(i.projects)?i.projects:[],u=t.project?.toLowerCase();if(!u)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=k.find(g=>{let c=C(g);if(!c)return false;let n=typeof c.projectName=="string"?c.projectName.toLowerCase():"",a=["projectPath","relativePath","path"].map(f=>c[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return n===u||a.some(f=>f.endsWith(`/${u}`)||f===u)});if(d){let g=R(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(g)return {status:"fail",message:g};let c=C(d),n=typeof c?.status=="string"?c.status:"unknown";return n==="failed"?{status:"fail",message:`Workspace run evidence failed for ${t.project}.`}:n==="passed"?{status:"pass",message:`Workspace run evidence passed for ${t.project}.`}:n==="skipped"?{status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}:{status:"warn",message:`Workspace run evidence status is ${n} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function R(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function Be(e){if(e.id==="workspace.doctor")return r.doctor;if(e.id==="workspace.readiness")return r.readiness;if(e.id==="workspace.contract.verify")return r.contractVerify;if(e.id==="workspace.analyze")return r.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function _e(e,t,r,s$1){let i=We(e,t),o=i?m.relative(t,i).split(m.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let k=i?await g(t,o??""):null;if(!i||!k)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:o,message:o?`Missing evidence report: ${o}`:"No evidence mapping exists for this command."};let u;try{u=await v.readJson(k);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=C(u);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:"Evidence report is not a JSON object."};let g$1=Be(e);if(g$1)try{a$2(d,g$1,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=R(d.generatedAt,s$1,"Doctor evidence");n?c={status:"fail",message:n}:c=je(d);}else if(e.id==="workspace.readiness"){let n=R(d.generatedAt,s$1,"Release readiness evidence");n?c={status:"fail",message:n}:c=xe(d);}else if(e.id==="workspace.contract.verify"){let n=R(d.generatedAt,s$1,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=Pe(d);}else if(e.id==="workspace.analyze"){let n=R(d.generatedAt,s$1,"Analyze evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.pipeline"){let n=R(d.generatedAt,s$1,"Pipeline evidence");n?c={status:"fail",message:n}:c=Oe(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion===s.doctorFixResult.schemaVersion?d:d.fixResult,a=C(n),f=typeof a?.generatedAt=="string"?a.generatedAt:void 0,y=R(f,s$1,"Doctor fix result");y?c={status:"fail",message:y}:await Fe(t,f)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=Ve(d);}else if(e.id.startsWith("project."))c=De(d,e,s$1);else {let n=R(d.generatedAt,s$1,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:o,message:c.message}}function Ne(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,o=e.filter(n=>n.status==="missing").length,k=e.filter(n=>n.status==="skipped").length,u=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,g="ready",c=0;return u.length>0||t.blockingReasons.length>0?(g="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(g="needs-attention",c=1),{verdict:g,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:o,stepsSkipped:k}}function He(e,t){let r=x(e.affectedProjects.map(a=>a.project?.name).filter(a=>typeof a=="string")),s=new Set(r.map(a=>a.toLowerCase())),i=x(e.transitiveImpact.map(a=>a.project?.name).filter(a=>typeof a=="string").filter(a=>!s.has(a.toLowerCase()))),o=new Map;for(let a of t){if(a.scope!=="project"||!a.project)continue;let f=a.project.toLowerCase(),y=o.get(f)??[];y.push(a),o.set(f,y);}let k=[],u=[],d=[],g=[],c=false,n=(a,f)=>{let y=o.get(a.toLowerCase())??[];if(y.length===0){d.push(a);return}let P=y.filter(p=>p.status==="fail"),b=P.filter(p=>p.required),I=y.filter(p=>p.status==="missing"),E=I.filter(p=>p.required),V=y.some(p=>p.status==="pass"||p.status==="warn");if(b.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has failed verification evidence (${b.map(p=>p.id).join(", ")}).`);return}if(P.length>0){u.push(a),c=true;return}if(E.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has missing required verification evidence (${E.map(p=>p.id).join(", ")}).`);return}if(I.length>0){u.push(a),c=true;return}if(V){k.push(a);return}d.push(a);};for(let a of r)n(a,"directly-changed");for(let a of i)n(a,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:x(k),uncovered:x(u),unverifiable:x(d)},blockingReasons:g,needsAttention:c}}function x(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function Me(e){let t=m.resolve(e.workspacePath);if(e.fromImpactPath){let o=Ae(t,e.fromImpactPath);return {impact:await ke(o),fromImpactRef:m.relative(t,o).split(m.sep).join("/"),impactFromDisk:true}}let r=m.join(t,g$1);if(await v.pathExists(r))return {impact:await ke(r),fromImpactRef:g$1,impactFromDisk:true};let s=m.join(t,d$3);if(await v.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$3,scope:e.scope,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),fromImpactRef:d$3,impactFromDisk:false};let i=await q$1({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {impact:{schemaVersion:f,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",diffRef:p.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:m$1(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:q.diff,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",toRef:p.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function Te(e,t){if(t)return e.generatedAt}async function bt(e){let t=m.resolve(e.workspacePath),{impact:r,fromImpactRef:s,impactFromDisk:i}=await Me(e),o$1=r.diff.currentModel,k=i?await q$1({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):o$1,u=[];if(i){let l=await p$1({workspacePath:t,fromPath:r.diff.fromRef,diff:r.diff,scope:e.scope,now:e.now}),W=[r.affectedProjects,r.transitiveImpact,r.verificationPlan],A=[l.affectedProjects,l.transitiveImpact,l.verificationPlan];JSON.stringify(W)!==JSON.stringify(A)&&u.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(k)!==r.diff.toHash&&u.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r.diff.git;if(i&&d$2?.available){let l=a(t,{ref:d$2.ref}),W=r.diff.changes.filter(h=>h.type.startsWith("git.")).map(h=>`${h.type}:${h.target.replace(/^git:/,"")}`).sort(),A=[...l.changedFiles.map(h=>`git.file.changed:${h}`),...l.untrackedFiles.map(h=>`git.untracked:${h}`),...l.deletedFiles.map(h=>`git.deleted:${h}`)].sort();(!l.available||l.commit!==d$2.commit||JSON.stringify(A)!==JSON.stringify(W))&&u.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let g=Te(r,i),c$1=Ee([...o(),...r.verificationPlan]).filter(l=>Se(e.scope,l)),n=[];for(let l of c$1)n.push(await _e(l,t,o$1.contracts.exists===true,g));let a$2=He(r,n),f=a$1(m$1(o$1)??{nodes:[],edges:[]}),y=b(o$1),P=await Ke(t),b$2=c(y,P?.freshness?.projectHashes),I={verdict:b$2.verdict,baseline:b$2.baseline,changed:b$2.changed,added:b$2.added,removed:b$2.removed,projectHashes:d$1(y)},E=b$1(f),V=o$1.policies?.mode??"warn",p=await Le(o$1,t),B=qe(V,p),S=Ne(n,{blockingReasons:[...a$2.blockingReasons,...E,...B.blockingReasons,...u],needsAttention:a$2.needsAttention||B.needsAttention}),he=n.filter(l=>l.status==="missing"&&l.evidencePath).map(l=>l.evidencePath),_=[...n.filter(l=>l.required&&(l.status==="fail"||l.status==="missing")).map(l=>`${l.id}: ${l.message}`),...a$2.blockingReasons,...E,...B.blockingReasons,...u],ve=p.filter(l=>l.severity==="error").length,be=o$1.summary?.projectCount??o$1.projects.length,U=ge({projectCount:be,verdict:S.verdict,exitCode:S.exitCode,blockingReasons:_,policyErrorCount:ve});S.verdict=U.verdict,S.exitCode=U.exitCode;let Y=Array.from(new Set(_.map(l=>l.trim()).filter(Boolean))).slice(0,12).map((l,W)=>{let A=n.find(h=>l.startsWith(`${h.id}:`));return me({reason:l,blockerId:`blocker-${W+1}`,sourceCommand:A?.command.display,sourceArtifact:A?.evidencePath,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:G})});return {schemaVersion:ye,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r.summary.changed,risk:r.summary.risk,affectedProjects:r.summary.affectedProjects,recommendedCommands:r.summary.recommendedCommands},summary:S,steps:n,missingEvidence:he,blockingReasons:_,...Y.length>0?{resolutionHints:Y}:{},verificationPlan:c$1,affectedSubgraph:a$2.subgraph,graphIntegrity:f,freshness:I,policyMode:V,policyViolations:p}}async function Le(e,t){let r=[];for(let i of e.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await g(t,p.contractVerify);try{if(s&&await v.pathExists(s)){let i=await v.readJson(s);if(Array.isArray(i.violations))for(let o of i.violations)typeof o=="string"&&o.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:o});}}catch{}return r.sort((i,o)=>i.source!==o.source?i.source.localeCompare(o.source):i.code!==o.code?i.code.localeCompare(o.code):i.message.localeCompare(o.message))}function qe(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function Ke(e){let t=m.join(e,G);try{if(!await v.pathExists(t))return null;let r=await v.readJson(t);return r&&r.schemaVersion===ye?r:null}catch{return null}}async function wt(e,t){return h(t,G,d$2(e))}function ze(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function Rt(e,t){return ze(e,t).exitCode}export{fe as a,tt as b,ye as c,G as d,He as e,bt as f,wt as g,ze as h,Rt as i};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,m}from'./chunk-
|
|
1
|
+
import {d,m}from'./chunk-TGDXD4CD.js';import {a,b}from'./chunk-S5KTATOU.js';function u(r){let s=new Map;for(let n of r.projects)s.has(n.name)||s.set(n.name,d(n));return s}function w(r){let s=u(r),n=m(r)??{nodes:r.projects.map(t=>({id:t.name,path:t.path})),edges:[]},a$1=a(n),o=new Map;for(let t of n.nodes){let e=s.get(t.id)??d({missing:t.id}),l=[...b(a$1,[t.id],{direction:"dependencies"}).keys()].filter(c=>c!==t.id).sort((c,f)=>c.localeCompare(f)).map(c=>({id:c,hash:s.get(c)??"<unknown>"}));o.set(t.id,{id:t.id,ownHash:e,transitiveInputsHash:d({own:e,dependencies:l})});}return o}function y(r,s){if(!s||Object.keys(s).length===0)return {verdict:"unknown",baseline:"none",changed:[],added:[],removed:[]};let n=[],a=[];for(let[e,i]of r.entries())e in s?s[e]!==i.transitiveInputsHash&&n.push(e):a.push(e);let o=[];for(let e of Object.keys(s))r.has(e)||o.push(e);return n.sort((e,i)=>e.localeCompare(i)),a.sort((e,i)=>e.localeCompare(i)),o.sort((e,i)=>e.localeCompare(i)),{verdict:n.length>0||a.length>0||o.length>0?"stale":"fresh",baseline:"recorded",changed:n,added:a,removed:o}}function M(r){let s={};for(let[n,a]of [...r.entries()].sort((o,t)=>o[0].localeCompare(t[0])))s[n]=a.transitiveInputsHash;return s}export{u as a,w as b,y as c,M as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {D as D$1}from'./chunk-5EVBOUYW.js';import {j,m as m$1}from'./chunk-YYELANJO.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2,g,f,h}from'./chunk-FE5R6EUV.js';import {b}from'./chunk-K33JJVQZ.js';import {a as a$3}from'./chunk-252EKOR6.js';import {l}from'./chunk-OCGZNSOE.js';import {t,p,s,q}from'./chunk-ODK4LCEL.js';import {c}from'./chunk-64XWHDZ3.js';import {a}from'./chunk-XWKGZRHN.js';import {t as t$1,u,q as q$1}from'./chunk-VQZ5PI5J.js';import*as m from'path';import m__default from'path';import k from'fs-extra';import Ee from'crypto';var Ce="unknown-run";function ce(e){let t=c();return !t||t===Ce?e:{...e,runId:t}}async function ie(e,t){await k.ensureDir(m.dirname(e));let r=`${e}.${process.pid}.${Date.now()}.${Ee.randomUUID()}.tmp`;try{await k.writeJSON(r,t,{spaces:2}),await k.move(r,e,{overwrite:true});}finally{await k.remove(r).catch(()=>{});}}function pe(e){return q$1(e,"imported-projects.json")}async function I(e){let t=(await Promise.all(t$1(e,"imported-projects.json").map(async r=>await k.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!t)return [];try{let r=await k.readJSON(t);if(!r||typeof r!="object"||r.version!==1||!Array.isArray(r.projects))throw new Error("expected a version 1 registry with a projects array");let o=r.projects,n=o.filter(i=>{if(!i||typeof i!="object")return false;let c=i;return typeof c.name=="string"&&typeof c.path=="string"&&typeof c.stack=="string"&&typeof c.confidence=="string"&&typeof c.importedAt=="string"});if(n.length!==o.length)throw new Error("one or more project entries are invalid");return n}catch(r){throw new Error(`Imported-project registry is invalid: ${t}`,{cause:r})}}async function Je(e,t){if(t.length===0)return;let r=pe(e);await a(`${r}.lock`,async()=>{let o=await I(e),n=new Map;for(let c of o)n.set(c.path,c);for(let c of t)n.set(c.path,c);let i=Array.from(n.values()).sort((c,u)=>c.name.localeCompare(u.name)).map(c=>({...c}));await ie(r,{version:1,updatedAt:new Date().toISOString(),projects:i});},{timeoutMs:3e4,staleMs:6e4,purpose:"imported-projects-registry-upsert"});}async function Ue(e,t){if(t.length===0)return;let r=pe(e);await a(`${r}.lock`,async()=>{let o=await I(e),n=new Set(t.map(c=>m.resolve(c))),i=o.filter(c=>!n.has(m.resolve(c.path)));await ie(r,{version:1,updatedAt:new Date().toISOString(),projects:i});},{timeoutMs:3e4,staleMs:6e4,purpose:"imported-projects-registry-remove"});}var Ye="workspace-dependency-graph.v1",de=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],le=["inferred","contract","manual"];var v=t.workspaceContract,ve=p.contractVerify,_=s.workspaceContract.schemaVersion,je=q.contractVerify,N=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function he(e){return e.replace(/\\/g,"/")}function z(e){let t=he(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function ue(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function be(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function me(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(i=>{if(!i||typeof i!="object"||Array.isArray(i))return null;let c=i,u=Number(c.port);if(!Number.isInteger(u)||u<1||u>65535)return null;let g=c.protocol==="https"||c.protocol==="grpc"||c.protocol==="tcp"||c.protocol==="udp"?c.protocol:"http";return {name:typeof c.name=="string"&&c.name.trim()?c.name:"http",port:u,protocol:g}}).filter(i=>i!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,n=Number(e.port??o?.default_port);return Number.isInteger(n)&&n>=1&&n<=65535?[{name:"http",port:n,protocol:"http"}]:[]}async function We(e){let t=m__default.join(e,"Dockerfile");if(!await k.pathExists(t))return [];try{let r=await k.readFile(t,"utf8"),o=new Map;for(let n of r.matchAll(/^\s*EXPOSE\s+(.+)$/gim))for(let i of n[1].split(/\s+/)){let c=i.match(/^(\d{1,5})(?:\/(tcp|udp))?$/i),u=Number(c?.[1]);if(!c||!Number.isInteger(u)||u<1||u>65535)continue;let g=c[2]?.toLowerCase();o.set(u,{name:"http",port:u,protocol:g==="udp"?"udp":"http"});}return [...o.values()].sort((n,i)=>n.port-i.port)}catch{return []}}async function D(e){for(let t of e)if(await k.pathExists(t))return t;return null}async function Se(e){for(let r of t$1(e,"workspace.json"))try{let o=await k.readJson(r);return {name:typeof o.workspace_name=="string"&&o.workspace_name.trim()||typeof o.name=="string"&&o.name.trim()||m__default.basename(e),profile:typeof o.profile=="string"?o.profile:void 0}}catch{}let t=await a$3(e);return t?.name?.trim()?{name:t.name.trim()}:{name:m__default.basename(e)}}async function Ae(e){let t=[],r=[e],o=new Set,n=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let i=r.shift();if(!i||o.has(i))continue;o.add(i);let c=await D(u(i,"project.json")),u$1=await D(u(i,"context.json"));if(c||u$1){t.push(c??u$1??"");continue}let g;try{g=await k.readdir(i,{withFileTypes:true});}catch{continue}for(let d of g)!d.isDirectory()||n.has(d.name)||a$1(d.name)||r.push(m__default.join(i,d.name));}return t.sort()}function Re(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function xe(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return r.includes("vscode-extension")?null:r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:r.startsWith("adopted.")?null:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function U(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function B(e,t,r){let o=e!==void 0&&e.source===void 0,n=xe(t.kit,t.runtime),i=e?.ports||[],c=t.ports||[],u=(t.kit||"").toLowerCase().includes("vscode-extension"),g=t.source==="adopted-local"&&e?.source!==void 0,d=t.source!==void 0&&e?.source!==void 0,p=(u&&c.length===0?[]:g?c.length>0?c:n?[{name:"http",port:U(n,r),protocol:"http"}]:[]:i.length>0?i:c.length>0?c:n?[{name:"http",port:U(n,r),protocol:"http"}]:[]).map(w=>({...w,port:U(w.port,r)}));for(let w of p)r.add(w.port);let f={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&z(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:d?t.runtime:e?.runtime||t.runtime,framework:d?t.framework:e?.framework||t.framework,kit:d?t.kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:p,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},h=JSON.stringify(e||null)!==JSON.stringify(f);return {project:f,changed:h}}async function ke(e){let t=m__default.resolve(e.workspacePath),r=await Se(t),o=await Ae(t),n=await I(t),i=new Map(n.map(s=>[m__default.resolve(s.path),s])),c=[];for(let s of n){let p=m__default.resolve(s.path),f=await D(u(p,"project.json"))??await D(u(p,"context.json"));!f||o.some(h=>m__default.resolve(h)===m__default.resolve(f))||c.push({projectJsonPath:f,registryEntry:s});}let u$1=[],g=[...o.map(s=>({projectJsonPath:s,registryEntry:i.get(m__default.resolve(m__default.dirname(m__default.dirname(s))))})),...c];for(let{projectJsonPath:s,registryEntry:p}of g){let f=m__default.dirname(m__default.dirname(s)),h=he(m__default.relative(t,f)),w=p!==void 0&&!z(h),C=ue(p?.name||m__default.basename(f),m__default.basename(f)),b=w?`external/${C}`:h||C,P=await k.readJson(s),a=typeof P.kit_name=="string"&&P.kit_name||typeof P.kit=="string"&&P.kit||void 0,E=j(P)?m$1(f,P):void 0,j$1=E!==void 0&&E.key!=="unknown",T=j$1?E.runtime:typeof P.runtime=="string"?P.runtime:void 0,y=j$1?E.key:typeof P.framework=="string"&&P.framework||Re(a),$=p?.relationship==="adopted"?"adopted":"imported",K=j$1?`${$}.${E.key}`:a;u$1.push({slug:p?.name||b||m__default.basename(f),relativePath:b,source:p?.source??"workspace",relationship:p?.relationship,externalPath:w?f:void 0,runtime:T,framework:y,kit:K,modules:be(P.modules),ports:me(P).length>0?me(P):await We(f),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let d=new Map;for(let s of u$1){let p=ue(s.slug,s.relativePath),f=d.get(p);(!f||f.source!=="workspace"&&s.source==="workspace")&&d.set(p,s);}return {schemaVersion:_,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...d.values()]}}async function ut(e){let t=m__default.resolve(e.outputPath||a$2(e.workspacePath,v));if(await k.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await ke({workspacePath:e.workspacePath,now:e.now}),o=new Set,n={...r,projects:r.projects.map(c=>B(void 0,c,o).project)},i=await ye({workspacePath:e.workspacePath,contractPath:t,contract:n});if(e.strict&&i.status==="failed")throw new N(i);return await we({workspacePath:e.workspacePath,contractPath:t,contract:n,now:e.now}),{contractPath:t,contract:n}}async function mt(e){let t=m__default.resolve(e.workspacePath),r=a$2(t,v),o=await g(t,v)??r,n=await ke({workspacePath:t,now:e.now}),i=await k.pathExists(o)?await k.readJson(o):null,c=new Map((i?.projects||[]).map(h=>[h.slug,h])),u=new Set,g$1=[],d=[],s=[];for(let h of n.projects){let w=c.get(h.slug),C=B(w,h,u);w?C.changed&&d.push(h.slug):g$1.push(h.slug),s.push(C.project),c.delete(h.slug);}for(let h of c.values()){if(h.source)continue;let w=B(h,h,u);s.push(w.project);}let p={schemaVersion:_,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...i?.workspace||{},...n.workspace,name:n.workspace.name||i?.workspace?.name||m__default.basename(t)},projects:s.sort((h,w)=>h.slug.localeCompare(w.slug))},f=await ye({workspacePath:t,contractPath:r,contract:p});if(e.strict&&f.status==="failed")throw new N(f);return await we({workspacePath:t,contractPath:r,contract:p,now:e.now}),{contractPath:r,contract:p,addedProjects:g$1,updatedProjects:d,verification:f}}async function ge(e){return await k.pathExists(e)?{exists:true,contents:await k.readFile(e)}:{exists:false}}async function fe(e,t){if(!t.exists){await k.remove(e);return}await k.outputFile(e,t.contents);}async function we(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-VKTJ7PHV.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),n=a$2(e.workspacePath,r),i=c=>{if(!c||typeof c!="object"||Array.isArray(c))return JSON.stringify(c);let{generatedAt:u,...g}=c;return JSON.stringify(g)};if(await k.pathExists(e.contractPath)&&await k.pathExists(n)){let[c,u]=await Promise.all([k.readJson(e.contractPath),k.readJson(n)]);if(i(c)===i(e.contract)&&i(u)===i(o))return}b(v,e.contract),b(r,o),await f(e.workspacePath,v,async()=>{let[c,u]=await Promise.all([ge(e.contractPath),ge(n)]);try{if(e.contractPath===a$2(e.workspacePath,v)?await h(e.workspacePath,v,e.contract):(await k.ensureDir(m__default.dirname(e.contractPath)),await k.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await h(e.workspacePath,r,o);}catch(g){let s=(await Promise.allSettled([fe(e.contractPath,c),fe(n,u)])).filter(p=>p.status==="rejected");throw s.length>0?new AggregateError([g,...s.map(p=>p.reason)],"Workspace contract publication failed and rollback was incomplete."):g}});}async function Pe(e){let t=e.contractPath??(await g(e.workspacePath,v)||a$2(e.workspacePath,v)),r=await k.readJson(t);return {contractPath:t,contract:r}}var _e={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function Ge(e,t){return t.externalPath?m__default.resolve(t.externalPath):m__default.resolve(e,t.relativePath)}async function Oe(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(_e))for(let n of o)await k.pathExists(m__default.join(e,n))&&t[r].push(n);try{let r=await k.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,n)=>o.localeCompare(n));return t}function x(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function Ie(e){try{let t=await k.readJson(m__default.join(e,"package.json")),r={runtime:x(t.dependencies),development:x(t.devDependencies),peer:x(t.peerDependencies),optional:x(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:x(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function Ne(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await k.readFile(m__default.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,n)=>o.localeCompare(n))}catch{}return []}function De(e,t){try{let r=D$1(e);if(r.engine!=="unknown")return r;let o=k.pathExistsSync(m__default.join(e,"package.json"))?"npm":k.pathExistsSync(m__default.join(e,"pyproject.toml"))?"python":k.pathExistsSync(m__default.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",runtimeCandidates:["unknown"],compositeRuntime:false,lifecycleCoverage:"complete",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function Te(e,t,r){let o=e.projects.map(n=>({id:n.slug,path:n.relativePath,runtime:n.runtime,framework:n.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function gt(e){let{contractPath:t,contract:r}=await Pe(e),o=e.now??new Date,n=o.toISOString(),{buildWorkspaceModel:i,workspaceModelProjectTopology:c}=await import('./workspace-model-2ODVOWDQ.js'),{hashWorkspaceModel:u}=await import('./workspace-model-hash-ZXYPIGCW.js'),g=await i({workspacePath:e.workspacePath,includeEvidence:false,now:o}),d=c(g)??Te(r,n,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(d.nodes.map(a=>[a.id,a.operationalProfile])),{buildWorkspaceKnowledgeGraph:p$1}=await import('./workspace-knowledge-graph-RL3I2FHY.js'),f=await p$1({workspacePath:e.workspacePath,workspace:{name:g.workspace.name,...g.workspace.profile?{profile:g.workspace.profile}:{}},contract:r,projectTopology:d,now:o,projects:g.projects.map(a=>({id:a.name,path:a.path,...a.absolutePath?{absolutePath:a.absolutePath}:{},runtime:a.runtime,runtimeCandidates:a.runtimeCandidates,framework:a.framework,...a.kit?{kit:a.kit}:{}})),source:{kind:"workspace-model",artifact:p.model,hashAlgorithm:"sha256",hash:u(g)}}),h=await Promise.all(r.projects.map(async a=>{let l=Ge(e.workspacePath,a),[E,j,T]=await Promise.all([Oe(l),Ie(l),Ne(l)]),y=De(l,a);return {id:a.slug,label:a.slug,relativePath:a.relativePath,source:a.source,relationship:a.relationship,externalPath:a.externalPath,runtime:a.runtime??y.runtime,framework:a.framework??y.framework,kit:a.kit,modules:a.modules,ports:a.ports,apis:a.contracts.apis,owns:a.contracts.owns,env:[...new Set([...a.contracts.env,...T])].sort(($,K)=>$.localeCompare(K)),contracts:{owns:[...a.contracts.owns],apis:[...a.contracts.apis],publishes:[...a.contracts.publishes],consumes:[...a.contracts.consumes],dependsOn:[...a.contracts.dependsOn],env:[...a.contracts.env]},capabilities:{engine:y.engine,supportTier:y.frameworkSupportTier,runtimeSupportTier:y.runtimeSupportTier,doctorSupport:y.runtimeDoctorSupport,moduleSupport:y.moduleSupport,fleetStages:[...y.fleetStages],localOnlyCommands:[...y.localOnlyCommands],supportedCommands:[...y.supportedCommands]},files:E,...j?{package:j}:{},...s.get(a.slug)?{operationalProfile:s.get(a.slug)}:{}}})),w=new Set(h.map(a=>a.id)),C=new Map,b=[];for(let a of r.projects){for(let l of a.contracts.dependsOn||[])w.has(l)&&b.push({from:l,to:a.slug,type:"dependency",label:"dependsOn"});for(let l of a.contracts.publishes||[])C.has(l)||C.set(l,new Set),C.get(l)?.add(a.slug);}for(let a of r.projects)for(let l of a.contracts.consumes||[]){let E=C.get(l);if(E)for(let j of E)j!==a.slug&&b.push({from:j,to:a.slug,type:"event",label:l});}let P={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:n,nodes:h.sort((a,l)=>a.id.localeCompare(l.id)),edges:b.sort((a,l)=>`${a.from}:${a.to}:${a.type}:${a.label}`.localeCompare(`${l.from}:${l.to}:${l.type}:${l.label}`)),dependencyGraph:d,knowledgeGraph:f,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:h.length,dependencyEdges:b.filter(a=>a.type==="dependency").length,eventEdges:b.filter(a=>a.type==="event").length,portCount:h.reduce((a,l)=>a+l.ports.length,0),apiCount:h.reduce((a,l)=>a+l.apis.length,0),relationshipEdges:d.stats.edgeCount,inferredEdges:d.stats.inferredEdges,authoritativeEdges:d.stats.authoritativeEdges,orphanProjects:d.stats.orphanCount,hotspotProjects:d.stats.hotspotCount,evidenceCoverageRatio:d.stats.evidenceCoverageRatio,edgeCoverageRatio:d.stats.edgeCoverageRatio,connectedProjects:d.stats.connectedNodeCount,lowConfidenceEdges:d.stats.lowConfidenceEdges,hasCycle:d.stats.hasCycle,manifestCount:h.reduce((a,l)=>a+l.files.manifests.length,0),entrypointCount:h.reduce((a,l)=>a+l.files.entrypoints.length,0),diagnostics:d.diagnostics?.length??0,relationshipKinds:Object.fromEntries(de.map(a=>[a,d.edges.filter(l=>l.kind===a).length])),relationshipSources:Object.fromEntries(le.map(a=>[a,d.edges.filter(l=>l.source===a).length])),entityCount:f.quality.entityCount,knowledgeRelations:f.quality.relationCount,proofCount:f.quality.proofCount,providerCount:f.providers.length,knowledgeUnknowns:f.quality.unknownCount}};return {contractPath:t,graph:P}}async function ye(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,v),contract:e.contract}:await Pe(e),{contractPath:r,contract:o}=t,n=[],i=[];o.kind!=="rapidkit.workspace.contract"&&n.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==_&&n.push(`Contract schemaVersion must be ${_}.`),o.workspace?.name||n.push("Contract workspace.name is required."),Array.isArray(o.projects)||n.push("Contract projects must be an array.");let c=new Set,u=new Map;for(let s of o.projects||[]){if(!s.slug){n.push("Every project must declare slug.");continue}c.has(s.slug)&&n.push(`Duplicate project slug: ${s.slug}.`),c.add(s.slug),s.relativePath?z(s.relativePath)||n.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):n.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||n.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),m__default.isAbsolute(s.externalPath)||n.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let p of s.ports||[]){(!Number.isInteger(p.port)||p.port<1||p.port>65535)&&n.push(`Project ${s.slug} declares invalid port: ${p.port}.`);let f=u.get(p.port);f&&n.push(`Port ${p.port} is claimed by both ${f} and ${s.slug}.`),u.set(p.port,s.slug);}for(let p of s.contracts?.apis||[])(!p.name?.trim()||!p.basePath?.startsWith("/"))&&n.push(`Project ${s.slug} declares invalid API contract.`);for(let p of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])p.trim()||n.push(`Project ${s.slug} declares an empty event contract.`);for(let p of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(p)||n.push(`Project ${s.slug} declares invalid env contract: ${p}.`);for(let p of s.contracts?.dependsOn||[])c.has(p);}for(let s of o.projects||[])for(let p of s.contracts?.dependsOn||[])c.has(p)||n.push(`Project ${s.slug} depends on unknown project: ${p}.`);i.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===_?"passed":"failed",message:"Contract schema and kind are valid."}),i.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),i.push({id:"ports",status:n.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),i.push({id:"dependencies",status:n.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),i.push({id:"contracts",status:n.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let g=await l(e.workspacePath);if(g.moduleCount>0){for(let s of g.issues)n.push(`${m__default.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);i.push({id:"module-paths",status:g.status,message:g.status==="passed"?`All ${g.moduleCount} registered module(s) resolve under canonical paths.`:`${g.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&i.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:n.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:i,violations:n}}async function ft(e){let t=m__default.resolve(e.workspacePath),r={schemaVersion:je,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return h(t,ve,ce(r))}
|
|
2
|
+
export{I as a,Je as b,Ue as c,ce as d,Ye as e,de as f,v as g,ve as h,_ as i,je as j,N as k,Ae as l,ke as m,ut as n,mt as o,Pe as p,gt as q,ye as r,ft as s};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a as a$1,b as b$1}from'./chunk-O5XQP5E7.js';import {a as a$2}from'./chunk-7Q7X4X5I.js';import {b as b$2}from'./chunk-AO2ZI42U.js';import {a,h,e}from'./chunk-FE5R6EUV.js';import {b}from'./chunk-252EKOR6.js';import {t,s}from'./chunk-ODK4LCEL.js';import y from'path';import {existsSync}from'fs';import ie from'fs-extra';var oe=[{artifactKind:"bootstrap-compliance",cardId:"bootstrap",fileNames:["bootstrap-compliance.latest.json"]},{artifactKind:"doctor-workspace",cardId:"doctor",fileNames:["doctor-remediation-plan-last-run.json","doctor-last-run.json"]},{artifactKind:"analyze",cardId:"analyze",fileNames:["analyze-last-run.json"]},{artifactKind:"readiness",cardId:"readiness",fileNames:["release-readiness-last-run.json"]},{artifactKind:"pipeline",cardId:"pipeline",fileNames:["pipeline-last-run.json"]},{artifactKind:"workspace-run",cardId:"workspaceRun",fileNames:["workspace-run-last.json"]},{artifactKind:"workspace-verify",cardId:"workspaceVerify",fileNames:["workspace-verify-last-run.json"]}];function f(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function w(e){return Array.isArray(e)?e.filter(i=>typeof i=="string"&&i.trim().length>0):[]}function P(e){return [...new Set(e.map(i=>i.trim()).filter(Boolean))]}function J(e){return (e.notes.includes("Doctor finding status: blocking")?16:0)+(e.transaction?8:0)+(e.operation?4:0)+(e.invocation?2:0)+(e.strategy?.length?1:0)}function ne(e){let i=J(e.incoming)>J(e.existing),r=structuredClone(i?e.incoming:e.existing),o=i?e.existing:e.incoming,t=o.sourceStepId;return r.order=e.existing.order,r.files=P([...r.files,...o.files]),r.notes=P([...r.notes,...o.notes.filter(n=>!n.startsWith("Source Doctor capability:")&&!n.startsWith("Doctor finding status:")),...t?[`Also satisfies Doctor capability: ${t}`]:[]]),r}function ae(e,i,r){return r?i:y.relative(e,i).split(y.sep).join("/")}function D(e){return e.includeAbsolutePaths?e.projectPath:b$1({workspacePath:e.workspacePath,projectPath:e.projectPath,projectName:e.projectName}).contractRelativePath}function Z(e){let i=y.isAbsolute(e.filePath)?y.resolve(e.filePath):y.resolve(e.projectPath,e.filePath);if(e.includeAbsolutePaths)return i;let r=y.relative(e.projectPath,i);return !r||r===".."||r.startsWith(`..${y.sep}`)||y.isAbsolute(r)?void 0:`${D(e)}/${r.split(y.sep).join("/")}`}function se(e){let i=e?.trim()||"npx workspai bootstrap";if(!/(?:^|\s)--ci(?:\s|$)/.test(i)&&/(?:^|\s)--json(?:\s|$)/.test(i))return i.replace(/(?:^|\s)--json(?:\s|$)/,o=>{let t=o.startsWith(" ")?" ":"",n=o.endsWith(" ")?" ":"";return `${t}--ci --json${n}`}).trim();let r=/(?:^|\s)--ci(?:\s|$)/.test(i)?i:`${i} --ci`;return /(?:^|\s)--json(?:\s|$)/.test(r)?r:`${r} --json`}function M(e,i){return y.basename(e).toLowerCase().replace(/\.cmd$/,"")==="npx"&&i[0]==="workspai"&&!i.includes("--no-install")?["--no-install",...i]:i}function U(e){return {cwd:".",executable:"npx",args:M("npx",["workspai",...e])}}function ce(e){return `${JSON.stringify({schemaVersion:s.compatibilityMatrix.schemaVersion,generatedAt:e,source:"workspai workspace remediation-plan",runtimes:{},notes:["Minimal enterprise baseline. Add runtime and toolchain entries as governance matures."]},null,2)}
|
|
2
|
+
`}function de(e){return `${JSON.stringify({schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:e,note:"Minimal enterprise baseline. Set enabled: true and add artifact entries to activate mirroring."},null,2)}
|
|
3
|
+
`}function le(e){let i=e.payload,r=w(i.blockers),o=w(i.blockingReasons),t=w(i.failures),n=w(i.reasons),d=w(i.policyViolations),c=f(i.summary),l=w(c?.blockers);if(e.artifactKind==="analyze"){let k=(Array.isArray(i.findings)?i.findings:[]).map(b=>f(b)).filter(b=>!!b).map(b=>String(b.message??b.title??b.id??"").trim()).filter(Boolean);return P([...r,...k,...o])}if(e.artifactKind==="workspace-run"){let p=f(i.stages),k=Object.entries(p??{}).flatMap(([b,s])=>{let a=f(s);return (Array.isArray(a?.projects)?a.projects:[]).map(u=>f(u)).filter(u=>!!u).filter(u=>u.status==="failed"||u.ok===false).map(u=>`${b}: ${String(u.project??u.name??"project")} failed`)});return P([...r,...k,...o])}return P([...r,...o,...t,...n,...d,...l])}function v(e){let i=e.findingId?.trim()||e.sourceStepId?.trim()||e.id,r=e.findingStatus??"blocking",o=e.causalKey?.trim()||[e.cardId,e.projectName??e.scope??"workspace",i].map(t=>String(t).trim().toLowerCase()).join(":");return {id:e.id,artifactKind:e.artifactKind,cardId:e.cardId,title:e.title,order:e.order,phase:e.phase,scope:e.scope??"workspace",...e.projectName?{projectName:e.projectName}:{},...e.projectPath?{projectPath:e.projectPath}:{},...e.sourceStepId?{sourceStepId:e.sourceStepId}:{},findingId:i,findingStatus:r,causalKey:o,...e.dependsOn?{dependsOn:e.dependsOn}:{},...e.strategy?{strategy:structuredClone(e.strategy)}:{},...e.transaction?{transaction:structuredClone(e.transaction)}:{},...e.requirements?{requirements:structuredClone(e.requirements)}:{},...e.retryPolicy?{retryPolicy:structuredClone(e.retryPolicy)}:{},status:e.status??"ready",mode:e.mode,risk:e.risk,requiresApproval:true,blocker:e.blocker,summary:e.summary,...e.command?{command:e.command}:{},...e.invocation?{invocation:structuredClone(e.invocation)}:{},verifyCommand:e.verifyCommand,cwd:e.cwd??"workspace",files:e.files??[],...e.operation?{operation:e.operation}:{},rollback:e.rollback??(e.operation?{available:true,strategy:"idempotent"}:{available:false,strategy:"none"}),notes:e.notes??[]}}function pe(e){return (Array.isArray(e.report.payload.steps)?e.report.payload.steps:[]).flatMap((r,o)=>{let t=f(r),n=typeof t?.id=="string"?t.id.trim():"",d=typeof t?.projectName=="string"?t.projectName.trim():"",c=typeof t?.projectPath=="string"?t.projectPath.trim():"",l=typeof t?.originalCommand=="string"?t.originalCommand.trim():"";if(!t||!n||!d||!c)return [];let p=f(t.studioStatus),k=p?.state==="ready"||p?.state==="review-required"||p?.state==="blocked"||p?.state==="guidance-only"?p.state:"guidance-only",b=t.risk==="safe"||t.risk==="guarded"||t.risk==="invasive"?t.risk:"guarded",s=f(t.preview),a=D({workspacePath:e.workspacePath,projectPath:c,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}),g=H({capability:{...t,command:l},absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),u=X({capability:t,absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),R=E({operation:t.operation,absoluteProjectPath:c}),h=t.findingStatus==="blocking"||t.findingStatus==="advisory"||t.findingStatus==="informational"?t.findingStatus:"unknown",j=typeof t.diagnosisFindingId=="string"&&t.diagnosisFindingId.trim()?t.diagnosisFindingId.trim():typeof t.issueId=="string"&&t.issueId.trim()?t.issueId.trim():n,x=typeof t.causalKey=="string"&&t.causalKey.trim()?t.causalKey.trim():void 0,m=!!g&&(t.executable===true||t.executableInCurrentEnvironment===true),A=Q({strategy:t.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),I=f(t.transaction),C=I?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(I):void 0;return C&&(C.projectPath=a),[v({id:`doctor.${n}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof s?.title=="string"&&s.title.trim()?s.title.trim():`Repair ${d}`,order:e.startOrder+o,phase:typeof t.phase=="string"?t.phase:"doctor-remediation",blocker:typeof s?.summary=="string"&&s.summary.trim()?s.summary.trim():`Doctor remediation is pending for ${d}.`,summary:typeof s?.summary=="string"&&s.summary.trim()?s.summary.trim():`Execute the CLI-authored Doctor step for ${d}.`,mode:m?"run-command":"manual-guidance",risk:b,status:k,...m&&g?{command:g}:{},...m&&u?{invocation:u}:{},...R?{operation:R}:{},verifyCommand:typeof t.verifyCommand=="string"&&t.verifyCommand.trim()?t.verifyCommand.trim():"npx workspai doctor project --json",files:w(t.files).map($=>Z({workspacePath:e.workspacePath,projectPath:c,projectName:d,filePath:$,includeAbsolutePaths:e.includeAbsolutePaths})).filter($=>!!$),notes:[`Source Doctor step: ${n}`,`Doctor finding id: ${j}`,`Doctor finding status: ${h}`,...typeof p?.reason=="string"?[p.reason]:[]],scope:"project",projectName:d,projectPath:a,sourceStepId:n,findingId:j,findingStatus:h,causalKey:x,dependsOn:w(t.dependsOn).map($=>`doctor.${$}`),strategy:A,transaction:C,cwd:"project",...f(t.rollback)?.available===true?{rollback:{available:true,strategy:"manual"}}:{}})]})}function H(e){let i=typeof e.capability.command=="string"?e.capability.command.trim():"";if(e.includeAbsolutePaths&&i)return i;let r=E({operation:e.capability.operation,absoluteProjectPath:e.absoluteProjectPath});if(r)return b$2(r);let o=f(e.capability.invocation),t=typeof o?.executable=="string"?o.executable.trim():"",n=M(t,w(o?.args));if(t)return [t,...n].map(c=>/^[a-zA-Z0-9_./:@=+-]+$/.test(c)?c:JSON.stringify(c)).join(" ");if(!i)return;let d=e.absoluteProjectPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return i.replace(new RegExp(`^cd\\s+["']?${d}["']?\\s*&&\\s*`,"i"),"").replaceAll(e.absoluteProjectPath,".")}function X(e){let i=f(e.capability.invocation),r=typeof i?.executable=="string"?i.executable.trim():"",o=w(i?.args);if(!(!r||o.length!==(Array.isArray(i?.args)?i.args.length:0)))return {cwd:e.includeAbsolutePaths?e.absoluteProjectPath:".",executable:r,args:M(r,o)}}function E(e){let i=f(e.operation);if(!i||typeof i.type!="string")return;let r=structuredClone(i);for(let o of ["path","sourcePath"]){let t=r[o];if(typeof t!="string")continue;let n=y.isAbsolute(t)?y.relative(e.absoluteProjectPath,t):t;if(!n||n===".."||n.startsWith(`..${y.sep}`)||y.isAbsolute(n))return;r[o]=n.split(y.sep).join("/");}return r}function Q(e){if(!Array.isArray(e.strategy))return;let i=structuredClone(e.strategy);if(!e.includeAbsolutePaths)for(let r of i)r.invocation&&(r.invocation.cwd=".");return i}function me(e){let i=Array.isArray(e.report.payload.projects)?e.report.payload.projects:e.report.payload.project?[e.report.payload.project]:[],r=new Set,o=[];for(let t of i){let n=f(t);if(!n)continue;let d=typeof n.name=="string"?n.name.trim():"",c=typeof n.path=="string"?n.path.trim():"";if(!d||!c)continue;let l=Array.isArray(n.repairCapabilities)?n.repairCapabilities:Array.isArray(n.probes)?n.probes.map(s=>f(s)?.repairCapability).filter(s=>s!==void 0):[],p=new Map,k=new Map,b=f(n.diagnosis);for(let s of Array.isArray(b?.findings)?b.findings:[]){let a=f(s),g=f(a?.repair),u=typeof g?.capabilityId=="string"?g.capabilityId.trim():"",R=typeof a?.id=="string"?a.id.trim():"",h=typeof a?.causalKey=="string"?a.causalKey.trim():"",j=a?.status==="blocking"||a?.status==="advisory"||a?.status==="informational"||a?.status==="unknown"?a.status:"unknown";u&&R&&h&&k.set(u,{findingId:R,causalKey:h,findingStatus:j});}for(let s of Array.isArray(n.probes)?n.probes:[]){let a=f(s),g=f(a?.repairCapability),u=typeof g?.id=="string"?g.id.trim():"";u&&p.set(u,a?.status==="fail"?"blocking":"advisory");}for(let s of l){let a=f(s),g=typeof a?.id=="string"?a.id.trim():"";if(!a||!g)continue;let u=`${d}:${g}`;if(r.has(u))continue;r.add(u);let R=a.risk==="safe"||a.risk==="guarded"||a.risk==="invasive"?a.risk:"guarded",h=H({capability:a,absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),j=X({capability:a,absoluteProjectPath:c,includeAbsolutePaths:e.includeAbsolutePaths}),x=E({operation:a.operation,absoluteProjectPath:c}),m=a.status==="available"&&!!h,A=f(a.transaction),I=A?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(A):void 0,C=k.get(g),$=C?.findingStatus??p.get(g)??(I?"blocking":"advisory");I&&(I.projectPath=D({workspacePath:e.workspacePath,projectPath:c,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}));let ee=Q({strategy:a.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),te=w(a.files).map(S=>Z({workspacePath:e.workspacePath,projectPath:c,projectName:d,filePath:S,includeAbsolutePaths:e.includeAbsolutePaths})).filter(S=>!!S),W=v({id:`doctor.${d}.${g}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof a.title=="string"&&a.title.trim()?a.title.trim():`Repair ${d}`,order:e.startOrder+o.length,phase:I?"dependency-remediation":"doctor-remediation",blocker:typeof a.reason=="string"&&a.reason.trim()?a.reason.trim():`Doctor remediation is pending for ${d}.`,summary:typeof a.reason=="string"&&a.reason.trim()?a.reason.trim():`Execute the Doctor-authored repair capability for ${d}.`,mode:m?a.canEditFiles===true?"edit-file":"run-command":"manual-guidance",risk:R,status:m?"ready":a.status==="manual"?"guidance-only":"blocked",...h?{command:h}:{},...j?{invocation:j}:{},verifyCommand:typeof a.verifyCommand=="string"&&a.verifyCommand.trim()?a.verifyCommand.trim():"npx workspai doctor project --json",files:te,notes:[`Source Doctor capability: ${g}`,`Doctor finding status: ${$}`,...w(a.limitations)],scope:"project",projectName:d,projectPath:D({workspacePath:e.workspacePath,projectPath:c,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}),sourceStepId:g,findingId:C?.findingId??(typeof a.issueId=="string"&&a.issueId.trim()?a.issueId.trim():g),findingStatus:$,causalKey:C?.causalKey,strategy:ee,transaction:I,cwd:"project",...x?{operation:x,rollback:{available:true,strategy:"manual"}}:{}}),O=h?o.findIndex(S=>S.projectName===d&&S.command===h&&S.cwd==="project"):-1;if(O>=0){o[O]=ne({existing:o[O],incoming:W});continue}o.push(W);}}return o}function ue(e){let i=[],r=se("npx workspai bootstrap --json");for(let o of e.blockers)o.includes("profile.enterprise.ci")&&i.push(v({id:"bootstrap.enterprise-ci",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Run bootstrap in deterministic CI mode",order:10,phase:"bootstrap-preflight",blocker:o,summary:"Enterprise bootstrap compliance requires --ci for deterministic execution.",mode:"run-command",risk:"safe",command:r,verifyCommand:r})),o.includes("profile.enterprise.compatibility-matrix")&&i.push(v({id:"bootstrap.compatibility-matrix",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise compatibility matrix baseline",order:20,phase:"bootstrap-config",blocker:o,summary:"Create the missing compatibility matrix baseline without overwriting user data.",mode:"edit-file",risk:"safe",verifyCommand:r,files:[t.compatibilityMatrix],operation:{type:"file-create",path:t.compatibilityMatrix,content:ce(e.generatedAt),overwrite:false}})),o.includes("profile.enterprise.mirror-config")&&i.push(v({id:"bootstrap.mirror-config",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise mirror config baseline",order:30,phase:"bootstrap-config",blocker:o,summary:"Create the missing mirror configuration baseline without enabling mirroring.",mode:"edit-file",risk:"safe",verifyCommand:r,files:[".workspai/mirror-config.json"],operation:{type:"file-create",path:".workspai/mirror-config.json",content:de(e.generatedAt),overwrite:false}}));return i}function fe(e){let i=Array.isArray(e.report.payload.steps)?e.report.payload.steps:[],r=[],o=new Map;for(let t of i){let n=f(t),d=f(n?.command),c=typeof n?.id=="string"?n.id.trim():"",l=typeof n?.project=="string"?n.project.trim():"",p=typeof n?.status=="string"?n.status:"",k=typeof d?.display=="string"?d.display.trim():"",b=n?.required===true;if(!c.startsWith("project.")||!l||!b||p!=="fail"&&p!=="missing"||!/^npx\s+workspai\s+workspace\s+run\s+/i.test(k))continue;let s=c.split(".").at(-1)??"stage",a=`workspaceVerify.${c}`,g=o.get(l),u=/(?:^|\s)--no-gates(?:\s|$)/.test(k)?k:`${k} --no-gates`;r.push(v({id:a,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof n.label=="string"&&n.label.trim()?n.label.trim():`Run ${s} for ${l}`,order:e.startOrder+r.length,phase:"fleet-run",blocker:typeof n.message=="string"&&n.message.trim()?n.message.trim():`${s} evidence is not current for ${l}.`,summary:`Produce fresh ${s} evidence for ${l} without re-entering the blocked aggregate gates.`,mode:"run-command",risk:s==="start"?"guarded":"safe",status:"ready",command:u,verifyCommand:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",scope:"project",projectName:l,projectPath:l,sourceStepId:c,...g?{dependsOn:[g]}:{},cwd:"workspace",notes:[`Source Workspace Verify step: ${c}`,"Aggregate verification must run only after this project evidence producer completes."]})),o.set(l,a);}return r}var T={python:["python3","python","py"],node:["node"],go:["go"],java:["java"],dotnet:["dotnet"],rust:["cargo"],php:["php"]};async function ge(e,i,r){for(let o of T[e]??[e])if(r?await r(o,i):await a$2({executable:o,cwd:i}))return o}async function ye(e){let i=P(e.blockers.flatMap(o=>{let t=o.match(/(?:project runtimes?|workspace)\s*\(([^)]+)\)\s+(?:is|are) not pinned/i);return t?.[1]?t[1].split(",").map(n=>n.trim().toLowerCase()).filter(n=>/^(python|node|go|java|dotnet|rust|php)$/.test(n)):[]})),r=[];for(let o of i){let t=T[o]??[o],n=await ge(o,e.workspacePath,e.toolAvailable),d=`environment.runtime.${o}`,c=`readiness.toolchain.${o}.setup`,l=e.blockers.find(p=>p.toLowerCase().includes(`(${o})`))??`The ${o} runtime is not pinned in the canonical workspace toolchain.`;n||r.push(v({id:d,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Provide the ${o} host runtime`,order:e.startOrder+r.length,phase:"host-prerequisite",blocker:`No launchable ${o} runtime is available in the current environment.`,summary:`Install or configure ${t.join(" or ")} outside Workspai, then refresh the remediation plan.`,mode:"manual-guidance",risk:"safe",status:"guidance-only",verifyCommand:`npx workspai setup ${o} --json`,requirements:[{kind:"executable",id:`executable:${o}`,status:"missing",executable:t.join("|"),message:`A launchable ${t.join(" or ")} executable must be visible to Workspai.`}],retryPolicy:{sameGeneration:"forbidden",resumeWhen:"environment-changed"},notes:["`workspai setup` detects and pins an existing runtime; it does not install host software."]})),r.push(v({id:c,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Pin ${o} in the workspace toolchain`,order:e.startOrder+r.length,phase:"toolchain-reconciliation",blocker:l,summary:`Detect and persist the current ${o} runtime in the canonical workspace toolchain lock.`,mode:"run-command",risk:"safe",status:n?"ready":"blocked",command:`npx workspai setup ${o} --json`,invocation:U(["setup",o,"--json"]),verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:n?void 0:[d],requirements:[{kind:"executable",id:`executable:${o}`,status:n?"satisfied":"missing",executable:n??t.join("|"),message:n?`Runtime prerequisite is launchable: ${n}.`:`Runtime prerequisite is unavailable: ${t.join(" or ")}.`},...n?[]:[{kind:"action",id:`action:${d}`,status:"pending",actionId:d,message:"The host runtime prerequisite must be resolved first."}]],retryPolicy:n?{sameGeneration:"allowed",resumeWhen:"immediate"}:{sameGeneration:"forbidden",resumeWhen:"environment-changed"},notes:["Run from the workspace root so the canonical toolchain.lock is updated."]})),r.push(v({id:`readiness.toolchain.${o}.bootstrap`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Reconcile the ${o} workspace foundation`,order:e.startOrder+r.length,phase:"toolchain-reconciliation",blocker:`The ${o} runtime pin must be reconciled with the workspace foundation.`,summary:"Refresh the workspace foundation after the runtime pin is written.",mode:"run-command",risk:"guarded",status:n?"ready":"blocked",command:"npx workspai bootstrap --ci --json",invocation:U(["bootstrap","--ci","--json"]),verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:[c],requirements:[{kind:"action",id:`action:${c}`,status:"pending",actionId:c,message:`The ${o} toolchain pin must complete first.`}],retryPolicy:{sameGeneration:n?"allowed":"forbidden",resumeWhen:n?"dependencies-complete":"environment-changed"}}));}return r}function be(e){if(e.report.artifactKind==="readiness"&&/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(e.blocker))return v({id:`${e.report.cardId}.doctor-owner.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:"Resolve dependency vulnerability through Doctor",order:e.order,phase:"dependency-remediation",blocker:e.blocker,summary:"Release Readiness is the aggregate gate; use the project-scoped Doctor remediation capability that owns this dependency failure.",mode:"verify-before-fix",risk:"guarded",status:"review-required",command:"npx workspai doctor workspace --plan --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Read doctor-remediation-plan-last-run.json and execute the matching surface-security-hygiene capability before rerunning Readiness.","Do not treat a Readiness refresh as remediation for a source dependency vulnerability."]});let r={analyze:{title:"Refresh analyze evidence",phase:"analysis",command:"npx workspai analyze --strict --json",verify:"npx workspai analyze --strict --json"},readiness:{title:"Refresh release readiness",phase:"release-readiness",command:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",verify:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json"},pipeline:{title:"Rerun governance pipeline",phase:"governance-pipeline",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"},"workspace-run":{title:"Rerun failed workspace stage",phase:"fleet-run",command:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json",verify:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json"},"workspace-verify":{title:"Refresh workspace verify gate",phase:"verification",command:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",verify:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json"},"doctor-workspace":{title:"Use Doctor remediation plan",phase:"doctor-remediation",command:"npx workspai doctor workspace --plan --json",verify:"npx workspai doctor workspace --json"}}[e.report.artifactKind]??{title:"Refresh artifact evidence",phase:"evidence-refresh",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"};return v({id:`${e.report.cardId}.refresh.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:r.title,order:e.order,phase:r.phase,blocker:e.blocker,summary:"No deterministic file operation is available for this artifact yet; refresh the evidence and continue with the card-specific plan.",mode:e.report.artifactKind==="doctor-workspace"?"verify-before-fix":"run-command",risk:"guarded",status:e.report.artifactKind==="doctor-workspace"?"review-required":"ready",command:r.command,verifyCommand:r.verify,notes:e.report.artifactKind==="doctor-workspace"?["Read doctor-remediation-plan-last-run.json for ordered file-level steps."]:[]})}function Y(e){let i=e.transaction?.ecosystem.toLowerCase(),r=y.basename(e.invocation?.executable??"").toLowerCase(),o=`${i??""}:${r}`;if(/(^|:)(python|pip|pip3|poetry|uv)(:|$)/.test(o))return "python";if(/(^|:)(node|npm|pnpm|yarn|bun)(:|$)/.test(o))return "node";if(/(^|:)(go)(:|$)/.test(o))return "go";if(/(^|:)(java|maven|mvn|mvnw|gradle|gradlew)(:|$)/.test(o))return "java";if(/(^|:)(dotnet|nuget)(:|$)/.test(o))return "dotnet";if(/(^|:)(rust|cargo|rustc)(:|$)/.test(o))return "rust";if(/(^|:)(php|composer)(:|$)/.test(o))return "php"}function he(e,i){let r=i.invocation?.cwd??e;return y.isAbsolute(r)?r:y.resolve(e,r)}function ke(e,i){let r=Y(e);if(r&&T[r]?.includes(y.basename(i)))return `environment.runtime.${r}`;let o=(e.projectName??"workspace").replace(/[^a-zA-Z0-9.-]+/g,"-"),t=y.basename(i).replace(/[^a-zA-Z0-9.-]+/g,"-");return `environment.executable.${o}.${t}`}async function Ae(e){let i=new Map,r=new Map(e.actions.map(t=>[t.id,t]));for(let t of e.actions){if(!t.invocation||t.status==="guidance-only")continue;let n=he(e.workspacePath,t),d=e.toolAvailable?await e.toolAvailable(t.invocation.executable,n):await a$2({executable:t.invocation.executable,cwd:n}),c={kind:"executable",id:`executable:${t.invocation.executable}`,status:d?"satisfied":"missing",executable:t.invocation.executable,message:d?`Required executable is launchable: ${t.invocation.executable}.`:`Required executable is unavailable: ${t.invocation.executable}.`};if(t.requirements=[...(t.requirements??[]).filter(p=>p.id!==c.id),c],d)continue;let l=ke(t,t.invocation.executable);!r.has(l)&&!i.has(l)&&i.set(l,v({id:l,artifactKind:t.artifactKind,cardId:"environment",title:`Provide ${y.basename(t.invocation.executable)}`,order:0,phase:"host-prerequisite",blocker:`The required executable ${t.invocation.executable} is unavailable.`,summary:"Install or configure the required executable outside Workspai, then refresh the plan.",mode:"manual-guidance",risk:"safe",status:"guidance-only",verifyCommand:t.verifyCommand,scope:t.scope,projectName:t.projectName,projectPath:t.projectPath,requirements:[c],retryPolicy:{sameGeneration:"forbidden",resumeWhen:"environment-changed"},notes:["The CLI does not install host runtimes or system package managers implicitly."]})),t.status="blocked",t.dependsOn=P([...t.dependsOn??[],l]),t.requirements.push({kind:"action",id:`action:${l}`,status:"pending",actionId:l,message:"Resolve the executable prerequisite and generate fresh evidence first."}),t.retryPolicy={sameGeneration:"forbidden",resumeWhen:"environment-changed"},t.notes.push("This action is not eligible in the current plan generation because its executable precondition failed.");}let o=[...i.values(),...e.actions];return o.forEach((t,n)=>{t.order=n+1;}),o}function we(e){let i=new Set(e.map(r=>r.id));for(let r of e){if(!r.transaction)continue;let o=Y(r);if(!o)continue;let t=`readiness.toolchain.${o}.bootstrap`;i.has(t)&&(r.dependsOn=P([...r.dependsOn??[],t]),r.requirements=[...r.requirements??[],{kind:"action",id:`action:${t}`,status:"pending",actionId:t,message:`The canonical ${o} workspace foundation must be reconciled first.`}],r.status==="ready"&&(r.retryPolicy={sameGeneration:"allowed",resumeWhen:"dependencies-complete"}));}}function ve(e){let i=e.filter(t=>t.status==="ready"&&(t.dependsOn?.length??0)===0).map(t=>t.id),r=e.filter(t=>t.status==="blocked").map(t=>t.id),o=e.find(t=>t.status==="guidance-only")?.id??null;return {nextActionId:i[0]??o,eligibleActionIds:i,blockedActionIds:r}}async function Re(e$1){let i=[a(e$1,".workspai/reports"),e(e$1,".workspai/reports")],r=[],o=new Set;for(let t of oe)for(let n of t.fileNames){let d=(await Promise.all(i.map(c=>y.join(c,n)))).find(c=>existsSync(c));if(!(!d||o.has(`${t.artifactKind}:${n}`))){o.add(`${t.artifactKind}:${n}`);try{let c=await ie.readJSON(d),l=f(c);if(!l)continue;r.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:n,absolutePath:d,payload:l});break}catch{r.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:n,absolutePath:d,payload:{blockers:[`${t.artifactKind}: report exists but could not be parsed.`]}});break}}}return r}async function Me(e){let i=y.resolve(e.workspacePath),r=e.includeAbsolutePaths===true,o=e.ciMode===true,t=new Date().toISOString(),n=a(i,".workspai/reports"),d=await Re(i),c=[],l=1;for(let s of d){if(s.artifactKind==="doctor-workspace"){let m=Array.isArray(s.payload.steps)?pe({report:s,workspacePath:i,includeAbsolutePaths:r,startOrder:l}):me({report:s,workspacePath:i,includeAbsolutePaths:r,startOrder:l});c.push(...m),l+=m.length;continue}let a=le(s);if(a.length===0)continue;if(s.artifactKind==="bootstrap-compliance"){c.push(...ue({blockers:a,generatedAt:t})),l=c.length+1;continue}if(s.artifactKind==="workspace-verify"){let m=fe({report:s,startOrder:l,ciMode:o});if(m.length>0){c.push(...m),l+=m.length;continue}}if(s.artifactKind==="readiness"){let m=await ye({report:s,blockers:a,startOrder:l,ciMode:o,workspacePath:i,toolAvailable:e.toolAvailable});if(m.length>0){c.push(...m),l+=m.length;continue}}let g=c.some(m=>m.transaction?.kind==="dependency-security"),u=s.artifactKind==="readiness"&&a.some(m=>/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(m));if(g&&u)continue;let R=a[0],h=be({report:s,blocker:R,order:l,ciMode:o}),x={readiness:new Set(["bootstrap","doctor"]),pipeline:new Set(["bootstrap","doctor","analyze","readiness"]),workspaceVerify:new Set(["bootstrap","doctor","readiness","workspaceRun"])}[s.cardId];if(s.cardId==="pipeline"){let m=["doctor","analyze","readiness"].find(A=>R.toLowerCase().includes(A));m&&(x=new Set([m]));}if(x){let m=c.filter(A=>x.has(A.cardId)&&A.risk!=="invasive"&&A.status!=="blocked"&&A.status!=="guidance-only").map(A=>A.id);m.length>0&&(h.dependsOn=P([...h.dependsOn??[],...m]),h.notes.push("This aggregate gate must run after its contract-owned upstream remediation actions."));}a.length>1&&h.notes.push(...a.slice(1,8).map(m=>`Related blocker: ${m}`)),c.push(h),l+=1;}we(c);let p=await Ae({actions:c,workspacePath:i,toolAvailable:e.toolAvailable}),k=ve(p),b$1={safe:p.filter(s=>s.risk==="safe").length,guarded:p.filter(s=>s.risk==="guarded").length,invasive:p.filter(s=>s.risk==="invasive").length};return {schemaVersion:a$1,generatedAt:t,workspace:{name:await b(i),...r?{path:i}:{}},source:{command:"workspace remediation-plan",reportsDir:ae(i,n,r),includeAbsolutePaths:r,ciMode:o},summary:{artifactsScanned:d.length,cardsCovered:P(p.map(s=>s.cardId)).length,totalActions:p.length,executableActions:p.filter(s=>s.status==="ready").length,blockedActions:p.filter(s=>s.status==="blocked").length,guidanceActions:p.filter(s=>s.status==="guidance-only").length,risk:b$1},execution:k,actions:p}}async function Ee(e,i){return h(i,t.artifactRemediationPlan,e)}export{Me as a,Ee as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-B6FJ6RG6.js';import {k,q as q$1}from'./chunk-46QH3ZVI.js';import {a}from'./chunk-
|
|
1
|
+
import {b as b$1}from'./chunk-B6FJ6RG6.js';import {k,q as q$1}from'./chunk-46QH3ZVI.js';import {a}from'./chunk-G6ADWA2B.js';import {c,j as j$1}from'./chunk-5EVBOUYW.js';import {m as m$2}from'./chunk-YYELANJO.js';import {e,f}from'./chunk-PKKSRXUS.js';import {b}from'./chunk-UJXE4UAX.js';import {m as m$1,t,k as k$2,u,l}from'./chunk-VQZ5PI5J.js';import le,{promises}from'fs';import c$1 from'path';import U,{homedir}from'os';import {pathToFileURL}from'url';import m from'process';import k$1 from'fs-extra';function Q(o){let t=o.label.indexOf(" \u2014 ");return t>=0?o.label.slice(t+3).trim():o.label.trim()}function X(){let o=c().map(n=>({value:n.id,label:`${D(n.category)} \xB7 ${Q(n)}`,hint:`${n.runtime} \xB7 tested baseline`,name:n.label})),e=k().map(n=>({value:n.kitId,label:`Frontend \xB7 ${n.displayName}`,hint:"official \xB7 latest stable",name:`${n.displayName} \u2014 ${n.framework}`})),t=q$1().map(n=>({value:n.kitId,label:`${D(n.category)} \xB7 ${n.displayName}`,hint:`${n.runtimeCandidates.join(" + ")} \xB7 official latest stable`,name:`${n.displayName} \u2014 ${n.category}`})),r=[...o,...e,...t].sort((n,i)=>{let s=["Backend","Frontend","Desktop","Extension"],a=n.label?.split(" \xB7 ")[0]??"",l=i.label?.split(" \xB7 ")[0]??"";return s.indexOf(a)-s.indexOf(l)||(n.label??"").localeCompare(i.label??"")});return T(r),r}function D(o){return o.charAt(0).toUpperCase()+o.slice(1)}function T(o){let e=new Set,t=new Set;for(let r of o){let n=r.label??r.name??String(r.value),i=String(r.value);if(e.has(n))throw new Error(`Duplicate kit picker label: ${n}`);if(t.has(i))throw new Error(`Duplicate kit picker value: ${i}`);e.add(n),t.add(i);}}var ee=".workspairc.json",oe=".rapidkitrc.json",te=["workspai.config.js","workspai.config.mjs","workspai.config.cjs","rapidkit.config.js","rapidkit.config.mjs","rapidkit.config.cjs"],ne=["workspai.config.json","rapidkit.config.json"];function B(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code==="ENOENT"}function C(o,e){let t=e instanceof Error?e.message:String(e),r=o.endsWith(".js")&&/module is not defined in ES module scope/i.test(t)?' CommonJS syntax in a .js config is not valid when the project package uses "type": "module"; rename the file to .cjs or use export default.':"";return `Failed to load Workspai config at ${o}.${r} Cause: ${t}`}async function Qe(){for(let o of [c$1.join(U.homedir(),ee),c$1.join(U.homedir(),oe)])try{let e$1=await promises.readFile(o,"utf-8"),t=JSON.parse(e$1);return e.debug(`Loaded config from ${o}`),t}catch{}return e.debug("No user config found, using defaults"),{}}async function Xe(o=process.cwd(),e$1={}){let t=o,r=c$1.parse(t).root;for(;t!==r;){for(let n of ne){let i=c$1.join(t,n);try{let s=await promises.readFile(i,"utf-8"),a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("configuration root must be a JSON object");return e.debug(`Loaded data-only Workspai config from ${n}`),a}catch(s){if(B(s))continue;throw new Error(C(i,s))}}for(let n of te){let i=c$1.join(t,n);try{await promises.access(i);}catch(s){if(B(s))continue;throw new Error(C(i,s))}if(e.debug(`Found config file: ${i}`),!e$1.trustExecutableConfig)throw new Error(`Refusing to execute Workspai config at ${i} without explicit trust. Use a data-only workspai.config.json file, pass --trust-config, or set WORKSPAI_TRUST_CONFIG=1.`);try{let a=await import(pathToFileURL(i).href),l=a.default||a;return e.debug(`Loaded Workspai config from ${n}`),l}catch(s){throw new Error(C(i,s))}}t=c$1.dirname(t);}return e.debug("No Workspai config file found, using defaults"),{}}function Ze(o,e,t){return {author:t.author||e.workspace?.defaultAuthor||o.author,pythonVersion:t.pythonVersion||e.workspace?.pythonVersion||o.pythonVersion,defaultInstallMethod:t.defaultInstallMethod||e.workspace?.installMethod||o.defaultInstallMethod,defaultKit:t.defaultKit||e.projects?.defaultKit||o.defaultKit,skipGit:t.skipGit??e.projects?.skipGit??o.skipGit,license:t.license||o.license,testRapidKitPath:t.testRapidKitPath||o.testRapidKitPath}}function eo(o){return f("DEV_PATH")||o.testRapidKitPath||void 0}var j=class extends Error{constructor(t,r){super(["Workspai workspaces cannot be nested.",`Target: ${t}`,`Containing workspace: ${r}`,"Choose Managed home or pass --output <path> with a location outside the current workspace."].join(`
|
|
2
2
|
`));this.targetPath=t;this.containingWorkspacePath=r;this.name="NestedWorkspaceCreationError";}targetPath;containingWorkspacePath;code="WORKSPACE_NESTING_NOT_SUPPORTED"};async function ie(o){try{return !!await k$1.stat(o)}catch{return false}}function se(o,e){let t=o.indexOf(e);if(t>=0&&t+1<o.length)return o[t+1];let r=o.find(n=>n.startsWith(`${e}=`));if(r)return r.slice(e.length+1)}function ae(o){return o.includes("--here")}async function J(o){let e=c$1.resolve(o);for(;;){let t=[c$1.join(e,".workspai-workspace"),c$1.join(e,".rapidkit-workspace"),c$1.join(e,".workspai","workspace.json"),c$1.join(e,".rapidkit","workspace.json")];if((await Promise.all(t.map(ie))).some(Boolean))return e;let r=c$1.dirname(e);if(r===e)return;e=r;}}async function po(o){let e=c$1.resolve(o),t=await J(c$1.dirname(e));if(t)throw new j(e,t)}async function ce(o,e=homedir()){let r=[{value:"managed",label:"Managed home",hint:l(e)}];return await J(o)||r.push({value:"here",label:"Current directory",hint:o}),r}function V(o,e=m.cwd()){if(ae(o))return c$1.resolve(e);let t=se(o,"--output");if(t)return c$1.resolve(t)}function uo(o,e=m.cwd()){let t=c$1.resolve(o),r=c$1.resolve(e),n=c$1.relative(r,t);return n.length>0&&!n.startsWith("..")&&!c$1.isAbsolute(n)?`cd ${n}`:`cd ${t}`}function mo(o,e={}){let t=e.argv??[],r=e.outputParent??V(t,m.cwd());return m$1(o.trim(),{homeDir:e.homeDir,outputDir:r})}function fo(o,e,t={}){return o?c$1.resolve(o)===c$1.resolve(e)?true:t.outputParent===void 0:false}async function go(o,e={}){let t=e.cwd??m.cwd(),r=e.homeDir??homedir(),n=V(o,t);if(n!==void 0)return n;let i=e.hasYes??(o.includes("--yes")||o.includes("-y"));if(!(e.interactive??(!i&&!!m.stdin.isTTY&&!b())))return;let a=await ce(t,r);if(a.length===1)return;let{location:l}=await b$1([{type:"rawlist",name:"location",message:"Where should the workspace be created?",choices:a,default:0}]);if(l==="here")return c$1.resolve(t)}var pe=["minimal","python-only","node-only","go-only","java-only","dotnet-only","polyglot","enterprise"],de=new Set(["minimal","node-only","go-only","java-only","dotnet-only"]),xo=new Set(["python-only","polyglot","enterprise"]);function ue(o){return typeof o=="string"&&pe.includes(o)}function jo(o){return ue(o)&&de.has(o)}var q={"python-only":"python","node-only":"node","go-only":"go","java-only":"java","dotnet-only":"dotnet"},me={python:"Python",node:"Node",go:"Go",java:"Java",dotnet:".NET",php:"PHP",ruby:"Ruby",rust:"Rust",elixir:"Elixir",clojure:"Clojure",scala:"Scala",kotlin:"Kotlin",deno:"Deno",bun:"Bun",c:"C",cpp:"C++",unknown:"Unknown"},fe={python:"python-only",node:"node-only",go:"go-only",java:"java-only",dotnet:"dotnet-only"},H=["node","deno","bun","python","go","java","kotlin","scala","dotnet","php","ruby","rust","elixir","clojure","c","cpp","unknown"];function E(o){return o==="bun"||o==="deno"?"node":o==="kotlin"||o==="scala"?"java":o}function v(o){return typeof o!="string"||o.trim().length===0?"minimal":o.trim().toLowerCase()}function g(o){if(typeof o!="string")return "unknown";let e=o.trim().toLowerCase();return e==="python"||e==="node"||e==="go"||e==="java"||e==="dotnet"||e==="php"||e==="ruby"||e==="rust"||e==="elixir"||e==="clojure"||e==="scala"||e==="kotlin"||e==="deno"||e==="bun"||e==="c"||e==="cpp"?e:e==="c++"||e==="cplusplus"||e==="cc"||e==="clang++"||e==="g++"?"cpp":e==="clang"||e==="gcc"?"c":"unknown"}function w(o){let e=new Set;for(let t of o)e.add(g(t));return [...e].sort((t,r)=>H.indexOf(t)-H.indexOf(r))}function ge(o){let e=w(o).filter(t=>t!=="unknown");if(e.length!==0)return e.length===1?fe[e[0]]:"polyglot"}function Y(o,e={}){return `npx workspai bootstrap --profile ${o}${e.ci?" --ci --json":""}`}function he(o,e){return o?"none":e==="strict"?"error":"warning"}function h(o){let e=o.ok?void 0:ge(o.runtimes)??"polyglot";return {ok:o.ok,checkId:o.checkId,status:o.ok?"passed":"failed",profile:o.profile,runtimes:o.runtimes,message:o.message,recommendedProfile:e,recommendedCommand:e?Y(e):void 0,ciRecommendedCommand:e?Y(e,{ci:true}):void 0,severity:he(o.ok,o.mode)}}function Eo(o){let e=v(o.profile),t=w(o.runtimes),r=o.mode??"warn",n=q[e];if(n){let i=t.length===0||t.every(s=>E(s)===n);return h({ok:i,checkId:`profile.${e}`,profile:e,runtimes:t,message:i?`${e} profile validated for discovered projects.`:`${e} profile mismatch: detected runtimes [${t.join(", ")}].`,mode:r})}if(e==="minimal"){let i=t.filter(l=>l!=="unknown"),a=new Set(i.map(l=>E(l))).size<=1;return h({ok:a,checkId:"profile.minimal",profile:e,runtimes:t,message:a?"minimal profile is compatible with detected runtime mix.":`minimal profile mismatch: multiple runtimes detected [${i.join(", ")}].`,mode:r})}return h({ok:true,checkId:`profile.${e}`,profile:e,runtimes:t,message:`${e} profile accepts the detected runtime mix.`,mode:r})}function vo(o){let e=v(o.profile),t=g(o.runtime),r=o.mode??"warn",n=q[e];if(!n||t==="unknown")return h({ok:true,checkId:`profile.${e}`,profile:e,runtimes:[t],message:t==="unknown"?`Project "${o.subjectLabel}" runtime is unknown; profile compatibility will be checked by workspace doctor.`:`${e} profile accepts project "${o.subjectLabel}".`,mode:r});let i=E(t)===n;return h({ok:i,checkId:`profile.${e}`,profile:e,runtimes:i?[t]:w([n,t]),message:i?`Project "${o.subjectLabel}" is compatible with workspace profile "${e}".`:`Project "${o.subjectLabel}" is ${me[t]}, but workspace profile is "${e}".`,mode:r})}async function Fo(o){let e=(await Promise.all(t(o,"policies.yml").map(async t=>await k$1.pathExists(t)?t:null))).find(t=>typeof t=="string");if(!e)return "warn";try{return (await k$1.readFile(e,"utf-8")).match(/^\s*mode:\s*(warn|strict)\s*(?:#.*)?$/m)?.[1]==="strict"?"strict":"warn"}catch{return "warn"}}async function Io(o){let e=(await Promise.all(t(o,"workspace.json").map(async t=>await k$1.pathExists(t)?t:null))).find(t=>typeof t=="string");if(!e)return "minimal";try{let t=await k$1.readJson(e);return v(t.profile)}catch{return "minimal"}}async function $o(o,e={}){let t=new Set,r=[],n=new Set,i=[o];for(;i.length>0;){let s=i.pop();if(!s||n.has(s))continue;n.add(s);let a=[];try{a=await le.promises.readdir(s,{withFileTypes:true});}catch{continue}for(let l of a){if(!l.isDirectory()||l.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(l.name))continue;let p=c$1.join(s,l.name);if(p!==o&&k$2(p))continue;if((await Promise.all([...u(p,"context.json"),...u(p,"project.json")].map(async z=>k$1.pathExists(z)))).some(Boolean)){r.push(p);continue}i.push(p);}}for(let s of r){if(e.excludeProjectPath&&c$1.resolve(s)===c$1.resolve(e.excludeProjectPath))continue;let a=j$1(s);t.add(g(m$2(s,a).runtime));}for(let s of await a(o))e.excludeProjectPath&&c$1.resolve(s.path)===c$1.resolve(e.excludeProjectPath)||t.add(g(s.runtime));for(let s of e.additionalRuntimes??[])t.add(g(s));return w(t)}function Ao(o,e={}){let t=e.ci?o.ciRecommendedCommand:o.recommendedCommand;return t?`Recommended: ${t}`:null}export{X as a,Qe as b,Xe as c,Ze as d,eo as e,po as f,uo as g,mo as h,fo as i,go as j,xo as k,jo as l,Eo as m,vo as n,Fo as o,Io as p,$o as q,Ao as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-MGL6DBOR.js';import {m as m$1}from'./chunk-6WOFOOM7.js';import {a as a$1}from'./chunk-GR6442P7.js';import {i,h}from'./chunk-FE5R6EUV.js';import {s,t}from'./chunk-ODK4LCEL.js';import {createHash}from'crypto';import l from'path';import {execa}from'execa';import v from'fs-extra';var D=s.projectTestCoverage.schemaVersion,P=t.projectTestCoverage,G=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deps.edn","project.clj","build.sbt","CMakeLists.txt","meson.build","deno.json","deno.jsonc"];function p(t){let e=Number(t);return Number.isFinite(e)&&e>=0?e:0}function m(t,e,o=0){let n=p(t),s=Math.min(p(e),n),r=p(o);return {total:n,covered:s,skipped:r,percent:n>0?Math.round(s/n*1e4)/100:null}}function W(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;return m(e.total,e.covered,e.skipped)}function y(t,e){let o=l.isAbsolute(e)?e:l.resolve(t,e),n=l.relative(t,o);return n&&!n.startsWith("..")?n.split(l.sep).join("/"):e}async function C(t){return createHash("sha256").update(await v.readFile(t)).digest("hex")}async function I(t){let e=l.resolve(t);for(;;){let o=await v.pathExists(l.join(e,".workspai","project.json"))||await v.pathExists(l.join(e,".rapidkit","project.json")),n=(await v.readdir(e).catch(()=>[])).some(r=>r.toLowerCase().endsWith(".gemspec"));if(o||n||(await Promise.all(G.map(r=>v.pathExists(l.join(e,r))))).some(Boolean))return e;let s=l.dirname(e);if(s===e)return l.resolve(t);e=s;}}async function V(t){return m$1(t).runtime}async function U(t,e,o=5){let n=[],s=[{dir:t,depth:0}],r=new Set([".git",".workspai",".rapidkit","node_modules",".venv","vendor","deps"]);for(;s.length>0;){let a=s.shift();if(!a)break;let i=await v.readdir(a.dir,{withFileTypes:true}).catch(()=>[]);for(let c of i){if(r.has(c.name)||a$1(c.name))continue;let u=l.join(a.dir,c.name),g=l.relative(t,u).split(l.sep).join("/");c.isFile()&&e(c.name,g)&&n.push(u),c.isDirectory()&&a.depth<o&&s.push({dir:u,depth:a.depth+1});}}return n}async function L(t,e){let o=await v.readJson(e),n=o.total??o,s={};for(let a of ["lines","branches","functions","statements"]){let i=W(n[a]);i&&(s[a]=i);}let r=[];for(let[a,i]of Object.entries(o)){if(a==="total"||!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u={};for(let g of ["lines","branches","functions","statements"]){let b=W(c[g]);b&&(u[g]=b);}r.push({path:y(t,a),metrics:u});}return {metrics:s,files:r,source:{format:"istanbul-json",path:e,sha256:await C(e)}}}async function z(t,e){let o=await v.readJson(e),n=o.totals??{},s={lines:m(n.num_statements,n.covered_lines)};p(n.num_branches)>0&&(s.branches=m(n.num_branches,n.covered_branches));let r=[];for(let[a,i]of Object.entries(o.files??{})){let c=i?.summary??{};r.push({path:y(t,a),metrics:{lines:m(c.num_statements,c.covered_lines),...p(c.num_branches)>0?{branches:m(c.num_branches,c.covered_branches)}:{}}});}return {metrics:s,files:r,source:{format:"coverage-py-json",path:e,sha256:await C(e)}}}function j(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,o=p(e.count),n=p(e.covered);return o>0?m(o,n):void 0}async function B(t,e){let o=await v.readJson(e),n=Array.isArray(o.data)?o.data[0]??{}:o,s=n.totals??{},r={};r.lines=j(s.lines),r.functions=j(s.functions),r.branches=j(s.branches),r.statements=j(s.regions);let a=[];for(let i of Array.isArray(n.files)?n.files:[]){if(!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u=c.summary??{};a.push({path:y(t,String(c.filename??"unknown")),metrics:{lines:j(u.lines),functions:j(u.functions),branches:j(u.branches),statements:j(u.regions)}});}return {metrics:r,files:a,source:{format:"llvm-cov-json",path:e,sha256:await C(e)}}}async function E(t,e){let o=await v.readFile(e,"utf8"),n=[],s="",r=0,a=0,i=0,c=0,u=0,g=0,b=d=>{s&&(n.push({path:y(t,s),metrics:{lines:m(d.lineTotal,d.lineCovered),functions:m(d.functionTotal,d.functionCovered),branches:m(d.branchTotal,d.branchCovered)}}),r+=d.lineTotal,a+=d.lineCovered,i+=d.functionTotal,c+=d.functionCovered,u+=d.branchTotal,g+=d.branchCovered);},h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0};for(let d of o.split(/\r?\n/))d.startsWith("SF:")?s=d.slice(3):d.startsWith("LF:")?h.lineTotal=p(d.slice(3)):d.startsWith("LH:")?h.lineCovered=p(d.slice(3)):d.startsWith("FNF:")?h.functionTotal=p(d.slice(4)):d.startsWith("FNH:")?h.functionCovered=p(d.slice(4)):d.startsWith("BRF:")?h.branchTotal=p(d.slice(4)):d.startsWith("BRH:")?h.branchCovered=p(d.slice(4)):d==="end_of_record"&&(b(h),s="",h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0});return {metrics:{lines:m(r,a),functions:m(i,c),branches:m(u,g)},files:n,source:{format:"lcov",path:e,sha256:await C(e)}}}async function K(t,e){let o=await v.readFile(e,"utf8"),n=new Map;for(let a of o.split(/\r?\n/).slice(1)){let i=/^(.+?):\d+\.\d+,\d+\.\d+\s+(\d+)\s+(\d+)$/.exec(a.trim());if(!i)continue;let c=n.get(i[1])??{total:0,covered:0},u=p(i[2]);c.total+=u,p(i[3])>0&&(c.covered+=u),n.set(i[1],c);}let s=[...n.entries()].map(([a,i])=>({path:y(t,a),metrics:{statements:m(i.total,i.covered)}})),r=[...n.values()].reduce((a,i)=>({total:a.total+i.total,covered:a.covered+i.covered}),{total:0,covered:0});return {metrics:{statements:m(r.total,r.covered)},files:s,source:{format:"go-coverprofile",path:e,sha256:await C(e)}}}function k(t,e){let n=[...t.matchAll(new RegExp(`<counter\\s+type=["']${e}["']\\s+missed=["'](\\d+)["']\\s+covered=["'](\\d+)["']\\s*\\/?\\s*>`,"gi"))].at(-1);return n?m(Number(n[1])+Number(n[2]),n[2]):void 0}async function x(t,e){let o=await v.readFile(t,"utf8"),n={};if(e==="cobertura-xml"){let s=/<coverage\b([^>]*)>/i.exec(o)?.[1]??"",r=/\bline-rate=["']([\d.]+)["']/i.exec(s)?.[1],a=/\bbranch-rate=["']([\d.]+)["']/i.exec(s)?.[1];r&&(n.lines=m(1e4,Math.round(Number(r)*1e4))),a&&(n.branches=m(1e4,Math.round(Number(a)*1e4)));}if(e==="clover-xml"){let r=[...o.matchAll(/<metrics\b([^>]*)\/?>/gi)].at(-1)?.[1]??"",a=g=>p(new RegExp(`\\b${g}=["'](\\d+)["']`,"i").exec(r)?.[1]),i=a("statements"),c=a("methods"),u=a("conditionals");i>0&&(n.statements=m(i,a("coveredstatements"))),c>0&&(n.functions=m(c,a("coveredmethods"))),u>0&&(n.branches=m(u,a("coveredconditionals")));}return n.lines??=k(o,"LINE"),n.branches??=k(o,"BRANCH"),n.functions??=k(o,"METHOD"),n.statements??=k(o,"INSTRUCTION"),{metrics:n,files:[],source:{format:e,path:t,sha256:await C(t)}}}async function X(t){let e=await v.readFile(t,"utf8"),o=/<scoverage\b([^>]*)>/i.exec(e)?.[1]??"",n=b=>p(new RegExp(`\\b${b}=["']([\\d.]+)["']`,"i").exec(o)?.[1]),s=n("statement-count"),r=n("statements-invoked"),a=n("branch-count"),i=n("branches-invoked"),c=n("statement-rate"),u=n("branch-rate"),g={};return s>0?g.statements=m(s,r):c>0&&(g.statements=m(1e4,Math.round(c*100))),a>0?g.branches=m(a,i):u>0&&(g.branches=m(1e4,Math.round(u*100))),{metrics:g,files:[],source:{format:"scoverage-xml",path:t,sha256:await C(t)}}}async function Q(t,e){let o=await v.readJson(e),n=new Map;for(let a of Object.values(o)){let i=a?.coverage;if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[c,u]of Object.entries(i)){if(!Array.isArray(u))continue;let g=n.get(c)??[];u.forEach((b,h)=>{typeof b=="number"&&(g[h]=Math.max(g[h]??0,b));}),n.set(c,g);}}let s=[...n.entries()].map(([a,i])=>{let c=i.filter(u=>typeof u=="number");return {path:y(t,a),metrics:{lines:m(c.length,c.filter(u=>u>0).length)}}}),r=s.reduce((a,i)=>{let c=i.metrics.lines;return {total:a.total+(c?.total??0),covered:a.covered+(c?.covered??0)}},{total:0,covered:0});return {metrics:{lines:m(r.total,r.covered)},files:s,source:{format:"simplecov-json",path:e,sha256:await C(e)}}}async function q(t,e={}){let o=[{relativePath:"coverage/coverage-summary.json",parser:r=>L(t,r)},{relativePath:"coverage.json",parser:async r=>{let a=await v.readJson(r);return Array.isArray(a.data)?B(t,r):z(t,r)}},{relativePath:"coverage/lcov.info",parser:r=>E(t,r)},{relativePath:"cover/lcov.info",parser:r=>E(t,r)},{relativePath:"lcov.info",parser:r=>E(t,r)},{relativePath:"coverage.out",parser:r=>K(t,r)},{relativePath:"target/site/jacoco/jacoco.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"build/reports/jacoco/test/jacocoTestReport.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"coverage.xml",parser:r=>x(r,"clover-xml")},{relativePath:".resultset.json",parser:r=>Q(t,r)}];for(let r of o){let a=l.join(t,r.relativePath);if(await v.pathExists(a))return r.parser(a)}if(e.recursive===false)return null;let s=(await U(t,(r,a)=>r==="coverage.cobertura.xml"||r==="jacoco.xml"||r==="clover.xml"||r==="scoverage.xml"||a.endsWith("/coverage-summary.json"),7)).sort()[0];return s?s.endsWith("coverage-summary.json")?L(t,s):s.endsWith("jacoco.xml")?x(s,"jacoco-xml"):s.endsWith("coverage.cobertura.xml")?x(s,"cobertura-xml"):s.endsWith("scoverage.xml")?X(s):x(s,"clover-xml"):null}async function Y(t){return v.readJson(l.join(t,"package.json")).catch(()=>null)}async function H(t,e){let o=(n,s)=>({cwd:t,executable:n,args:s});if(e==="node"||e==="bun"){let s=(await Y(t))?.scripts??{},r=["test:coverage","test:cov","coverage"].find(i=>typeof s[i]=="string"),a=e==="bun"?"bun":await v.pathExists(l.join(t,"pnpm-lock.yaml"))?"pnpm":await v.pathExists(l.join(t,"yarn.lock"))?"yarn":"npm";if(r)return {runner:String(s[r]).split(/\s+/)[0]||a,invocations:[o(a,a==="yarn"?[r]:["run",r])],diagnostics:[]};if(typeof s.test=="string"){let i=a==="yarn"?["test","--coverage"]:a==="bun"?["test","--coverage","--coverage-reporter=lcov"]:["test","--","--coverage"];return {runner:String(s.test).split(/\s+/)[0]||a,invocations:[o(a,i)],diagnostics:[]}}return {runner:null,invocations:[],diagnostics:["No project-owned test or coverage script was detected."]}}if(e==="deno")return {runner:"deno",invocations:[o("deno",["test","--coverage=coverage"]),o("deno",["coverage","--lcov","--output=coverage/lcov.info","coverage"])],diagnostics:[]};if(e==="python")return {runner:"pytest-cov",invocations:[o(await v.pathExists(l.join(t,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"))?l.join(".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"):process.platform==="win32"?"python":"python3",["-m","pytest","--cov=.","--cov-report=json:coverage.json"])],diagnostics:[]};if(e==="go")return {runner:"go test",invocations:[o("go",["test","./...","-coverprofile=coverage.out"])],diagnostics:[]};if(e==="java"){let n=await v.pathExists(l.join(t,"gradlew")),s=await v.pathExists(l.join(t,"gradlew.bat")),r=n||s,a=await v.pathExists(l.join(t,"mvnw")),i=await v.pathExists(l.join(t,"mvnw.cmd")),c=r?process.platform==="win32"&&s?".\\gradlew.bat":"./gradlew":await v.pathExists(l.join(t,"pom.xml"))?process.platform==="win32"&&i?".\\mvnw.cmd":a?"./mvnw":"mvn":"gradle";return {runner:r?"jacoco/gradle":"jacoco/maven",invocations:[o(c,r?["test","jacocoTestReport"]:["test","jacoco:report"])],diagnostics:[]}}return e==="dotnet"?{runner:"dotnet coverlet",invocations:[o("dotnet",["test","--collect:XPlat Code Coverage"])],diagnostics:[]}:e==="rust"?{runner:"cargo llvm-cov",invocations:[o("cargo",["llvm-cov","--json","--output-path","coverage.json"])],diagnostics:["cargo-llvm-cov must be available in the project toolchain."]}:e==="php"?{runner:"phpunit",invocations:[o(process.platform==="win32"?"vendor\\bin\\phpunit.bat":"vendor/bin/phpunit",["--coverage-clover","coverage.xml"])],diagnostics:[]}:e==="ruby"?{runner:"simplecov",invocations:[o("bundle",["exec","rspec"])],diagnostics:["The test suite must enable SimpleCov to emit .resultset.json."]}:e==="elixir"?{runner:"mix cover",invocations:[o("mix",["test","--cover"])],diagnostics:["Configure ExCoveralls for JSON or LCOV interchange when machine-readable coverage is required."]}:e==="clojure"?{runner:"cloverage",invocations:[o("clojure",["-M:coverage"])],diagnostics:["The project must declare a coverage alias such as cloverage."]}:e==="scala"?{runner:"sbt-scoverage",invocations:[o("sbt",["clean","coverage","test","coverageReport"])],diagnostics:["The project must declare the scoverage plugin."]}:e==="kotlin"?{runner:"jacoco/gradle",invocations:[o(await v.pathExists(l.join(t,process.platform==="win32"?"gradlew.bat":"gradlew"))?process.platform==="win32"?".\\gradlew.bat":"./gradlew":"gradle",["test","jacocoTestReport"])],diagnostics:["The project must declare the JaCoCo Gradle plugin."]}:e==="c"||e==="cpp"?{runner:"CTest/LLVM coverage",invocations:[o("ctest",["--test-dir","build","--output-on-failure"])],diagnostics:["The native build must be instrumented for coverage and export LCOV, Cobertura, or LLVM JSON evidence."]}:{runner:null,invocations:[],diagnostics:["Project runtime could not be detected."]}}async function ve(t,e){let o=await I(t),n=e??await V(o),s=await H(o,n),r=await q(o,{recursive:false}).catch(()=>null),a=r?.source.path&&r.source.sha256?[{path:l.relative(o,r.source.path).split(l.sep).join("/"),sha256:r.source.sha256}]:[],i=[...s.diagnostics],c=r?"available":s.invocations.length===0||n==="unknown"?"unsupported":i.length>0?"requires-setup":"available";return {runtime:n,runner:s.runner,status:c,existingEvidence:a,invocations:s.invocations,prerequisites:i}}function Z(t,e){let o=t?l.relative(t,e).split(l.sep).join("/"):l.resolve(e),n=l.basename(e).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"project",s=createHash("sha256").update(o).digest("hex").slice(0,12);return `${n}--${s}`}function ee(t){return t.lines?"lines":t.statements?"statements":t.branches?"branches":"functions"}async function me(t={}){let e=await I(t.projectPath??process.cwd()),o=a(e),n=t.runtime??await V(e),s=Math.max(0,Math.min(100,Math.round(t.target??80))),r=await H(e,n),a$1=[],i$1=Date.now();if(t.run)for(let f of r.invocations){let w=await execa(f.executable,f.args,{cwd:f.cwd,reject:false,timeout:6e5}).catch(()=>({exitCode:1}));if(a$1.push(Number(w.exitCode??1)),Number(w.exitCode??1)!==0)break}let c=await q(e).catch(()=>null),u=c?ee(c.metrics):"lines",g=c?.metrics[u]?.percent??null,b=t.run&&a$1.some(f=>f!==0)?"failed":g===null?"unavailable":g>=s?"passed":"below-target",h$1=Z(o,e),d=l.join(e,P),R=o?`.workspai/reports/projects/${h$1}/project-test-coverage-last-run.json`:null,T={schemaVersion:D,generatedAt:new Date().toISOString(),status:b,project:{id:h$1,name:l.basename(e),path:e,workspacePath:o},runtime:n,runner:r.runner,target:{metric:u,percent:s},metrics:c?.metrics??{},files:c?.files??[],lowCoverageFiles:(c?.files??[]).map(f=>{let w=f.metrics[u]??f.metrics.lines??f.metrics.statements;return {path:f.path,percent:w?.percent??null,uncovered:Math.max(0,(w?.total??0)-(w?.covered??0))}}).filter(f=>f.percent===null||f.percent<s).sort((f,w)=>w.uncovered-f.uncovered||f.path.localeCompare(w.path)),source:c?.source??{format:"unknown",path:null,sha256:null},execution:{requested:t.run===true,invocations:r.invocations,exitCodes:a$1,durationMs:Date.now()-i$1},diagnostics:[...r.diagnostics,...c?[]:["No supported machine-readable coverage artifact was found."]],artifactPaths:{project:d,workspaceLatest:o?l.join(o,P):null,workspaceProject:o&&R?l.join(o,R):null}};return o&&R&&await i(o,P,[{relativePath:P,payload:T},{relativePath:R,payload:T}]),await h(e,P,T),T}export{D as a,P as b,ve as c,me as d};
|
|
1
|
+
import {a}from'./chunk-MGL6DBOR.js';import {m as m$1}from'./chunk-YYELANJO.js';import {a as a$1}from'./chunk-GR6442P7.js';import {i,h}from'./chunk-FE5R6EUV.js';import {s,t}from'./chunk-ODK4LCEL.js';import {createHash}from'crypto';import l from'path';import {execa}from'execa';import v from'fs-extra';var D=s.projectTestCoverage.schemaVersion,P=t.projectTestCoverage,G=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deps.edn","project.clj","build.sbt","CMakeLists.txt","meson.build","deno.json","deno.jsonc"];function p(t){let e=Number(t);return Number.isFinite(e)&&e>=0?e:0}function m(t,e,o=0){let n=p(t),s=Math.min(p(e),n),r=p(o);return {total:n,covered:s,skipped:r,percent:n>0?Math.round(s/n*1e4)/100:null}}function W(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;return m(e.total,e.covered,e.skipped)}function y(t,e){let o=l.isAbsolute(e)?e:l.resolve(t,e),n=l.relative(t,o);return n&&!n.startsWith("..")?n.split(l.sep).join("/"):e}async function C(t){return createHash("sha256").update(await v.readFile(t)).digest("hex")}async function I(t){let e=l.resolve(t);for(;;){let o=await v.pathExists(l.join(e,".workspai","project.json"))||await v.pathExists(l.join(e,".rapidkit","project.json")),n=(await v.readdir(e).catch(()=>[])).some(r=>r.toLowerCase().endsWith(".gemspec"));if(o||n||(await Promise.all(G.map(r=>v.pathExists(l.join(e,r))))).some(Boolean))return e;let s=l.dirname(e);if(s===e)return l.resolve(t);e=s;}}async function V(t){return m$1(t).runtime}async function U(t,e,o=5){let n=[],s=[{dir:t,depth:0}],r=new Set([".git",".workspai",".rapidkit","node_modules",".venv","vendor","deps"]);for(;s.length>0;){let a=s.shift();if(!a)break;let i=await v.readdir(a.dir,{withFileTypes:true}).catch(()=>[]);for(let c of i){if(r.has(c.name)||a$1(c.name))continue;let u=l.join(a.dir,c.name),g=l.relative(t,u).split(l.sep).join("/");c.isFile()&&e(c.name,g)&&n.push(u),c.isDirectory()&&a.depth<o&&s.push({dir:u,depth:a.depth+1});}}return n}async function L(t,e){let o=await v.readJson(e),n=o.total??o,s={};for(let a of ["lines","branches","functions","statements"]){let i=W(n[a]);i&&(s[a]=i);}let r=[];for(let[a,i]of Object.entries(o)){if(a==="total"||!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u={};for(let g of ["lines","branches","functions","statements"]){let b=W(c[g]);b&&(u[g]=b);}r.push({path:y(t,a),metrics:u});}return {metrics:s,files:r,source:{format:"istanbul-json",path:e,sha256:await C(e)}}}async function z(t,e){let o=await v.readJson(e),n=o.totals??{},s={lines:m(n.num_statements,n.covered_lines)};p(n.num_branches)>0&&(s.branches=m(n.num_branches,n.covered_branches));let r=[];for(let[a,i]of Object.entries(o.files??{})){let c=i?.summary??{};r.push({path:y(t,a),metrics:{lines:m(c.num_statements,c.covered_lines),...p(c.num_branches)>0?{branches:m(c.num_branches,c.covered_branches)}:{}}});}return {metrics:s,files:r,source:{format:"coverage-py-json",path:e,sha256:await C(e)}}}function j(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,o=p(e.count),n=p(e.covered);return o>0?m(o,n):void 0}async function B(t,e){let o=await v.readJson(e),n=Array.isArray(o.data)?o.data[0]??{}:o,s=n.totals??{},r={};r.lines=j(s.lines),r.functions=j(s.functions),r.branches=j(s.branches),r.statements=j(s.regions);let a=[];for(let i of Array.isArray(n.files)?n.files:[]){if(!i||typeof i!="object"||Array.isArray(i))continue;let c=i,u=c.summary??{};a.push({path:y(t,String(c.filename??"unknown")),metrics:{lines:j(u.lines),functions:j(u.functions),branches:j(u.branches),statements:j(u.regions)}});}return {metrics:r,files:a,source:{format:"llvm-cov-json",path:e,sha256:await C(e)}}}async function E(t,e){let o=await v.readFile(e,"utf8"),n=[],s="",r=0,a=0,i=0,c=0,u=0,g=0,b=d=>{s&&(n.push({path:y(t,s),metrics:{lines:m(d.lineTotal,d.lineCovered),functions:m(d.functionTotal,d.functionCovered),branches:m(d.branchTotal,d.branchCovered)}}),r+=d.lineTotal,a+=d.lineCovered,i+=d.functionTotal,c+=d.functionCovered,u+=d.branchTotal,g+=d.branchCovered);},h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0};for(let d of o.split(/\r?\n/))d.startsWith("SF:")?s=d.slice(3):d.startsWith("LF:")?h.lineTotal=p(d.slice(3)):d.startsWith("LH:")?h.lineCovered=p(d.slice(3)):d.startsWith("FNF:")?h.functionTotal=p(d.slice(4)):d.startsWith("FNH:")?h.functionCovered=p(d.slice(4)):d.startsWith("BRF:")?h.branchTotal=p(d.slice(4)):d.startsWith("BRH:")?h.branchCovered=p(d.slice(4)):d==="end_of_record"&&(b(h),s="",h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0});return {metrics:{lines:m(r,a),functions:m(i,c),branches:m(u,g)},files:n,source:{format:"lcov",path:e,sha256:await C(e)}}}async function K(t,e){let o=await v.readFile(e,"utf8"),n=new Map;for(let a of o.split(/\r?\n/).slice(1)){let i=/^(.+?):\d+\.\d+,\d+\.\d+\s+(\d+)\s+(\d+)$/.exec(a.trim());if(!i)continue;let c=n.get(i[1])??{total:0,covered:0},u=p(i[2]);c.total+=u,p(i[3])>0&&(c.covered+=u),n.set(i[1],c);}let s=[...n.entries()].map(([a,i])=>({path:y(t,a),metrics:{statements:m(i.total,i.covered)}})),r=[...n.values()].reduce((a,i)=>({total:a.total+i.total,covered:a.covered+i.covered}),{total:0,covered:0});return {metrics:{statements:m(r.total,r.covered)},files:s,source:{format:"go-coverprofile",path:e,sha256:await C(e)}}}function k(t,e){let n=[...t.matchAll(new RegExp(`<counter\\s+type=["']${e}["']\\s+missed=["'](\\d+)["']\\s+covered=["'](\\d+)["']\\s*\\/?\\s*>`,"gi"))].at(-1);return n?m(Number(n[1])+Number(n[2]),n[2]):void 0}async function x(t,e){let o=await v.readFile(t,"utf8"),n={};if(e==="cobertura-xml"){let s=/<coverage\b([^>]*)>/i.exec(o)?.[1]??"",r=/\bline-rate=["']([\d.]+)["']/i.exec(s)?.[1],a=/\bbranch-rate=["']([\d.]+)["']/i.exec(s)?.[1];r&&(n.lines=m(1e4,Math.round(Number(r)*1e4))),a&&(n.branches=m(1e4,Math.round(Number(a)*1e4)));}if(e==="clover-xml"){let r=[...o.matchAll(/<metrics\b([^>]*)\/?>/gi)].at(-1)?.[1]??"",a=g=>p(new RegExp(`\\b${g}=["'](\\d+)["']`,"i").exec(r)?.[1]),i=a("statements"),c=a("methods"),u=a("conditionals");i>0&&(n.statements=m(i,a("coveredstatements"))),c>0&&(n.functions=m(c,a("coveredmethods"))),u>0&&(n.branches=m(u,a("coveredconditionals")));}return n.lines??=k(o,"LINE"),n.branches??=k(o,"BRANCH"),n.functions??=k(o,"METHOD"),n.statements??=k(o,"INSTRUCTION"),{metrics:n,files:[],source:{format:e,path:t,sha256:await C(t)}}}async function X(t){let e=await v.readFile(t,"utf8"),o=/<scoverage\b([^>]*)>/i.exec(e)?.[1]??"",n=b=>p(new RegExp(`\\b${b}=["']([\\d.]+)["']`,"i").exec(o)?.[1]),s=n("statement-count"),r=n("statements-invoked"),a=n("branch-count"),i=n("branches-invoked"),c=n("statement-rate"),u=n("branch-rate"),g={};return s>0?g.statements=m(s,r):c>0&&(g.statements=m(1e4,Math.round(c*100))),a>0?g.branches=m(a,i):u>0&&(g.branches=m(1e4,Math.round(u*100))),{metrics:g,files:[],source:{format:"scoverage-xml",path:t,sha256:await C(t)}}}async function Q(t,e){let o=await v.readJson(e),n=new Map;for(let a of Object.values(o)){let i=a?.coverage;if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[c,u]of Object.entries(i)){if(!Array.isArray(u))continue;let g=n.get(c)??[];u.forEach((b,h)=>{typeof b=="number"&&(g[h]=Math.max(g[h]??0,b));}),n.set(c,g);}}let s=[...n.entries()].map(([a,i])=>{let c=i.filter(u=>typeof u=="number");return {path:y(t,a),metrics:{lines:m(c.length,c.filter(u=>u>0).length)}}}),r=s.reduce((a,i)=>{let c=i.metrics.lines;return {total:a.total+(c?.total??0),covered:a.covered+(c?.covered??0)}},{total:0,covered:0});return {metrics:{lines:m(r.total,r.covered)},files:s,source:{format:"simplecov-json",path:e,sha256:await C(e)}}}async function q(t,e={}){let o=[{relativePath:"coverage/coverage-summary.json",parser:r=>L(t,r)},{relativePath:"coverage.json",parser:async r=>{let a=await v.readJson(r);return Array.isArray(a.data)?B(t,r):z(t,r)}},{relativePath:"coverage/lcov.info",parser:r=>E(t,r)},{relativePath:"cover/lcov.info",parser:r=>E(t,r)},{relativePath:"lcov.info",parser:r=>E(t,r)},{relativePath:"coverage.out",parser:r=>K(t,r)},{relativePath:"target/site/jacoco/jacoco.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"build/reports/jacoco/test/jacocoTestReport.xml",parser:r=>x(r,"jacoco-xml")},{relativePath:"coverage.xml",parser:r=>x(r,"clover-xml")},{relativePath:".resultset.json",parser:r=>Q(t,r)}];for(let r of o){let a=l.join(t,r.relativePath);if(await v.pathExists(a))return r.parser(a)}if(e.recursive===false)return null;let s=(await U(t,(r,a)=>r==="coverage.cobertura.xml"||r==="jacoco.xml"||r==="clover.xml"||r==="scoverage.xml"||a.endsWith("/coverage-summary.json"),7)).sort()[0];return s?s.endsWith("coverage-summary.json")?L(t,s):s.endsWith("jacoco.xml")?x(s,"jacoco-xml"):s.endsWith("coverage.cobertura.xml")?x(s,"cobertura-xml"):s.endsWith("scoverage.xml")?X(s):x(s,"clover-xml"):null}async function Y(t){return v.readJson(l.join(t,"package.json")).catch(()=>null)}async function H(t,e){let o=(n,s)=>({cwd:t,executable:n,args:s});if(e==="node"||e==="bun"){let s=(await Y(t))?.scripts??{},r=["test:coverage","test:cov","coverage"].find(i=>typeof s[i]=="string"),a=e==="bun"?"bun":await v.pathExists(l.join(t,"pnpm-lock.yaml"))?"pnpm":await v.pathExists(l.join(t,"yarn.lock"))?"yarn":"npm";if(r)return {runner:String(s[r]).split(/\s+/)[0]||a,invocations:[o(a,a==="yarn"?[r]:["run",r])],diagnostics:[]};if(typeof s.test=="string"){let i=a==="yarn"?["test","--coverage"]:a==="bun"?["test","--coverage","--coverage-reporter=lcov"]:["test","--","--coverage"];return {runner:String(s.test).split(/\s+/)[0]||a,invocations:[o(a,i)],diagnostics:[]}}return {runner:null,invocations:[],diagnostics:["No project-owned test or coverage script was detected."]}}if(e==="deno")return {runner:"deno",invocations:[o("deno",["test","--coverage=coverage"]),o("deno",["coverage","--lcov","--output=coverage/lcov.info","coverage"])],diagnostics:[]};if(e==="python")return {runner:"pytest-cov",invocations:[o(await v.pathExists(l.join(t,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"))?l.join(".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"):process.platform==="win32"?"python":"python3",["-m","pytest","--cov=.","--cov-report=json:coverage.json"])],diagnostics:[]};if(e==="go")return {runner:"go test",invocations:[o("go",["test","./...","-coverprofile=coverage.out"])],diagnostics:[]};if(e==="java"){let n=await v.pathExists(l.join(t,"gradlew")),s=await v.pathExists(l.join(t,"gradlew.bat")),r=n||s,a=await v.pathExists(l.join(t,"mvnw")),i=await v.pathExists(l.join(t,"mvnw.cmd")),c=r?process.platform==="win32"&&s?".\\gradlew.bat":"./gradlew":await v.pathExists(l.join(t,"pom.xml"))?process.platform==="win32"&&i?".\\mvnw.cmd":a?"./mvnw":"mvn":"gradle";return {runner:r?"jacoco/gradle":"jacoco/maven",invocations:[o(c,r?["test","jacocoTestReport"]:["test","jacoco:report"])],diagnostics:[]}}return e==="dotnet"?{runner:"dotnet coverlet",invocations:[o("dotnet",["test","--collect:XPlat Code Coverage"])],diagnostics:[]}:e==="rust"?{runner:"cargo llvm-cov",invocations:[o("cargo",["llvm-cov","--json","--output-path","coverage.json"])],diagnostics:["cargo-llvm-cov must be available in the project toolchain."]}:e==="php"?{runner:"phpunit",invocations:[o(process.platform==="win32"?"vendor\\bin\\phpunit.bat":"vendor/bin/phpunit",["--coverage-clover","coverage.xml"])],diagnostics:[]}:e==="ruby"?{runner:"simplecov",invocations:[o("bundle",["exec","rspec"])],diagnostics:["The test suite must enable SimpleCov to emit .resultset.json."]}:e==="elixir"?{runner:"mix cover",invocations:[o("mix",["test","--cover"])],diagnostics:["Configure ExCoveralls for JSON or LCOV interchange when machine-readable coverage is required."]}:e==="clojure"?{runner:"cloverage",invocations:[o("clojure",["-M:coverage"])],diagnostics:["The project must declare a coverage alias such as cloverage."]}:e==="scala"?{runner:"sbt-scoverage",invocations:[o("sbt",["clean","coverage","test","coverageReport"])],diagnostics:["The project must declare the scoverage plugin."]}:e==="kotlin"?{runner:"jacoco/gradle",invocations:[o(await v.pathExists(l.join(t,process.platform==="win32"?"gradlew.bat":"gradlew"))?process.platform==="win32"?".\\gradlew.bat":"./gradlew":"gradle",["test","jacocoTestReport"])],diagnostics:["The project must declare the JaCoCo Gradle plugin."]}:e==="c"||e==="cpp"?{runner:"CTest/LLVM coverage",invocations:[o("ctest",["--test-dir","build","--output-on-failure"])],diagnostics:["The native build must be instrumented for coverage and export LCOV, Cobertura, or LLVM JSON evidence."]}:{runner:null,invocations:[],diagnostics:["Project runtime could not be detected."]}}async function ve(t,e){let o=await I(t),n=e??await V(o),s=await H(o,n),r=await q(o,{recursive:false}).catch(()=>null),a=r?.source.path&&r.source.sha256?[{path:l.relative(o,r.source.path).split(l.sep).join("/"),sha256:r.source.sha256}]:[],i=[...s.diagnostics],c=r?"available":s.invocations.length===0||n==="unknown"?"unsupported":i.length>0?"requires-setup":"available";return {runtime:n,runner:s.runner,status:c,existingEvidence:a,invocations:s.invocations,prerequisites:i}}function Z(t,e){let o=t?l.relative(t,e).split(l.sep).join("/"):l.resolve(e),n=l.basename(e).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"project",s=createHash("sha256").update(o).digest("hex").slice(0,12);return `${n}--${s}`}function ee(t){return t.lines?"lines":t.statements?"statements":t.branches?"branches":"functions"}async function me(t={}){let e=await I(t.projectPath??process.cwd()),o=a(e),n=t.runtime??await V(e),s=Math.max(0,Math.min(100,Math.round(t.target??80))),r=await H(e,n),a$1=[],i$1=Date.now();if(t.run)for(let f of r.invocations){let w=await execa(f.executable,f.args,{cwd:f.cwd,reject:false,timeout:6e5}).catch(()=>({exitCode:1}));if(a$1.push(Number(w.exitCode??1)),Number(w.exitCode??1)!==0)break}let c=await q(e).catch(()=>null),u=c?ee(c.metrics):"lines",g=c?.metrics[u]?.percent??null,b=t.run&&a$1.some(f=>f!==0)?"failed":g===null?"unavailable":g>=s?"passed":"below-target",h$1=Z(o,e),d=l.join(e,P),R=o?`.workspai/reports/projects/${h$1}/project-test-coverage-last-run.json`:null,T={schemaVersion:D,generatedAt:new Date().toISOString(),status:b,project:{id:h$1,name:l.basename(e),path:e,workspacePath:o},runtime:n,runner:r.runner,target:{metric:u,percent:s},metrics:c?.metrics??{},files:c?.files??[],lowCoverageFiles:(c?.files??[]).map(f=>{let w=f.metrics[u]??f.metrics.lines??f.metrics.statements;return {path:f.path,percent:w?.percent??null,uncovered:Math.max(0,(w?.total??0)-(w?.covered??0))}}).filter(f=>f.percent===null||f.percent<s).sort((f,w)=>w.uncovered-f.uncovered||f.path.localeCompare(w.path)),source:c?.source??{format:"unknown",path:null,sha256:null},execution:{requested:t.run===true,invocations:r.invocations,exitCodes:a$1,durationMs:Date.now()-i$1},diagnostics:[...r.diagnostics,...c?[]:["No supported machine-readable coverage artifact was found."]],artifactPaths:{project:d,workspaceLatest:o?l.join(o,P):null,workspaceProject:o&&R?l.join(o,R):null}};return o&&R&&await i(o,P,[{relativePath:P,payload:T},{relativePath:R,payload:T}]),await h(e,P,T),T}export{D as a,P as b,ve as c,me as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import a from'path';import Y from'fs-extra';import q from'chalk';async function U(p,n={}){let e=a.resolve(p),{WORKSPACE_CONTRACT_PATH:l,syncWorkspaceContract:d,verifyWorkspaceContract:S,writeWorkspaceContractVerifyEvidence:j}=await import('./workspace-contract-
|
|
1
|
+
import a from'path';import Y from'fs-extra';import q from'chalk';async function U(p,n={}){let e=a.resolve(p),{WORKSPACE_CONTRACT_PATH:l,syncWorkspaceContract:d,verifyWorkspaceContract:S,writeWorkspaceContractVerifyEvidence:j}=await import('./workspace-contract-GRZY7WRD.js'),w=await d({workspacePath:e,strict:true}),{syncWorkspaceReadme:E,WORKSPACE_README_PATH:R}=await import('./workspace-readme-HA6XLDME.js'),x=await E({workspacePath:e,workspaceName:w.contract.workspace.name,profile:w.contract.workspace.profile??"minimal",projectCount:w.contract.projects.length}),{buildWorkspaceModel:h,writeWorkspaceModel:g}=await import('./workspace-model-2ODVOWDQ.js'),r=await h({workspacePath:e,includeEvidence:true}),k=await g(r,e),{buildWorkspaceImpact:G,buildWorkspaceModelSnapshot:O,diffWorkspaceModel:$,writeWorkspaceImpact:M,writeWorkspaceModelDiff:T,writeWorkspaceModelSnapshot:_}=await import('./workspace-intelligence-26YT6KMN.js'),{WORKSPACE_INTELLIGENCE_ARTIFACTS:s}=await import('./workspace-intelligence-runtime-registry-ZLPF7BAY.js'),{syncWorkspaceAgentGrounding:P}=await import('./workspace-agent-sync-TN6QDNBR.js'),W=await P({workspacePath:e,model:r,write:true,refreshContext:true,strict:false,preset:"enterprise",targets:["all"],projectGrounding:n.projectGrounding??"managed"}),v=new Set(W.writtenFiles),i=new Set(W.projectLenses?.skipped.map(t=>`${t.name}: ${t.reason}`)??[]),{readWorkspaceKnowledgeGraphSnapshot:C}=await import('./workspace-knowledge-graph-snapshot-JEJMRQZL.js'),o=await C(e),y=false;if(o.status==="miss"){if(o.reason!=="live-input-mismatch")throw new Error(`Workspace consumer sync could not validate canonical Model/Graph evidence (${o.reason}).`);r=await h({workspacePath:e,includeEvidence:true}),k=await g(r,e);let{buildWorkspaceAgentContext:t,writeWorkspaceAgentContext:f}=await import('./workspace-context-Y3TNY2XZ.js'),m=await t({workspacePath:e,model:r,agent:"generic",includeEvidence:true});await f(m,e);let b=await P({workspacePath:e,model:r,write:true,refreshContext:false,strict:false,preset:"enterprise",targets:["all"],projectGrounding:n.projectGrounding??"managed"});for(let c of b.writtenFiles)v.add(c);for(let c of b.projectLenses?.skipped??[])i.add(`${c.name}: ${c.reason}`);if(o=await C(e),o.status==="miss")throw new Error(`Workspace consumer reconciliation did not produce fresh canonical evidence (${o.reason}).`);y=true;}let F=a.join(e,s.snapshot),u=false;if(!await Y.pathExists(F)){let t=await O({workspacePath:e,model:r});await _(t,e),u=true;}let I=await $({workspacePath:e,fromPath:s.snapshot,model:r}),N=await T(I,e),L=await G({workspacePath:e,fromPath:s.diff}),K=await M(L,e),z=await S({workspacePath:e,strict:true}),H=await j({workspacePath:e,result:z}),V=(o.graph.source.inputs?.scopes??[]).filter(t=>t.truncated);for(let t of V)i.add(`${t.kind}:${t.id} graph inventory reached its ${t.fileLimit}-file emergency bound; inventory completeness is bounded.`);let A=o.graph.quality.completeness?.providers.bounded??0;A>0&&i.add(`${A} graph provider(s) used declared adaptive semantic/deep budgets; inspect provider inputCoverage before making exhaustive symbol-level claims.`);let D=[l,(await import('./workspace-registry-summary-VKTJ7PHV.js')).WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH,a.relative(e,x).split(a.sep).join("/")||R,a.relative(e,k).split(a.sep).join("/"),s.knowledgeGraph,...u?[s.snapshot]:[],a.relative(e,N).split(a.sep).join("/"),a.relative(e,K).split(a.sep).join("/"),a.relative(e,H).split(a.sep).join("/"),...v].filter((t,f,m)=>m.indexOf(t)===f);return n.silent||console.log(q.gray(`\u2713 Workspace Intelligence synced \xB7 ${r.summary.projectCount} project(s) \xB7 model + graph + agent grounding \xB7 freshness sealed`)),{workspacePath:e,projectCount:r.summary.projectCount,baselineCreated:u,freshnessSealed:true,reconciledAfterGrounding:y,writtenFiles:D,warnings:[...i].sort()}}async function ee(p,n={}){let e=a.resolve(p),l=n.workspaceName??a.basename(e),{registerWorkspaceStrict:d}=await import('./workspace-XTIGVLGH.js');return await d(e,l),U(e,{silent:n.silent})}export{U as a,ee as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-COICGD62.js';import {b}from'./chunk-QYXX6G5O.js';import {q as q$1,f,g}from'./chunk-BVWDG66W.js';import {d}from'./chunk-WPZUKU2B.js';import {h,g as g$1}from'./chunk-FE5R6EUV.js';import {q,p}from'./chunk-ODK4LCEL.js';import E from'path';import A from'fs-extra';var re=q.agentContext,se=p.agentContext;function ne(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="gemini"||t==="qwen"||t==="kimi"||t==="grok"||t==="copilot"||t==="windsurf"||t==="amazon-q"||t==="orca"?t:"generic"}function G(e){return `npx --yes --package workspai workspai ${e}`.trim()}function x(e){return `npx workspai ${e}`.trim()}async function C(e,t,i){let s=E.join(e,t);if(!await A.pathExists(s))return null;try{let n=await A.readJson(s);return typeof n!="object"||n===null||!("schemaVersion"in n)||n.schemaVersion!==i?null:n}catch{return null}}function m(e){return {id:e.id,scope:e.scope,display:x(e.args),execute:G(e.args),description:e.description,...e.project?{project:e.project}:{},freshness:f({id:`command.${e.id}`,label:`${e.id} command`,scope:"command",value:{display:x(e.args),execute:G(e.args)},...e.project?{project:e.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e.generatedAt,now:e.now,sourceArtifact:p.model,sourcePath:`safeCommands.${e.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function L(e,t){return `workspace run ${t} --scope project:${e.name}`}function ae(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function ie(e,t,i){let s={generatedAt:e.generatedAt,now:i},n=[m({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),m({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),m({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),m({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),m({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),m({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),m({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),m({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=t?[t]:e.projects;for(let a of c)a.commands.fleetStages.includes("test")&&n.push(m({id:`project.${a.name}.test`,scope:"project",project:a.name,args:L(a,"test"),description:`Run tests for ${a.name} through workspace orchestration.`,...s})),a.commands.fleetStages.includes("build")&&n.push(m({id:`project.${a.name}.build`,scope:"project",project:a.name,args:L(a,"build"),description:`Build ${a.name} through workspace orchestration.`,...s}));return n}function ce(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function pe(e,t){if(!t?.startsWith("project:"))return;let i=ae(t);if(i)return e.projects.find(s=>oe(s).includes(i))}function de(e,t,i){let s=[...e.validation?.issues??[]];t?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let n=s.filter(a=>a.severity==="error").length,c=s.filter(a=>a.severity==="warning").length;return {status:n>0?"failed":c>0?"warning":"passed",errors:n,warnings:c,issues:s}}async function me(e,t){let i=[],s=[];for(let[n,c]of Object.entries(e.evidence))c&&await g$1(t,c.path)!==null?i.push(`${n}: ${c.path}`):s.push(n);return {available:i.sort(),missing:s.sort()}}function le(e){let t=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${i}, and ${s}.`}function ge(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),((e.summary.extendedProjects??0)>0||e.summary.observedProjects>0)&&t.push("Some projects use extended or observed support tiers; command coverage may be partial."),t}async function We(e){let t=e.model??await q$1({workspacePath:e.workspacePath,includeEvidence:e.includeEvidence===true,observableScanDepth:e.observableScanDepth,now:e.now}),i=ne(e.agent),s=pe(t,e.scope),n=de(t,e.scope,s);if(e.strict===true&&n.status!=="passed"){let r=n.issues.map(g=>`${g.severity}:${g.code}:${g.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${r}`)}let c=e.now??new Date,a=t.facts??[],K=new Set((s?[s]:t.projects).map(r=>r.name)),R=a.filter(r=>r.project?K.has(r.project):true),H=(s?[s]:t.projects).map(r=>{let g=R.filter(p=>p.project===r.name);return {name:r.name,path:r.path,kind:r.kind,category:r.category,runtime:r.runtime,framework:r.frameworkDisplayName,...r.generator?{generator:r.generator}:{},createCapability:r.createCapability,supportTier:r.supportTier,...r.governance?{governance:r.governance}:{},safeCommands:ce(r),importantFiles:r.importantFiles,facts:g}}),S=await me(t,e.workspacePath),F=E.join(e.workspacePath,p.knowledgeGraph),u=await A.pathExists(F)?await A.readJson(F).catch(()=>null):null,N=false;if(u?.schemaVersion===q.knowledgeGraph)try{b(u,t),N=true;}catch{}let $=le(t),M=ie(t,s,c),b$2=await C(e.workspacePath,p.impact,q.impact),l=await C(e.workspacePath,p.doctor,q.doctor),v=await C(e.workspacePath,p.analyze,q.analyze),k=await C(e.workspacePath,p.readiness,q.readiness),h=await C(e.workspacePath,p.verify,q.verify),w=await C(e.workspacePath,p.explain,q.explain),f$1=await C(e.workspacePath,p.diff,q.diff),B=b$2?.summary?{changed:b$2.summary.changed,risk:b$2.summary.risk,affectedProjects:b$2.summary.affectedProjects,blastRadius:b$2.summary.blastRadius,recommendedCommands:b$2.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let r=Array.isArray(l.projects)?l.projects:[],g=[];for(let p of r.slice(0,6)){let te=Array.isArray(p.probes)?p.probes:[];for(let y of te.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&g.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return g.slice(0,8)})()}:void 0,J=v?.summary?{score:v.summary.score,verdict:v.summary.verdict,findingCounts:v.summary.findings,topFindings:(Array.isArray(v.findings)?v.findings:[]).filter(p=>p?.severity==="fail"||p?.severity==="warn").slice(0,8).map(p=>({severity:p.severity,title:p.title,target:p.target,remediation:p.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(r=>({gate:r.gate,status:r.status,summary:r.summary})):void 0}:void 0,Q=h?.summary?{verdict:h.summary.verdict,exitCode:h.summary.exitCode,stepsFailed:h.summary.stepsFailed,stepsMissing:h.summary.stepsMissing,blockingReasons:h.blockingReasons,missingEvidence:h.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(r=>({id:r.id,title:r.title,body:r.body})):void 0}:void 0,Z=f$1?.summary?{changed:f$1.summary.changed,addedProjects:f$1.summary.addedProjects,removedProjects:f$1.summary.removedProjects,changedProjects:f$1.summary.changedProjects,workspaceChanges:f$1.summary.workspaceChanges,validationChanges:f$1.summary.validationChanges,gitChangedFiles:f$1.summary.gitChangedFiles}:void 0,ee=M.map(r=>f({id:`context.command.${r.id}`,label:`${r.id} safe command`,scope:"command",value:{display:r.display,execute:r.execute,scope:r.scope},...r.project?{project:r.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:c,sourceArtifact:p.agentContext,sourcePath:`safeCommands.${r.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),I=[...R,...ee],W=g({facts:I,generatedAt:c.toISOString(),now:c}),j=b$1();return {schemaVersion:re,generatedAt:c.toISOString(),agent:i,workspaceSummary:$,modelRef:p.model,knowledgeGraph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,available:N,...typeof u?.quality?.entityCount=="number"?{entityCount:u.quality.entityCount}:{},...typeof u?.quality?.relationCount=="number"?{relationCount:u.quality.relationCount}:{},...typeof u?.quality?.proofCount=="number"?{proofCount:u.quality.proofCount}:{},queryCommands:[x("workspace graph search <query> --limit 12 --json"),x("workspace graph entities [kind] --json"),x("workspace graph evidence <entity-or-relation> --json"),x("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:j.schemaVersion,contractPath:j.contractPath,currentStep:"context",canonicalReadOrder:[...j.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:`workspace:${t.workspace.name}`,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:M,facts:I,factFreshness:W,evidence:S,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:n,agentInstructions:[`Read \`${p.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${p.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ge(t),...W.verifyBeforeUseFacts>0?[`${W.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[$,`Evidence available: ${S.available.length}. Missing evidence groups: ${S.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
|
|
1
|
+
import {b as b$1}from'./chunk-COICGD62.js';import {b}from'./chunk-5Y4YRYZI.js';import {q as q$1,f,g}from'./chunk-TGDXD4CD.js';import {d}from'./chunk-G6ADWA2B.js';import {h,g as g$1}from'./chunk-FE5R6EUV.js';import {q,p}from'./chunk-ODK4LCEL.js';import E from'path';import A from'fs-extra';var re=q.agentContext,se=p.agentContext;function ne(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let t=e.trim().toLowerCase();return t==="codex"||t==="claude"||t==="cursor"||t==="gemini"||t==="qwen"||t==="kimi"||t==="grok"||t==="copilot"||t==="windsurf"||t==="amazon-q"||t==="orca"?t:"generic"}function G(e){return `npx --yes --package workspai workspai ${e}`.trim()}function x(e){return `npx workspai ${e}`.trim()}async function C(e,t,i){let s=E.join(e,t);if(!await A.pathExists(s))return null;try{let n=await A.readJson(s);return typeof n!="object"||n===null||!("schemaVersion"in n)||n.schemaVersion!==i?null:n}catch{return null}}function m(e){return {id:e.id,scope:e.scope,display:x(e.args),execute:G(e.args),description:e.description,...e.project?{project:e.project}:{},freshness:f({id:`command.${e.id}`,label:`${e.id} command`,scope:"command",value:{display:x(e.args),execute:G(e.args)},...e.project?{project:e.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e.generatedAt,now:e.now,sourceArtifact:p.model,sourcePath:`safeCommands.${e.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function L(e,t){return `workspace run ${t} --scope project:${e.name}`}function ae(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim().toLowerCase())}function ie(e,t,i){let s={generatedAt:e.generatedAt,now:i},n=[m({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),m({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),m({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),m({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),m({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),m({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),m({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),m({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=t?[t]:e.projects;for(let a of c)a.commands.fleetStages.includes("test")&&n.push(m({id:`project.${a.name}.test`,scope:"project",project:a.name,args:L(a,"test"),description:`Run tests for ${a.name} through workspace orchestration.`,...s})),a.commands.fleetStages.includes("build")&&n.push(m({id:`project.${a.name}.build`,scope:"project",project:a.name,args:L(a,"build"),description:`Build ${a.name} through workspace orchestration.`,...s}));return n}function ce(e){return e.commands.fleetStages.filter(t=>t==="test"||t==="build").map(t=>`workspace run ${t}`)}function pe(e,t){if(!t?.startsWith("project:"))return;let i=ae(t);if(i)return e.projects.find(s=>oe(s).includes(i))}function de(e,t,i){let s=[...e.validation?.issues??[]];t?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${t}`,target:t});let n=s.filter(a=>a.severity==="error").length,c=s.filter(a=>a.severity==="warning").length;return {status:n>0?"failed":c>0?"warning":"passed",errors:n,warnings:c,issues:s}}async function me(e,t){let i=[],s=[];for(let[n,c]of Object.entries(e.evidence))c&&await g$1(t,c.path)!==null?i.push(`${n}: ${c.path}`):s.push(n);return {available:i.sort(),missing:s.sort()}}function le(e){let t=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${t} project${t===1?"":"s"}, ${i}, and ${s}.`}function ge(e){let t=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||t.push("Workspace contract is missing; dependency and API edges may be incomplete."),((e.summary.extendedProjects??0)>0||e.summary.observedProjects>0)&&t.push("Some projects use extended or observed support tiers; command coverage may be partial."),t}async function We(e){let t=e.model??await q$1({workspacePath:e.workspacePath,includeEvidence:e.includeEvidence===true,observableScanDepth:e.observableScanDepth,now:e.now}),i=ne(e.agent),s=pe(t,e.scope),n=de(t,e.scope,s);if(e.strict===true&&n.status!=="passed"){let r=n.issues.map(g=>`${g.severity}:${g.code}:${g.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${r}`)}let c=e.now??new Date,a=t.facts??[],K=new Set((s?[s]:t.projects).map(r=>r.name)),R=a.filter(r=>r.project?K.has(r.project):true),H=(s?[s]:t.projects).map(r=>{let g=R.filter(p=>p.project===r.name);return {name:r.name,path:r.path,kind:r.kind,category:r.category,runtime:r.runtime,framework:r.frameworkDisplayName,...r.generator?{generator:r.generator}:{},createCapability:r.createCapability,supportTier:r.supportTier,...r.governance?{governance:r.governance}:{},safeCommands:ce(r),importantFiles:r.importantFiles,facts:g}}),S=await me(t,e.workspacePath),F=E.join(e.workspacePath,p.knowledgeGraph),u=await A.pathExists(F)?await A.readJson(F).catch(()=>null):null,N=false;if(u?.schemaVersion===q.knowledgeGraph)try{b(u,t),N=true;}catch{}let $=le(t),M=ie(t,s,c),b$2=await C(e.workspacePath,p.impact,q.impact),l=await C(e.workspacePath,p.doctor,q.doctor),v=await C(e.workspacePath,p.analyze,q.analyze),k=await C(e.workspacePath,p.readiness,q.readiness),h=await C(e.workspacePath,p.verify,q.verify),w=await C(e.workspacePath,p.explain,q.explain),f$1=await C(e.workspacePath,p.diff,q.diff),B=b$2?.summary?{changed:b$2.summary.changed,risk:b$2.summary.risk,affectedProjects:b$2.summary.affectedProjects,blastRadius:b$2.summary.blastRadius,recommendedCommands:b$2.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let r=Array.isArray(l.projects)?l.projects:[],g=[];for(let p of r.slice(0,6)){let te=Array.isArray(p.probes)?p.probes:[];for(let y of te.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&g.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return g.slice(0,8)})()}:void 0,J=v?.summary?{score:v.summary.score,verdict:v.summary.verdict,findingCounts:v.summary.findings,topFindings:(Array.isArray(v.findings)?v.findings:[]).filter(p=>p?.severity==="fail"||p?.severity==="warn").slice(0,8).map(p=>({severity:p.severity,title:p.title,target:p.target,remediation:p.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(r=>({gate:r.gate,status:r.status,summary:r.summary})):void 0}:void 0,Q=h?.summary?{verdict:h.summary.verdict,exitCode:h.summary.exitCode,stepsFailed:h.summary.stepsFailed,stepsMissing:h.summary.stepsMissing,blockingReasons:h.blockingReasons,missingEvidence:h.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(r=>({id:r.id,title:r.title,body:r.body})):void 0}:void 0,Z=f$1?.summary?{changed:f$1.summary.changed,addedProjects:f$1.summary.addedProjects,removedProjects:f$1.summary.removedProjects,changedProjects:f$1.summary.changedProjects,workspaceChanges:f$1.summary.workspaceChanges,validationChanges:f$1.summary.validationChanges,gitChangedFiles:f$1.summary.gitChangedFiles}:void 0,ee=M.map(r=>f({id:`context.command.${r.id}`,label:`${r.id} safe command`,scope:"command",value:{display:r.display,execute:r.execute,scope:r.scope},...r.project?{project:r.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:t.generatedAt,now:c,sourceArtifact:p.agentContext,sourcePath:`safeCommands.${r.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),I=[...R,...ee],W=g({facts:I,generatedAt:c.toISOString(),now:c}),j=b$1();return {schemaVersion:re,generatedAt:c.toISOString(),agent:i,workspaceSummary:$,modelRef:p.model,knowledgeGraph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,available:N,...typeof u?.quality?.entityCount=="number"?{entityCount:u.quality.entityCount}:{},...typeof u?.quality?.relationCount=="number"?{relationCount:u.quality.relationCount}:{},...typeof u?.quality?.proofCount=="number"?{proofCount:u.quality.proofCount}:{},queryCommands:[x("workspace graph search <query> --limit 12 --json"),x("workspace graph entities [kind] --json"),x("workspace graph evidence <entity-or-relation> --json"),x("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:j.schemaVersion,contractPath:j.contractPath,currentStep:"context",canonicalReadOrder:[...j.consumers.agents.canonicalReadOrder]},workspace:{name:t.workspace.name,root:`workspace:${t.workspace.name}`,type:t.identity.workspaceType,...t.workspace.profile?{profile:t.workspace.profile}:{}},scope:{requested:e.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:M,facts:I,factFreshness:W,evidence:S,policies:{mode:t.policies.mode,source:t.policies.source},contracts:{exists:t.contracts.exists,path:t.contracts.workspaceContractPath},validation:n,agentInstructions:[`Read \`${p.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${p.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ge(t),...W.verifyBeforeUseFacts>0?[`${W.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[$,`Evidence available: ${S.available.length}. Missing evidence groups: ${S.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
|
|
2
2
|
`),impactSummary:B,doctorSummary:U,analyzeSummary:J,readinessSummary:X,verifySummary:Q,explainSummary:Y,diffSummary:Z}}async function je(e,t){return h(t,se,d(e))}export{re as a,se as b,We as c,je as d};
|