workspai 0.61.0 → 0.63.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.
Files changed (65) hide show
  1. package/README.md +7 -5
  2. package/contracts/studio-card-repair-capabilities.v1.json +65 -1
  3. package/contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json +31 -3
  4. package/contracts/workspace-intelligence/agent-customization-pack-report.v1.json +5 -1
  5. package/contracts/workspace-intelligence/agent-reports-index.v1.json +5 -1
  6. package/contracts/workspace-intelligence/project-agent-entry.v1.json +32 -4
  7. package/contracts/workspace-intelligence/project-context-agent.v1.json +34 -2
  8. package/contracts/workspace-intelligence/studio-blocker-handoff.v1.json +28 -0
  9. package/contracts/workspace-intelligence/workspace-context.v1.json +4 -1
  10. package/contracts/workspace-intelligence-chain.v1.json +4 -5
  11. package/dist/{artifact-remediation-plan-HPNQTNJ2.js → artifact-remediation-plan-XIQNI35L.js} +1 -1
  12. package/dist/autopilot-release-NUQKFKKK.js +1 -0
  13. package/dist/{chunk-NJ6WJ7VU.js → chunk-2LLMKTMO.js} +1 -1
  14. package/dist/{chunk-2FPANIX3.js → chunk-GXPOT3A7.js} +14 -12
  15. package/dist/{chunk-YGONW6VG.js → chunk-J5OMC4RZ.js} +1 -1
  16. package/dist/{chunk-WQX3JYEP.js → chunk-LNXIMF3O.js} +1 -1
  17. package/dist/chunk-ODJAKGQF.js +49 -0
  18. package/dist/{chunk-2JVRDBJC.js → chunk-PPQL5UTI.js} +1 -1
  19. package/dist/{chunk-JEGG4EEZ.js → chunk-QB3BLYUR.js} +1 -1
  20. package/dist/{chunk-4KNDIFJ5.js → chunk-QQU536KA.js} +1 -1
  21. package/dist/{chunk-GWMC6SSY.js → chunk-TTQVOCG6.js} +1 -1
  22. package/dist/{chunk-JRIEP4BY.js → chunk-TVCJKE2U.js} +1 -1
  23. package/dist/chunk-U5WVR74V.js +1 -0
  24. package/dist/{chunk-5YNZR74I.js → chunk-UDXFUASA.js} +1 -1
  25. package/dist/chunk-UIBBSKJ3.js +94 -0
  26. package/dist/chunk-VYDURWN7.js +1 -0
  27. package/dist/chunk-WRQWVSBJ.js +3 -0
  28. package/dist/chunk-YUGKQ44M.js +1 -0
  29. package/dist/chunk-Z5L2IK54.js +2 -0
  30. package/dist/{create-TPUFKW6B.js → create-2VELRQAX.js} +1 -1
  31. package/dist/{doctor-MAPZ2ZCD.js → doctor-LDZ7BIU3.js} +1 -1
  32. package/dist/{goal-lifecycle-BNLXDHED.js → goal-lifecycle-HAWBRYDF.js} +1 -1
  33. package/dist/{goal-pack-2PF775AU.js → goal-pack-HNQHQFRW.js} +1 -1
  34. package/dist/index.js +170 -170
  35. package/dist/{pipeline-BY2YL7C6.js → pipeline-TWHWU6GP.js} +1 -1
  36. package/dist/{project-agent-entry-VXCOXRJB.js → project-agent-entry-YFRLKNOB.js} +1 -1
  37. package/dist/{project-intelligence-lens-BA6JLXQH.js → project-intelligence-lens-VWBLAGQ7.js} +1 -1
  38. package/dist/{verified-goal-5OV4BALK.js → verified-goal-Y4NTKSWH.js} +1 -1
  39. package/dist/{workspace-J4OGSSNO.js → workspace-XWKEBPS3.js} +1 -1
  40. package/dist/{workspace-agent-sync-MU7W3C4S.js → workspace-agent-sync-FQU6VIEU.js} +1 -1
  41. package/dist/{workspace-context-MDACPLHD.js → workspace-context-DPDGFTWJ.js} +1 -1
  42. package/dist/workspace-explain-OU2PEVYO.js +1 -0
  43. package/dist/{workspace-explain-contract-JWFM22L4.js → workspace-explain-contract-V2IVSROX.js} +1 -1
  44. package/dist/{workspace-foundation-3X5OBEMM.js → workspace-foundation-MHKSQDKT.js} +1 -1
  45. package/dist/{workspace-intelligence-runner-DEW3CZKA.js → workspace-intelligence-runner-YQWX5VAM.js} +1 -1
  46. package/dist/{workspace-mcp-serve-S5IXSJJL.js → workspace-mcp-serve-PYKYJIE6.js} +1 -1
  47. package/dist/{workspace-onboarding-LK5IK6LE.js → workspace-onboarding-DRFJWRLH.js} +1 -1
  48. package/dist/{workspace-readme-56YZ4EAZ.js → workspace-readme-G7TZ3V5T.js} +1 -1
  49. package/dist/workspace-repair-engine-XZLHR27V.js +3 -0
  50. package/dist/workspace-run-YXI5L466.js +1 -0
  51. package/docs/agent-entry.md +32 -2
  52. package/docs/ci-workflows.md +1 -1
  53. package/package.json +1 -1
  54. package/dist/autopilot-release-7Q5JT7YN.js +0 -1
  55. package/dist/chunk-7DSYI7YN.js +0 -3
  56. package/dist/chunk-ASOFWN6J.js +0 -1
  57. package/dist/chunk-BQCGULHR.js +0 -1
  58. package/dist/chunk-PVXSIYLP.js +0 -1
  59. package/dist/chunk-RALI2ESF.js +0 -49
  60. package/dist/chunk-VDFHUYAQ.js +0 -91
  61. package/dist/chunk-ZJ62F4U3.js +0 -2
  62. package/dist/workspace-explain-NWP3JTFR.js +0 -1
  63. package/dist/workspace-repair-engine-3OLRNXD6.js +0 -3
  64. package/dist/workspace-run-JTEIX4WA.js +0 -1
  65. /package/dist/{chunk-JMFCMPWI.js → chunk-QA62UOE4.js} +0 -0
@@ -0,0 +1 @@
1
+ import {h as h$1}from'./chunk-NZ3WZYD5.js';import o from'path';var h=h$1.artifactRemediationPlan.schemaVersion;function c(t){return t.replace(/\\/g,"/")}function P(t,r){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||r}function p(t,r){let e=c(o.relative(t,r));return !e||e.startsWith("..")?true:e.split("/").filter(Boolean).some(a=>a==="..")}function A(t){let r=c(o.relative(t.workspacePath,t.projectPath)),e=p(t.workspacePath,t.projectPath),a=P(t.projectName,o.basename(t.projectPath)),n=e?`external/${a}`:r||a;return {relativePath:r||n,contractRelativePath:n,isExternal:e}}export{h as a,A as b};
@@ -0,0 +1,3 @@
1
+ import {a as a$1,b as b$1}from'./chunk-VYDURWN7.js';import {b as b$2}from'./chunk-AO2ZI42U.js';import {a,e,b}from'./chunk-CCDGHPEJ.js';import {i,h as h$1}from'./chunk-NZ3WZYD5.js';import h from'path';import {existsSync}from'fs';import X from'fs-extra';var Y=[{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 g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function w(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0):[]}function I(e){return [...new Set(e.map(r=>r.trim()).filter(Boolean))]}function V(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 ee(e){let r=V(e.incoming)>V(e.existing),o=structuredClone(r?e.incoming:e.existing),i=r?e.existing:e.incoming,t=i.sourceStepId;return o.order=e.existing.order,o.files=I([...o.files,...i.files]),o.notes=I([...o.notes,...i.notes.filter(a=>!a.startsWith("Source Doctor capability:")&&!a.startsWith("Doctor finding status:")),...t?[`Also satisfies Doctor capability: ${t}`]:[]]),o}function te(e,r,o){return o?r:h.relative(e,r).split(h.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 r=h.isAbsolute(e.filePath)?h.resolve(e.filePath):h.resolve(e.projectPath,e.filePath);if(e.includeAbsolutePaths)return r;let o=h.relative(e.projectPath,r);return !o||o===".."||o.startsWith(`..${h.sep}`)||h.isAbsolute(o)?void 0:`${D(e)}/${o.split(h.sep).join("/")}`}function re(e){let r=e?.trim()||"npx workspai bootstrap";if(!/(?:^|\s)--ci(?:\s|$)/.test(r)&&/(?:^|\s)--json(?:\s|$)/.test(r))return r.replace(/(?:^|\s)--json(?:\s|$)/,i=>{let t=i.startsWith(" ")?" ":"",a=i.endsWith(" ")?" ":"";return `${t}--ci --json${a}`}).trim();let o=/(?:^|\s)--ci(?:\s|$)/.test(r)?r:`${r} --ci`;return /(?:^|\s)--json(?:\s|$)/.test(o)?o:`${o} --json`}function q(e,r){return h.basename(e).toLowerCase().replace(/\.cmd$/,"")==="npx"&&r[0]==="workspai"&&!r.includes("--no-install")?["--no-install",...r]:r}function oe(e){return `${JSON.stringify({schemaVersion:h$1.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 ie(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 ae(e){let r=e.payload,o=w(r.blockers),i=w(r.blockingReasons),t=w(r.failures),a=w(r.reasons),d=w(r.policyViolations),s=g(r.summary),f=w(s?.blockers);if(e.artifactKind==="analyze"){let c=(Array.isArray(r.findings)?r.findings:[]).map(y=>g(y)).filter(y=>!!y).map(y=>String(y.message??y.title??y.id??"").trim()).filter(Boolean);return I([...o,...c,...i])}if(e.artifactKind==="workspace-run"){let b=g(r.stages),c=Object.entries(b??{}).flatMap(([y,m])=>{let n=g(m);return (Array.isArray(n?.projects)?n.projects:[]).map(p=>g(p)).filter(p=>!!p).filter(p=>p.status==="failed"||p.ok===false).map(p=>`${y}: ${String(p.project??p.name??"project")} failed`)});return I([...o,...c,...i])}return I([...o,...i,...t,...a,...d,...f])}function j(e){let r=e.findingId?.trim()||e.sourceStepId?.trim()||e.id,o=e.findingStatus??"blocking",i=e.causalKey?.trim()||[e.cardId,e.projectName??e.scope??"workspace",r].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:r,findingStatus:o,causalKey:i,...e.dependsOn?{dependsOn:e.dependsOn}:{},...e.strategy?{strategy:structuredClone(e.strategy)}:{},...e.transaction?{transaction:structuredClone(e.transaction)}:{},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 ne(e){return (Array.isArray(e.report.payload.steps)?e.report.payload.steps:[]).flatMap((o,i)=>{let t=g(o),a=typeof t?.id=="string"?t.id.trim():"",d=typeof t?.projectName=="string"?t.projectName.trim():"",s=typeof t?.projectPath=="string"?t.projectPath.trim():"",f=typeof t?.originalCommand=="string"?t.originalCommand.trim():"";if(!t||!a||!d||!s)return [];let b=g(t.studioStatus),c=b?.state==="ready"||b?.state==="review-required"||b?.state==="blocked"||b?.state==="guidance-only"?b.state:"guidance-only",y=t.risk==="safe"||t.risk==="guarded"||t.risk==="invasive"?t.risk:"guarded",m=g(t.preview),n=D({workspacePath:e.workspacePath,projectPath:s,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}),u=J({capability:{...t,command:f},absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),p=U({capability:t,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),P=M({operation:t.operation,absoluteProjectPath:s}),k=t.findingStatus==="blocking"||t.findingStatus==="advisory"||t.findingStatus==="informational"?t.findingStatus:"unknown",l=typeof t.diagnosisFindingId=="string"&&t.diagnosisFindingId.trim()?t.diagnosisFindingId.trim():typeof t.issueId=="string"&&t.issueId.trim()?t.issueId.trim():a,A=typeof t.causalKey=="string"&&t.causalKey.trim()?t.causalKey.trim():void 0,S=t.executableInCurrentEnvironment===true&&!!u,$=H({strategy:t.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),R=g(t.transaction),x=R?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(R):void 0;return x&&(x.projectPath=n),[j({id:`doctor.${a}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof m?.title=="string"&&m.title.trim()?m.title.trim():`Repair ${d}`,order:e.startOrder+i,phase:typeof t.phase=="string"?t.phase:"doctor-remediation",blocker:typeof m?.summary=="string"&&m.summary.trim()?m.summary.trim():`Doctor remediation is pending for ${d}.`,summary:typeof m?.summary=="string"&&m.summary.trim()?m.summary.trim():`Execute the CLI-authored Doctor step for ${d}.`,mode:S?"run-command":"manual-guidance",risk:y,status:c,...S&&u?{command:u}:{},...S&&p?{invocation:p}:{},...P?{operation:P}:{},verifyCommand:typeof t.verifyCommand=="string"&&t.verifyCommand.trim()?t.verifyCommand.trim():"npx workspai doctor project --json",files:w(t.files).map(v=>z({workspacePath:e.workspacePath,projectPath:s,projectName:d,filePath:v,includeAbsolutePaths:e.includeAbsolutePaths})).filter(v=>!!v),notes:[`Source Doctor step: ${a}`,`Doctor finding id: ${l}`,`Doctor finding status: ${k}`,...typeof b?.reason=="string"?[b.reason]:[]],scope:"project",projectName:d,projectPath:n,sourceStepId:a,findingId:l,findingStatus:k,causalKey:A,dependsOn:w(t.dependsOn).map(v=>`doctor.${v}`),strategy:$,transaction:x,cwd:"project",...g(t.rollback)?.available===true?{rollback:{available:true,strategy:"manual"}}:{}})]})}function J(e){let r=typeof e.capability.command=="string"?e.capability.command.trim():"";if(e.includeAbsolutePaths&&r)return r;let o=M({operation:e.capability.operation,absoluteProjectPath:e.absoluteProjectPath});if(o)return b$2(o);let i=g(e.capability.invocation),t=typeof i?.executable=="string"?i.executable.trim():"",a=q(t,w(i?.args));if(t)return [t,...a].map(s=>/^[a-zA-Z0-9_./:@=+-]+$/.test(s)?s:JSON.stringify(s)).join(" ");if(!r)return;let d=e.absoluteProjectPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return r.replace(new RegExp(`^cd\\s+["']?${d}["']?\\s*&&\\s*`,"i"),"").replaceAll(e.absoluteProjectPath,".")}function U(e){let r=g(e.capability.invocation),o=typeof r?.executable=="string"?r.executable.trim():"",i=w(r?.args);if(!(!o||i.length!==(Array.isArray(r?.args)?r.args.length:0)))return {cwd:e.includeAbsolutePaths?e.absoluteProjectPath:".",executable:o,args:q(o,i)}}function M(e){let r=g(e.operation);if(!r||typeof r.type!="string")return;let o=structuredClone(r);for(let i of ["path","sourcePath"]){let t=o[i];if(typeof t!="string")continue;let a=h.isAbsolute(t)?h.relative(e.absoluteProjectPath,t):t;if(!a||a===".."||a.startsWith(`..${h.sep}`)||h.isAbsolute(a))return;o[i]=a.split(h.sep).join("/");}return o}function H(e){if(!Array.isArray(e.strategy))return;let r=structuredClone(e.strategy);if(!e.includeAbsolutePaths)for(let o of r)o.invocation&&(o.invocation.cwd=".");return r}function se(e){let r=Array.isArray(e.report.payload.projects)?e.report.payload.projects:e.report.payload.project?[e.report.payload.project]:[],o=new Set,i=[];for(let t of r){let a=g(t);if(!a)continue;let d=typeof a.name=="string"?a.name.trim():"",s=typeof a.path=="string"?a.path.trim():"";if(!d||!s)continue;let f=Array.isArray(a.repairCapabilities)?a.repairCapabilities:Array.isArray(a.probes)?a.probes.map(m=>g(m)?.repairCapability).filter(m=>m!==void 0):[],b=new Map,c=new Map,y=g(a.diagnosis);for(let m of Array.isArray(y?.findings)?y.findings:[]){let n=g(m),u=g(n?.repair),p=typeof u?.capabilityId=="string"?u.capabilityId.trim():"",P=typeof n?.id=="string"?n.id.trim():"",k=typeof n?.causalKey=="string"?n.causalKey.trim():"",l=n?.status==="blocking"||n?.status==="advisory"||n?.status==="informational"||n?.status==="unknown"?n.status:"unknown";p&&P&&k&&c.set(p,{findingId:P,causalKey:k,findingStatus:l});}for(let m of Array.isArray(a.probes)?a.probes:[]){let n=g(m),u=g(n?.repairCapability),p=typeof u?.id=="string"?u.id.trim():"";p&&b.set(p,n?.status==="fail"?"blocking":"advisory");}for(let m of f){let n=g(m),u=typeof n?.id=="string"?n.id.trim():"";if(!n||!u)continue;let p=`${d}:${u}`;if(o.has(p))continue;o.add(p);let P=n.risk==="safe"||n.risk==="guarded"||n.risk==="invasive"?n.risk:"guarded",k=J({capability:n,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),l=U({capability:n,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),A=M({operation:n.operation,absoluteProjectPath:s}),S=n.status==="available"&&!!k,$=g(n.transaction),R=$?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone($):void 0,x=c.get(u),v=x?.findingStatus??b.get(u)??(R?"blocking":"advisory");R&&(R.projectPath=D({workspacePath:e.workspacePath,projectPath:s,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}));let Z=H({strategy:n.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),G=w(n.files).map(C=>z({workspacePath:e.workspacePath,projectPath:s,projectName:d,filePath:C,includeAbsolutePaths:e.includeAbsolutePaths})).filter(C=>!!C),E=j({id:`doctor.${d}.${u}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof n.title=="string"&&n.title.trim()?n.title.trim():`Repair ${d}`,order:e.startOrder+i.length,phase:R?"dependency-remediation":"doctor-remediation",blocker:typeof n.reason=="string"&&n.reason.trim()?n.reason.trim():`Doctor remediation is pending for ${d}.`,summary:typeof n.reason=="string"&&n.reason.trim()?n.reason.trim():`Execute the Doctor-authored repair capability for ${d}.`,mode:S?n.canEditFiles===true?"edit-file":"run-command":"manual-guidance",risk:P,status:S?"ready":n.status==="manual"?"guidance-only":"blocked",...k?{command:k}:{},...l?{invocation:l}:{},verifyCommand:typeof n.verifyCommand=="string"&&n.verifyCommand.trim()?n.verifyCommand.trim():"npx workspai doctor project --json",files:G,notes:[`Source Doctor capability: ${u}`,`Doctor finding status: ${v}`,...w(n.limitations)],scope:"project",projectName:d,projectPath:D({workspacePath:e.workspacePath,projectPath:s,projectName:d,includeAbsolutePaths:e.includeAbsolutePaths}),sourceStepId:u,findingId:x?.findingId??(typeof n.issueId=="string"&&n.issueId.trim()?n.issueId.trim():u),findingStatus:v,causalKey:x?.causalKey,strategy:Z,transaction:R,cwd:"project",...A?{operation:A,rollback:{available:true,strategy:"manual"}}:{}}),O=k?i.findIndex(C=>C.projectName===d&&C.command===k&&C.cwd==="project"):-1;if(O>=0){i[O]=ee({existing:i[O],incoming:E});continue}i.push(E);}}return i}function ce(e){let r=[],o=re("npx workspai bootstrap --json");for(let i$1 of e.blockers)i$1.includes("profile.enterprise.ci")&&r.push(j({id:"bootstrap.enterprise-ci",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Run bootstrap in deterministic CI mode",order:10,phase:"bootstrap-preflight",blocker:i$1,summary:"Enterprise bootstrap compliance requires --ci for deterministic execution.",mode:"run-command",risk:"safe",command:o,verifyCommand:o})),i$1.includes("profile.enterprise.compatibility-matrix")&&r.push(j({id:"bootstrap.compatibility-matrix",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise compatibility matrix baseline",order:20,phase:"bootstrap-config",blocker:i$1,summary:"Create the missing compatibility matrix baseline without overwriting user data.",mode:"edit-file",risk:"safe",verifyCommand:o,files:[i.compatibilityMatrix],operation:{type:"file-create",path:i.compatibilityMatrix,content:oe(e.generatedAt),overwrite:false}})),i$1.includes("profile.enterprise.mirror-config")&&r.push(j({id:"bootstrap.mirror-config",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise mirror config baseline",order:30,phase:"bootstrap-config",blocker:i$1,summary:"Create the missing mirror configuration baseline without enabling mirroring.",mode:"edit-file",risk:"safe",verifyCommand:o,files:[".workspai/mirror-config.json"],operation:{type:"file-create",path:".workspai/mirror-config.json",content:ie(e.generatedAt),overwrite:false}}));return r}function de(e){let r=Array.isArray(e.report.payload.steps)?e.report.payload.steps:[],o=[],i=new Map;for(let t of r){let a=g(t),d=g(a?.command),s=typeof a?.id=="string"?a.id.trim():"",f=typeof a?.project=="string"?a.project.trim():"",b=typeof a?.status=="string"?a.status:"",c=typeof d?.display=="string"?d.display.trim():"",y=a?.required===true;if(!s.startsWith("project.")||!f||!y||b!=="fail"&&b!=="missing"||!/^npx\s+workspai\s+workspace\s+run\s+/i.test(c))continue;let m=s.split(".").at(-1)??"stage",n=`workspaceVerify.${s}`,u=i.get(f),p=/(?:^|\s)--no-gates(?:\s|$)/.test(c)?c:`${c} --no-gates`;o.push(j({id:n,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof a.label=="string"&&a.label.trim()?a.label.trim():`Run ${m} for ${f}`,order:e.startOrder+o.length,phase:"fleet-run",blocker:typeof a.message=="string"&&a.message.trim()?a.message.trim():`${m} evidence is not current for ${f}.`,summary:`Produce fresh ${m} evidence for ${f} without re-entering the blocked aggregate gates.`,mode:"run-command",risk:m==="start"?"guarded":"safe",status:"ready",command:p,verifyCommand:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",scope:"project",projectName:f,projectPath:f,sourceStepId:s,...u?{dependsOn:[u]}:{},cwd:"workspace",notes:[`Source Workspace Verify step: ${s}`,"Aggregate verification must run only after this project evidence producer completes."]})),i.set(f,n);}return o}function le(e){let r=I(e.blockers.flatMap(i=>{let t=i.match(/(?:project runtimes?|workspace)\s*\(([^)]+)\)\s+(?:is|are) not pinned/i);return t?.[1]?t[1].split(",").map(a=>a.trim().toLowerCase()).filter(a=>/^(python|node|go|java|dotnet|rust|php)$/.test(a)):[]})),o=[];for(let i of r){let t=`readiness.toolchain.${i}.setup`,a=e.blockers.find(d=>d.toLowerCase().includes(`(${i})`))??`The ${i} runtime is not pinned in the canonical workspace toolchain.`;o.push(j({id:t,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Pin ${i} in the workspace toolchain`,order:e.startOrder+o.length,phase:"toolchain-reconciliation",blocker:a,summary:`Detect and persist the current ${i} runtime in the canonical workspace toolchain lock.`,mode:"run-command",risk:"safe",command:`npx workspai setup ${i} --json`,verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Run from the workspace root so the canonical toolchain.lock is updated."]})),o.push(j({id:`readiness.toolchain.${i}.bootstrap`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Reconcile the ${i} workspace foundation`,order:e.startOrder+o.length,phase:"toolchain-reconciliation",blocker:`The ${i} 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",command:"npx workspai bootstrap --ci --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:[t]}));}return o}function pe(e){if(e.report.artifactKind==="readiness"&&/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(e.blocker))return j({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 o={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 j({id:`${e.report.cardId}.refresh.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:o.title,order:e.order,phase:o.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:o.command,verifyCommand:o.verify,notes:e.report.artifactKind==="doctor-workspace"?["Read doctor-remediation-plan-last-run.json for ordered file-level steps."]:[]})}async function fe(e){let r=[a(e,".workspai/reports"),b(e,".workspai/reports")],o=[],i=new Set;for(let t of Y)for(let a of t.fileNames){let d=(await Promise.all(r.map(s=>h.join(s,a)))).find(s=>existsSync(s));if(!(!d||i.has(`${t.artifactKind}:${a}`))){i.add(`${t.artifactKind}:${a}`);try{let s=await X.readJSON(d),f=g(s);if(!f)continue;o.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:a,absolutePath:d,payload:f});break}catch{o.push({artifactKind:t.artifactKind,cardId:t.cardId,fileName:a,absolutePath:d,payload:{blockers:[`${t.artifactKind}: report exists but could not be parsed.`]}});break}}}return o}async function Pe(e){let r=h.resolve(e.workspacePath),o=e.includeAbsolutePaths===true,i=e.ciMode===true,t=new Date().toISOString(),a$2=a(r,".workspai/reports"),d=await fe(r),s=[],f=1;for(let c of d){if(c.artifactKind==="doctor-workspace"){let l=Array.isArray(c.payload.steps)?ne({report:c,workspacePath:r,includeAbsolutePaths:o,startOrder:f}):se({report:c,workspacePath:r,includeAbsolutePaths:o,startOrder:f});s.push(...l),f+=l.length;continue}let y=ae(c);if(y.length===0)continue;if(c.artifactKind==="bootstrap-compliance"){s.push(...ce({blockers:y,generatedAt:t})),f=s.length+1;continue}if(c.artifactKind==="workspace-verify"){let l=de({report:c,startOrder:f,ciMode:i});if(l.length>0){s.push(...l),f+=l.length;continue}}if(c.artifactKind==="readiness"){let l=le({report:c,blockers:y,startOrder:f,ciMode:i});if(l.length>0){s.push(...l),f+=l.length;continue}}let m=s.some(l=>l.transaction?.kind==="dependency-security"),n=c.artifactKind==="readiness"&&y.some(l=>/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(l));if(m&&n)continue;let u=y[0],p=pe({report:c,blocker:u,order:f,ciMode:i}),k={readiness:new Set(["bootstrap","doctor"]),pipeline:new Set(["bootstrap","doctor","analyze","readiness"]),workspaceVerify:new Set(["bootstrap","doctor","readiness","workspaceRun"])}[c.cardId];if(c.cardId==="pipeline"){let l=["doctor","analyze","readiness"].find(A=>u.toLowerCase().includes(A));l&&(k=new Set([l]));}if(k){let l=s.filter(A=>k.has(A.cardId)&&A.risk!=="invasive"&&A.status!=="blocked"&&A.status!=="guidance-only").map(A=>A.id);l.length>0&&(p.dependsOn=I([...p.dependsOn??[],...l]),p.notes.push("This aggregate gate must run after its contract-owned upstream remediation actions."));}y.length>1&&p.notes.push(...y.slice(1,8).map(l=>`Related blocker: ${l}`)),s.push(p),f+=1;}let b={safe:s.filter(c=>c.risk==="safe").length,guarded:s.filter(c=>c.risk==="guarded").length,invasive:s.filter(c=>c.risk==="invasive").length};return {schemaVersion:a$1,generatedAt:t,workspace:{name:h.basename(r),...o?{path:r}:{}},source:{command:"workspace remediation-plan",reportsDir:te(r,a$2,o),includeAbsolutePaths:o,ciMode:i},summary:{artifactsScanned:d.length,cardsCovered:I(s.map(c=>c.cardId)).length,totalActions:s.length,executableActions:s.filter(c=>c.status==="ready").length,risk:b},actions:s}}async function Re(e$1,r){return e(r,i.artifactRemediationPlan,e$1)}export{Pe as a,Re as b};
@@ -0,0 +1 @@
1
+ import {i,e}from'./chunk-NZ3WZYD5.js';var _=".workspai/skills";var a=e.skillsIndex,c=e.explain,P=i.workspaceWhy,O=i.workspaceTrace,I=".workspai/AGENT-GROUNDING.md",A=".rapidkit/AGENT-GROUNDING.md",R=".cursor/rules/workspai-grounding.mdc",E=".cursor/rules/workspai-evidence.mdc",T=".cursor/rules/workspai-diagnose.mdc",L=".cursor/rules/workspai-repair.mdc",S=".cursor/rules/workspai-release.mdc",d=".cursor/rules/rapidkit-grounding.mdc",k=".windsurfrules",C=".windsurf/rules/workspai-grounding.md",u=".windsurf/rules/workspai-evidence.md",N=".grok/rules/workspai-grounding.md",l=".grok/rules/workspai-evidence.md",K=".claude/rules/workspai-evidence.md",m=".claude/rules/workspai-workspace.md",g=".claude/rules/rapidkit-evidence.md",G=".amazonq/rules/workspai-workspace.md",x=".github/instructions/workspai-workspace.instructions.md",w=".github/instructions/rapidkit-workspace.instructions.md",H=".github/instructions/workspai-evidence.instructions.md",D=".github/instructions/rapidkit-evidence.instructions.md",U=".github/prompts/workspai-diagnose.prompt.md",W=".github/prompts/rapidkit-diagnose.prompt.md",h=".github/prompts/workspai-repair.prompt.md",b=".github/prompts/rapidkit-repair.prompt.md",M=".github/prompts/workspai-release-readiness.prompt.md",Y=".github/prompts/rapidkit-release-readiness.prompt.md",f=".github/prompts/workspai-project-onboard.prompt.md",v=".github/prompts/rapidkit-project-onboard.prompt.md",B=".github/prompts/workspai-adopt-project.prompt.md",V=".github/prompts/rapidkit-adopt-project.prompt.md",y=".github/skills/workspai-grounding/SKILL.md",F=".github/skills/rapidkit-grounding/SKILL.md",j=".github/skills/workspai-workspace-intelligence/SKILL.md",J=".github/skills/rapidkit-workspace-intelligence/SKILL.md",X=".cursor/skills/workspai-grounding/SKILL.md",$=".claude/skills/workspai-grounding/SKILL.md",z=".agents/skills/workspai-grounding/SKILL.md",q=".grok/skills/workspai-grounding/SKILL.md",Q=i.workspaiMcpDesign,Z=i.legacyMcpDesign,ss=i.agentHooks,os=".vscode/rapidkit-agent-hooks.json";var n=["workspai-diagnose-api-failure","workspai-release-readiness","workspai-safe-schema-migration","workspai-dependency-upgrade","workspai-rename-contract"];function ts(o){let t=o.trim();if(!t||t.includes("..")||t.includes("/"))throw new Error(`Invalid operational skill id: ${o}`);return `${_}/${t}.md`}function rs(o){return n.includes(o)}var _s={"workspai-diagnose-api-failure":"workspai-diagnose","workspai-release-readiness":"workspai-release-readiness","workspai-safe-schema-migration":"workspai-safe-schema-migration","workspai-dependency-upgrade":"workspai-dependency-upgrade","workspai-rename-contract":"workspai-rename-contract"};export{U as A,W as B,h as C,b as D,M as E,Y as F,f as G,v as H,B as I,V as J,y as K,F as L,j as M,J as N,X as O,$ as P,z as Q,q as R,Q as S,Z as T,ss as U,os as V,ts as W,rs as X,_s as Y,_ as a,a as b,c,P as d,O as e,I as f,A as g,R as h,E as i,T as j,L as k,S as l,d as m,k as n,C as o,u as p,N as q,l as r,K as s,m as t,g as u,G as v,x as w,w as x,H as y,D as z};
@@ -0,0 +1,2 @@
1
+ import {l}from'./chunk-J5OMC4RZ.js';import {b as b$1}from'./chunk-GPOZILMY.js';import {a as a$1}from'./chunk-A4BK7C7M.js';import {c}from'./chunk-EWZZUQBR.js';import {b as b$2}from'./chunk-D65FCQIO.js';import {a}from'./chunk-AFIFZTOY.js';import {h,i,e}from'./chunk-NZ3WZYD5.js';import he from'crypto';import O from'fs';import M from'fs/promises';import m from'path';var te=h.projectAgentEntry.schemaVersion,b=i.projectAgentEntry,me="workspai.agent-bootstrap-receipt.v1",_e="<!-- WORKSPAI:AGENT-ENTRY:START -->",Ne="<!-- WORKSPAI:AGENT-ENTRY:END -->",G=["generic","codex","claude","gemini","qwen","kimi","grok","copilot","cursor","windsurf","amazon-q"],He=["CLAUDE.md","GEMINI.md","QWEN.md",".amazonq/rules/workspai-agent-entry.md"];function fe(t){let r=t?.trim().toLowerCase()||"generic";if(r==="orca")return "grok";if(G.includes(r))return r;throw new Error(`Unsupported agent host "${r}". Expected one of: ${G.join(", ")}.`)}function oe(t){let r=t.map(i=>i.id).sort(),n=[...G].sort();if(r.length!==n.length||r.some((i,c)=>i!==n[c]))throw new Error("Project agent entry must define each supported host exactly once.")}function L(t){let{integrity:r,...n}=t;return n}function E(t){return c(t)}function Oe(t){oe(t.hosts);let r={schemaVersion:te,generatedAt:t.context.generatedAt,project:{name:t.context.project.name,relativePath:t.context.project.relativePath,...t.context.project.runtime?{runtime:t.context.project.runtime}:{},...t.context.project.framework?{framework:t.context.project.framework}:{}},workspace:{name:t.context.workspace.name,relationship:t.context.workspace.relationship,localBinding:i.projectWorkspaceLink,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},canonical:{projectContext:i.projectContextAgent,projectGrounding:".workspai/PROJECT-GROUNDING.md",goalIndex:`workspace:${i.goalIndex}`,workspaceIndex:`workspace:${e.agentIndex}`,workspaceContext:`workspace:${e.agentContext}`,workspaceSkillsIndex:`workspace:${e.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json"},protocol:{mode:"canonical-first",bootstrapCommand:"workspai agent bootstrap --for-agent generic --strict --json",verifyCommand:"workspai project agent-entry verify --for-agent all --strict --json",requiredReadOrder:[b,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",i.projectContextAgent,`workspace:${i.goalIndex}`,`workspace:${e.agentIndex}`,`workspace:${e.agentContext}`,`workspace:${e.skillsIndex}`,"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json","source:targeted-live-files"],sourcePolicy:{liveSourceAuthority:"exact-implementation",workspaceEvidenceAuthority:"identity-topology-readiness-goals",broadScanBeforeBootstrap:false,sourceMutation:"governed-only",verificationClaims:"cli-evidence-only"},degradedMode:{discloseMissingEvidence:true,allowCompleteArchitectureClaims:false,allowReadOnlySourceInspection:true}},hosts:[...t.hosts].sort((i,c)=>i.id.localeCompare(c.id))},n={...r,integrity:{algorithm:"sha256",projectContextHash:t.context.integrity.payloadHash,payloadHash:E(r),portable:true,absolutePathsEmitted:false}};if(!k(n))throw new Error("Project agent entry rejected a non-portable local path.");return a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n}function k(t){return typeof t=="string"?!(/^[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(t)||/(?:^|[\s("'`])file:\/\//i.test(t)||/(?:^|[\s("'`])\\\\[^\\\s]+[\\]/.test(t)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(t)):Array.isArray(t)?t.every(k):t&&typeof t=="object"?Object.values(t).every(k):true}async function ue(t){let r=m.join(t,b),n=JSON.parse(await M.readFile(r,"utf8"));if(a(n,"contracts/workspace-intelligence/project-agent-entry.v1.json","Project agent entry"),n.integrity.payloadHash!==E(L(n)))throw new Error("Project agent entry integrity validation failed.");if(oe(n.hosts),!k(n)||n.integrity.absolutePathsEmitted)throw new Error("Project agent entry contains a non-portable local path.");return n}async function ye(t){let r=m.join(t,i.projectContextAgent),n=JSON.parse(await M.readFile(r,"utf8"));a(n,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent");let i$1=L(n),c=he.createHash("sha256").update(JSON.stringify(i$1)).digest("hex");if(n.integrity.payloadHash!==c)throw new Error("Project context agent integrity validation failed.");if(!k(n)||n.integrity.absolutePathsEmitted)throw new Error("Project context agent contains a non-portable local path.");return n}function ke(t){return t.includes("blocked")?"blocked":t.includes("degraded")?"degraded":"ready"}async function Ge(t){let r=b$1({startPath:m.resolve(t.startPath??process.cwd()),strict:true,requireProjectMembership:true});if(!r?.projectPath)throw new Error("No canonically bound Workspai project was resolved.");let n=r.projectPath,i$1=r.workspacePath,c=await ue(n),o=await ye(n);if(c.integrity.projectContextHash!==o.integrity.payloadHash||c.project.name!==o.project.name||c.workspace.name!==o.workspace.name)throw new Error("Project agent entry is not bound to the current project context.");let $=t.forAgent?.trim().toLowerCase()||"generic",F=$==="all",g=F?"all":fe($),W=g,h=F?c.hosts:c.hosts.filter(e=>e.id===g),q=c.hosts.find(e=>e.id==="generic");if(h.length===0&&q&&h.push(q),h.length===0)throw new Error("Project agent entry does not define generic host coverage.");let w=[],p=(e,s,I,u)=>w.push({id:e,status:s,message:I,...u?{artifact:u}:{}});p("workspace-binding","passed","Canonical workspace membership is resolved."),p("entry-integrity","passed","Project entry manifest integrity is valid.",b),p("project-context-integrity","passed","Project context integrity and manifest binding are valid.",i.projectContextAgent);let R=[...new Set(h.flatMap(e=>e.entryFiles))].sort(),ne=R.filter(e=>!O.existsSync(m.join(n,e))),f=h.some(e=>e.status==="blocked")||ne.length>0?"blocked":h.some(e=>e.status==="degraded")?"degraded":"ready";p("host-discovery",f==="ready"?"passed":f==="degraded"?"warning":"failed",f==="ready"?`${g} has discoverable Workspai entry coverage.`:f==="degraded"?h.find(e=>e.reason)?.reason??`${g} entry coverage is degraded.`:`${g} entry coverage is missing required files.`,R[0]);let K=[e.agentIndex,e.agentContext,e.skillsIndex,e.model,e.knowledgeGraph],v=K.filter(e=>!O.existsSync(m.join(i$1,e)));p("canonical-evidence",v.length===0?"passed":"failed",v.length===0?"Required canonical workspace evidence is present.":`Required canonical evidence is missing: ${v.join(", ")}.`);let j=[],P=null,V=null;for(let e$1 of K)if(!v.includes(e$1))try{let s=JSON.parse(await M.readFile(m.join(i$1,e$1),"utf8"));b$2(e$1,s,e$1),e$1===e.model&&(P=s),e$1===e.knowledgeGraph&&(V=s);}catch{j.push(e$1);}p("canonical-contracts",j.length===0?"passed":"failed",j.length===0?"Canonical workspace evidence satisfies its published schemas.":`Canonical evidence failed contract validation: ${j.join(", ")}.`);let se=P?.workspace,re=V?.workspace,ae=Array.isArray(P?.projects)?P.projects:[],B=j.length===0&&se?.name===o.workspace.name&&re?.name===o.workspace.name&&ae.some(e=>e.name===o.project.name);p("canonical-project-membership",B?"passed":"failed",B?"The project and workspace identities agree across the entry, Model, and Graph.":"The project or workspace identity is missing or inconsistent in canonical evidence.");let J=!o.intelligence.freshness.graphMatchesModel||["missing","stale"].includes(o.intelligence.freshness.model)||["missing","stale"].includes(o.intelligence.freshness.graph)?"failed":o.intelligence.freshness.model==="unknown"||o.intelligence.freshness.graph==="unknown"?"warning":"passed",C=false,x;if(t.validateLiveInputs!==false)try{let e=await a$1(i$1);C=e.status==="hit";let s=e.status==="hit"?"Live project inputs match the persisted Model and Knowledge Graph snapshot.":`Live project inputs require an intelligence refresh (${e.reason}).`;x={id:"live-inputs",status:C?"passed":"failed",message:s};}catch{x={id:"live-inputs",status:"failed",message:"Live project inputs could not be validated against canonical graph evidence."};}else x={id:"live-inputs",status:"warning",message:"Live input validation was skipped; persisted compatibility was checked only."};let _=J==="warning"&&o.intelligence.freshness.model==="unknown"&&o.intelligence.freshness.graph==="fresh"&&o.intelligence.freshness.graphMatchesModel&&C?"passed":J;p("persisted-freshness",_,_==="passed"?o.intelligence.freshness.model==="unknown"?"Model and Graph bindings are current; live input validation closes structural freshness while verify-before-use facts remain individually governed.":"Persisted Model and Knowledge Graph bindings are current.":_==="warning"?"Persisted evidence is compatible, but at least one freshness state is unknown.":"Persisted Model or Knowledge Graph evidence is missing, stale, or mismatched."),w.push(x);let l$1={present:false,appliesToProject:false,status:"none"},T=[],ie=m.join(i$1,i.goalIndex);if(O.existsSync(ie)){let e=null;try{e=await l({workspacePath:i$1,validateBindings:false});}catch{T.push("workspai goal --list --json"),p("active-goal","failed","The Goal index is present but invalid.");}if(e?.active&&(l$1={present:true,appliesToProject:e.active.scope.projects.includes(o.project.name),status:"invalid",id:e.active.id,objective:e.active.objective,lifecycle:e.active.lifecycle,goalPack:`workspace:${e.active.goalPack}`,agentHandoff:`workspace:${e.active.agentHandoff}`}),e)try{let s=await l({workspacePath:i$1,validateBindings:true});s.active&&(l$1={present:true,appliesToProject:s.active.scope.projects.includes(o.project.name),status:"ready",id:s.active.id,objective:s.active.objective,lifecycle:s.active.lifecycle,goalPack:`workspace:${s.active.goalPack}`,agentHandoff:`workspace:${s.active.agentHandoff}`}),p("active-goal","passed",s.active?"The active Goal Pack and agent handoff have valid canonical bindings.":"No active Goal Pack is selected.");}catch(s){let I=s instanceof Error?s.message:String(s),u=l$1.present&&/\bstale\b|--refresh/i.test(I);if(l$1.present&&(l$1.status=u?"stale":"invalid"),u&&l$1.objective){let y=e.active,ge=y?.scope.kind==="project"&&y.scope.projects.length===1?`project:${y.scope.projects[0]}`:y?.scope.kind==="project-set"&&y.scope.projects.length>1?`projects:${y.scope.projects.join(",")}`:"workspace";T.push(`workspai goal ${JSON.stringify(l$1.objective)} --scope ${ge} --for-agent generic --refresh --json`);}else T.push("workspai goal --status --json");p("active-goal","failed",u?"The selected Goal Pack is present but stale; regenerate it against current canonical evidence before acting.":l$1.present?"The selected Goal Pack is present but its canonical binding or handoff is invalid.":"The Goal index could not be validated.");}}else p("active-goal","passed","No Goal index is present for this workspace.");let ce=w.some(e=>e.status==="failed")?"blocked":w.some(e=>e.status==="warning")?"degraded":"ready",S=ke([f,ce]),le=`command:workspai agent bootstrap --for-agent ${g} --strict --json`,pe=c.protocol.requiredReadOrder.map(e=>e==="command:workspai agent bootstrap --for-agent generic --strict --json"?le:e),U={schemaVersion:me,generatedAt:(t.now??new Date).toISOString(),status:S,requestedAgent:W,resolvedHost:g,project:{name:o.project.name,relativePath:o.project.relativePath,...o.project.runtime?{runtime:o.project.runtime}:{},...o.project.framework?{framework:o.project.framework}:{}},workspace:{name:o.workspace.name,relationship:o.workspace.relationship,resolved:true,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"},entry:{artifact:b,schemaVersion:te,hostStatus:f,entryFiles:R},canonicalEvidence:{projectContext:i.projectContextAgent,workspaceIndex:`workspace:${e.agentIndex}`,workspaceContext:`workspace:${e.agentContext}`,workspaceSkillsIndex:`workspace:${e.skillsIndex}`,boundedGraphSearch:"command:workspai workspace graph search <task-query> --scope project:<project> --limit 12 --json",modelFreshness:o.intelligence.freshness.model,graphFreshness:o.intelligence.freshness.graph,graphMatchesModel:o.intelligence.freshness.graphMatchesModel,liveInputsValidated:C,blockerCount:o.blockers.length},activeGoal:l$1,requiredReadOrder:pe,claims:{architecture:S==="ready"?"allowed-with-citations":"prohibited",sourceInspection:"bounded-and-targeted",sourceMutation:"governed-cli-transaction-only",verification:"cli-evidence-only"},checks:w,nextActions:S==="ready"?[...l$1.present&&l$1.appliesToProject&&l$1.agentHandoff?[`read:${l$1.agentHandoff}`]:[],`workspai workspace graph search <task-query> --scope project:${o.project.name} --limit 12 --json`,"inspect only the returned proof paths and target source files"]:[...T,"workspai workspace intelligence run --for-agent generic --strict --json",`workspai agent bootstrap --for-agent ${g} --strict --json`]},Y=E(L(c)),de=E({manifestHash:Y,projectContextHash:o.integrity.payloadHash,requestedAgent:W,status:S,generatedAt:U.generatedAt}),D={...U,receiptId:de},N={...D,integrity:{algorithm:"sha256",manifestHash:Y,projectContextHash:o.integrity.payloadHash,payloadHash:E(D),portable:true,absolutePathsEmitted:false}};if(!k(N))throw new Error("Agent bootstrap receipt rejected a non-portable local path.");return a(N,"contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json","Agent bootstrap receipt"),N}
2
+ export{te as a,b,me as c,_e as d,Ne as e,G as f,He as g,fe as h,Oe as i,Ge as j};
@@ -1 +1 @@
1
- export{c as PYTHON_FREE_WORKSPACE_PROFILES,a as buildWorkspaceManifest,f as createProject,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,b as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-5YNZR74I.js';
1
+ export{c as PYTHON_FREE_WORKSPACE_PROFILES,a as buildWorkspaceManifest,f as createProject,g as registerWorkspaceAtPath,d as resolvePythonFreeFallbackProfile,b as syncWorkspaceFoundationFiles,e as writeWorkspaceLauncher}from'./chunk-UDXFUASA.js';
@@ -1 +1 @@
1
- export{a as DOCTOR_WORKSPACE_REPORT_PATH,n as applyEnvKeyAddFix,j as applyFileAppendFix,k as applyFileCopyFix,i as applyFileCreateFix,m as applyJsonEditFix,o as applyMakefileTargetFix,h as applyPackageScriptFix,f as assertOperationPathInsideProject,g as assertOperationPathInsideProjectResolved,e as buildRepairOperationIdentity,q as computeDoctorFixAwareExitCode,p as computeDoctorGateExitCode,l as decodeJsonPointerSegment,d as parseInternalRepairCommand,c as parsePackageScriptFix,b as resolveDoctorPolicyProfile,r as runDoctor}from'./chunk-VDFHUYAQ.js';
1
+ export{a as DOCTOR_WORKSPACE_REPORT_PATH,n as applyEnvKeyAddFix,j as applyFileAppendFix,k as applyFileCopyFix,i as applyFileCreateFix,m as applyJsonEditFix,o as applyMakefileTargetFix,h as applyPackageScriptFix,f as assertOperationPathInsideProject,g as assertOperationPathInsideProjectResolved,e as buildRepairOperationIdentity,q as computeDoctorFixAwareExitCode,p as computeDoctorGateExitCode,l as decodeJsonPointerSegment,d as parseInternalRepairCommand,c as parsePackageScriptFix,b as resolveDoctorPolicyProfile,r as runDoctor}from'./chunk-UIBBSKJ3.js';
@@ -1 +1 @@
1
- export{f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,k as buildGoalLifecycleResult,l as inspectGoalLifecycle,p as linkGoalRepairTransaction,n as prepareGoalVerification,m as transitionGoalLifecycle,o as verifyGoalLifecycle}from'./chunk-YGONW6VG.js';
1
+ export{f as GOAL_INDEX_PATH,e as GOAL_INDEX_SCHEMA_VERSION,k as buildGoalLifecycleResult,l as inspectGoalLifecycle,p as linkGoalRepairTransaction,n as prepareGoalVerification,m as transitionGoalLifecycle,o as verifyGoalLifecycle}from'./chunk-J5OMC4RZ.js';
@@ -1 +1 @@
1
- import {c as c$5}from'./chunk-DIJGQUEV.js';import {c}from'./chunk-GWMC6SSY.js';import {j,i,d as d$1,f as f$2,c as c$3,e as e$1,h}from'./chunk-YGONW6VG.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-YGONW6VG.js';import {f as f$3}from'./chunk-4PUJVYRM.js';import {b}from'./chunk-GPOZILMY.js';import {a as a$1}from'./chunk-A4BK7C7M.js';import {c as c$4}from'./chunk-TFOOSYGO.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {c as c$2,f as f$1}from'./chunk-CCDGHPEJ.js';import {a}from'./chunk-AFIFZTOY.js';import {f,e}from'./chunk-NZ3WZYD5.js';import v from'path';import S from'fs-extra';var he=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/,fe=/(?:^|\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]+)/,be=/(?:-----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,we=[{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|memory|cpu|optimi[sz]e|faster|slower)\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|implement|introduce|support)\b/i]},{category:"system-understanding",patterns:[/\b(?:understand|explain|map|find|where|how|architecture|analy[sz]e|search)\b/i]}];function ke(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(he.test(t))throw new Error("Goal intent contains unsupported control characters.");if(fe.test(t))throw new Error("Goal intent contains a machine-local absolute path. Use a workspace-relative path or project scope.");if(be.test(t))throw new Error("Goal intent appears to contain secret material and was not persisted.");return t}function ve(e){let t=e.match(/\b(?:coverage\D{0,24})?(100|\d{1,2})(?:\.\d+)?\s*%/i);if(!t||!/coverage/i.test(e))return null;let o=Number(t[1]);return Number.isFinite(o)&&o>=0&&o<=100?o:null}var te=[{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 ye(e){return te.filter(t=>t.patterns.some(o=>o.test(e))).map(t=>t.runtime)}function $(e,t={}){let o=ke(e),r=we.filter(y=>y.patterns.some(k=>k.test(o))).map(y=>y.category),i=r[0]??"feature-change",l=ve(o),c=ye(o),p=c.length===0&&t.selectedCoverageRuntime?[t.selectedCoverageRuntime]:c,u=[...new Set((t.availableCoverageRuntimes??[]).filter(y=>te.some(k=>k.runtime===y)))].sort(),b=[];return r.length>1&&r[0]!=="test-coverage"&&b.push(`The intent also contains signals for: ${r.slice(1).join(", ")}.`),i==="test-coverage"&&l===null&&b.push("A numeric test coverage target is required for machine verification."),i==="test-coverage"&&p.length>1&&b.push(`The Goal names multiple coverage runtimes: ${p.join(", ")}. Select one runtime per Goal.`),i==="test-coverage"&&p.length===0&&u.length>1&&b.push(`Coverage scope is ambiguous across detected runtimes: ${u.join(", ")}. Name one runtime or language in the Goal.`),i==="test-coverage"&&p.length===1&&u.length>0&&!u.includes(p[0])&&b.push(`The requested ${p[0]} coverage runtime is not present in the selected scope. Detected runtimes: ${u.join(", ")}.`),{original:o,normalized:o.toLocaleLowerCase("en-US"),statement:o.replace(/[.!?]+$/,""),category:i,confidence:r.length===1?"high":r.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 re(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 oe="contracts/workspace-intelligence/goal-pack.v1.json",ne="contracts/workspace-intelligence/goal-agent-handoff.v1.json",Pe="contracts/workspace-intelligence/goal-plan-result.v1.json",ce="contracts/workspace-intelligence/goal-index.v1.json",le=new Set(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"]);function ae(e){return e.split(v.sep).join("/")}function V(e,t){return v.resolve(t.absolutePath??v.join(e,t.path))}function se(e){let t=e.requested.trim().replace(/^project:/,"");if(!t)throw new Error("Project goal scope must name a project.");let o=v.isAbsolute(t)?v.resolve(t):null,r=e.model.projects.filter(i=>i.name===t||ae(i.path)===ae(t)||o!==null&&V(e.workspacePath,i)===o);if(r.length!==1)throw new Error(r.length===0?`Project goal scope was not found in the canonical model: ${t}`:`Project goal scope is ambiguous in the canonical model: ${t}`);return r[0]}async function je(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:o,graph:r}=t;return a(o,"contracts/workspace-intelligence/workspace-model.v1.json","Goal source model"),a(r,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Goal source graph"),c$4(r,o),{model:o,graph:r}}function ie(e){let t=e.scope.trim();if(t==="workspace")return {kind:"workspace",projects:e.model.projects.map(r=>r.name).sort(),selectionSource:e.selectionSource,resolution:"selected"};let o=t.startsWith("projects:")?"projects:":t.startsWith("project:")&&t.slice(8).includes(",")?"project:":null;if(o){let r=t.slice(o.length).split(",").map(c=>c.trim()).filter(Boolean);if(r.length<2)throw new Error("A project-set Goal scope must name at least two projects.");let i=r.map(c=>se({workspacePath:e.workspacePath,model:e.model,requested:c})),l=[...new Set(i.map(c=>c.name))].sort();if(l.length!==r.length)throw new Error("A project-set Goal scope must not contain duplicate projects.");return {kind:"project-set",projects:l,selectionSource:e.selectionSource,resolution:"selected"}}if(t)return {kind:"project",projects:[se({workspacePath:e.workspacePath,model:e.model,requested:t}).name],selectionSource:e.selectionSource,resolution:"selected"};throw new Error("Goal scope cannot be empty.")}async function Ge(e){if(e.explicitScope?.trim())return {scope:ie({workspacePath:e.workspacePath,model:e.model,scope:e.explicitScope,selectionSource:"explicit"}),selectionRequired:false};if(e.invocationProjectPath){let t=v.resolve(e.invocationProjectPath),o=e.model.projects.filter(r=>V(e.workspacePath,r)===t);if(o.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:[o[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(r=>({name:r.name,runtime:r.runtime,runtimeCandidates:[...r.runtimeCandidates].sort(),framework:r.framework})).sort((r,i)=>r.name.localeCompare(i.name))}),o=t.kind==="workspace"?"workspace":t.projects.length===1?`project:${t.projects[0]}`:`projects:${t.projects.join(",")}`;return {scope:ie({workspacePath:e.workspacePath,model:e.model,scope:o,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 Ae(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 o=new Set(t.projects),r=e.entities.filter(u=>u.projectId!==void 0&&o.has(u.projectId)),i=new Set(r.map(u=>u.id)),l=e.relations.filter(u=>i.has(u.from)||i.has(u.to)),c=new Set([...r.flatMap(u=>u.proofIds),...l.flatMap(u=>u.proofIds)]),p=l.filter(u=>u.proofIds.length>0).length;return {entities:r.length,relationships:l.length,proofs:c.size,unresolved:l.length-p,proofCoveragePercent:l.length===0?100:Number((p/l.length*100).toFixed(2))}}async function Ce(e$1){let t=v.join(e$1.workspacePath,e.intelligenceRun),o=await S.readJson(t).catch(()=>null),i=(Array.isArray(o?.stages)?o.stages:[]).filter(n=>n.status==="blocked"||n.status==="failed").map(n=>String(n.id??"unknown")).sort(),l=o?.status,c={status:l==="passed"?"passed":l==="blocked"||l==="failed"?"blocked":"unknown",artifact:e.intelligenceRun,blockedStages:i},p={status:"not-applicable",runtime:null,runtimeChoices:[],runner:null,existingEvidence:[],prerequisites:[]};if(e$1.intent.category==="test-coverage"){let n=e$1.intent.requestedTarget?.runtime;if(e$1.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 ")))p={status:"requires-setup",runtime:n??null,runtimeChoices:e$1.coverageRuntimeChoices,runner:null,existingEvidence:[],prerequisites:["Select exactly one detected runtime or language for this coverage Goal."]};else {let P=n?e$1.projects.filter(a=>a.runtimeCandidates.includes(n)):e$1.projects,f=await Promise.all(P.map(async a=>({project:a,capability:await c$5(V(e$1.workspacePath,a),n??(le.has(a.runtime)?a.runtime:"unknown"))}))),s=f.map(a=>a.capability.status);p={status:s.includes("unsupported")?"unsupported":s.includes("requires-setup")?"requires-setup":"available",runtime:f.length===1?f[0].capability.runtime:[...new Set(f.map(a=>a.capability.runtime))].join(","),runtimeChoices:e$1.coverageRuntimeChoices,runner:f.length===1?f[0].capability.runner:[...new Set(f.flatMap(a=>a.capability.runner?[a.capability.runner]:[]))].join(",")||null,existingEvidence:f.flatMap(a=>a.capability.existingEvidence.map(g=>({project:a.project.name,...g}))).filter((a,g,L)=>L.findIndex(j=>j.project===a.project&&j.path===a.path&&j.sha256===a.sha256)===g).sort((a,g)=>a.project.localeCompare(g.project)||a.path.localeCompare(g.path)),prerequisites:[...new Set(f.flatMap(a=>a.capability.prerequisites))].sort()};}}let u=re(e$1.intent),b=u.map(n=>{let w=e$1.projects.map(s=>f$3(e$1.graph,{query:n,projectId:s.name,limit:20,relationsPerEntity:0,minimumTermMatches:2}).entities),P=[],f=new Set;for(let s=0;w.some(a=>s<a.length);s+=1)for(let a of w){let g=a[s];!g||f.has(g.id)||(f.add(g.id),P.push(g));}return P}),y={"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"]},k=new Set(e$1.projects.map(n=>n.name)),N=e$1.graph.entities.filter(n=>n.proofIds.length>0&&(!n.projectId||k.has(n.projectId))&&y[e$1.intent.category].includes(n.kind)).sort((n,w)=>y[e$1.intent.category].indexOf(n.kind)-y[e$1.intent.category].indexOf(w.kind)||n.label.localeCompare(w.label)),h=[],m=new Set,A=n=>{!n||h.length>=20||m.has(n.id)||(m.add(n.id),h.push(n));},C=(e$1.intent.statement.match(/[A-Za-z][A-Za-z0-9+#.-]{1,}/g)??[]).length>=2,x=C?b[0]??[]:[];for(let n of x.slice(0,12))A(n);if(!C)for(let n of N)A(n);for(let n=0;h.length<20&&b.slice(1).some(w=>n<w.length);n+=1)for(let w of b.slice(1))A(w[n]);if(C)for(let n of N)A(n);for(let n of x.slice(12))A(n);let d=h.map(n=>({entityId:n.id,kind:n.kind,label:n.label,proofIds:n.proofIds.slice(0,12)})),E=b[0]?.length??0;return {workspaceIntelligence:c,measurement:p,retrieval:{status:C&&E>=3?"grounded":d.length>0?"partial":"empty",strategy:"deterministic-category-v1",queries:u,anchors:d}}}async function Re(e){let t=v.join(e,f$2);if(!await S.pathExists(t))return {schemaVersion:e$1,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let o=await S.readJson(t);a(o,ce,"Goal index");try{i(o);}catch(r){let i=h(o);if(!(i!==null&&r instanceof Error&&r.message==="Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")||!i)throw r;return i}return o}function Se(e,t,o){let r=e.goals.find(c=>c.id===t.id),i=t.state==="ready-to-plan",l={id:t.id,fingerprint:t.fingerprint,objective:t.intent.statement,category:t.intent.category,state:t.state,lifecycle:r?.lifecycle==="cancelled"?"cancelled":i?"active":"planned",scope:t.scope,createdAt:r?.createdAt??t.generatedAt,updatedAt:o,goalPack:t.artifacts.goalPack,agentHandoff:t.artifacts.agentHandoff,...r?.verifiedGoalId?{verifiedGoalId:r.verifiedGoalId}:{},...r?.repairTransactionId?{repairTransactionId:r.repairTransactionId}:{},...r?.repairTransactionIds?{repairTransactionIds:r.repairTransactionIds}:{},...r?.verificationReceipt?{verificationReceipt:r.verificationReceipt}:{}};return {schemaVersion:e$1,generatedAt:o,activeGoalId:l.lifecycle==="active"?t.id:e.activeGoalId===t.id?null:e.activeGoalId,goals:[...e.goals.filter(c=>c.id!==t.id).map(c=>l.lifecycle==="active"&&c.lifecycle==="active"?{...c,lifecycle:"planned",updatedAt:o}:c),l].sort((c,p)=>c.id.localeCompare(p.id))}}async function De(e$1){let t=b({startPath:v.resolve(e$1.startPath),explicitWorkspacePath:e$1.workspacePath,strict:true,requireProjectMembership:true});if(!t)throw new Error("No canonical Workspai workspace could be resolved.");let o=v.resolve(t.workspacePath);e$1.refresh&&await c({workspacePath:o,strict:false,agent:"generic"});let{model:r,graph:i$1}=await je(o),l=await Ge({workspacePath:o,invocationProjectPath:t.projectPath,model:r,explicitScope:e$1.scope,selectScope:e$1.selectScope}),c$4=l.scope,p=r.projects.filter(s=>c$4.projects.includes(s.name));if(p.length===0)throw new Error("A Goal Pack requires at least one registered project in its selected scope.");let u=e$1.maxAttempts??5;if(!Number.isInteger(u)||u<1||u>25)throw new Error("--max-attempts must be an integer from 1 to 25.");let b$1=new Date().toISOString(),y=d(r),k=p.map(s=>({name:s.name,runtimes:[...new Set(s.runtimeCandidates.filter(a=>le.has(a)))].sort()})),N=[...new Set(k.flatMap(s=>s.runtimes))].sort(),h=k.length<=1?N:k[0].runtimes.filter(s=>k.every(a=>a.runtimes.includes(s))),m=$(e$1.intent,{availableCoverageRuntimes:h,...e$1.runtime?{selectedCoverageRuntime:e$1.runtime}:h.length===1?{selectedCoverageRuntime:h[0]}:{}});if(e$1.runtime&&!h.includes(e$1.runtime)){let s=e$1.runtime,a=k.filter(g=>!g.runtimes.includes(s)).map(g=>g.name);throw new Error(p.length>1&&a.length>0?`--runtime ${e$1.runtime} is not canonical for every project in the selected Goal scope. Missing from: ${a.join(", ")}. Split the projects into runtime-compatible Goal scopes.`:`--runtime ${e$1.runtime} is not present in the canonical Workspace Model for the selected Goal scope. Available runtimes: ${h.join(", ")||"none"}.`)}if(e$1.runtime&&m.category!=="test-coverage")throw new Error("--runtime is valid only for a test-coverage Goal.");if(e$1.runtime&&m.requestedTarget?.runtime&&m.requestedTarget.runtime!==e$1.runtime)throw new Error(`--runtime ${e$1.runtime} conflicts with the ${m.requestedTarget.runtime} runtime named in the Goal intent.`);if(!l.selectionRequired&&m.category==="test-coverage"&&m.requestedTarget&&!m.requestedTarget.runtime&&h.length>1&&!e$1.runtime&&e$1.selectCoverageRuntime){let s=await e$1.selectCoverageRuntime({workspaceName:r.workspace.name,scope:c$4,projects:p.map(a=>({name:a.name,runtime:a.runtime,runtimeCandidates:[...a.runtimeCandidates].sort()})),runtimes:h});if(!h.includes(s))throw new Error("The selected coverage runtime is outside the canonical Goal scope.");m=$(e$1.intent,{availableCoverageRuntimes:h,selectedCoverageRuntime:s});}!l.selectionRequired&&m.category==="test-coverage"&&p.length>1&&h.length===0&&(m={...m,ambiguities:[`The selected projects do not share a common canonical coverage runtime: ${k.map(s=>`${s.name} (${s.runtimes.join(", ")||"none"})`).join("; ")}. Split them into runtime-compatible Goal scopes so every selected project is verified.`,...m.ambiguities]}),l.selectionRequired&&(m={...m,ambiguities:[`Goal scope is unresolved across ${c$4.projects.length} registered projects: ${c$4.projects.join(", ")}. Select one project, multiple projects, or the entire workspace.`,...m.ambiguities]});let A=await Ce({workspacePath:o,projects:p,graph:i$1,intent:m,coverageRuntimeChoices:h}),C={generatedAt:b$1,intent:m,workspaceName:r.workspace.name,scope:c$4,sourceBinding:{model:{artifact:e.model,schemaVersion:f.model,hashAlgorithm:"sha256",hashSemantics:"workspace-model-structural-v1",hash:y,generatedAt:r.generatedAt},graph:{artifact:e.knowledgeGraph,schemaVersion:f.knowledgeGraph,hashAlgorithm:"sha256",hashSemantics:"canonical-json-v1",hash:c$1(i$1),generatedAt:i$1.generatedAt,modelHash:i$1.source.hash,...i$1.source.inputs?.hash?{inputHash:i$1.source.inputs.hash}:{}}},preflight:A,baseline:{projectCount:p.length,runtimes:[...new Set(p.flatMap(s=>s.runtimeCandidates))].sort(),frameworks:[...new Set(p.map(s=>s.framework))].sort(),graph:Ae(i$1,c$4)},maxAttempts:u,consumer:e$1.consumer??"generic"},x={digestCanonical:c$1},{goalPack:d$2,handoff:E}=j(C,x);a(d$2,oe,"Goal Pack"),a(E,ne,"Goal agent handoff");let n=false,w=async()=>{let s=v.join(o,d$2.artifacts.goalPack),a$1=v.join(o,d$2.artifacts.agentHandoff),[g,L]=await Promise.all([S.pathExists(s),S.pathExists(a$1)]);if(g!==L)throw new Error(`Goal Pack instance is incomplete and cannot be resumed: ${d$2.id}`);if(!g)return;let[j$1,q]=await Promise.all([S.readJson(s),S.readJson(a$1)]);a(j$1,oe,"Persisted Goal Pack"),a(q,ne,"Persisted goal agent handoff");let z=j({...C,generatedAt:j$1.generatedAt,sourceBinding:j$1.sourceBinding},x);if(j$1.id!==d$2.id||q.goalId!==d$2.id||c$1(j$1)!==c$1(z.goalPack)||c$1(q)!==c$1(z.handoff))throw new Error(`Goal Pack instance failed immutable integrity validation: ${d$2.id}`);d$2=j$1,E=q,n=true;};if(e$1.dryRun)await w();else {let s=`.workspai/goals/${d$2.id}/publication`;await c$2(o,s,async()=>{await w();let a$1=Se(await Re(o),d$2,new Date().toISOString());a(a$1,ce,"Goal index"),i(a$1),await f$1(o,d$1,n?[{relativePath:d$1,payload:d$2},{relativePath:f$2,payload:a$1}]:[{relativePath:d$2.artifacts.goalPack,payload:d$2},{relativePath:d$2.artifacts.agentHandoff,payload:E},{relativePath:d$1,payload:d$2},{relativePath:f$2,payload:a$1}]);});}let P=[d$2.artifacts.goalPack,d$2.artifacts.agentHandoff,d$1,f$2],f$3={schemaVersion:c$3,result:d$2.state==="needs-confirmation"?"needs-confirmation":d$2.state==="blocked"?"blocked":d$2.state==="needs-evidence"?"needs-evidence":"planned",resolution:{source:t.source,invocationScope:t.projectPath?"project":"workspace"},goalPack:d$2,agentHandoff:E,writtenArtifacts:e$1.dryRun?[]:n?[d$1,f$2]:P,dryRun:e$1.dryRun===true,resumed:n};return a(f$3,Pe,"Goal plan result"),f$3}export{De as planGoalPack};
1
+ import {c as c$5}from'./chunk-DIJGQUEV.js';import {c}from'./chunk-TTQVOCG6.js';import {j,i,d as d$1,f as f$2,c as c$3,e as e$1,h}from'./chunk-J5OMC4RZ.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-J5OMC4RZ.js';import {f as f$3}from'./chunk-4PUJVYRM.js';import {b}from'./chunk-GPOZILMY.js';import {a as a$1}from'./chunk-A4BK7C7M.js';import {c as c$4}from'./chunk-TFOOSYGO.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {c as c$2,f as f$1}from'./chunk-CCDGHPEJ.js';import {a}from'./chunk-AFIFZTOY.js';import {f,e}from'./chunk-NZ3WZYD5.js';import v from'path';import S from'fs-extra';var he=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/,fe=/(?:^|\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]+)/,be=/(?:-----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,we=[{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|memory|cpu|optimi[sz]e|faster|slower)\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|implement|introduce|support)\b/i]},{category:"system-understanding",patterns:[/\b(?:understand|explain|map|find|where|how|architecture|analy[sz]e|search)\b/i]}];function ke(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(he.test(t))throw new Error("Goal intent contains unsupported control characters.");if(fe.test(t))throw new Error("Goal intent contains a machine-local absolute path. Use a workspace-relative path or project scope.");if(be.test(t))throw new Error("Goal intent appears to contain secret material and was not persisted.");return t}function ve(e){let t=e.match(/\b(?:coverage\D{0,24})?(100|\d{1,2})(?:\.\d+)?\s*%/i);if(!t||!/coverage/i.test(e))return null;let o=Number(t[1]);return Number.isFinite(o)&&o>=0&&o<=100?o:null}var te=[{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 ye(e){return te.filter(t=>t.patterns.some(o=>o.test(e))).map(t=>t.runtime)}function $(e,t={}){let o=ke(e),r=we.filter(y=>y.patterns.some(k=>k.test(o))).map(y=>y.category),i=r[0]??"feature-change",l=ve(o),c=ye(o),p=c.length===0&&t.selectedCoverageRuntime?[t.selectedCoverageRuntime]:c,u=[...new Set((t.availableCoverageRuntimes??[]).filter(y=>te.some(k=>k.runtime===y)))].sort(),b=[];return r.length>1&&r[0]!=="test-coverage"&&b.push(`The intent also contains signals for: ${r.slice(1).join(", ")}.`),i==="test-coverage"&&l===null&&b.push("A numeric test coverage target is required for machine verification."),i==="test-coverage"&&p.length>1&&b.push(`The Goal names multiple coverage runtimes: ${p.join(", ")}. Select one runtime per Goal.`),i==="test-coverage"&&p.length===0&&u.length>1&&b.push(`Coverage scope is ambiguous across detected runtimes: ${u.join(", ")}. Name one runtime or language in the Goal.`),i==="test-coverage"&&p.length===1&&u.length>0&&!u.includes(p[0])&&b.push(`The requested ${p[0]} coverage runtime is not present in the selected scope. Detected runtimes: ${u.join(", ")}.`),{original:o,normalized:o.toLocaleLowerCase("en-US"),statement:o.replace(/[.!?]+$/,""),category:i,confidence:r.length===1?"high":r.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 re(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 oe="contracts/workspace-intelligence/goal-pack.v1.json",ne="contracts/workspace-intelligence/goal-agent-handoff.v1.json",Pe="contracts/workspace-intelligence/goal-plan-result.v1.json",ce="contracts/workspace-intelligence/goal-index.v1.json",le=new Set(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"]);function ae(e){return e.split(v.sep).join("/")}function V(e,t){return v.resolve(t.absolutePath??v.join(e,t.path))}function se(e){let t=e.requested.trim().replace(/^project:/,"");if(!t)throw new Error("Project goal scope must name a project.");let o=v.isAbsolute(t)?v.resolve(t):null,r=e.model.projects.filter(i=>i.name===t||ae(i.path)===ae(t)||o!==null&&V(e.workspacePath,i)===o);if(r.length!==1)throw new Error(r.length===0?`Project goal scope was not found in the canonical model: ${t}`:`Project goal scope is ambiguous in the canonical model: ${t}`);return r[0]}async function je(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:o,graph:r}=t;return a(o,"contracts/workspace-intelligence/workspace-model.v1.json","Goal source model"),a(r,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Goal source graph"),c$4(r,o),{model:o,graph:r}}function ie(e){let t=e.scope.trim();if(t==="workspace")return {kind:"workspace",projects:e.model.projects.map(r=>r.name).sort(),selectionSource:e.selectionSource,resolution:"selected"};let o=t.startsWith("projects:")?"projects:":t.startsWith("project:")&&t.slice(8).includes(",")?"project:":null;if(o){let r=t.slice(o.length).split(",").map(c=>c.trim()).filter(Boolean);if(r.length<2)throw new Error("A project-set Goal scope must name at least two projects.");let i=r.map(c=>se({workspacePath:e.workspacePath,model:e.model,requested:c})),l=[...new Set(i.map(c=>c.name))].sort();if(l.length!==r.length)throw new Error("A project-set Goal scope must not contain duplicate projects.");return {kind:"project-set",projects:l,selectionSource:e.selectionSource,resolution:"selected"}}if(t)return {kind:"project",projects:[se({workspacePath:e.workspacePath,model:e.model,requested:t}).name],selectionSource:e.selectionSource,resolution:"selected"};throw new Error("Goal scope cannot be empty.")}async function Ge(e){if(e.explicitScope?.trim())return {scope:ie({workspacePath:e.workspacePath,model:e.model,scope:e.explicitScope,selectionSource:"explicit"}),selectionRequired:false};if(e.invocationProjectPath){let t=v.resolve(e.invocationProjectPath),o=e.model.projects.filter(r=>V(e.workspacePath,r)===t);if(o.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:[o[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(r=>({name:r.name,runtime:r.runtime,runtimeCandidates:[...r.runtimeCandidates].sort(),framework:r.framework})).sort((r,i)=>r.name.localeCompare(i.name))}),o=t.kind==="workspace"?"workspace":t.projects.length===1?`project:${t.projects[0]}`:`projects:${t.projects.join(",")}`;return {scope:ie({workspacePath:e.workspacePath,model:e.model,scope:o,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 Ae(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 o=new Set(t.projects),r=e.entities.filter(u=>u.projectId!==void 0&&o.has(u.projectId)),i=new Set(r.map(u=>u.id)),l=e.relations.filter(u=>i.has(u.from)||i.has(u.to)),c=new Set([...r.flatMap(u=>u.proofIds),...l.flatMap(u=>u.proofIds)]),p=l.filter(u=>u.proofIds.length>0).length;return {entities:r.length,relationships:l.length,proofs:c.size,unresolved:l.length-p,proofCoveragePercent:l.length===0?100:Number((p/l.length*100).toFixed(2))}}async function Ce(e$1){let t=v.join(e$1.workspacePath,e.intelligenceRun),o=await S.readJson(t).catch(()=>null),i=(Array.isArray(o?.stages)?o.stages:[]).filter(n=>n.status==="blocked"||n.status==="failed").map(n=>String(n.id??"unknown")).sort(),l=o?.status,c={status:l==="passed"?"passed":l==="blocked"||l==="failed"?"blocked":"unknown",artifact:e.intelligenceRun,blockedStages:i},p={status:"not-applicable",runtime:null,runtimeChoices:[],runner:null,existingEvidence:[],prerequisites:[]};if(e$1.intent.category==="test-coverage"){let n=e$1.intent.requestedTarget?.runtime;if(e$1.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 ")))p={status:"requires-setup",runtime:n??null,runtimeChoices:e$1.coverageRuntimeChoices,runner:null,existingEvidence:[],prerequisites:["Select exactly one detected runtime or language for this coverage Goal."]};else {let P=n?e$1.projects.filter(a=>a.runtimeCandidates.includes(n)):e$1.projects,f=await Promise.all(P.map(async a=>({project:a,capability:await c$5(V(e$1.workspacePath,a),n??(le.has(a.runtime)?a.runtime:"unknown"))}))),s=f.map(a=>a.capability.status);p={status:s.includes("unsupported")?"unsupported":s.includes("requires-setup")?"requires-setup":"available",runtime:f.length===1?f[0].capability.runtime:[...new Set(f.map(a=>a.capability.runtime))].join(","),runtimeChoices:e$1.coverageRuntimeChoices,runner:f.length===1?f[0].capability.runner:[...new Set(f.flatMap(a=>a.capability.runner?[a.capability.runner]:[]))].join(",")||null,existingEvidence:f.flatMap(a=>a.capability.existingEvidence.map(g=>({project:a.project.name,...g}))).filter((a,g,L)=>L.findIndex(j=>j.project===a.project&&j.path===a.path&&j.sha256===a.sha256)===g).sort((a,g)=>a.project.localeCompare(g.project)||a.path.localeCompare(g.path)),prerequisites:[...new Set(f.flatMap(a=>a.capability.prerequisites))].sort()};}}let u=re(e$1.intent),b=u.map(n=>{let w=e$1.projects.map(s=>f$3(e$1.graph,{query:n,projectId:s.name,limit:20,relationsPerEntity:0,minimumTermMatches:2}).entities),P=[],f=new Set;for(let s=0;w.some(a=>s<a.length);s+=1)for(let a of w){let g=a[s];!g||f.has(g.id)||(f.add(g.id),P.push(g));}return P}),y={"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"]},k=new Set(e$1.projects.map(n=>n.name)),N=e$1.graph.entities.filter(n=>n.proofIds.length>0&&(!n.projectId||k.has(n.projectId))&&y[e$1.intent.category].includes(n.kind)).sort((n,w)=>y[e$1.intent.category].indexOf(n.kind)-y[e$1.intent.category].indexOf(w.kind)||n.label.localeCompare(w.label)),h=[],m=new Set,A=n=>{!n||h.length>=20||m.has(n.id)||(m.add(n.id),h.push(n));},C=(e$1.intent.statement.match(/[A-Za-z][A-Za-z0-9+#.-]{1,}/g)??[]).length>=2,x=C?b[0]??[]:[];for(let n of x.slice(0,12))A(n);if(!C)for(let n of N)A(n);for(let n=0;h.length<20&&b.slice(1).some(w=>n<w.length);n+=1)for(let w of b.slice(1))A(w[n]);if(C)for(let n of N)A(n);for(let n of x.slice(12))A(n);let d=h.map(n=>({entityId:n.id,kind:n.kind,label:n.label,proofIds:n.proofIds.slice(0,12)})),E=b[0]?.length??0;return {workspaceIntelligence:c,measurement:p,retrieval:{status:C&&E>=3?"grounded":d.length>0?"partial":"empty",strategy:"deterministic-category-v1",queries:u,anchors:d}}}async function Re(e){let t=v.join(e,f$2);if(!await S.pathExists(t))return {schemaVersion:e$1,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let o=await S.readJson(t);a(o,ce,"Goal index");try{i(o);}catch(r){let i=h(o);if(!(i!==null&&r instanceof Error&&r.message==="Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")||!i)throw r;return i}return o}function Se(e,t,o){let r=e.goals.find(c=>c.id===t.id),i=t.state==="ready-to-plan",l={id:t.id,fingerprint:t.fingerprint,objective:t.intent.statement,category:t.intent.category,state:t.state,lifecycle:r?.lifecycle==="cancelled"?"cancelled":i?"active":"planned",scope:t.scope,createdAt:r?.createdAt??t.generatedAt,updatedAt:o,goalPack:t.artifacts.goalPack,agentHandoff:t.artifacts.agentHandoff,...r?.verifiedGoalId?{verifiedGoalId:r.verifiedGoalId}:{},...r?.repairTransactionId?{repairTransactionId:r.repairTransactionId}:{},...r?.repairTransactionIds?{repairTransactionIds:r.repairTransactionIds}:{},...r?.verificationReceipt?{verificationReceipt:r.verificationReceipt}:{}};return {schemaVersion:e$1,generatedAt:o,activeGoalId:l.lifecycle==="active"?t.id:e.activeGoalId===t.id?null:e.activeGoalId,goals:[...e.goals.filter(c=>c.id!==t.id).map(c=>l.lifecycle==="active"&&c.lifecycle==="active"?{...c,lifecycle:"planned",updatedAt:o}:c),l].sort((c,p)=>c.id.localeCompare(p.id))}}async function De(e$1){let t=b({startPath:v.resolve(e$1.startPath),explicitWorkspacePath:e$1.workspacePath,strict:true,requireProjectMembership:true});if(!t)throw new Error("No canonical Workspai workspace could be resolved.");let o=v.resolve(t.workspacePath);e$1.refresh&&await c({workspacePath:o,strict:false,agent:"generic"});let{model:r,graph:i$1}=await je(o),l=await Ge({workspacePath:o,invocationProjectPath:t.projectPath,model:r,explicitScope:e$1.scope,selectScope:e$1.selectScope}),c$4=l.scope,p=r.projects.filter(s=>c$4.projects.includes(s.name));if(p.length===0)throw new Error("A Goal Pack requires at least one registered project in its selected scope.");let u=e$1.maxAttempts??5;if(!Number.isInteger(u)||u<1||u>25)throw new Error("--max-attempts must be an integer from 1 to 25.");let b$1=new Date().toISOString(),y=d(r),k=p.map(s=>({name:s.name,runtimes:[...new Set(s.runtimeCandidates.filter(a=>le.has(a)))].sort()})),N=[...new Set(k.flatMap(s=>s.runtimes))].sort(),h=k.length<=1?N:k[0].runtimes.filter(s=>k.every(a=>a.runtimes.includes(s))),m=$(e$1.intent,{availableCoverageRuntimes:h,...e$1.runtime?{selectedCoverageRuntime:e$1.runtime}:h.length===1?{selectedCoverageRuntime:h[0]}:{}});if(e$1.runtime&&!h.includes(e$1.runtime)){let s=e$1.runtime,a=k.filter(g=>!g.runtimes.includes(s)).map(g=>g.name);throw new Error(p.length>1&&a.length>0?`--runtime ${e$1.runtime} is not canonical for every project in the selected Goal scope. Missing from: ${a.join(", ")}. Split the projects into runtime-compatible Goal scopes.`:`--runtime ${e$1.runtime} is not present in the canonical Workspace Model for the selected Goal scope. Available runtimes: ${h.join(", ")||"none"}.`)}if(e$1.runtime&&m.category!=="test-coverage")throw new Error("--runtime is valid only for a test-coverage Goal.");if(e$1.runtime&&m.requestedTarget?.runtime&&m.requestedTarget.runtime!==e$1.runtime)throw new Error(`--runtime ${e$1.runtime} conflicts with the ${m.requestedTarget.runtime} runtime named in the Goal intent.`);if(!l.selectionRequired&&m.category==="test-coverage"&&m.requestedTarget&&!m.requestedTarget.runtime&&h.length>1&&!e$1.runtime&&e$1.selectCoverageRuntime){let s=await e$1.selectCoverageRuntime({workspaceName:r.workspace.name,scope:c$4,projects:p.map(a=>({name:a.name,runtime:a.runtime,runtimeCandidates:[...a.runtimeCandidates].sort()})),runtimes:h});if(!h.includes(s))throw new Error("The selected coverage runtime is outside the canonical Goal scope.");m=$(e$1.intent,{availableCoverageRuntimes:h,selectedCoverageRuntime:s});}!l.selectionRequired&&m.category==="test-coverage"&&p.length>1&&h.length===0&&(m={...m,ambiguities:[`The selected projects do not share a common canonical coverage runtime: ${k.map(s=>`${s.name} (${s.runtimes.join(", ")||"none"})`).join("; ")}. Split them into runtime-compatible Goal scopes so every selected project is verified.`,...m.ambiguities]}),l.selectionRequired&&(m={...m,ambiguities:[`Goal scope is unresolved across ${c$4.projects.length} registered projects: ${c$4.projects.join(", ")}. Select one project, multiple projects, or the entire workspace.`,...m.ambiguities]});let A=await Ce({workspacePath:o,projects:p,graph:i$1,intent:m,coverageRuntimeChoices:h}),C={generatedAt:b$1,intent:m,workspaceName:r.workspace.name,scope:c$4,sourceBinding:{model:{artifact:e.model,schemaVersion:f.model,hashAlgorithm:"sha256",hashSemantics:"workspace-model-structural-v1",hash:y,generatedAt:r.generatedAt},graph:{artifact:e.knowledgeGraph,schemaVersion:f.knowledgeGraph,hashAlgorithm:"sha256",hashSemantics:"canonical-json-v1",hash:c$1(i$1),generatedAt:i$1.generatedAt,modelHash:i$1.source.hash,...i$1.source.inputs?.hash?{inputHash:i$1.source.inputs.hash}:{}}},preflight:A,baseline:{projectCount:p.length,runtimes:[...new Set(p.flatMap(s=>s.runtimeCandidates))].sort(),frameworks:[...new Set(p.map(s=>s.framework))].sort(),graph:Ae(i$1,c$4)},maxAttempts:u,consumer:e$1.consumer??"generic"},x={digestCanonical:c$1},{goalPack:d$2,handoff:E}=j(C,x);a(d$2,oe,"Goal Pack"),a(E,ne,"Goal agent handoff");let n=false,w=async()=>{let s=v.join(o,d$2.artifacts.goalPack),a$1=v.join(o,d$2.artifacts.agentHandoff),[g,L]=await Promise.all([S.pathExists(s),S.pathExists(a$1)]);if(g!==L)throw new Error(`Goal Pack instance is incomplete and cannot be resumed: ${d$2.id}`);if(!g)return;let[j$1,q]=await Promise.all([S.readJson(s),S.readJson(a$1)]);a(j$1,oe,"Persisted Goal Pack"),a(q,ne,"Persisted goal agent handoff");let z=j({...C,generatedAt:j$1.generatedAt,sourceBinding:j$1.sourceBinding},x);if(j$1.id!==d$2.id||q.goalId!==d$2.id||c$1(j$1)!==c$1(z.goalPack)||c$1(q)!==c$1(z.handoff))throw new Error(`Goal Pack instance failed immutable integrity validation: ${d$2.id}`);d$2=j$1,E=q,n=true;};if(e$1.dryRun)await w();else {let s=`.workspai/goals/${d$2.id}/publication`;await c$2(o,s,async()=>{await w();let a$1=Se(await Re(o),d$2,new Date().toISOString());a(a$1,ce,"Goal index"),i(a$1),await f$1(o,d$1,n?[{relativePath:d$1,payload:d$2},{relativePath:f$2,payload:a$1}]:[{relativePath:d$2.artifacts.goalPack,payload:d$2},{relativePath:d$2.artifacts.agentHandoff,payload:E},{relativePath:d$1,payload:d$2},{relativePath:f$2,payload:a$1}]);});}let P=[d$2.artifacts.goalPack,d$2.artifacts.agentHandoff,d$1,f$2],f$3={schemaVersion:c$3,result:d$2.state==="needs-confirmation"?"needs-confirmation":d$2.state==="blocked"?"blocked":d$2.state==="needs-evidence"?"needs-evidence":"planned",resolution:{source:t.source,invocationScope:t.projectPath?"project":"workspace"},goalPack:d$2,agentHandoff:E,writtenArtifacts:e$1.dryRun?[]:n?[d$1,f$2]:P,dryRun:e$1.dryRun===true,resumed:n};return a(f$3,Pe,"Goal plan result"),f$3}export{De as planGoalPack};