workspai 0.73.0 → 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-3GO7BJ5J.js → chunk-4JJDDL3X.js} +1 -1
- package/dist/chunk-5EVBOUYW.js +3 -0
- package/dist/chunk-5Y4YRYZI.js +12 -0
- package/dist/{chunk-J44PN2FX.js → chunk-773WUMFU.js} +15 -15
- package/dist/{chunk-FRH7AIGY.js → chunk-BTJPTJLT.js} +2 -2
- package/dist/{chunk-OIGI7MP6.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-R5OJD5K2.js → chunk-DTLLIA2C.js} +1 -1
- package/dist/{chunk-LDJAUIAG.js → chunk-FYR4FD7K.js} +1 -1
- package/dist/chunk-G6ADWA2B.js +2 -0
- package/dist/chunk-H333GKL4.js +3 -0
- package/dist/{chunk-EDDGQ6LM.js → chunk-H5DRKXXC.js} +1 -1
- package/dist/{chunk-DNKELRK6.js → chunk-IQFXLJIM.js} +1 -1
- package/dist/{chunk-UCNIXOTL.js → chunk-IUOMBLRR.js} +1 -1
- package/dist/chunk-K3FXRBER.js +4 -0
- package/dist/{chunk-TIZCESKY.js → chunk-KCIET26G.js} +1 -1
- package/dist/chunk-LEEOZRWR.js +7 -0
- package/dist/{chunk-T5NBSCVX.js → chunk-NCZJUPG5.js} +49 -49
- package/dist/{chunk-TSYDTKXO.js → chunk-RPM67N7A.js} +1 -1
- package/dist/{chunk-NSMRQOWP.js → chunk-SAZXL36B.js} +1 -1
- package/dist/chunk-SVGUAVMG.js +1 -0
- package/dist/chunk-TBOIXIQA.js +1 -0
- package/dist/chunk-TGDXD4CD.js +1 -0
- package/dist/{chunk-IPZT6WKM.js → chunk-TVSMNF5G.js} +1 -1
- package/dist/{chunk-D3N2WFDV.js → chunk-UHT2SW7O.js} +1 -1
- package/dist/chunk-VLKX5U4H.js +13 -0
- package/dist/chunk-XF65LQ6M.js +1 -0
- package/dist/chunk-ZKYH44ER.js +1 -0
- package/dist/{chunk-TZK2R6RD.js → chunk-ZNKZ2KXR.js} +1 -1
- package/dist/chunk-ZS7JHATN.js +1 -0
- package/dist/{create-XYKXS3JB.js → create-EKA2QG5R.js} +1 -1
- package/dist/doctor-BXSNADVR.js +1 -0
- package/dist/{goal-lifecycle-BIX2JVNO.js → goal-lifecycle-XXWNMIAD.js} +1 -1
- package/dist/{goal-pack-SUWH6K7U.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-Y3NEHZED.js → project-agent-entry-ZNUHGCVC.js} +1 -1
- package/dist/{project-intelligence-lens-6Q6XSUDJ.js → project-intelligence-lens-W72OUEDW.js} +1 -1
- package/dist/{proof-carrying-change-456TYEDW.js → proof-carrying-change-WLUPMUO7.js} +1 -1
- package/dist/verified-goal-6O2JZOOR.js +1 -0
- package/dist/{workspace-ROUEA3RT.js → workspace-XTIGVLGH.js} +1 -1
- package/dist/{workspace-agent-sync-6UYG33EQ.js → workspace-agent-sync-TN6QDNBR.js} +1 -1
- package/dist/{workspace-context-H7ZXR6VI.js → workspace-context-Y3TNY2XZ.js} +1 -1
- package/dist/{workspace-contract-2V2BI6A3.js → workspace-contract-GRZY7WRD.js} +1 -1
- package/dist/{workspace-explain-IBMTRUSF.js → workspace-explain-KUYHJFLY.js} +1 -1
- package/dist/{workspace-foundation-H5B3TTZD.js → workspace-foundation-ZBUJTR56.js} +1 -1
- package/dist/{workspace-graph-stream-YDEET5LK.js → workspace-graph-stream-KC2XUAE4.js} +1 -1
- package/dist/workspace-graph-token-efficiency-YHXFGH3Z.js +1 -0
- package/dist/{workspace-intelligence-DXKQXTTM.js → workspace-intelligence-26YT6KMN.js} +1 -1
- package/dist/{workspace-intelligence-benchmark-L46EGZZM.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-SCB44IXU.js → workspace-intelligence-runner-HVYKHCTX.js} +1 -1
- package/dist/{workspace-knowledge-graph-BNEVFEOW.js → workspace-knowledge-graph-RL3I2FHY.js} +1 -1
- package/dist/{workspace-knowledge-graph-query-GOC365ZR.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-JLZTTEVG.js → workspace-mcp-serve-2FGRXJG4.js} +1 -1
- package/dist/{workspace-model-XSNLDUI2.js → workspace-model-2ODVOWDQ.js} +1 -1
- package/dist/{workspace-onboarding-IRBVZTT4.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-CBZDSG6I.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-QTRY7WW3.js → workspace-verify-NFJ7RKKT.js} +1 -1
- package/dist/{workspace-watch-PDQKYBYQ.js → workspace-watch-3DBBB6IP.js} +1 -1
- package/docs/ci-workflows.md +1 -1
- package/package.json +1 -1
- package/dist/analyze-WC2TY5AT.js +0 -1
- package/dist/autopilot-release-LJDRECFW.js +0 -1
- package/dist/chunk-2BCECNIW.js +0 -1
- package/dist/chunk-2LIVMG5C.js +0 -2
- package/dist/chunk-3SNP6M4M.js +0 -2
- package/dist/chunk-4HQU2GQM.js +0 -1
- package/dist/chunk-4JAURS76.js +0 -13
- package/dist/chunk-7O7P4MRD.js +0 -1
- package/dist/chunk-AQNU5RXV.js +0 -2
- package/dist/chunk-CQBM6BBP.js +0 -2
- package/dist/chunk-CY4QZ3PE.js +0 -3
- package/dist/chunk-F6CTGVJA.js +0 -9
- package/dist/chunk-K3O3HENC.js +0 -5
- package/dist/chunk-LGC4CRUF.js +0 -3
- package/dist/chunk-NNQE4DS2.js +0 -2
- package/dist/chunk-NSH7TTSV.js +0 -1
- package/dist/chunk-SO4CGS35.js +0 -4
- package/dist/chunk-UNXG3ZFV.js +0 -1
- package/dist/chunk-VBMWFT7Q.js +0 -1
- package/dist/chunk-ZZWGD3X3.js +0 -12
- package/dist/doctor-LQ7FT6AZ.js +0 -1
- package/dist/pipeline-NSPPWD7U.js +0 -5
- package/dist/verified-goal-GRH5UOJR.js +0 -1
- package/dist/workspace-graph-token-efficiency-XM3LYFUC.js +0 -1
- package/dist/workspace-knowledge-graph-snapshot-2NMV7LEJ.js +0 -1
- package/dist/workspace-marker-XGAWZZDX.js +0 -1
- package/dist/workspace-repair-engine-TDUNQSFJ.js +0 -3
- package/dist/workspace-run-I2W5PIPK.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$1,b as b$2}from'./chunk-X7FYEKLI.js';import {c,d as d$1}from'./chunk-N4B2M44I.js';import {f as f$1,e}from'./chunk-NSH7TTSV.js';import {a,b}from'./chunk-MGL6DBOR.js';import {j as j$1,i}from'./chunk-LGC4CRUF.js';import {a as a$2,h}from'./chunk-FE5R6EUV.js';import {b as b$1}from'./chunk-K33JJVQZ.js';import {q as q$1,p as p$1}from'./chunk-ODK4LCEL.js';import {t}from'./chunk-VQZ5PI5J.js';import p from'chalk';import d from'fs';import f from'path';var K=p$1.readiness;function H(n){return n.vulnerableDependencies>0?`${n.vulnerableDependencies} known dependency vulnerability finding(s) reported`:`${n.blockingFindings} blocking dependency/security finding(s) reported`}var U=q$1.readiness;function q(n){let e=j(n,"workspace.contract.json");if(!d.existsSync(e))return [];try{let t=JSON.parse(d.readFileSync(e,"utf-8"));return (Array.isArray(t.projects)?t.projects:[]).map(i=>{let c=v(i),o=typeof c.externalPath=="string"?c.externalPath.trim():"",s=typeof c.relativePath=="string"?c.relativePath.trim():"",r=o||s;return r?f.resolve(n,r):""}).filter(Boolean)}catch{return []}}function B(n,e){let t=f.resolve(n);if(!b(t))return t;let a=j(e,"workspace.contract.json");if(d.existsSync(a))try{let o=JSON.parse(d.readFileSync(a,"utf-8")),s=Array.isArray(o.projects)?o.projects:[];for(let r of s){let y=v(r),m=typeof y.externalPath=="string"?y.externalPath.trim():"";if(m)return f.resolve(e,m);let g=typeof y.relativePath=="string"?y.relativePath.trim():"";if(g)return f.join(e,g)}}catch{}let i=M(e),c=Array.isArray(i.payload?.projects)?i.payload.projects:[];for(let o of c){let s=v(o),r=typeof s.path=="string"?s.path.trim():"";if(r)return f.resolve(r)}return t}function z(n){let e=j$1(n);return i(e,n)}function _(n,e){if(!d.existsSync(n))return null;let t=d.readdirSync(n).filter(a=>a.endsWith(".json")&&e.some(i=>i.test(a))).map(a=>f.join(n,a));return t.length===0?null:(t.sort((a,i)=>d.statSync(i).mtimeMs-d.statSync(a).mtimeMs),t[0])}function v(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function J(n){for(let e of n)if(d.existsSync(e))return e;return null}function j(n,...e){let t$1=t(n,...e);return J(t$1)??t$1[0]}function A(n,e){let t=a$2(n,`.workspai/reports/${e}`);return J([t,f.join(n,".rapidkit","reports",e)])??t}async function Q(n){let{readWorkspaceRegistrySummary:e,resolveWorkspaceRegisteredProjects:t}=await import('./workspace-registry-summary-CBZDSG6I.js'),a=await e(n);return a?a.projectCount:(await t(n)).summary.projectCount}function X(n,e,t){let a=j(n,"toolchain.lock");if(!d.existsSync(a))return {gate:"env",status:"fail",summary:"toolchain.lock is missing",details:["Run workspai bootstrap to pin runtime versions and generate a reproducible toolchain."],evidencePath:a};try{let i=JSON.parse(d.readFileSync(a,"utf-8")),c=v(i.runtime),o=["python","node","go","java","dotnet","rust","php"],s=o.filter(l=>{let u=v(c[l]);return typeof u.version=="string"&&u.version.trim().length>0});if(s.length===0)return {gate:"env",status:"fail",summary:"No runtime versions are pinned in toolchain.lock",details:["Pin at least one runtime version via workspai setup <runtime> and re-run bootstrap."],evidencePath:a};let r=[...new Set((Array.isArray(e)?e:[e]).filter(l=>l!=="unknown"))],y=r.filter(l=>o.includes(l)),m=r.filter(l=>!o.includes(l)),g=y.filter(l=>{let u=v(c[l]);return typeof u.version!="string"||u.version.trim().length===0});return g.length>0?{gate:"env",status:"fail",summary:`${t?.hasRegisteredProjects?"Project runtime":"Workspace"}${g.length===1?"":"s"} (${g.join(", ")}) ${g.length===1?"is":"are"} not pinned in toolchain.lock`,details:g.map(u=>`Run workspai setup ${u} and workspai bootstrap to lock ${u} for this workspace.`),evidencePath:a}:m.length>0?{gate:"env",status:"warn",summary:`${t?.hasRegisteredProjects?"Project runtime":"Workspace"}${m.length===1?"":"s"} (${m.join(", ")}) cannot be verified by toolchain.lock`,details:[`Pinned Workspai runtimes (${s.join(", ")}) do not prove the ${m.join(", ")} compiler or runtime toolchain.`,"Declare and verify this runtime or toolchain through the project command contract or organization CI policy."],evidencePath:a}:{gate:"env",status:"pass",summary:`Pinned runtimes: ${s.join(", ")}`,details:[],evidencePath:a}}catch{return {gate:"env",status:"fail",summary:"toolchain.lock is invalid JSON",details:["Regenerate lockfile with workspai bootstrap."],evidencePath:a}}}function M(n){let e=A(n,"doctor-last-run.json");if(!d.existsSync(e))return {payload:null,path:e};try{let t=JSON.parse(d.readFileSync(e,"utf-8"));return c(t,"workspace")?(d$1(t),{payload:t,path:e}):{payload:null,path:e}}catch{return {payload:null,path:e}}}function Y(n){let e=M(n);if(!e.payload)return {gate:{gate:"doctor",status:"fail",summary:"Doctor evidence is missing",details:["Run workspai doctor workspace --json before release readiness checks."],evidencePath:e.path},payload:null};let t=a$1(e.payload);if(t.hasSystemErrors)return {gate:{gate:"doctor",status:"fail",summary:"Doctor reported system errors",details:["Resolve system-level doctor errors before proceeding."],evidencePath:e.path},payload:e.payload};if(t.blockingFindings>0)return {gate:{gate:"doctor",status:"fail",summary:`Doctor reported ${t.blockingFindings} blocking finding(s)`,details:["Resolve the canonical Doctor findings and regenerate fresh Doctor evidence."],evidencePath:e.path},payload:e.payload};let a=[...t.advisoryFindings>0?[`${t.advisoryFindings} advisory finding(s)`]:[],...t.unknownFindings>0?[`${t.unknownFindings} unknown finding(s)`]:[],...t.contradictionCount>0?[`${t.contradictionCount} evidence contradiction(s)`]:[],...t.missingDiagnosisProjects>0?[`${t.missingDiagnosisProjects} project(s) without canonical diagnosis`]:[],...t.staleEvidence?["stale Doctor evidence"]:[],...t.unknownFreshness?["unknown Doctor evidence freshness"]:[],...t.minimumDiagnosisCompleteness<100?[`diagnosis completeness ${t.minimumDiagnosisCompleteness}%`]:[]];return a.length>0?{gate:{gate:"doctor",status:"warn",summary:"Doctor evidence requires attention",details:a,evidencePath:e.path},payload:e.payload}:{gate:{gate:"doctor",status:"pass",summary:"Doctor checks passed without issues",details:[],evidencePath:e.path},payload:e.payload}}function Z(n){let e=A(n,"analyze-last-run.json");if(!d.existsSync(e))return {gate:"analyze",status:"fail",summary:"Analyze evidence is missing",details:["Run workspai analyze --json before release readiness checks."],evidencePath:e};try{let t=JSON.parse(d.readFileSync(e,"utf-8"));b$1(p$1.analyze,t,e);let a=v(t.summary),i=String(a.verdict??"").toLowerCase(),c=Number(a.score??0),o=v(a.findings),s=Number(o.fail??0);return i==="blocked"||s>0?{gate:"analyze",status:"fail",summary:`Analyze verdict is blocked (score ${c}/100)`,details:["Resolve analyze findings and regenerate analyze-last-run.json."],evidencePath:e}:i==="needs-attention"?{gate:"analyze",status:"warn",summary:`Analyze needs attention (score ${c}/100)`,details:["Review analyze warnings before release."],evidencePath:e}:{gate:"analyze",status:"pass",summary:`Analyze passed (score ${c}/100)`,details:[],evidencePath:e}}catch{return {gate:"analyze",status:"fail",summary:"Analyze evidence is invalid or violates its contract",details:["Re-run workspai analyze --json to regenerate evidence."],evidencePath:e}}}function ee(n){try{let e=JSON.parse(d.readFileSync(n,"utf-8")),t=String(e.status??"").toLowerCase(),a=v(e.summary),i=Number(a.failedChecks??0);return t==="fail"||i>0?{gate:"verify",status:"fail",summary:"Verify-pack contract reports failed checks",details:["Fix failed verify checks and regenerate verify-pack contract evidence."],evidencePath:n}:t==="pass"?{gate:"verify",status:"pass",summary:"Verify-pack contract passed",details:[],evidencePath:n}:{gate:"verify",status:"warn",summary:"Verify-pack contract status is not explicit",details:["Ensure contract status is pass/fail and keep schema aligned with v1 contract."],evidencePath:n}}catch{return {gate:"verify",status:"fail",summary:"Verify-pack contract is invalid JSON",details:["Regenerate verify-pack contract artifact."],evidencePath:n}}}async function te(n,e){if(e.skipVerify)return {gate:"verify",status:"pass",summary:"Verify gate skipped (--skip-verify)",details:["Verification was explicitly skipped for this readiness run."]};let t=[a$2(n,".workspai/reports"),f.join(n,".rapidkit","reports")],a=t[0],i=t.map(s=>_(s,[/verify-pack-contract/i,/^verify.*\.json$/i])).find(s=>typeof s=="string")??null;if(i)return ee(i);let c=a$2(n,p$1.contractVerify),o=t.map(s=>_(s,[/workspace-contract-verify-last-run/i,/workspace-contract-verify/i])).find(s=>typeof s=="string")??null;if(o)try{let s=JSON.parse(d.readFileSync(o,"utf-8")),r=String(s.status??"").toLowerCase();if(r==="passed"||r==="pass")return {gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI cache)",details:[],evidencePath:o};if(r==="failed"||r==="fail")return {gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI cache)",details:(Array.isArray(s.violations)?s.violations:[]).slice(0,5),evidencePath:o}}catch{}try{let{verifyWorkspaceContract:s}=await import('./workspace-contract-2V2BI6A3.js'),r=await s({workspacePath:n}),y={schemaVersion:"v1",source:"cli",generatedAt:new Date().toISOString(),status:r.status,contractPath:r.contractPath,projectCount:r.projectCount,checks:r.checks,violations:r.violations};return await h(n,p$1.contractVerify,y),r.status==="failed"?{gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI)",details:r.violations.slice(0,5),evidencePath:c}:{gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI)",details:[],evidencePath:c}}catch(s){return {gate:"verify",status:"fail",summary:"No verify evidence and workspace contract verification unavailable",details:["Run workspai workspace contract verify --json or export verify-pack contract from CI.",s instanceof Error?s.message:String(s)],evidencePath:f.join(a,"*verify*.json")}}}function ne(n,e){let t=A(e,"doctor-last-run.json");if(!n)return {gate:"dependency",status:"warn",summary:"Dependency risk check skipped (doctor evidence missing)",details:["Run workspai doctor workspace --json to include dependency findings."],evidencePath:t};let a=b$2(n);return a.blockingFindings>0||a.vulnerableDependencies>0?{gate:"dependency",status:"fail",summary:H(a),details:["Resolve the typed dependency/security findings and regenerate focused audit evidence."],evidencePath:t}:a.auditFailed>0?{gate:"dependency",status:"fail",summary:`${a.auditFailed} dependency audit(s) failed`,details:["Repair the audit runner or dependency environment; failed audits are not clean."],evidencePath:t}:a.missingDependencies>0||a.auditUnavailable>0||a.unknownFindings>0||a.advisoryFindings>0?{gate:"dependency",status:"warn",summary:"Dependency evidence is incomplete or requires attention",details:[...a.missingDependencies>0?[`${a.missingDependencies} project(s) have no materialized dependency tree.`]:[],...a.auditUnavailable>0?[`${a.auditUnavailable} audit provider(s) are unavailable or unsupported.`]:[],...a.unknownFindings>0?[`${a.unknownFindings} dependency/security finding(s) remain unknown.`]:[],...a.advisoryFindings>0?[`${a.advisoryFindings} dependency/security advisory finding(s) remain.`]:[]],evidencePath:t}:{gate:"dependency",status:"pass",summary:"No dependency vulnerabilities reported",details:[],evidencePath:t}}function ae(n){return n.some(e=>e.status==="fail")?"fail":n.some(e=>e.status==="warn")?"warn":"pass"}async function se(n,e){return h(n,K,e)}async function re(n={}){let e$1=f.resolve(n.startPath??process.cwd()),t=a(e$1)??e$1,a$1=await Q(t)>0,i=a$1&&b(e$1)?t:B(e$1,t),c=i===t?"unknown":z(i),o=a$1?c:"unknown";if(a$1&&i===t){let{resolveWorkspaceRegisteredProjects:h}=await import('./workspace-registry-summary-CBZDSG6I.js'),T=await h(t),E=q(t);o=(E.length>0?E:T.summary.projects.map(w=>f.resolve(t,w.relativePath))).map(w=>z(w));}let s=X(t,o,{hasRegisteredProjects:a$1}),r=Y(t),y=Z(t),m=await te(t,{skipVerify:n.skipVerify}),g=ne(r.payload,t),l=[s,r.gate,y,m,g],u=ae(l),k={schemaVersion:U,generatedAt:new Date().toISOString(),workspacePath:t,projectPath:i,action:n.action,overallStatus:u,blocking:u==="fail",blockingReasons:l.filter(h=>h.status==="fail").map(h=>`${h.gate}: ${h.summary}`),gates:l};if(n.writeReport!==false){let h=f$1(k,{commandId:"workspaceReadiness",exitCode:u==="fail"?2:u==="warn"?1:0,generatedAt:k.generatedAt,blockers:k.blockingReasons,runId:e()});k.evidencePath=await se(t,h);}return k}function ie(n){return n==="pass"?p.green("PASS"):n==="warn"?p.yellow("WARN"):p.red("FAIL")}function oe(n){return n==="pass"?p.green("PASS"):n==="warn"?p.yellow("WARN"):p.red("FAIL")}async function Se(n){let e=await re({startPath:n.workspace,writeReport:true,skipVerify:n.skipVerify===true});if(n.json)console.log(JSON.stringify(e,null,2));else {console.log(p.bold.cyan(`
|
|
1
|
+
import {f as f$1,e}from'./chunk-XF65LQ6M.js';import {a as a$1,b as b$2}from'./chunk-X7FYEKLI.js';import {c,d as d$1}from'./chunk-N4B2M44I.js';import {a,b}from'./chunk-MGL6DBOR.js';import {j as j$1,i}from'./chunk-5EVBOUYW.js';import {a as a$2,h}from'./chunk-FE5R6EUV.js';import {b as b$1}from'./chunk-K33JJVQZ.js';import {q as q$1,p as p$1}from'./chunk-ODK4LCEL.js';import {t}from'./chunk-VQZ5PI5J.js';import p from'chalk';import d from'fs';import f from'path';var K=p$1.readiness;function H(n){return n.vulnerableDependencies>0?`${n.vulnerableDependencies} known dependency vulnerability finding(s) reported`:`${n.blockingFindings} blocking dependency/security finding(s) reported`}var U=q$1.readiness;function q(n){let e=j(n,"workspace.contract.json");if(!d.existsSync(e))return [];try{let t=JSON.parse(d.readFileSync(e,"utf-8"));return (Array.isArray(t.projects)?t.projects:[]).map(i=>{let c=v(i),o=typeof c.externalPath=="string"?c.externalPath.trim():"",s=typeof c.relativePath=="string"?c.relativePath.trim():"",r=o||s;return r?f.resolve(n,r):""}).filter(Boolean)}catch{return []}}function B(n,e){let t=f.resolve(n);if(!b(t))return t;let a=j(e,"workspace.contract.json");if(d.existsSync(a))try{let o=JSON.parse(d.readFileSync(a,"utf-8")),s=Array.isArray(o.projects)?o.projects:[];for(let r of s){let y=v(r),m=typeof y.externalPath=="string"?y.externalPath.trim():"";if(m)return f.resolve(e,m);let g=typeof y.relativePath=="string"?y.relativePath.trim():"";if(g)return f.join(e,g)}}catch{}let i=M(e),c=Array.isArray(i.payload?.projects)?i.payload.projects:[];for(let o of c){let s=v(o),r=typeof s.path=="string"?s.path.trim():"";if(r)return f.resolve(r)}return t}function z(n){let e=j$1(n);return i(e,n)}function _(n,e){if(!d.existsSync(n))return null;let t=d.readdirSync(n).filter(a=>a.endsWith(".json")&&e.some(i=>i.test(a))).map(a=>f.join(n,a));return t.length===0?null:(t.sort((a,i)=>d.statSync(i).mtimeMs-d.statSync(a).mtimeMs),t[0])}function v(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function J(n){for(let e of n)if(d.existsSync(e))return e;return null}function j(n,...e){let t$1=t(n,...e);return J(t$1)??t$1[0]}function A(n,e){let t=a$2(n,`.workspai/reports/${e}`);return J([t,f.join(n,".rapidkit","reports",e)])??t}async function Q(n){let{readWorkspaceRegistrySummary:e,resolveWorkspaceRegisteredProjects:t}=await import('./workspace-registry-summary-VKTJ7PHV.js'),a=await e(n);return a?a.projectCount:(await t(n)).summary.projectCount}function X(n,e,t){let a=j(n,"toolchain.lock");if(!d.existsSync(a))return {gate:"env",status:"fail",summary:"toolchain.lock is missing",details:["Run workspai bootstrap to pin runtime versions and generate a reproducible toolchain."],evidencePath:a};try{let i=JSON.parse(d.readFileSync(a,"utf-8")),c=v(i.runtime),o=["python","node","go","java","dotnet","rust","php"],s=o.filter(l=>{let u=v(c[l]);return typeof u.version=="string"&&u.version.trim().length>0});if(s.length===0)return {gate:"env",status:"fail",summary:"No runtime versions are pinned in toolchain.lock",details:["Pin at least one runtime version via workspai setup <runtime> and re-run bootstrap."],evidencePath:a};let r=[...new Set((Array.isArray(e)?e:[e]).filter(l=>l!=="unknown"))],y=r.filter(l=>o.includes(l)),m=r.filter(l=>!o.includes(l)),g=y.filter(l=>{let u=v(c[l]);return typeof u.version!="string"||u.version.trim().length===0});return g.length>0?{gate:"env",status:"fail",summary:`${t?.hasRegisteredProjects?"Project runtime":"Workspace"}${g.length===1?"":"s"} (${g.join(", ")}) ${g.length===1?"is":"are"} not pinned in toolchain.lock`,details:g.map(u=>`Run workspai setup ${u} and workspai bootstrap to lock ${u} for this workspace.`),evidencePath:a}:m.length>0?{gate:"env",status:"warn",summary:`${t?.hasRegisteredProjects?"Project runtime":"Workspace"}${m.length===1?"":"s"} (${m.join(", ")}) cannot be verified by toolchain.lock`,details:[`Pinned Workspai runtimes (${s.join(", ")}) do not prove the ${m.join(", ")} compiler or runtime toolchain.`,"Declare and verify this runtime or toolchain through the project command contract or organization CI policy."],evidencePath:a}:{gate:"env",status:"pass",summary:`Pinned runtimes: ${s.join(", ")}`,details:[],evidencePath:a}}catch{return {gate:"env",status:"fail",summary:"toolchain.lock is invalid JSON",details:["Regenerate lockfile with workspai bootstrap."],evidencePath:a}}}function M(n){let e=A(n,"doctor-last-run.json");if(!d.existsSync(e))return {payload:null,path:e};try{let t=JSON.parse(d.readFileSync(e,"utf-8"));return c(t,"workspace")?(d$1(t),{payload:t,path:e}):{payload:null,path:e}}catch{return {payload:null,path:e}}}function Y(n){let e=M(n);if(!e.payload)return {gate:{gate:"doctor",status:"fail",summary:"Doctor evidence is missing",details:["Run workspai doctor workspace --json before release readiness checks."],evidencePath:e.path},payload:null};let t=a$1(e.payload);if(t.hasSystemErrors)return {gate:{gate:"doctor",status:"fail",summary:"Doctor reported system errors",details:["Resolve system-level doctor errors before proceeding."],evidencePath:e.path},payload:e.payload};if(t.blockingFindings>0)return {gate:{gate:"doctor",status:"fail",summary:`Doctor reported ${t.blockingFindings} blocking finding(s)`,details:["Resolve the canonical Doctor findings and regenerate fresh Doctor evidence."],evidencePath:e.path},payload:e.payload};let a=[...t.advisoryFindings>0?[`${t.advisoryFindings} advisory finding(s)`]:[],...t.unknownFindings>0?[`${t.unknownFindings} unknown finding(s)`]:[],...t.contradictionCount>0?[`${t.contradictionCount} evidence contradiction(s)`]:[],...t.missingDiagnosisProjects>0?[`${t.missingDiagnosisProjects} project(s) without canonical diagnosis`]:[],...t.staleEvidence?["stale Doctor evidence"]:[],...t.unknownFreshness?["unknown Doctor evidence freshness"]:[],...t.minimumDiagnosisCompleteness<100?[`diagnosis completeness ${t.minimumDiagnosisCompleteness}%`]:[]];return a.length>0?{gate:{gate:"doctor",status:"warn",summary:"Doctor evidence requires attention",details:a,evidencePath:e.path},payload:e.payload}:{gate:{gate:"doctor",status:"pass",summary:"Doctor checks passed without issues",details:[],evidencePath:e.path},payload:e.payload}}function Z(n){let e=A(n,"analyze-last-run.json");if(!d.existsSync(e))return {gate:"analyze",status:"fail",summary:"Analyze evidence is missing",details:["Run workspai analyze --json before release readiness checks."],evidencePath:e};try{let t=JSON.parse(d.readFileSync(e,"utf-8"));b$1(p$1.analyze,t,e);let a=v(t.summary),i=String(a.verdict??"").toLowerCase(),c=Number(a.score??0),o=v(a.findings),s=Number(o.fail??0);return i==="blocked"||s>0?{gate:"analyze",status:"fail",summary:`Analyze verdict is blocked (score ${c}/100)`,details:["Resolve analyze findings and regenerate analyze-last-run.json."],evidencePath:e}:i==="needs-attention"?{gate:"analyze",status:"warn",summary:`Analyze needs attention (score ${c}/100)`,details:["Review analyze warnings before release."],evidencePath:e}:{gate:"analyze",status:"pass",summary:`Analyze passed (score ${c}/100)`,details:[],evidencePath:e}}catch{return {gate:"analyze",status:"fail",summary:"Analyze evidence is invalid or violates its contract",details:["Re-run workspai analyze --json to regenerate evidence."],evidencePath:e}}}function ee(n){try{let e=JSON.parse(d.readFileSync(n,"utf-8")),t=String(e.status??"").toLowerCase(),a=v(e.summary),i=Number(a.failedChecks??0);return t==="fail"||i>0?{gate:"verify",status:"fail",summary:"Verify-pack contract reports failed checks",details:["Fix failed verify checks and regenerate verify-pack contract evidence."],evidencePath:n}:t==="pass"?{gate:"verify",status:"pass",summary:"Verify-pack contract passed",details:[],evidencePath:n}:{gate:"verify",status:"warn",summary:"Verify-pack contract status is not explicit",details:["Ensure contract status is pass/fail and keep schema aligned with v1 contract."],evidencePath:n}}catch{return {gate:"verify",status:"fail",summary:"Verify-pack contract is invalid JSON",details:["Regenerate verify-pack contract artifact."],evidencePath:n}}}async function te(n,e){if(e.skipVerify)return {gate:"verify",status:"pass",summary:"Verify gate skipped (--skip-verify)",details:["Verification was explicitly skipped for this readiness run."]};let t=[a$2(n,".workspai/reports"),f.join(n,".rapidkit","reports")],a=t[0],i=t.map(s=>_(s,[/verify-pack-contract/i,/^verify.*\.json$/i])).find(s=>typeof s=="string")??null;if(i)return ee(i);let c=a$2(n,p$1.contractVerify),o=t.map(s=>_(s,[/workspace-contract-verify-last-run/i,/workspace-contract-verify/i])).find(s=>typeof s=="string")??null;if(o)try{let s=JSON.parse(d.readFileSync(o,"utf-8")),r=String(s.status??"").toLowerCase();if(r==="passed"||r==="pass")return {gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI cache)",details:[],evidencePath:o};if(r==="failed"||r==="fail")return {gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI cache)",details:(Array.isArray(s.violations)?s.violations:[]).slice(0,5),evidencePath:o}}catch{}try{let{verifyWorkspaceContract:s}=await import('./workspace-contract-GRZY7WRD.js'),r=await s({workspacePath:n}),y={schemaVersion:"v1",source:"cli",generatedAt:new Date().toISOString(),status:r.status,contractPath:r.contractPath,projectCount:r.projectCount,checks:r.checks,violations:r.violations};return await h(n,p$1.contractVerify,y),r.status==="failed"?{gate:"verify",status:"fail",summary:"Workspace contract verification failed (CLI)",details:r.violations.slice(0,5),evidencePath:c}:{gate:"verify",status:"pass",summary:"Workspace contract verification passed (CLI)",details:[],evidencePath:c}}catch(s){return {gate:"verify",status:"fail",summary:"No verify evidence and workspace contract verification unavailable",details:["Run workspai workspace contract verify --json or export verify-pack contract from CI.",s instanceof Error?s.message:String(s)],evidencePath:f.join(a,"*verify*.json")}}}function ne(n,e){let t=A(e,"doctor-last-run.json");if(!n)return {gate:"dependency",status:"warn",summary:"Dependency risk check skipped (doctor evidence missing)",details:["Run workspai doctor workspace --json to include dependency findings."],evidencePath:t};let a=b$2(n);return a.blockingFindings>0||a.vulnerableDependencies>0?{gate:"dependency",status:"fail",summary:H(a),details:["Resolve the typed dependency/security findings and regenerate focused audit evidence."],evidencePath:t}:a.auditFailed>0?{gate:"dependency",status:"fail",summary:`${a.auditFailed} dependency audit(s) failed`,details:["Repair the audit runner or dependency environment; failed audits are not clean."],evidencePath:t}:a.missingDependencies>0||a.auditUnavailable>0||a.unknownFindings>0||a.advisoryFindings>0?{gate:"dependency",status:"warn",summary:"Dependency evidence is incomplete or requires attention",details:[...a.missingDependencies>0?[`${a.missingDependencies} project(s) have no materialized dependency tree.`]:[],...a.auditUnavailable>0?[`${a.auditUnavailable} audit provider(s) are unavailable or unsupported.`]:[],...a.unknownFindings>0?[`${a.unknownFindings} dependency/security finding(s) remain unknown.`]:[],...a.advisoryFindings>0?[`${a.advisoryFindings} dependency/security advisory finding(s) remain.`]:[]],evidencePath:t}:{gate:"dependency",status:"pass",summary:"No dependency vulnerabilities reported",details:[],evidencePath:t}}function ae(n){return n.some(e=>e.status==="fail")?"fail":n.some(e=>e.status==="warn")?"warn":"pass"}async function se(n,e){return h(n,K,e)}async function re(n={}){let e$1=f.resolve(n.startPath??process.cwd()),t=a(e$1)??e$1,a$1=await Q(t)>0,i=a$1&&b(e$1)?t:B(e$1,t),c=i===t?"unknown":z(i),o=a$1?c:"unknown";if(a$1&&i===t){let{resolveWorkspaceRegisteredProjects:h}=await import('./workspace-registry-summary-VKTJ7PHV.js'),T=await h(t),E=q(t);o=(E.length>0?E:T.summary.projects.map(w=>f.resolve(t,w.relativePath))).map(w=>z(w));}let s=X(t,o,{hasRegisteredProjects:a$1}),r=Y(t),y=Z(t),m=await te(t,{skipVerify:n.skipVerify}),g=ne(r.payload,t),l=[s,r.gate,y,m,g],u=ae(l),k={schemaVersion:U,generatedAt:new Date().toISOString(),workspacePath:t,projectPath:i,action:n.action,overallStatus:u,blocking:u==="fail",blockingReasons:l.filter(h=>h.status==="fail").map(h=>`${h.gate}: ${h.summary}`),gates:l};if(n.writeReport!==false){let h=f$1(k,{commandId:"workspaceReadiness",exitCode:u==="fail"?2:u==="warn"?1:0,generatedAt:k.generatedAt,blockers:k.blockingReasons,runId:e()});k.evidencePath=await se(t,h);}return k}function ie(n){return n==="pass"?p.green("PASS"):n==="warn"?p.yellow("WARN"):p.red("FAIL")}function oe(n){return n==="pass"?p.green("PASS"):n==="warn"?p.yellow("WARN"):p.red("FAIL")}async function Se(n){let e=await re({startPath:n.workspace,writeReport:true,skipVerify:n.skipVerify===true});if(n.json)console.log(JSON.stringify(e,null,2));else {console.log(p.bold.cyan(`
|
|
2
2
|
\u{1F6A6} Workspai Release Readiness
|
|
3
3
|
`)),console.log(p.bold(`Workspace: ${p.cyan(f.basename(e.workspacePath))}`)),console.log(p.gray(`Path: ${e.workspacePath}`)),console.log(`Overall: ${oe(e.overallStatus)}`);for(let t of e.gates){console.log(` - ${t.gate}: ${ie(t.status)} ${t.summary}`);for(let a of t.details)console.log(p.gray(` ${a}`));t.evidencePath&&console.log(p.gray(` evidence: ${t.evidencePath}`));}e.evidencePath&&console.log(p.gray(`
|
|
4
4
|
Evidence saved: ${e.evidencePath}`));}n.strict&&e.overallStatus!=="pass"&&process.exit(1);}export{re as a,Se as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-AFIFZTOY.js';import {q,p}from'./chunk-ODK4LCEL.js';import d from'crypto';import s from'path';import {open,unlink,stat}from'fs/promises';import u from'fs-extra';var y="model-usage-event.v1",f=q.evaluationLive,I="workspace-intelligence-evaluation-comparison.v1",S=["provider-reported","tokenizer-counted","estimated","unavailable"];var v=p.evaluationLive,h=p.evaluationLastRun,W="contracts/workspace-intelligence/model-usage-event.v1.json",k="contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",M="contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json",P=3e4,L=100,V=25;function w(){return {modelCalls:0,toolCalls:0,tokenSources:{providerReported:0,tokenizerCounted:0,estimated:0,unavailable:0},tokens:{input:0,output:0,cachedInput:0,reasoning:0,observedTotal:0},latencyMs:0,costs:[],outcome:{status:"unknown",verified:false,blockersResolved:0},efficiency:{tokensPerVerifiedOutcome:null,noProgressDecisions:0,repeatedArtifactReads:0}}}function m(t){return t??0}function A(t){let e=w(),n=new Map,r=new Map;for(let o of t){if(o.kind==="model-call"){e.modelCalls+=1;let a={"provider-reported":"providerReported","tokenizer-counted":"tokenizerCounted",estimated:"estimated",unavailable:"unavailable"}[o.modelCall.source];if(e.tokenSources[a]+=1,e.tokens.input+=m(o.modelCall.inputTokens),e.tokens.output+=m(o.modelCall.outputTokens),e.tokens.cachedInput+=m(o.modelCall.cachedInputTokens),e.tokens.reasoning+=m(o.modelCall.reasoningTokens),e.latencyMs+=o.modelCall.latencyMs??0,o.modelCall.cost){let i=o.modelCall.cost.currency.toUpperCase(),l=r.get(i)??{currency:i,amount:0,providerReported:0,estimated:0};l.amount+=o.modelCall.cost.amount,o.modelCall.cost.source==="provider-reported"?l.providerReported+=o.modelCall.cost.amount:l.estimated+=o.modelCall.cost.amount,r.set(i,l);}continue}if(o.kind==="tool-call"){e.toolCalls+=1,e.latencyMs+=o.toolCall.durationMs??0,!o.toolCall.changedSource&&o.toolCall.result==="passed"&&(e.efficiency.noProgressDecisions+=1),o.toolCall.artifact&&n.set(o.toolCall.artifact,(n.get(o.toolCall.artifact)??0)+1);continue}o.kind==="outcome"&&(e.outcome={status:o.outcome.status,verified:o.outcome.verified,blockersResolved:o.outcome.blockersResolved});}return e.tokens.observedTotal=e.tokens.input+e.tokens.output,e.costs=[...r.values()].map(o=>({...o,amount:Number(o.amount.toFixed(8)),providerReported:Number(o.providerReported.toFixed(8)),estimated:Number(o.estimated.toFixed(8))})).sort((o,a)=>o.currency.localeCompare(a.currency)),e.efficiency.repeatedArtifactReads=[...n.values()].reduce((o,a)=>o+Math.max(0,a-1),0),e.efficiency.tokensPerVerifiedOutcome=e.outcome.verified&&e.outcome.status==="passed"&&e.tokenSources.providerReported+e.tokenSources.tokenizerCounted+e.tokenSources.estimated>0?e.tokens.observedTotal:null,e}function U(t,e=new Date){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Evaluation event must be a JSON object.");let n=t,r={...n,schemaVersion:y,eventId:typeof n.eventId=="string"&&n.eventId.trim()?n.eventId.trim():d.randomUUID(),recordedAt:typeof n.recordedAt=="string"&&n.recordedAt.trim()?n.recordedAt:e.toISOString()};a(r,W,"workspace evaluation event");let o={"model-call":"modelCall","tool-call":"toolCall",outcome:"outcome",milestone:"milestone"}[r.kind],a$1=["modelCall","toolCall","outcome","milestone"].filter(i=>n[i]!==void 0);if(a$1.length!==1||a$1[0]!==o)throw new Error(`Evaluation event kind ${r.kind} requires only ${o}.`);if(r.kind==="model-call"&&r.modelCall.source!=="unavailable"&&r.modelCall.inputTokens===null&&r.modelCall.outputTokens===null)throw new Error("Measured model calls require at least one input or output token count.");return r}function B(t){let e=t.now??new Date,n=s.resolve(t.workspacePath),r={schemaVersion:f,runId:t.runId??d.randomUUID(),sessionId:t.sessionId??d.randomUUID(),status:"live",startedAt:e.toISOString(),updatedAt:e.toISOString(),workspace:{name:t.workspaceName?.trim()||s.basename(n),path:n},configuration:{taskId:t.taskId.trim(),strategy:t.strategy??"workspace-intelligence",...t.provider?{provider:t.provider}:{},...t.model?{model:t.model}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.baselineRunId?{baselineRunId:t.baselineRunId}:{}},methodology:{id:"provider-usage-and-verified-outcome.v1",claimBoundary:"Provider-reported and tokenizer-counted values are measured; estimated values remain explicitly labelled. Verified task success is required before reporting tokens per successful outcome."},events:[],summary:w()};return a(r,k,"workspace evaluation"),r}async function x(t,e){await u.ensureDir(s.dirname(t));let n=`${t}.${process.pid}.${d.randomUUID()}.tmp`;try{await u.writeJson(n,e,{spaces:2}),await u.rename(n,t);}finally{await u.remove(n).catch(()=>{});}}async function b(t,e){let n=s.join(s.resolve(t),`${v}.lock`);await u.ensureDir(s.dirname(n));for(let r=0;r<L;r+=1)try{let o=await open(n,"wx");try{return await o.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await o.close(),await unlink(n).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let i=await stat(n).catch(()=>null);if(i&&Date.now()-i.mtimeMs>P){await unlink(n).catch(()=>{});continue}await new Promise(l=>setTimeout(l,V));}throw new Error("Timed out waiting for the workspace evaluation writer lock.")}async function E(t,e,n=v){let r=s.join(s.resolve(t),n);return a(e,k,n),await x(r,e),r}async function _(t,e=v){let n=s.isAbsolute(e)?e:s.join(s.resolve(t),e),r=await u.readJson(n);return a(r,k,n),r}async function Y(t){return b(t.workspacePath,async()=>{let e=await _(t.workspacePath);if(e.status!=="live")throw new Error(`Evaluation ${e.runId} is ${e.status}; initialize a new run.`);let n=U(t.payload,t.now);if(e.events.some(o=>o.eventId===n.eventId))return e;let r={...e,updatedAt:(t.now??new Date).toISOString(),events:[...e.events,n],summary:A([...e.events,n])};return await E(t.workspacePath,r),r})}async function X(t){return b(t.workspacePath,async()=>{let e=await _(t.workspacePath),n=(t.now??new Date).toISOString(),r={...e,status:t.status??"completed",updatedAt:n,completedAt:n,summary:A(e.events)},o=await E(t.workspacePath,r,h);return await E(t.workspacePath,r),{report:r,outputPath:o}})}function Q(t,e){let n=t.summary.tokens.observedTotal,r=e.summary.tokens.observedTotal,o=n-r,a$1={schemaVersion:I,generatedAt:new Date().toISOString(),taskAligned:t.configuration.taskId===e.configuration.taskId,current:{runId:t.runId,strategy:t.configuration.strategy,tokens:n,verified:t.summary.outcome.verified,status:t.summary.outcome.status},baseline:{runId:e.runId,strategy:e.configuration.strategy,tokens:r,verified:e.summary.outcome.verified,status:e.summary.outcome.status},delta:{tokens:o,reductionPercent:r===0?null:Number((-o/r*100).toFixed(2)),modelCalls:t.summary.modelCalls-e.summary.modelCalls,toolCalls:t.summary.toolCalls-e.summary.toolCalls,latencyMs:Number((t.summary.latencyMs-e.summary.latencyMs).toFixed(2))},comparableOutcome:t.summary.outcome.verified&&e.summary.outcome.verified&&t.summary.outcome.status===e.summary.outcome.status};return a(a$1,M,"workspace evaluation comparison"),a$1}function Z(){if(S.length!==4)throw new Error("Model usage source taxonomy is incomplete.")}export{y as a,f as b,I as c,v as d,h as e,A as f,U as g,B as h,E as i,_ as j,Y as k,X as l,Q as m,Z as n};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{b as buildWorkspaceManifest,f as createProject,a as initializeStandaloneGitRepository,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,c as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-
|
|
1
|
+
export{b as buildWorkspaceManifest,f as createProject,a as initializeStandaloneGitRepository,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,c as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-773WUMFU.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{d as DOCTOR_WORKSPACE_REPORT_PATH,r as applyEnvKeyAddFix,n as applyFileAppendFix,o as applyFileCopyFix,m as applyFileCreateFix,q as applyJsonEditFix,s as applyMakefileTargetFix,l as applyPackageScriptFix,j as assertOperationPathInsideProject,k as assertOperationPathInsideProjectResolved,i as buildRepairOperationIdentity,u as computeDoctorFixAwareExitCode,t as computeDoctorGateExitCode,p as decodeJsonPointerSegment,h as parseInternalRepairCommand,g as parsePackageScriptFix,f as pythonPackageListProvesDependencies,e as resolveDoctorPolicyProfile,v as runDoctor}from'./chunk-NCZJUPG5.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,k as buildGoalLifecycleResult,l as inspectGoalLifecycle,q as linkGoalChangeTransaction,p as linkGoalRepairTransaction,n as prepareGoalVerification,m as transitionGoalLifecycle,o as verifyGoalLifecycle}from'./chunk-
|
|
1
|
+
export{f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,k as buildGoalLifecycleResult,l as inspectGoalLifecycle,q as linkGoalChangeTransaction,p as linkGoalRepairTransaction,n as prepareGoalVerification,m as transitionGoalLifecycle,o as verifyGoalLifecycle}from'./chunk-TBOIXIQA.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {c as c$3}from'./chunk-HAZGSAKP.js';import {c}from'./chunk-2BCECNIW.js';import {j,i,d as d$1,f as f$1,c as c$2,e,h}from'./chunk-VBMWFT7Q.js';export{b as GOAL_AGENT_HANDOFF_SCHEMA_VERSION,f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,g as GOAL_LIFECYCLE_RESULT_SCHEMA_VERSION,d as GOAL_PACK_LAST_RUN_PATH,a as GOAL_PACK_SCHEMA_VERSION,c as GOAL_PLAN_RESULT_SCHEMA_VERSION}from'./chunk-VBMWFT7Q.js';import {f as f$2}from'./chunk-7O7P4MRD.js';import {a as a$1}from'./chunk-D3N2WFDV.js';import {b}from'./chunk-EBQS5T7Q.js';import {b as b$1}from'./chunk-ZZWGD3X3.js';import {f,i as i$1}from'./chunk-FE5R6EUV.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {q,p}from'./chunk-ODK4LCEL.js';import C from'path';import _ from'fs-extra';var ve=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/,ye=/(?:^|\s)(?:\/(?:home|Users|private|var|tmp|mnt|opt|srv|root|workspace|workspaces|data|Volumes|etc|usr|run|dev|proc|sys)\/[^\s]+|[A-Za-z]:[\\/][^\s]+|\\\\[^\\\s]+\\[^\s]+)/,Pe=/(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:github_pat_|gh[pousr]_|glpat-|npm_|xox[baprs]-|sk-(?:proj-)?)[A-Za-z0-9_-]{12,}|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[A-Za-z0-9_-]{20,}|\bBearer\s+[A-Za-z0-9._~+/-]{16,}|[a-z][a-z0-9+.-]*:\/\/[^\s:/]+:[^\s@/]+@|\b(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^\s]{6,})/i,je=[{category:"test-coverage",patterns:[/\b(?:test\s+)?coverage\b/i,/\bcoverage\s+(?:to|above|at least)\b/i]},{category:"dependency-security",patterns:[/\b(?:dependency|dependencies|package|packages)\b.*\b(?:security|vulnerab|audit)\b/i,/\b(?:security|vulnerab|audit)\b.*\b(?:dependency|dependencies|package|packages)\b/i]},{category:"release-readiness",patterns:[/\brelease[ -]readiness\b/i,/\bready (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare\b[^\n]{0,80}\bfor release\b/i]},{category:"defect-repair",patterns:[/\b(?:fix|repair|resolve|debug)\b.*\b(?:bug|error|failure|issue|regression)\b/i]},{category:"performance",patterns:[/\b(?:performance|latency|throughput|cpu|optimi[sz]e|faster|slower)\b/i,/\b(?:memory\s+(?:allocation|consumption|footprint|leak|pressure|usage)|out[ -]of[ -]memory|heap|ram)\b/i]},{category:"refactor",patterns:[/\b(?:refactor|restructure|decouple|extract|simplify|cleanup|clean up)\b/i]},{category:"documentation",patterns:[/\b(?:document|documentation|readme|guide|tutorial|docs)\b/i]},{category:"feature-change",patterns:[/\b(?:add|build|create|enforce|enhance|harden|implement|improve|introduce|support)\b/i]},{category:"system-understanding",patterns:[/\b(?:understand|explain|map|find|where|how|architecture|analy[sz]e|search)\b/i]}];function Ge(e){if(typeof e!="string")throw new Error("Goal intent must be text.");let t=e.trim().replace(/\s+/g," ");if(!t)throw new Error("Goal intent cannot be empty.");if(t.length>2e3)throw new Error("Goal intent exceeds the 2000 character safety limit.");if(ve.test(t))throw new Error("Goal intent contains unsupported control characters.");if(ye.test(t))throw new Error("Goal intent contains a machine-local absolute path. Use a workspace-relative path or project scope.");if(Pe.test(t))throw new Error("Goal intent appears to contain secret material and was not persisted.");return t}function Ce(e){let t=e.match(/\b(?:coverage\D{0,24})?((?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?))\s*(?:%|percent(?:age)?(?:\s+points?)?)/i);if(!t||!/coverage/i.test(e))return null;let r=Number(t[1]);return Number.isFinite(r)&&r>=0&&r<=100?r:null}var re=[{runtime:"cpp",patterns:[/\bc\+\+/i,/\bcpp\b/i]},{runtime:"dotnet",patterns:[/\.net\b/i,/\bdotnet\b/i,/\bc#/i,/\bcsharp\b/i]},{runtime:"node",patterns:[/\bnode(?:\.js)?\b/i,/\btypescript\b/i,/\bjavascript\b/i,/\b(?:js|ts)\b/i]},{runtime:"python",patterns:[/\bpython\b/i,/\bpytest\b/i]},{runtime:"go",patterns:[/\bgolang\b/i,/\bgo(?:\s+(?:test|coverage|tests))\b/i]},{runtime:"java",patterns:[/\bjava\b/i,/\bjunit\b/i,/\bjacoco\b/i]},{runtime:"rust",patterns:[/\brust\b/i,/\bcargo\b/i]},{runtime:"php",patterns:[/\bphp\b/i,/\bphpunit\b/i]},{runtime:"ruby",patterns:[/\bruby\b/i,/\brspec\b/i]},{runtime:"kotlin",patterns:[/\bkotlin\b/i]},{runtime:"scala",patterns:[/\bscala\b/i]},{runtime:"clojure",patterns:[/\bclojure\b/i]},{runtime:"elixir",patterns:[/\belixir\b/i]},{runtime:"deno",patterns:[/\bdeno\b/i]},{runtime:"bun",patterns:[/\bbun\b/i]},{runtime:"c",patterns:[/\bc(?:\s+(?:test|coverage|tests|code))\b/i]}];function Ae(e){return re.filter(t=>t.patterns.some(r=>r.test(e))).map(t=>t.runtime)}function K(e,t={}){let r=Ge(e),n=je.filter(u=>u.patterns.some(j=>j.test(r))).map(u=>u.category),a=n.some(u=>u!=="feature-change")?n.filter(u=>u!=="feature-change"):n,s=a[0]??"feature-change",l=Ce(r),d=Ae(r),p=d.length===0&&t.selectedCoverageRuntime?[t.selectedCoverageRuntime]:d,m=[...new Set((t.availableCoverageRuntimes??[]).filter(u=>re.some(j=>j.runtime===u)))].sort(),b=[];return a.length>1&&a[0]!=="test-coverage"&&b.push(`The intent also contains signals for: ${a.slice(1).join(", ")}.`),s==="test-coverage"&&l===null&&b.push("A numeric test coverage target is required for machine verification."),s==="test-coverage"&&p.length>1&&b.push(`The Goal names multiple coverage runtimes: ${p.join(", ")}. Select one runtime per Goal.`),s==="test-coverage"&&p.length===0&&m.length>1&&b.push(`Coverage scope is ambiguous across detected runtimes: ${m.join(", ")}. Name one runtime or language in the Goal.`),s==="test-coverage"&&p.length===1&&m.length>0&&!m.includes(p[0])&&b.push(`The requested ${p[0]} coverage runtime is not present in the selected scope. Detected runtimes: ${m.join(", ")}.`),{original:r,normalized:r.toLocaleLowerCase("en-US"),statement:r.replace(/[.!?]+$/,""),category:s,confidence:a.length===1?"high":a.length>1?"medium":"low",ambiguities:b,...l===null?{}:{requestedTarget:{metric:"test-coverage-percent",operator:"at-least",value:l,...p.length===1?{runtime:p[0]}:{}}}}}function oe(e){let t={"test-coverage":["test suite coverage configuration instrumentation","CI tests LCOV Cobertura JaCoCo LLVM coverage"],"dependency-security":["dependency manifest lockfile security audit vulnerability"],"release-readiness":["release pipeline readiness gates build test deploy"],"defect-repair":["failure error test implementation call path"],"feature-change":["API implementation module dependency tests"],refactor:["module dependency ownership implementation tests"],performance:["performance benchmark latency throughput runtime"],documentation:["documentation README guide architecture decision"],"system-understanding":["architecture service API dependency ownership"]};return [...new Set([e.statement,...t[e.category]])].slice(0,3)}var ae="contracts/workspace-intelligence/goal-pack.v1.json",se="contracts/workspace-intelligence/goal-agent-handoff.v1.json",Re="contracts/workspace-intelligence/goal-plan-result.v1.json",pe="contracts/workspace-intelligence/goal-index.v1.json",ue=new Set(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"]);function Se(e,t){let r=e.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)??[],n=new Set(t.map(m=>m.toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"")).filter(Boolean)),a=[];for(let m=0;m<r.length;){let b=0;for(let u=Math.min(4,r.length-m);u>=1;u-=1){let j=r.slice(m,m+u).join("").toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"");if(n.has(j)){b=u;break}}if(b>0){m+=b;continue}a.push(r[m]),m+=1;}let s=a.findIndex((m,b)=>{let u=m.toLocaleLowerCase("en-US"),j=a[b+1]?.toLocaleLowerCase("en-US");return u==="without"&&["breaking","changing","modifying","removing"].includes(j??"")||u==="while"&&["keeping","maintaining","preserving"].includes(j??"")}),l=s>=2?a.slice(0,s):a,d=l.length>=2?l.join(" "):e;if(s<2)return [d];let p=a.slice(s).filter(m=>!["without","while","breaking","changing","modifying","removing","keeping","maintaining","preserving"].includes(m.toLocaleLowerCase("en-US")));return p.length>0?[d,p.join(" ")]:[d]}function ie(e){return e.split(C.sep).join("/")}function V(e,t){return C.resolve(t.absolutePath??C.join(e,t.path))}function ce(e){let t=e.requested.trim().replace(/^project:/,"");if(!t)throw new Error("Project goal scope must name a project.");let r=C.isAbsolute(t)?C.resolve(t):null,n=e.model.projects.filter(a=>a.name===t||ie(a.path)===ie(t)||r!==null&&V(e.workspacePath,a)===r);if(n.length!==1)throw new Error(n.length===0?`Project goal scope was not found in the canonical model: ${t}`:`Project goal scope is ambiguous in the canonical model: ${t}`);return n[0]}async function Ee(e){let t=await a$1(e);if(t.status==="miss")throw new Error(`Canonical model and live graph evidence are required (${t.reason}). Run \`workspai workspace intelligence run --for-agent generic --strict --json\` or retry with --refresh.`);let{model:r,graph:n}=t;return a(r,"contracts/workspace-intelligence/workspace-model.v1.json","Goal source model"),a(n,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Goal source graph"),b$1(n,r),{model:r,graph:n}}function le(e){let t=e.scope.trim();if(t==="workspace")return {kind:"workspace",projects:e.model.projects.map(n=>n.name).sort(),selectionSource:e.selectionSource,resolution:"selected"};let r=t.startsWith("projects:")?"projects:":t.startsWith("project:")&&t.slice(8).includes(",")?"project:":null;if(r){let n=t.slice(r.length).split(",").map(l=>l.trim()).filter(Boolean);if(n.length<2)throw new Error("A project-set Goal scope must name at least two projects.");let a=n.map(l=>ce({workspacePath:e.workspacePath,model:e.model,requested:l})),s=[...new Set(a.map(l=>l.name))].sort();if(s.length!==n.length)throw new Error("A project-set Goal scope must not contain duplicate projects.");return {kind:"project-set",projects:s,selectionSource:e.selectionSource,resolution:"selected"}}if(t)return {kind:"project",projects:[ce({workspacePath:e.workspacePath,model:e.model,requested:t}).name],selectionSource:e.selectionSource,resolution:"selected"};throw new Error("Goal scope cannot be empty.")}async function Ie(e){if(e.explicitScope?.trim())return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:e.explicitScope,selectionSource:"explicit"}),selectionRequired:false};if(e.invocationProjectPath){let t=C.resolve(e.invocationProjectPath),r=e.model.projects.filter(n=>V(e.workspacePath,n)===t);if(r.length!==1)throw new Error("The invocation project is not represented uniquely in the canonical workspace model. Refresh intelligence or pass --scope explicitly.");return {scope:{kind:"project",projects:[r[0].name],selectionSource:"invocation-project",resolution:"selected"},selectionRequired:false}}if(e.model.projects.length===1)return {scope:{kind:"project",projects:[e.model.projects[0].name],selectionSource:"single-project-workspace",resolution:"selected"},selectionRequired:false};if(e.selectScope){let t=await e.selectScope({workspaceName:e.model.workspace.name,projects:e.model.projects.map(n=>({name:n.name,runtime:n.runtime,runtimeCandidates:[...n.runtimeCandidates].sort(),framework:n.framework})).sort((n,a)=>n.name.localeCompare(a.name))}),r=t.kind==="workspace"?"workspace":t.projects.length===1?`project:${t.projects[0]}`:`projects:${t.projects.join(",")}`;return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:r,selectionSource:"interactive"}),selectionRequired:false}}return {scope:{kind:"workspace",projects:e.model.projects.map(t=>t.name).sort(),selectionSource:"workspace",resolution:"selection-required"},selectionRequired:true}}function Te(e,t){if(t.kind==="workspace")return {entities:e.quality.entityCount,relationships:e.quality.relationCount,proofs:e.quality.proofCount,unresolved:e.quality.unknownCount,proofCoveragePercent:Number((e.quality.relationProofCoverageRatio*100).toFixed(2))};let r=new Set(t.projects),n=e.entities.filter(p=>p.projectId!==void 0&&r.has(p.projectId)),a=new Set(n.map(p=>p.id)),s=e.relations.filter(p=>a.has(p.from)||a.has(p.to)),l=new Set([...n.flatMap(p=>p.proofIds),...s.flatMap(p=>p.proofIds)]),d=s.filter(p=>p.proofIds.length>0).length;return {entities:n.length,relationships:s.length,proofs:l.size,unresolved:s.length-d,proofCoveragePercent:s.length===0?100:Number((d/s.length*100).toFixed(2))}}function xe(e){let t=new Map;for(let n of e){let a=t.get(n.kind)??[];a.push(n),t.set(n.kind,a);}let r=[];for(let n=0;[...t.values()].some(a=>n<a.length);n+=1)for(let a of t.values()){let s=a[n];s&&r.push(s);}return r}async function _e(e){let t=C.join(e.workspacePath,p.intelligenceRun),r=await _.readJson(t).catch(()=>null),a=(Array.isArray(r?.stages)?r.stages:[]).filter(o=>o.status==="blocked"||o.status==="failed").map(o=>String(o.id??"unknown")).sort(),s=r?.status,l={status:s==="passed"?"passed":s==="blocked"||s==="failed"?"blocked":"unknown",artifact:p.intelligenceRun,blockedStages:a},d={status:"not-applicable",runtime:null,runtimeChoices:[],runner:null,existingEvidence:[],prerequisites:[]};if(e.intent.category==="test-coverage"){let o=e.intent.requestedTarget?.runtime;if(e.intent.ambiguities.some(P=>P.startsWith("Coverage scope is ambiguous")||P.startsWith("The Goal names multiple coverage runtimes")||P.startsWith("The selected projects do not share a common canonical coverage runtime")||P.startsWith("The requested ")))d={status:"requires-setup",runtime:o??null,runtimeChoices:e.coverageRuntimeChoices,runner:null,existingEvidence:[],prerequisites:["Select exactly one detected runtime or language for this coverage Goal."]};else {let P=o?e.projects.filter(c=>c.runtimeCandidates.includes(o)):e.projects,i=await Promise.all(P.map(async c=>({project:c,capability:await c$3(V(e.workspacePath,c),o??(ue.has(c.runtime)?c.runtime:"unknown"))}))),h=i.map(c=>c.capability.status);d={status:h.includes("unsupported")?"unsupported":h.includes("requires-setup")?"requires-setup":"available",runtime:i.length===1?i[0].capability.runtime:[...new Set(i.map(c=>c.capability.runtime))].join(","),runtimeChoices:e.coverageRuntimeChoices,runner:i.length===1?i[0].capability.runner:[...new Set(i.flatMap(c=>c.capability.runner?[c.capability.runner]:[]))].join(",")||null,existingEvidence:i.flatMap(c=>c.capability.existingEvidence.map(A=>({project:c.project.name,...A}))).filter((c,A,w)=>w.findIndex(k=>k.project===c.project&&k.path===c.path&&k.sha256===c.sha256)===A).sort((c,A)=>c.project.localeCompare(A.project)||c.path.localeCompare(A.path)),prerequisites:[...new Set(i.flatMap(c=>c.capability.prerequisites))].sort()};}}let p$1=oe(e.intent),m=[...Se(p$1[0],e.projects.map(o=>o.name)),...p$1.slice(1)].filter((o,y,P)=>P.indexOf(o)===y).slice(0,3),b=m.map((o,y)=>{let P=o.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)?.length??0,i=y===0&&P>=4?2:1,h=e.projects.map(w=>{let k=G=>f$2(e.graph,{query:o,projectId:w.name,...G?{kind:G}:{},limit:60,relationsPerEntity:0,minimumTermMatches:i}).entities,S=k(),de=[...new Set(e.graph.entities.filter(G=>G.projectId===w.name||G.projectId===void 0&&G.identity.scope==="workspace").map(G=>G.kind))].flatMap(G=>k(G).slice(0,8)),U=[...S,...de];return U.filter((G,me)=>U.findIndex(ge=>ge.id===G.id)===me)}),c=[],A=new Set;for(let w=0;h.some(k=>w<k.length);w+=1)for(let k of h){let S=k[w];!S||A.has(S.id)||(A.add(S.id),c.push(S));}return xe(c)}),u={"test-coverage":["test-suite"],"dependency-security":["package","module"],"release-readiness":["pipeline","deployment","lifecycle-stage"],"defect-repair":["test-suite","lifecycle-stage"],"feature-change":["project","runtime-unit","api","package","module","test-suite"],refactor:["package","module","api","test-suite"],performance:["lifecycle-stage","test-suite","pipeline"],documentation:["document","decision"],"system-understanding":["project","service","api","package","protocol"]},j=new Set(e.projects.map(o=>o.name)),v=e.graph.entities.filter(o=>o.proofIds.length>0&&(!o.projectId||j.has(o.projectId))&&u[e.intent.category].includes(o.kind)).sort((o,y)=>u[e.intent.category].indexOf(o.kind)-u[e.intent.category].indexOf(y.kind)||o.label.localeCompare(y.label)),f=[],M=new Set,E=o=>{!o||f.length>=20||M.has(o.id)||(M.add(o.id),f.push(o));},I=(e.intent.statement.match(/[A-Za-z][A-Za-z0-9+#.-]{1,}/g)??[]).length>=2,g=I?b[0]??[]:[];for(let o of g.slice(0,12))E(o);if(!I)for(let o of v)E(o);for(let o=0;f.length<20&&b.slice(1).some(y=>o<y.length);o+=1)for(let y of b.slice(1))E(y[o]);if(I)for(let o of v)E(o);for(let o of g.slice(12))E(o);let T=f.map(o=>({entityId:o.id,kind:o.kind,label:o.label,proofIds:o.proofIds.slice(0,12)})),L=b[0]?.length??0;return {workspaceIntelligence:l,measurement:d,retrieval:{status:I&&L>=3?"grounded":T.length>0?"partial":"empty",strategy:"deterministic-category-v1",queries:m,anchors:T}}}async function Le(e$1){let t=C.join(e$1,f$1);if(!await _.pathExists(t))return {schemaVersion:e,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let r=await _.readJson(t);a(r,pe,"Goal index");try{i(r);}catch(n){let a=h(r);if(!(a!==null&&n instanceof Error&&n.message==="Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")||!a)throw n;return a}return r}function Ne(e$1,t,r){let n=e$1.goals.find(l=>l.id===t.id),a=t.state==="ready-to-plan",s={id:t.id,fingerprint:t.fingerprint,objective:t.intent.statement,category:t.intent.category,state:t.state,lifecycle:n?.lifecycle==="cancelled"?"cancelled":a?"active":"planned",scope:t.scope,createdAt:n?.createdAt??t.generatedAt,updatedAt:r,goalPack:t.artifacts.goalPack,agentHandoff:t.artifacts.agentHandoff,...n?.verifiedGoalId?{verifiedGoalId:n.verifiedGoalId}:{},...n?.repairTransactionId?{repairTransactionId:n.repairTransactionId}:{},...n?.repairTransactionIds?{repairTransactionIds:n.repairTransactionIds}:{},...n?.changeTransactionId?{changeTransactionId:n.changeTransactionId}:{},...n?.changeTransactionIds?{changeTransactionIds:n.changeTransactionIds}:{},...n?.verificationReceipt?{verificationReceipt:n.verificationReceipt}:{}};return {schemaVersion:e,generatedAt:r,activeGoalId:s.lifecycle==="active"?t.id:e$1.activeGoalId===t.id?null:e$1.activeGoalId,goals:[...e$1.goals.filter(l=>l.id!==t.id).map(l=>s.lifecycle==="active"&&l.lifecycle==="active"?{...l,lifecycle:"planned",updatedAt:r}:l),s].sort((l,d)=>l.id.localeCompare(d.id))}}async function et(e){let t=b({startPath:C.resolve(e.startPath),explicitWorkspacePath:e.workspacePath,strict:true,requireProjectMembership:!e.scope?.trim()});if(!t)throw new Error("No canonical Workspai workspace could be resolved.");let r=C.resolve(t.workspacePath);e.refresh&&await c({workspacePath:r,strict:false,agent:"generic"});let{model:n,graph:a$1}=await Ee(r),s=await Ie({workspacePath:r,invocationProjectPath:t.projectPath,model:n,explicitScope:e.scope,selectScope:e.selectScope}),l=s.scope,d$2=n.projects.filter(i=>l.projects.includes(i.name));if(d$2.length===0)throw new Error("A Goal Pack requires at least one registered project in its selected scope.");let p$1=e.maxAttempts??5;if(!Number.isInteger(p$1)||p$1<1||p$1>25)throw new Error("--max-attempts must be an integer from 1 to 25.");let m=new Date().toISOString(),b$1=d(n),u=d$2.map(i=>({name:i.name,runtimes:[...new Set(i.runtimeCandidates.filter(h=>ue.has(h)))].sort()})),j$1=[...new Set(u.flatMap(i=>i.runtimes))].sort(),v=u.length<=1?j$1:u[0].runtimes.filter(i=>u.every(h=>h.runtimes.includes(i))),f$2=K(e.intent,{availableCoverageRuntimes:v,...e.runtime?{selectedCoverageRuntime:e.runtime}:v.length===1?{selectedCoverageRuntime:v[0]}:{}});if(e.runtime&&!v.includes(e.runtime)){let i=e.runtime,h=u.filter(c=>!c.runtimes.includes(i)).map(c=>c.name);throw new Error(d$2.length>1&&h.length>0?`--runtime ${e.runtime} is not canonical for every project in the selected Goal scope. Missing from: ${h.join(", ")}. Split the projects into runtime-compatible Goal scopes.`:`--runtime ${e.runtime} is not present in the canonical Workspace Model for the selected Goal scope. Available runtimes: ${v.join(", ")||"none"}.`)}if(e.runtime&&f$2.category!=="test-coverage")throw new Error("--runtime is valid only for a test-coverage Goal.");if(e.runtime&&f$2.requestedTarget?.runtime&&f$2.requestedTarget.runtime!==e.runtime)throw new Error(`--runtime ${e.runtime} conflicts with the ${f$2.requestedTarget.runtime} runtime named in the Goal intent.`);if(!s.selectionRequired&&f$2.category==="test-coverage"&&f$2.requestedTarget&&!f$2.requestedTarget.runtime&&v.length>1&&!e.runtime&&e.selectCoverageRuntime){let i=await e.selectCoverageRuntime({workspaceName:n.workspace.name,scope:l,projects:d$2.map(h=>({name:h.name,runtime:h.runtime,runtimeCandidates:[...h.runtimeCandidates].sort()})),runtimes:v});if(!v.includes(i))throw new Error("The selected coverage runtime is outside the canonical Goal scope.");f$2=K(e.intent,{availableCoverageRuntimes:v,selectedCoverageRuntime:i});}!s.selectionRequired&&f$2.category==="test-coverage"&&d$2.length>1&&v.length===0&&(f$2={...f$2,ambiguities:[`The selected projects do not share a common canonical coverage runtime: ${u.map(i=>`${i.name} (${i.runtimes.join(", ")||"none"})`).join("; ")}. Split them into runtime-compatible Goal scopes so every selected project is verified.`,...f$2.ambiguities]}),s.selectionRequired&&(f$2={...f$2,ambiguities:[`Goal scope is unresolved across ${l.projects.length} registered projects: ${l.projects.join(", ")}. Select one project, multiple projects, or the entire workspace.`,...f$2.ambiguities]});let M=await _e({workspacePath:r,projects:d$2,graph:a$1,intent:f$2,coverageRuntimeChoices:v}),E={generatedAt:m,intent:f$2,workspaceName:n.workspace.name,scope:l,sourceBinding:{model:{artifact:p.model,schemaVersion:q.model,hashAlgorithm:"sha256",hashSemantics:"workspace-model-structural-v1",hash:b$1,generatedAt:n.generatedAt},graph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,hashAlgorithm:"sha256",hashSemantics:"canonical-json-v1",hash:c$1(a$1),generatedAt:a$1.generatedAt,modelHash:a$1.source.hash,...a$1.source.inputs?.hash?{inputHash:a$1.source.inputs.hash}:{}}},preflight:M,baseline:{projectCount:d$2.length,runtimes:[...new Set(d$2.flatMap(i=>i.runtimeCandidates))].sort(),frameworks:[...new Set(d$2.map(i=>i.framework))].sort(),graph:Te(a$1,l)},maxAttempts:p$1,consumer:e.consumer??"generic"},I={digestCanonical:c$1},{goalPack:g,handoff:T}=j(E,I);a(g,ae,"Goal Pack"),a(T,se,"Goal agent handoff");let L=false,o=async()=>{let i=C.join(r,g.artifacts.goalPack),h=C.join(r,g.artifacts.agentHandoff),[c,A]=await Promise.all([_.pathExists(i),_.pathExists(h)]);if(c!==A)throw new Error(`Goal Pack instance is incomplete and cannot be resumed: ${g.id}`);if(!c)return;let[w,k]=await Promise.all([_.readJson(i),_.readJson(h)]);a(w,ae,"Persisted Goal Pack"),a(k,se,"Persisted goal agent handoff");let S=j({...E,generatedAt:w.generatedAt,sourceBinding:w.sourceBinding},I);if(w.id!==g.id||k.goalId!==g.id||c$1(w)!==c$1(S.goalPack)||c$1(k)!==c$1(S.handoff))throw new Error(`Goal Pack instance failed immutable integrity validation: ${g.id}`);g=w,T=k,L=true;};if(e.dryRun)await o();else {let i$2=`.workspai/goals/${g.id}/publication`;await f(r,i$2,async()=>{await o();let h=Ne(await Le(r),g,new Date().toISOString());a(h,pe,"Goal index"),i(h),await i$1(r,d$1,L?[{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]:[{relativePath:g.artifacts.goalPack,payload:g},{relativePath:g.artifacts.agentHandoff,payload:T},{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]);});}let y=[g.artifacts.goalPack,g.artifacts.agentHandoff,d$1,f$1],P={schemaVersion:c$2,result:g.state==="needs-confirmation"?"needs-confirmation":g.state==="blocked"?"blocked":g.state==="needs-evidence"?"needs-evidence":"planned",resolution:{source:t.source,invocationScope:t.projectPath?"project":"workspace"},goalPack:g,agentHandoff:T,writtenArtifacts:e.dryRun?[]:L?[d$1,f$1]:y,dryRun:e.dryRun===true,resumed:L};return a(P,Re,"Goal plan result"),P}export{et as planGoalPack};
|
|
1
|
+
import {c as c$3}from'./chunk-HAZGSAKP.js';import {c}from'./chunk-SVGUAVMG.js';import {j,i,d as d$1,f as f$1,c as c$2,e,h}from'./chunk-TBOIXIQA.js';export{b as GOAL_AGENT_HANDOFF_SCHEMA_VERSION,f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,g as GOAL_LIFECYCLE_RESULT_SCHEMA_VERSION,d as GOAL_PACK_LAST_RUN_PATH,a as GOAL_PACK_SCHEMA_VERSION,c as GOAL_PLAN_RESULT_SCHEMA_VERSION}from'./chunk-TBOIXIQA.js';import {f as f$2}from'./chunk-ZKYH44ER.js';import {a as a$1}from'./chunk-UHT2SW7O.js';import {b}from'./chunk-EBQS5T7Q.js';import {b as b$1}from'./chunk-5Y4YRYZI.js';import {f,i as i$1}from'./chunk-FE5R6EUV.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {q,p}from'./chunk-ODK4LCEL.js';import C from'path';import _ from'fs-extra';var ve=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/,ye=/(?:^|\s)(?:\/(?:home|Users|private|var|tmp|mnt|opt|srv|root|workspace|workspaces|data|Volumes|etc|usr|run|dev|proc|sys)\/[^\s]+|[A-Za-z]:[\\/][^\s]+|\\\\[^\\\s]+\\[^\s]+)/,Pe=/(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:github_pat_|gh[pousr]_|glpat-|npm_|xox[baprs]-|sk-(?:proj-)?)[A-Za-z0-9_-]{12,}|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[A-Za-z0-9_-]{20,}|\bBearer\s+[A-Za-z0-9._~+/-]{16,}|[a-z][a-z0-9+.-]*:\/\/[^\s:/]+:[^\s@/]+@|\b(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^\s]{6,})/i,je=[{category:"test-coverage",patterns:[/\b(?:test\s+)?coverage\b/i,/\bcoverage\s+(?:to|above|at least)\b/i]},{category:"dependency-security",patterns:[/\b(?:dependency|dependencies|package|packages)\b.*\b(?:security|vulnerab|audit)\b/i,/\b(?:security|vulnerab|audit)\b.*\b(?:dependency|dependencies|package|packages)\b/i]},{category:"release-readiness",patterns:[/\brelease[ -]readiness\b/i,/\bready (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare\b[^\n]{0,80}\bfor release\b/i]},{category:"defect-repair",patterns:[/\b(?:fix|repair|resolve|debug)\b.*\b(?:bug|error|failure|issue|regression)\b/i]},{category:"performance",patterns:[/\b(?:performance|latency|throughput|cpu|optimi[sz]e|faster|slower)\b/i,/\b(?:memory\s+(?:allocation|consumption|footprint|leak|pressure|usage)|out[ -]of[ -]memory|heap|ram)\b/i]},{category:"refactor",patterns:[/\b(?:refactor|restructure|decouple|extract|simplify|cleanup|clean up)\b/i]},{category:"documentation",patterns:[/\b(?:document|documentation|readme|guide|tutorial|docs)\b/i]},{category:"feature-change",patterns:[/\b(?:add|build|create|enforce|enhance|harden|implement|improve|introduce|support)\b/i]},{category:"system-understanding",patterns:[/\b(?:understand|explain|map|find|where|how|architecture|analy[sz]e|search)\b/i]}];function Ge(e){if(typeof e!="string")throw new Error("Goal intent must be text.");let t=e.trim().replace(/\s+/g," ");if(!t)throw new Error("Goal intent cannot be empty.");if(t.length>2e3)throw new Error("Goal intent exceeds the 2000 character safety limit.");if(ve.test(t))throw new Error("Goal intent contains unsupported control characters.");if(ye.test(t))throw new Error("Goal intent contains a machine-local absolute path. Use a workspace-relative path or project scope.");if(Pe.test(t))throw new Error("Goal intent appears to contain secret material and was not persisted.");return t}function Ce(e){let t=e.match(/\b(?:coverage\D{0,24})?((?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?))\s*(?:%|percent(?:age)?(?:\s+points?)?)/i);if(!t||!/coverage/i.test(e))return null;let r=Number(t[1]);return Number.isFinite(r)&&r>=0&&r<=100?r:null}var re=[{runtime:"cpp",patterns:[/\bc\+\+/i,/\bcpp\b/i]},{runtime:"dotnet",patterns:[/\.net\b/i,/\bdotnet\b/i,/\bc#/i,/\bcsharp\b/i]},{runtime:"node",patterns:[/\bnode(?:\.js)?\b/i,/\btypescript\b/i,/\bjavascript\b/i,/\b(?:js|ts)\b/i]},{runtime:"python",patterns:[/\bpython\b/i,/\bpytest\b/i]},{runtime:"go",patterns:[/\bgolang\b/i,/\bgo(?:\s+(?:test|coverage|tests))\b/i]},{runtime:"java",patterns:[/\bjava\b/i,/\bjunit\b/i,/\bjacoco\b/i]},{runtime:"rust",patterns:[/\brust\b/i,/\bcargo\b/i]},{runtime:"php",patterns:[/\bphp\b/i,/\bphpunit\b/i]},{runtime:"ruby",patterns:[/\bruby\b/i,/\brspec\b/i]},{runtime:"kotlin",patterns:[/\bkotlin\b/i]},{runtime:"scala",patterns:[/\bscala\b/i]},{runtime:"clojure",patterns:[/\bclojure\b/i]},{runtime:"elixir",patterns:[/\belixir\b/i]},{runtime:"deno",patterns:[/\bdeno\b/i]},{runtime:"bun",patterns:[/\bbun\b/i]},{runtime:"c",patterns:[/\bc(?:\s+(?:test|coverage|tests|code))\b/i]}];function Ae(e){return re.filter(t=>t.patterns.some(r=>r.test(e))).map(t=>t.runtime)}function K(e,t={}){let r=Ge(e),n=je.filter(u=>u.patterns.some(j=>j.test(r))).map(u=>u.category),a=n.some(u=>u!=="feature-change")?n.filter(u=>u!=="feature-change"):n,s=a[0]??"feature-change",l=Ce(r),d=Ae(r),p=d.length===0&&t.selectedCoverageRuntime?[t.selectedCoverageRuntime]:d,m=[...new Set((t.availableCoverageRuntimes??[]).filter(u=>re.some(j=>j.runtime===u)))].sort(),b=[];return a.length>1&&a[0]!=="test-coverage"&&b.push(`The intent also contains signals for: ${a.slice(1).join(", ")}.`),s==="test-coverage"&&l===null&&b.push("A numeric test coverage target is required for machine verification."),s==="test-coverage"&&p.length>1&&b.push(`The Goal names multiple coverage runtimes: ${p.join(", ")}. Select one runtime per Goal.`),s==="test-coverage"&&p.length===0&&m.length>1&&b.push(`Coverage scope is ambiguous across detected runtimes: ${m.join(", ")}. Name one runtime or language in the Goal.`),s==="test-coverage"&&p.length===1&&m.length>0&&!m.includes(p[0])&&b.push(`The requested ${p[0]} coverage runtime is not present in the selected scope. Detected runtimes: ${m.join(", ")}.`),{original:r,normalized:r.toLocaleLowerCase("en-US"),statement:r.replace(/[.!?]+$/,""),category:s,confidence:a.length===1?"high":a.length>1?"medium":"low",ambiguities:b,...l===null?{}:{requestedTarget:{metric:"test-coverage-percent",operator:"at-least",value:l,...p.length===1?{runtime:p[0]}:{}}}}}function oe(e){let t={"test-coverage":["test suite coverage configuration instrumentation","CI tests LCOV Cobertura JaCoCo LLVM coverage"],"dependency-security":["dependency manifest lockfile security audit vulnerability"],"release-readiness":["release pipeline readiness gates build test deploy"],"defect-repair":["failure error test implementation call path"],"feature-change":["API implementation module dependency tests"],refactor:["module dependency ownership implementation tests"],performance:["performance benchmark latency throughput runtime"],documentation:["documentation README guide architecture decision"],"system-understanding":["architecture service API dependency ownership"]};return [...new Set([e.statement,...t[e.category]])].slice(0,3)}var ae="contracts/workspace-intelligence/goal-pack.v1.json",se="contracts/workspace-intelligence/goal-agent-handoff.v1.json",Re="contracts/workspace-intelligence/goal-plan-result.v1.json",pe="contracts/workspace-intelligence/goal-index.v1.json",ue=new Set(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"]);function Se(e,t){let r=e.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)??[],n=new Set(t.map(m=>m.toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"")).filter(Boolean)),a=[];for(let m=0;m<r.length;){let b=0;for(let u=Math.min(4,r.length-m);u>=1;u-=1){let j=r.slice(m,m+u).join("").toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"");if(n.has(j)){b=u;break}}if(b>0){m+=b;continue}a.push(r[m]),m+=1;}let s=a.findIndex((m,b)=>{let u=m.toLocaleLowerCase("en-US"),j=a[b+1]?.toLocaleLowerCase("en-US");return u==="without"&&["breaking","changing","modifying","removing"].includes(j??"")||u==="while"&&["keeping","maintaining","preserving"].includes(j??"")}),l=s>=2?a.slice(0,s):a,d=l.length>=2?l.join(" "):e;if(s<2)return [d];let p=a.slice(s).filter(m=>!["without","while","breaking","changing","modifying","removing","keeping","maintaining","preserving"].includes(m.toLocaleLowerCase("en-US")));return p.length>0?[d,p.join(" ")]:[d]}function ie(e){return e.split(C.sep).join("/")}function V(e,t){return C.resolve(t.absolutePath??C.join(e,t.path))}function ce(e){let t=e.requested.trim().replace(/^project:/,"");if(!t)throw new Error("Project goal scope must name a project.");let r=C.isAbsolute(t)?C.resolve(t):null,n=e.model.projects.filter(a=>a.name===t||ie(a.path)===ie(t)||r!==null&&V(e.workspacePath,a)===r);if(n.length!==1)throw new Error(n.length===0?`Project goal scope was not found in the canonical model: ${t}`:`Project goal scope is ambiguous in the canonical model: ${t}`);return n[0]}async function Ee(e){let t=await a$1(e);if(t.status==="miss")throw new Error(`Canonical model and live graph evidence are required (${t.reason}). Run \`workspai workspace intelligence run --for-agent generic --strict --json\` or retry with --refresh.`);let{model:r,graph:n}=t;return a(r,"contracts/workspace-intelligence/workspace-model.v1.json","Goal source model"),a(n,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Goal source graph"),b$1(n,r),{model:r,graph:n}}function le(e){let t=e.scope.trim();if(t==="workspace")return {kind:"workspace",projects:e.model.projects.map(n=>n.name).sort(),selectionSource:e.selectionSource,resolution:"selected"};let r=t.startsWith("projects:")?"projects:":t.startsWith("project:")&&t.slice(8).includes(",")?"project:":null;if(r){let n=t.slice(r.length).split(",").map(l=>l.trim()).filter(Boolean);if(n.length<2)throw new Error("A project-set Goal scope must name at least two projects.");let a=n.map(l=>ce({workspacePath:e.workspacePath,model:e.model,requested:l})),s=[...new Set(a.map(l=>l.name))].sort();if(s.length!==n.length)throw new Error("A project-set Goal scope must not contain duplicate projects.");return {kind:"project-set",projects:s,selectionSource:e.selectionSource,resolution:"selected"}}if(t)return {kind:"project",projects:[ce({workspacePath:e.workspacePath,model:e.model,requested:t}).name],selectionSource:e.selectionSource,resolution:"selected"};throw new Error("Goal scope cannot be empty.")}async function Ie(e){if(e.explicitScope?.trim())return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:e.explicitScope,selectionSource:"explicit"}),selectionRequired:false};if(e.invocationProjectPath){let t=C.resolve(e.invocationProjectPath),r=e.model.projects.filter(n=>V(e.workspacePath,n)===t);if(r.length!==1)throw new Error("The invocation project is not represented uniquely in the canonical workspace model. Refresh intelligence or pass --scope explicitly.");return {scope:{kind:"project",projects:[r[0].name],selectionSource:"invocation-project",resolution:"selected"},selectionRequired:false}}if(e.model.projects.length===1)return {scope:{kind:"project",projects:[e.model.projects[0].name],selectionSource:"single-project-workspace",resolution:"selected"},selectionRequired:false};if(e.selectScope){let t=await e.selectScope({workspaceName:e.model.workspace.name,projects:e.model.projects.map(n=>({name:n.name,runtime:n.runtime,runtimeCandidates:[...n.runtimeCandidates].sort(),framework:n.framework})).sort((n,a)=>n.name.localeCompare(a.name))}),r=t.kind==="workspace"?"workspace":t.projects.length===1?`project:${t.projects[0]}`:`projects:${t.projects.join(",")}`;return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:r,selectionSource:"interactive"}),selectionRequired:false}}return {scope:{kind:"workspace",projects:e.model.projects.map(t=>t.name).sort(),selectionSource:"workspace",resolution:"selection-required"},selectionRequired:true}}function Te(e,t){if(t.kind==="workspace")return {entities:e.quality.entityCount,relationships:e.quality.relationCount,proofs:e.quality.proofCount,unresolved:e.quality.unknownCount,proofCoveragePercent:Number((e.quality.relationProofCoverageRatio*100).toFixed(2))};let r=new Set(t.projects),n=e.entities.filter(p=>p.projectId!==void 0&&r.has(p.projectId)),a=new Set(n.map(p=>p.id)),s=e.relations.filter(p=>a.has(p.from)||a.has(p.to)),l=new Set([...n.flatMap(p=>p.proofIds),...s.flatMap(p=>p.proofIds)]),d=s.filter(p=>p.proofIds.length>0).length;return {entities:n.length,relationships:s.length,proofs:l.size,unresolved:s.length-d,proofCoveragePercent:s.length===0?100:Number((d/s.length*100).toFixed(2))}}function xe(e){let t=new Map;for(let n of e){let a=t.get(n.kind)??[];a.push(n),t.set(n.kind,a);}let r=[];for(let n=0;[...t.values()].some(a=>n<a.length);n+=1)for(let a of t.values()){let s=a[n];s&&r.push(s);}return r}async function _e(e){let t=C.join(e.workspacePath,p.intelligenceRun),r=await _.readJson(t).catch(()=>null),a=(Array.isArray(r?.stages)?r.stages:[]).filter(o=>o.status==="blocked"||o.status==="failed").map(o=>String(o.id??"unknown")).sort(),s=r?.status,l={status:s==="passed"?"passed":s==="blocked"||s==="failed"?"blocked":"unknown",artifact:p.intelligenceRun,blockedStages:a},d={status:"not-applicable",runtime:null,runtimeChoices:[],runner:null,existingEvidence:[],prerequisites:[]};if(e.intent.category==="test-coverage"){let o=e.intent.requestedTarget?.runtime;if(e.intent.ambiguities.some(P=>P.startsWith("Coverage scope is ambiguous")||P.startsWith("The Goal names multiple coverage runtimes")||P.startsWith("The selected projects do not share a common canonical coverage runtime")||P.startsWith("The requested ")))d={status:"requires-setup",runtime:o??null,runtimeChoices:e.coverageRuntimeChoices,runner:null,existingEvidence:[],prerequisites:["Select exactly one detected runtime or language for this coverage Goal."]};else {let P=o?e.projects.filter(c=>c.runtimeCandidates.includes(o)):e.projects,i=await Promise.all(P.map(async c=>({project:c,capability:await c$3(V(e.workspacePath,c),o??(ue.has(c.runtime)?c.runtime:"unknown"))}))),h=i.map(c=>c.capability.status);d={status:h.includes("unsupported")?"unsupported":h.includes("requires-setup")?"requires-setup":"available",runtime:i.length===1?i[0].capability.runtime:[...new Set(i.map(c=>c.capability.runtime))].join(","),runtimeChoices:e.coverageRuntimeChoices,runner:i.length===1?i[0].capability.runner:[...new Set(i.flatMap(c=>c.capability.runner?[c.capability.runner]:[]))].join(",")||null,existingEvidence:i.flatMap(c=>c.capability.existingEvidence.map(A=>({project:c.project.name,...A}))).filter((c,A,w)=>w.findIndex(k=>k.project===c.project&&k.path===c.path&&k.sha256===c.sha256)===A).sort((c,A)=>c.project.localeCompare(A.project)||c.path.localeCompare(A.path)),prerequisites:[...new Set(i.flatMap(c=>c.capability.prerequisites))].sort()};}}let p$1=oe(e.intent),m=[...Se(p$1[0],e.projects.map(o=>o.name)),...p$1.slice(1)].filter((o,y,P)=>P.indexOf(o)===y).slice(0,3),b=m.map((o,y)=>{let P=o.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)?.length??0,i=y===0&&P>=4?2:1,h=e.projects.map(w=>{let k=G=>f$2(e.graph,{query:o,projectId:w.name,...G?{kind:G}:{},limit:60,relationsPerEntity:0,minimumTermMatches:i}).entities,S=k(),de=[...new Set(e.graph.entities.filter(G=>G.projectId===w.name||G.projectId===void 0&&G.identity.scope==="workspace").map(G=>G.kind))].flatMap(G=>k(G).slice(0,8)),U=[...S,...de];return U.filter((G,me)=>U.findIndex(ge=>ge.id===G.id)===me)}),c=[],A=new Set;for(let w=0;h.some(k=>w<k.length);w+=1)for(let k of h){let S=k[w];!S||A.has(S.id)||(A.add(S.id),c.push(S));}return xe(c)}),u={"test-coverage":["test-suite"],"dependency-security":["package","module"],"release-readiness":["pipeline","deployment","lifecycle-stage"],"defect-repair":["test-suite","lifecycle-stage"],"feature-change":["project","runtime-unit","api","package","module","test-suite"],refactor:["package","module","api","test-suite"],performance:["lifecycle-stage","test-suite","pipeline"],documentation:["document","decision"],"system-understanding":["project","service","api","package","protocol"]},j=new Set(e.projects.map(o=>o.name)),v=e.graph.entities.filter(o=>o.proofIds.length>0&&(!o.projectId||j.has(o.projectId))&&u[e.intent.category].includes(o.kind)).sort((o,y)=>u[e.intent.category].indexOf(o.kind)-u[e.intent.category].indexOf(y.kind)||o.label.localeCompare(y.label)),f=[],M=new Set,E=o=>{!o||f.length>=20||M.has(o.id)||(M.add(o.id),f.push(o));},I=(e.intent.statement.match(/[A-Za-z][A-Za-z0-9+#.-]{1,}/g)??[]).length>=2,g=I?b[0]??[]:[];for(let o of g.slice(0,12))E(o);if(!I)for(let o of v)E(o);for(let o=0;f.length<20&&b.slice(1).some(y=>o<y.length);o+=1)for(let y of b.slice(1))E(y[o]);if(I)for(let o of v)E(o);for(let o of g.slice(12))E(o);let T=f.map(o=>({entityId:o.id,kind:o.kind,label:o.label,proofIds:o.proofIds.slice(0,12)})),L=b[0]?.length??0;return {workspaceIntelligence:l,measurement:d,retrieval:{status:I&&L>=3?"grounded":T.length>0?"partial":"empty",strategy:"deterministic-category-v1",queries:m,anchors:T}}}async function Le(e$1){let t=C.join(e$1,f$1);if(!await _.pathExists(t))return {schemaVersion:e,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let r=await _.readJson(t);a(r,pe,"Goal index");try{i(r);}catch(n){let a=h(r);if(!(a!==null&&n instanceof Error&&n.message==="Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")||!a)throw n;return a}return r}function Ne(e$1,t,r){let n=e$1.goals.find(l=>l.id===t.id),a=t.state==="ready-to-plan",s={id:t.id,fingerprint:t.fingerprint,objective:t.intent.statement,category:t.intent.category,state:t.state,lifecycle:n?.lifecycle==="cancelled"?"cancelled":a?"active":"planned",scope:t.scope,createdAt:n?.createdAt??t.generatedAt,updatedAt:r,goalPack:t.artifacts.goalPack,agentHandoff:t.artifacts.agentHandoff,...n?.verifiedGoalId?{verifiedGoalId:n.verifiedGoalId}:{},...n?.repairTransactionId?{repairTransactionId:n.repairTransactionId}:{},...n?.repairTransactionIds?{repairTransactionIds:n.repairTransactionIds}:{},...n?.changeTransactionId?{changeTransactionId:n.changeTransactionId}:{},...n?.changeTransactionIds?{changeTransactionIds:n.changeTransactionIds}:{},...n?.verificationReceipt?{verificationReceipt:n.verificationReceipt}:{}};return {schemaVersion:e,generatedAt:r,activeGoalId:s.lifecycle==="active"?t.id:e$1.activeGoalId===t.id?null:e$1.activeGoalId,goals:[...e$1.goals.filter(l=>l.id!==t.id).map(l=>s.lifecycle==="active"&&l.lifecycle==="active"?{...l,lifecycle:"planned",updatedAt:r}:l),s].sort((l,d)=>l.id.localeCompare(d.id))}}async function et(e){let t=b({startPath:C.resolve(e.startPath),explicitWorkspacePath:e.workspacePath,strict:true,requireProjectMembership:!e.scope?.trim()});if(!t)throw new Error("No canonical Workspai workspace could be resolved.");let r=C.resolve(t.workspacePath);e.refresh&&await c({workspacePath:r,strict:false,agent:"generic"});let{model:n,graph:a$1}=await Ee(r),s=await Ie({workspacePath:r,invocationProjectPath:t.projectPath,model:n,explicitScope:e.scope,selectScope:e.selectScope}),l=s.scope,d$2=n.projects.filter(i=>l.projects.includes(i.name));if(d$2.length===0)throw new Error("A Goal Pack requires at least one registered project in its selected scope.");let p$1=e.maxAttempts??5;if(!Number.isInteger(p$1)||p$1<1||p$1>25)throw new Error("--max-attempts must be an integer from 1 to 25.");let m=new Date().toISOString(),b$1=d(n),u=d$2.map(i=>({name:i.name,runtimes:[...new Set(i.runtimeCandidates.filter(h=>ue.has(h)))].sort()})),j$1=[...new Set(u.flatMap(i=>i.runtimes))].sort(),v=u.length<=1?j$1:u[0].runtimes.filter(i=>u.every(h=>h.runtimes.includes(i))),f$2=K(e.intent,{availableCoverageRuntimes:v,...e.runtime?{selectedCoverageRuntime:e.runtime}:v.length===1?{selectedCoverageRuntime:v[0]}:{}});if(e.runtime&&!v.includes(e.runtime)){let i=e.runtime,h=u.filter(c=>!c.runtimes.includes(i)).map(c=>c.name);throw new Error(d$2.length>1&&h.length>0?`--runtime ${e.runtime} is not canonical for every project in the selected Goal scope. Missing from: ${h.join(", ")}. Split the projects into runtime-compatible Goal scopes.`:`--runtime ${e.runtime} is not present in the canonical Workspace Model for the selected Goal scope. Available runtimes: ${v.join(", ")||"none"}.`)}if(e.runtime&&f$2.category!=="test-coverage")throw new Error("--runtime is valid only for a test-coverage Goal.");if(e.runtime&&f$2.requestedTarget?.runtime&&f$2.requestedTarget.runtime!==e.runtime)throw new Error(`--runtime ${e.runtime} conflicts with the ${f$2.requestedTarget.runtime} runtime named in the Goal intent.`);if(!s.selectionRequired&&f$2.category==="test-coverage"&&f$2.requestedTarget&&!f$2.requestedTarget.runtime&&v.length>1&&!e.runtime&&e.selectCoverageRuntime){let i=await e.selectCoverageRuntime({workspaceName:n.workspace.name,scope:l,projects:d$2.map(h=>({name:h.name,runtime:h.runtime,runtimeCandidates:[...h.runtimeCandidates].sort()})),runtimes:v});if(!v.includes(i))throw new Error("The selected coverage runtime is outside the canonical Goal scope.");f$2=K(e.intent,{availableCoverageRuntimes:v,selectedCoverageRuntime:i});}!s.selectionRequired&&f$2.category==="test-coverage"&&d$2.length>1&&v.length===0&&(f$2={...f$2,ambiguities:[`The selected projects do not share a common canonical coverage runtime: ${u.map(i=>`${i.name} (${i.runtimes.join(", ")||"none"})`).join("; ")}. Split them into runtime-compatible Goal scopes so every selected project is verified.`,...f$2.ambiguities]}),s.selectionRequired&&(f$2={...f$2,ambiguities:[`Goal scope is unresolved across ${l.projects.length} registered projects: ${l.projects.join(", ")}. Select one project, multiple projects, or the entire workspace.`,...f$2.ambiguities]});let M=await _e({workspacePath:r,projects:d$2,graph:a$1,intent:f$2,coverageRuntimeChoices:v}),E={generatedAt:m,intent:f$2,workspaceName:n.workspace.name,scope:l,sourceBinding:{model:{artifact:p.model,schemaVersion:q.model,hashAlgorithm:"sha256",hashSemantics:"workspace-model-structural-v1",hash:b$1,generatedAt:n.generatedAt},graph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,hashAlgorithm:"sha256",hashSemantics:"canonical-json-v1",hash:c$1(a$1),generatedAt:a$1.generatedAt,modelHash:a$1.source.hash,...a$1.source.inputs?.hash?{inputHash:a$1.source.inputs.hash}:{}}},preflight:M,baseline:{projectCount:d$2.length,runtimes:[...new Set(d$2.flatMap(i=>i.runtimeCandidates))].sort(),frameworks:[...new Set(d$2.map(i=>i.framework))].sort(),graph:Te(a$1,l)},maxAttempts:p$1,consumer:e.consumer??"generic"},I={digestCanonical:c$1},{goalPack:g,handoff:T}=j(E,I);a(g,ae,"Goal Pack"),a(T,se,"Goal agent handoff");let L=false,o=async()=>{let i=C.join(r,g.artifacts.goalPack),h=C.join(r,g.artifacts.agentHandoff),[c,A]=await Promise.all([_.pathExists(i),_.pathExists(h)]);if(c!==A)throw new Error(`Goal Pack instance is incomplete and cannot be resumed: ${g.id}`);if(!c)return;let[w,k]=await Promise.all([_.readJson(i),_.readJson(h)]);a(w,ae,"Persisted Goal Pack"),a(k,se,"Persisted goal agent handoff");let S=j({...E,generatedAt:w.generatedAt,sourceBinding:w.sourceBinding},I);if(w.id!==g.id||k.goalId!==g.id||c$1(w)!==c$1(S.goalPack)||c$1(k)!==c$1(S.handoff))throw new Error(`Goal Pack instance failed immutable integrity validation: ${g.id}`);g=w,T=k,L=true;};if(e.dryRun)await o();else {let i$2=`.workspai/goals/${g.id}/publication`;await f(r,i$2,async()=>{await o();let h=Ne(await Le(r),g,new Date().toISOString());a(h,pe,"Goal index"),i(h),await i$1(r,d$1,L?[{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]:[{relativePath:g.artifacts.goalPack,payload:g},{relativePath:g.artifacts.agentHandoff,payload:T},{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]);});}let y=[g.artifacts.goalPack,g.artifacts.agentHandoff,d$1,f$1],P={schemaVersion:c$2,result:g.state==="needs-confirmation"?"needs-confirmation":g.state==="blocked"?"blocked":g.state==="needs-evidence"?"needs-evidence":"planned",resolution:{source:t.source,invocationScope:t.projectPath?"project":"workspace"},goalPack:g,agentHandoff:T,writtenArtifacts:e.dryRun?[]:L?[d$1,f$1]:y,dryRun:e.dryRun===true,resumed:L};return a(P,Re,"Goal plan result"),P}export{et as planGoalPack};
|