workspai 0.60.1 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +92 -33
- package/contracts/analyze-last-run.v1.json +7 -1
- package/contracts/extension-cli-compatibility.v1.json +1 -1
- package/contracts/studio-card-repair-capabilities.v1.json +1 -1
- package/contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json +31 -3
- package/contracts/workspace-intelligence/agent-customization-pack-report.v1.json +5 -1
- package/contracts/workspace-intelligence/agent-reports-index.v1.json +5 -1
- package/contracts/workspace-intelligence/project-agent-entry.v1.json +32 -4
- package/contracts/workspace-intelligence/project-context-agent.v1.json +34 -2
- package/contracts/workspace-intelligence/workspace-context.v1.json +4 -1
- package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +1 -0
- package/contracts/workspace-intelligence-chain.v1.json +4 -5
- package/dist/analyze-K6JDMF5C.js +1 -0
- package/dist/autopilot-release-GNTOXKIL.js +1 -0
- package/dist/{chunk-KNTPDRZB.js → chunk-3VU7ROHY.js} +1 -1
- package/dist/chunk-46USUSIK.js +49 -0
- package/dist/{chunk-S4CWUZ4K.js → chunk-BQCGULHR.js} +1 -1
- package/dist/{chunk-TYQMO36U.js → chunk-JNPXLZA6.js} +1 -1
- package/dist/{chunk-WQX3JYEP.js → chunk-LNXIMF3O.js} +1 -1
- package/dist/{chunk-AJ535F22.js → chunk-MWCKJOOU.js} +14 -12
- package/dist/{chunk-WUB6QGC7.js → chunk-PKKP5H3T.js} +1 -1
- package/dist/{chunk-WLFJHRB3.js → chunk-PPQL5UTI.js} +1 -1
- package/dist/{chunk-MDF2FBLS.js → chunk-SS7NJMFL.js} +1 -1
- package/dist/{chunk-KTW4EN47.js → chunk-TR6OFSJM.js} +1 -1
- package/dist/chunk-TVCJKE2U.js +2 -0
- package/dist/chunk-UZNACYV7.js +2 -0
- package/dist/{chunk-VV55EAWO.js → chunk-VDEFHP6I.js} +1 -1
- package/dist/chunk-VRQLHCE2.js +8 -0
- package/dist/chunk-YUGKQ44M.js +1 -0
- package/dist/{create-ZLDOBXG4.js → create-CKUQRSJF.js} +1 -1
- package/dist/{goal-lifecycle-OV6NZDD6.js → goal-lifecycle-7L5JFYOI.js} +1 -1
- package/dist/{goal-pack-Q3O2Z7R5.js → goal-pack-SGHXUPMU.js} +1 -1
- package/dist/index.js +19 -19
- package/dist/{pipeline-NICVJLZF.js → pipeline-W2CKUZBS.js} +1 -1
- package/dist/{project-agent-entry-DVPKQST7.js → project-agent-entry-66GTQQPX.js} +1 -1
- package/dist/{project-intelligence-lens-RLYSPJB2.js → project-intelligence-lens-NWNWLJMB.js} +1 -1
- package/dist/{verified-goal-2BRQZQBL.js → verified-goal-AY5VU6LG.js} +1 -1
- package/dist/{workspace-LQ77WAHC.js → workspace-FSOLFNAJ.js} +1 -1
- package/dist/workspace-agent-sync-ZURWHL3H.js +1 -0
- package/dist/{workspace-context-YAK5XX27.js → workspace-context-DPDGFTWJ.js} +1 -1
- package/dist/workspace-explain-OU2PEVYO.js +1 -0
- package/dist/{workspace-explain-contract-ZL4NMLZI.js → workspace-explain-contract-V2IVSROX.js} +1 -1
- package/dist/{workspace-foundation-G4KPT5CN.js → workspace-foundation-PPZKC36U.js} +1 -1
- package/dist/{workspace-intelligence-runner-T6CVJIQQ.js → workspace-intelligence-runner-7RIOUCCM.js} +1 -1
- package/dist/{workspace-mcp-serve-ALIZV72K.js → workspace-mcp-serve-PYKYJIE6.js} +1 -1
- package/dist/{workspace-onboarding-46BE3EQD.js → workspace-onboarding-RP3RZ3CC.js} +1 -1
- package/dist/{workspace-readme-56YZ4EAZ.js → workspace-readme-G7TZ3V5T.js} +1 -1
- package/dist/workspace-repair-engine-L47XZXYZ.js +3 -0
- package/dist/workspace-run-QV5ER2VW.js +1 -0
- package/docs/README.md +16 -14
- package/docs/agent-entry.md +32 -2
- package/docs/ci-workflows.md +1 -1
- package/docs/workspace-repair-engine.md +48 -2
- package/package.json +1 -1
- package/dist/analyze-FYNMI5KT.js +0 -1
- package/dist/autopilot-release-IRXB2VOH.js +0 -1
- package/dist/chunk-7ITSLGPZ.js +0 -8
- package/dist/chunk-I2O6AC2Z.js +0 -2
- package/dist/chunk-KBR4Y4RW.js +0 -1
- package/dist/chunk-NRVSDL4J.js +0 -39
- package/dist/chunk-OU7DF6MP.js +0 -2
- package/dist/workspace-agent-sync-YLP75OWF.js +0 -1
- package/dist/workspace-explain-QH4FXQW5.js +0 -1
- package/dist/workspace-repair-engine-SZZKV3JF.js +0 -3
- package/dist/workspace-run-JTEFCQYQ.js +0 -1
- /package/dist/{chunk-HQWDW2BV.js → chunk-GGOQHTZV.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {g,b,i as i$1,d as d$2,e as e$1,f}from'./chunk-I2O6AC2Z.js';import {c}from'./chunk-GPOZILMY.js';import {c as c$1}from'./chunk-X7FYEKLI.js';import {d as d$3,b as b$1,a as a$1}from'./chunk-3RBUSW7H.js';import {d as d$1}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-AFIFZTOY.js';import {h,e,i}from'./chunk-NZ3WZYD5.js';import {t,h as h$1,g as g$1}from'./chunk-MOSXTVPU.js';import le from'crypto';import H from'fs';import k from'fs/promises';import d from'path';import {execa}from'execa';import he from'fs-extra';var ke=h.projectContextAgent.schemaVersion,Ze=["managed","local","off"],de="<!-- WORKSPAI:PROJECT-GROUNDING:START -->",pe="<!-- WORKSPAI:PROJECT-GROUNDING:END -->";function oe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}async function E(e){try{return JSON.parse(await k.readFile(e,"utf8"))}catch(t){return null}}function G(e){return e.replace(/\\/g,"/").replace(/^\.\/+/,"")}function x(e,t,n){let o=e.replace(/\\/g,"/"),i=/^[A-Za-z]:\//.test(o);if(!d.isAbsolute(e)&&!i)return G(o);if(i&&process.platform!=="win32")return null;let c=d.resolve(e),s=d.relative(n,c);if(s&&!s.startsWith("..")&&!d.isAbsolute(s))return G(s);let l=d.relative(t,c);return l&&!l.startsWith("..")&&!d.isAbsolute(l)?`workspace:${G(l)}`:null}function P(e,t,n){return [[n,"project:"],[n.replace(/\\/g,"/"),"project:"],[t,"workspace:"],[t.replace(/\\/g,"/"),"workspace:"]].reduce((i,[c,s])=>c.length>0?i.split(c).join(s):i,e)}function ge(e,t){return oe(e?.adoption)?.mode==="linked"?"adopted":oe(e?.import)?"imported":t}function we(e){if(!e.model)return null;let t=G(e.relativePath);return e.model.projects.find(n=>n.name===e.projectName||G(n.path)===t)??null}function ne(e,t){e[t]=(e[t]??0)+1;}var ye=["project","language","service","api","endpoint","schema","protocol","runtime-unit","lifecycle-stage","database","queue","container","deployment","pipeline","environment","test-suite","owner","decision","document","package","file","module","symbol"];function je(e,t=160){let n={language:32,api:32,service:32,endpoint:32,schema:32,protocol:32,"runtime-unit":32,"lifecycle-stage":32,file:8,module:8,symbol:8},o=[];for(let i of ye){let c=e.filter(s=>s.kind===i).sort((s,l)=>s.label.localeCompare(l.label)||s.id.localeCompare(l.id)).slice(0,n[i]??32);for(let s of c){if(o.length>=t)return o;o.push(s);}}return o}function Pe(e,t){if(!e)return {entityCount:0,relationCount:0,proofCount:0,entitiesByKind:{},relationsByKind:{},languages:{},semantic:{protocolConceptCount:0,protocolImplementationBindings:0,equivalenceBindings:0,generationBindings:0,runtimeUnitCount:0,lifecycleStageCount:0,runtimeCoverage:[]},relatedProjects:[],proofArtifacts:[],entities:[],relations:[],proofs:[],topology:{status:"unavailable",dependencies:[],dependents:[]},diagnostics:[]};let n=e.entities.find(r=>r.kind==="project"&&(r.id===t||r.label===t||r.projectId===t)),o=new Set(e.entities.filter(r=>r.projectId===t||r.id===n?.id||r.kind==="project"&&r.label===t).map(r=>r.id));n&&o.add(n.id);let i=e.relations.filter(r=>o.has(r.from)||o.has(r.to)),c=new Set(o);for(let r of i)c.add(r.from),c.add(r.to);let s=e.entities.filter(r=>c.has(r.id)),l=new Set,g={},u={},f={},w=new Set(s.filter(r=>r.kind==="language").map(r=>r.attributes.language).filter(r=>typeof r=="string"));for(let r of s){ne(g,r.kind);let a=typeof r.attributes.language=="string"?r.attributes.language:void 0;if(a&&r.kind==="language")f[a]={fileCount:typeof r.attributes.fileCount=="number"?r.attributes.fileCount:0,symbolCount:f[a]?.symbolCount??0,generatedFileCount:typeof r.attributes.generatedFileCount=="number"?r.attributes.generatedFileCount:0};else if(a&&(r.kind==="file"||r.kind==="symbol")){let h=f[a]??{fileCount:0,symbolCount:0,generatedFileCount:0};r.kind==="file"&&!w.has(a)?(h.fileCount+=1,r.attributes.generated===true&&(h.generatedFileCount+=1)):r.kind==="symbol"&&(h.symbolCount+=1),f[a]=h;}for(let h of r.proofIds)l.add(h);}for(let r of i){ne(u,r.kind);for(let a of r.proofIds)l.add(a);}let y=e.proofs.filter(r=>l.has(r.id)),b=[...new Set(e.entities.filter(r=>c.has(r.id)&&r.projectId&&r.projectId!==t).map(r=>r.projectId))].sort(),m=e.diagnostics.filter(r=>r.entityIds?.some(a=>c.has(a))||r.relationIds?.some(a=>i.some(h=>h.id===a))).map(r=>({code:r.code,severity:r.severity,message:r.message,...r.recommendation?{recommendation:r.recommendation}:{}})),p=(r,a)=>({project:a,kind:r.kind,source:r.source,confidence:r.confidence,evidence:[...new Set(r.evidence.map(h=>h.file.replace(/\\/g,"/")))].sort()}),v=e.projectTopology.edges.filter(r=>r.from===t).map(r=>p(r,r.to)).sort((r,a)=>`${r.project}:${r.kind}`.localeCompare(`${a.project}:${a.kind}`)),C=e.projectTopology.edges.filter(r=>r.to===t).map(r=>p(r,r.from)).sort((r,a)=>`${r.project}:${r.kind}`.localeCompare(`${a.project}:${a.kind}`)),R=je(s),N=s.filter(r=>r.kind==="runtime-unit"),j=new Set(R.map(r=>r.id)),_=[...i].sort((r,a)=>{let h=Number(j.has(r.from)||j.has(r.to));return Number(j.has(a.from)||j.has(a.to))-h||r.id.localeCompare(a.id)}).slice(0,128),$=new Set([...R.flatMap(r=>r.proofIds),..._.flatMap(r=>r.proofIds)]);return {entityCount:s.length,relationCount:i.length,proofCount:y.length,entitiesByKind:g,relationsByKind:u,languages:Object.fromEntries(Object.entries(f).sort(([r],[a])=>r.localeCompare(a))),semantic:{protocolConceptCount:g.protocol??0,protocolImplementationBindings:u["implements-protocol"]??0,equivalenceBindings:u["equivalent-to"]??0,generationBindings:(u["generated-from"]??0)+(u["generated-by"]??0),runtimeUnitCount:N.length,lifecycleStageCount:g["lifecycle-stage"]??0,runtimeCoverage:[...new Set(N.map(r=>r.attributes.runtime).filter(r=>typeof r=="string"))].sort()},relatedProjects:b,proofArtifacts:[...new Set(y.map(r=>r.artifact))].sort(),entities:R,relations:_,proofs:y.filter(r=>$.has(r.id)).sort((r,a)=>r.id.localeCompare(a.id)).slice(0,128),topology:{status:v.length>0||C.length>0?"proven":e.projectTopology.nodes.some(r=>r.id===t)?"unproven":"unavailable",dependencies:v,dependents:C},diagnostics:m}}function ue(e,t,n){return Array.isArray(e)?e.map(o=>typeof o=="string"?P(o,t,n):o):typeof e=="string"?P(e,t,n):e}function be(e,t,n){return {id:e.id,kind:e.kind,label:P(e.label,t,n),attributes:Object.fromEntries(Object.entries(e.attributes).map(([o,i])=>[o,ue(i,t,n)])),proofIds:[...e.proofIds].sort()}}function ve(e,t,n){let o=(...c)=>e.filter(s=>c.includes(s.kind)).map(s=>be(s,t,n)).slice(0,32),i=[];for(let c of e){for(let[s,l]of Object.entries(c.attributes))if(/(?:^|[-_.])ports?(?:$|[-_.])/i.test(s)&&(i.push({entityId:c.id,label:P(c.label,t,n),attribute:s,value:ue(l,t,n)}),i.length>=32))break;if(i.length>=32)break}return {services:o("service"),packages:o("package"),protocols:o("protocol"),runtimeUnits:o("runtime-unit"),lifecycleStages:o("lifecycle-stage"),apis:o("api"),endpoints:o("endpoint"),dataStores:o("database","queue"),deployments:o("container","deployment","environment"),pipelines:o("pipeline"),tests:o("test-suite"),owners:o("owner"),decisions:o("decision"),ports:i}}function Ae(e,t,n){let o=x(e.artifact,t,n);return o?{id:e.id,provider:e.provider,artifact:o,...e.pointer?{pointer:P(e.pointer,t,n)}:{},...e.line!==void 0?{line:e.line}:{},derivation:e.derivation,trust:e.trust,confidence:e.confidence,freshness:e.freshness}:null}async function Ee(e,t,n){let o=[],i=await E(d.join(e,".workspai","reports","INDEX.json"));if(Array.isArray(i?.blockers))for(let s of i.blockers)typeof s=="string"&&(s.startsWith(`${n}:`)||s.includes(`project:${n}`)||s.includes(`project ${n}`))&&o.push({source:"workspace-report-index",severity:"error",message:P(s,e,t)});let c=await E(d.join(e,".workspai","reports","doctor-project-last-run.json"));if(c?.projectName===n)for(let s of c$1({project:c.project}))o.push({source:"doctor-project",severity:s.status==="blocking"?"error":"warning",message:P(s.message,e,t),...s.id?{code:s.id}:{}});return [...new Map(o.map(s=>[`${s.source}:${s.code??""}:${s.message}`,s])).values()].slice(0,32)}function U(e,t=[]){return typeof e=="string"?/^[A-Za-z]:[\\/]/.test(e)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(e)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(e)||t.some(n=>n.length>0&&(e.includes(n)||e.includes(n.replace(/\\/g,"/")))):Array.isArray(e)?e.some(n=>U(n,t)):e&&typeof e=="object"?Object.values(e).some(n=>U(n,t)):false}function Ce(e){return le.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Re(e$1){let t$1=d.resolve(e$1.workspacePath),n=d.resolve(e$1.projectPath),o=t(n,"project.json").find(a=>H.existsSync(a)),i$1=o?await E(o):null,c=await E(d.join(t$1,".workspai","workspace.contract.json")),s=d.resolve(n),l=c?.projects?.find(a=>a.externalPath?d.resolve(a.externalPath)===s:!a.relativePath||a.relativePath.startsWith("external/")?false:d.resolve(t$1,a.relativePath)===s)??c?.projects?.find(a=>a.slug===e$1.projectName||a.slug===d.basename(n)),g=e$1.projectName??(typeof i$1?.name=="string"?i$1.name:void 0)??l?.slug??d.basename(n),u=l?.relativePath??(()=>{let a=G(d.relative(t$1,n));return !a||a.startsWith("..")?`external/${g}`:a})(),f=await E(d.join(t$1,e.model)),w=await E(d.join(t$1,e.knowledgeGraph)),y=f?d$1(f):void 0,b$1=!!(y&&w?.source.hash===y),m=we({model:f,projectName:g,relativePath:u}),p=Pe(b$1?w:null,g),v=await Ee(t$1,n,g),C=p.proofs.map(a=>a.freshness),R=w?!b$1||C.includes("stale")?"stale":C.includes("unknown")?"unknown":"fresh":"missing",N=f?f.factFreshness?.status??"unknown":"missing",j=[...f?[]:[{code:"project.context.model-missing",severity:"warning",message:"The canonical Workspace Model has not been generated yet. Refresh workspace intelligence before relying on project topology."}],...f&&!m?[{code:"project.context.project-not-materialized",severity:"warning",message:"The project is registered in the workspace contract but is not present in the current Workspace Model."}]:[],...w?[]:[{code:"project.context.graph-missing",severity:"warning",message:"The Workspace Knowledge Graph has not been generated yet. Run the workspace intelligence loop to build proof-backed relationships."}],...w&&!b$1?[{code:"project.context.graph-model-mismatch",severity:"warning",message:"The persisted Knowledge Graph does not match the current Workspace Model and was excluded from this project lens."}]:[]],_=ge(i$1,e$1.relationship??l?.relationship??"managed"),$={schemaVersion:ke,generatedAt:(e$1.now??new Date).toISOString(),workspace:{name:c?.workspace?.name??f?.workspace.name??d.basename(t$1),...c?.workspace?.profile||f?.workspace.profile?{profile:c?.workspace?.profile??f?.workspace.profile}:{},relationship:_,contract:`workspace:${i.workspaceContract}`,model:`workspace:${e.model}`,knowledgeGraph:`workspace:${e.knowledgeGraph}`,access:{localBinding:i.projectWorkspaceLink,canonicalEvidenceAvailableAtGeneration:true,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"}},project:{name:g,relativePath:u,...m?.kind?{kind:m.kind}:{},...m?.runtime||l?.runtime?{runtime:m?.runtime??l?.runtime}:{},...m?.runtimeCandidates?.length?{runtimeCandidates:[...m.runtimeCandidates].sort()}:{},...m?.framework||l?.framework?{framework:m?.framework??l?.framework}:{},...m?.kit||l?.kit?{kit:m?.kit??l?.kit}:{},...m?.supportTier?{supportTier:m.supportTier}:{},commands:{supported:[...m?.commands.supported??[]].sort(),unsupported:[...m?.commands.unsupported??[]].sort(),fleetStages:[...m?.commands.fleetStages??[]].sort()},importantFiles:[...new Set((m?.importantFiles??[]).map(a=>x(a,t$1,n)).filter(a=>a!==null))].sort()},intelligence:{...f?.generatedAt?{modelGeneratedAt:f.generatedAt}:{},...w?.generatedAt?{graphGeneratedAt:w.generatedAt}:{},...w?.source.hash?{graphModelHash:w.source.hash}:{},entityCount:p.entityCount,relationCount:p.relationCount,proofCount:p.proofCount,entitiesByKind:p.entitiesByKind,relationsByKind:p.relationsByKind,languages:p.languages,semantic:p.semantic,relatedProjects:p.relatedProjects,freshness:{model:N,graph:R,graphMatchesModel:b$1},topology:{...p.topology,dependencies:p.topology.dependencies.map(a=>({...a,evidence:a.evidence.map(h=>x(h,t$1,n)).filter(h=>h!==null)})),dependents:p.topology.dependents.map(a=>({...a,evidence:a.evidence.map(h=>x(h,t$1,n)).filter(h=>h!==null)}))},surfaces:ve(p.entities,t$1,n),diagnostics:[...j,...p.diagnostics].map(a=>({...a,message:P(a.message,t$1,n),...a.recommendation?{recommendation:P(a.recommendation,t$1,n)}:{}}))},evidence:{readOrder:[b,".workspai/PROJECT-GROUNDING.md",i.projectContextAgent,"AGENTS.md","workspace:.workspai/goals/index.json",`workspace:${i.goalPackLastRun}`,"workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json",`workspace:${e.model}`,`workspace:${e.knowledgeGraph}`],projectProofArtifacts:[...new Set(p.proofArtifacts.map(a=>x(a,t$1,n)).filter(a=>a!==null))],relations:p.relations.map(a=>({id:a.id,from:a.from,to:a.to,kind:a.kind,derivation:a.derivation,trust:a.trust,confidence:a.confidence,proofIds:[...a.proofIds].sort()})),proofs:p.proofs.map(a=>Ae(a,t$1,n)).filter(a=>a!==null)},blockers:v,agentRouting:{enforcement:"required",mandatoryPreflight:{command:"workspai agent bootstrap --for-agent generic --strict --json",successCondition:"ready"},workspaceLocator:{command:"workspai project workspace status --json",successCondition:"resolved",outputClassification:"machine-local",persistence:"forbidden",disclosure:"forbidden",portableUriScheme:"workspace:"},workspaceEvidenceRequiredFor:["repository-analysis","architecture-analysis","change-impact","cross-project-change","contract-change","infrastructure-change","release-readiness"],requiredReadOrder:[b,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",i.projectContextAgent,"workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json",`command:npx workspai workspace graph search ${JSON.stringify(g)} --scope ${JSON.stringify(`project:${g}`)} --limit 12 --json`],degradedMode:{allowCompleteArchitectureClaims:false,requireDisclosure:true}},commands:{refresh:"workspai workspace intelligence run --for-agent generic --strict --json",verify:"workspai workspace verify --strict --json",graphSearch:`workspai workspace graph search ${JSON.stringify(g)} --scope ${JSON.stringify(`project:${g}`)} --limit 12 --json`,doctor:"workspai doctor project --json",workspaceStatus:"workspai project workspace status --json"}};if(U($,[t$1,n]))throw new Error("Project context lens rejected a non-portable absolute path.");let r={...$,integrity:{algorithm:"sha256",...y?{modelHash:y}:{},payloadHash:Ce($),portable:true,absolutePathsEmitted:false}};return a(r,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent"),r}function Te(e){let t=e.intelligence.relatedProjects.length>0?e.intelligence.relatedProjects.map(i=>`\`${i}\``).join(", "):"No proven cross-project relation is currently available.",n=e.intelligence.diagnostics.length>0?e.intelligence.diagnostics.slice(0,8).map(i=>`- **${i.severity} \xB7 ${i.code}:** ${i.message}`).join(`
|
|
1
|
+
import {g,b,i as i$1,d as d$2,e as e$1,f}from'./chunk-UZNACYV7.js';import {c}from'./chunk-GPOZILMY.js';import {c as c$1}from'./chunk-X7FYEKLI.js';import {d as d$3,b as b$1,a as a$1}from'./chunk-3RBUSW7H.js';import {d as d$1}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-AFIFZTOY.js';import {h,e,i}from'./chunk-NZ3WZYD5.js';import {t,h as h$1,g as g$1}from'./chunk-MOSXTVPU.js';import le from'crypto';import H from'fs';import k from'fs/promises';import d from'path';import {execa}from'execa';import he from'fs-extra';var ke=h.projectContextAgent.schemaVersion,Ze=["managed","local","off"],de="<!-- WORKSPAI:PROJECT-GROUNDING:START -->",pe="<!-- WORKSPAI:PROJECT-GROUNDING:END -->";function oe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}async function E(e){try{return JSON.parse(await k.readFile(e,"utf8"))}catch(t){return null}}function x(e){return e.replace(/\\/g,"/").replace(/^\.\/+/,"")}function O(e,t,n){let o=e.replace(/\\/g,"/"),i=/^[A-Za-z]:\//.test(o);if(!d.isAbsolute(e)&&!i)return x(o);if(i&&process.platform!=="win32")return null;let c=d.resolve(e),s=d.relative(n,c);if(s&&!s.startsWith("..")&&!d.isAbsolute(s))return x(s);let l=d.relative(t,c);return l&&!l.startsWith("..")&&!d.isAbsolute(l)?`workspace:${x(l)}`:null}function P(e,t,n){return [[n,"project:"],[n.replace(/\\/g,"/"),"project:"],[t,"workspace:"],[t.replace(/\\/g,"/"),"workspace:"]].reduce((i,[c,s])=>c.length>0?i.split(c).join(s):i,e)}function ge(e,t){return oe(e?.adoption)?.mode==="linked"?"adopted":oe(e?.import)?"imported":t}function we(e){if(!e.model)return null;let t=x(e.relativePath);return e.model.projects.find(n=>n.name===e.projectName||x(n.path)===t)??null}function ne(e,t){e[t]=(e[t]??0)+1;}var ye=["project","language","service","api","endpoint","schema","protocol","runtime-unit","lifecycle-stage","database","queue","container","deployment","pipeline","environment","test-suite","owner","decision","document","package","file","module","symbol"];function je(e,t=160){let n={language:32,api:32,service:32,endpoint:32,schema:32,protocol:32,"runtime-unit":32,"lifecycle-stage":32,file:8,module:8,symbol:8},o=[];for(let i of ye){let c=e.filter(s=>s.kind===i).sort((s,l)=>s.label.localeCompare(l.label)||s.id.localeCompare(l.id)).slice(0,n[i]??32);for(let s of c){if(o.length>=t)return o;o.push(s);}}return o}function Pe(e,t){if(!e)return {entityCount:0,relationCount:0,proofCount:0,entitiesByKind:{},relationsByKind:{},languages:{},semantic:{protocolConceptCount:0,protocolImplementationBindings:0,equivalenceBindings:0,generationBindings:0,runtimeUnitCount:0,lifecycleStageCount:0,runtimeCoverage:[]},relatedProjects:[],proofArtifacts:[],entities:[],relations:[],proofs:[],topology:{status:"unavailable",dependencies:[],dependents:[]},diagnostics:[]};let n=e.entities.find(r=>r.kind==="project"&&(r.id===t||r.label===t||r.projectId===t)),o=new Set(e.entities.filter(r=>r.projectId===t||r.id===n?.id||r.kind==="project"&&r.label===t).map(r=>r.id));n&&o.add(n.id);let i=e.relations.filter(r=>o.has(r.from)||o.has(r.to)),c=new Set(o);for(let r of i)c.add(r.from),c.add(r.to);let s=e.entities.filter(r=>c.has(r.id)),l=new Set,p={},u={},f={},w=new Set(s.filter(r=>r.kind==="language").map(r=>r.attributes.language).filter(r=>typeof r=="string"));for(let r of s){ne(p,r.kind);let a=typeof r.attributes.language=="string"?r.attributes.language:void 0;if(a&&r.kind==="language")f[a]={fileCount:typeof r.attributes.fileCount=="number"?r.attributes.fileCount:0,symbolCount:f[a]?.symbolCount??0,generatedFileCount:typeof r.attributes.generatedFileCount=="number"?r.attributes.generatedFileCount:0};else if(a&&(r.kind==="file"||r.kind==="symbol")){let h=f[a]??{fileCount:0,symbolCount:0,generatedFileCount:0};r.kind==="file"&&!w.has(a)?(h.fileCount+=1,r.attributes.generated===true&&(h.generatedFileCount+=1)):r.kind==="symbol"&&(h.symbolCount+=1),f[a]=h;}for(let h of r.proofIds)l.add(h);}for(let r of i){ne(u,r.kind);for(let a of r.proofIds)l.add(a);}let y=e.proofs.filter(r=>l.has(r.id)),b=[...new Set(e.entities.filter(r=>c.has(r.id)&&r.projectId&&r.projectId!==t).map(r=>r.projectId))].sort(),m=e.diagnostics.filter(r=>r.entityIds?.some(a=>c.has(a))||r.relationIds?.some(a=>i.some(h=>h.id===a))).map(r=>({code:r.code,severity:r.severity,message:r.message,...r.recommendation?{recommendation:r.recommendation}:{}})),g=(r,a)=>({project:a,kind:r.kind,source:r.source,confidence:r.confidence,evidence:[...new Set(r.evidence.map(h=>h.file.replace(/\\/g,"/")))].sort()}),v=e.projectTopology.edges.filter(r=>r.from===t).map(r=>g(r,r.to)).sort((r,a)=>`${r.project}:${r.kind}`.localeCompare(`${a.project}:${a.kind}`)),C=e.projectTopology.edges.filter(r=>r.to===t).map(r=>g(r,r.from)).sort((r,a)=>`${r.project}:${r.kind}`.localeCompare(`${a.project}:${a.kind}`)),R=je(s),S=s.filter(r=>r.kind==="runtime-unit"),j=new Set(R.map(r=>r.id)),_=[...i].sort((r,a)=>{let h=Number(j.has(r.from)||j.has(r.to));return Number(j.has(a.from)||j.has(a.to))-h||r.id.localeCompare(a.id)}).slice(0,128),W=new Set([...R.flatMap(r=>r.proofIds),..._.flatMap(r=>r.proofIds)]);return {entityCount:s.length,relationCount:i.length,proofCount:y.length,entitiesByKind:p,relationsByKind:u,languages:Object.fromEntries(Object.entries(f).sort(([r],[a])=>r.localeCompare(a))),semantic:{protocolConceptCount:p.protocol??0,protocolImplementationBindings:u["implements-protocol"]??0,equivalenceBindings:u["equivalent-to"]??0,generationBindings:(u["generated-from"]??0)+(u["generated-by"]??0),runtimeUnitCount:S.length,lifecycleStageCount:p["lifecycle-stage"]??0,runtimeCoverage:[...new Set(S.map(r=>r.attributes.runtime).filter(r=>typeof r=="string"))].sort()},relatedProjects:b,proofArtifacts:[...new Set(y.map(r=>r.artifact))].sort(),entities:R,relations:_,proofs:y.filter(r=>W.has(r.id)).sort((r,a)=>r.id.localeCompare(a.id)).slice(0,128),topology:{status:v.length>0||C.length>0?"proven":e.projectTopology.nodes.some(r=>r.id===t)?"unproven":"unavailable",dependencies:v,dependents:C},diagnostics:m}}function ue(e,t,n){return Array.isArray(e)?e.map(o=>typeof o=="string"?P(o,t,n):o):typeof e=="string"?P(e,t,n):e}function be(e,t,n){return {id:e.id,kind:e.kind,label:P(e.label,t,n),attributes:Object.fromEntries(Object.entries(e.attributes).map(([o,i])=>[o,ue(i,t,n)])),proofIds:[...e.proofIds].sort()}}function ve(e,t,n){let o=(...c)=>e.filter(s=>c.includes(s.kind)).map(s=>be(s,t,n)).slice(0,32),i=[];for(let c of e){for(let[s,l]of Object.entries(c.attributes))if(/(?:^|[-_.])ports?(?:$|[-_.])/i.test(s)&&(i.push({entityId:c.id,label:P(c.label,t,n),attribute:s,value:ue(l,t,n)}),i.length>=32))break;if(i.length>=32)break}return {services:o("service"),packages:o("package"),protocols:o("protocol"),runtimeUnits:o("runtime-unit"),lifecycleStages:o("lifecycle-stage"),apis:o("api"),endpoints:o("endpoint"),dataStores:o("database","queue"),deployments:o("container","deployment","environment"),pipelines:o("pipeline"),tests:o("test-suite"),owners:o("owner"),decisions:o("decision"),ports:i}}function Ae(e,t,n){let o=O(e.artifact,t,n);return o?{id:e.id,provider:e.provider,artifact:o,...e.pointer?{pointer:P(e.pointer,t,n)}:{},...e.line!==void 0?{line:e.line}:{},derivation:e.derivation,trust:e.trust,confidence:e.confidence,freshness:e.freshness}:null}async function Ee(e,t,n){let o=[],i=await E(d.join(e,".workspai","reports","INDEX.json"));if(Array.isArray(i?.blockers))for(let s of i.blockers)typeof s=="string"&&(s.startsWith(`${n}:`)||s.includes(`project:${n}`)||s.includes(`project ${n}`))&&o.push({source:"workspace-report-index",severity:"error",message:P(s,e,t)});let c=await E(d.join(e,".workspai","reports","doctor-project-last-run.json"));if(c?.projectName===n)for(let s of c$1({project:c.project}))o.push({source:"doctor-project",severity:s.status==="blocking"?"error":"warning",message:P(s.message,e,t),...s.id?{code:s.id}:{}});return [...new Map(o.map(s=>[`${s.source}:${s.code??""}:${s.message}`,s])).values()].slice(0,32)}function U(e,t=[]){return typeof e=="string"?/^[A-Za-z]:[\\/]/.test(e)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(e)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(e)||t.some(n=>n.length>0&&(e.includes(n)||e.includes(n.replace(/\\/g,"/")))):Array.isArray(e)?e.some(n=>U(n,t)):e&&typeof e=="object"?Object.values(e).some(n=>U(n,t)):false}function Ce(e){return le.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Re(e$1){let t$1=d.resolve(e$1.workspacePath),n=d.resolve(e$1.projectPath),o=t(n,"project.json").find(a=>H.existsSync(a)),i$1=o?await E(o):null,c=await E(d.join(t$1,".workspai","workspace.contract.json")),s=d.resolve(n),l=c?.projects?.find(a=>a.externalPath?d.resolve(a.externalPath)===s:!a.relativePath||a.relativePath.startsWith("external/")?false:d.resolve(t$1,a.relativePath)===s)??c?.projects?.find(a=>a.slug===e$1.projectName||a.slug===d.basename(n)),p=e$1.projectName??(typeof i$1?.name=="string"?i$1.name:void 0)??l?.slug??d.basename(n),u=l?.relativePath??(()=>{let a=x(d.relative(t$1,n));return !a||a.startsWith("..")?`external/${p}`:a})(),f=await E(d.join(t$1,e.model)),w=await E(d.join(t$1,e.knowledgeGraph)),y=f?d$1(f):void 0,b$1=!!(y&&w?.source.hash===y),m=we({model:f,projectName:p,relativePath:u}),g=Pe(b$1?w:null,p),v=await Ee(t$1,n,p),C=g.proofs.map(a=>a.freshness),R=w?!b$1||C.includes("stale")?"stale":C.includes("unknown")?"unknown":"fresh":"missing",S=f?f.factFreshness?.status??"unknown":"missing",j=[...f?[]:[{code:"project.context.model-missing",severity:"warning",message:"The canonical Workspace Model has not been generated yet. Refresh workspace intelligence before relying on project topology."}],...f&&!m?[{code:"project.context.project-not-materialized",severity:"warning",message:"The project is registered in the workspace contract but is not present in the current Workspace Model."}]:[],...w?[]:[{code:"project.context.graph-missing",severity:"warning",message:"The Workspace Knowledge Graph has not been generated yet. Run the workspace intelligence loop to build proof-backed relationships."}],...w&&!b$1?[{code:"project.context.graph-model-mismatch",severity:"warning",message:"The persisted Knowledge Graph does not match the current Workspace Model and was excluded from this project lens."}]:[]],_=ge(i$1,e$1.relationship??l?.relationship??"managed"),W={schemaVersion:ke,generatedAt:(e$1.now??new Date).toISOString(),workspace:{name:c?.workspace?.name??f?.workspace.name??d.basename(t$1),...c?.workspace?.profile||f?.workspace.profile?{profile:c?.workspace?.profile??f?.workspace.profile}:{},relationship:_,contract:`workspace:${i.workspaceContract}`,index:`workspace:${e.agentIndex}`,context:`workspace:${e.agentContext}`,skillsIndex:`workspace:${e.skillsIndex}`,boundedGraphSearch:`workspai workspace graph search <task-query> --scope project:${p} --limit 12 --json`,access:{localBinding:i.projectWorkspaceLink,canonicalEvidenceAvailableAtGeneration:true,identityIsFilesystemPath:false,resolverCommand:"workspai project workspace status --json",portableUriScheme:"workspace:",resolvedPathPolicy:"runtime-private-never-persist"}},project:{name:p,relativePath:u,...m?.kind?{kind:m.kind}:{},...m?.runtime||l?.runtime?{runtime:m?.runtime??l?.runtime}:{},...m?.runtimeCandidates?.length?{runtimeCandidates:[...m.runtimeCandidates].sort()}:{},...m?.framework||l?.framework?{framework:m?.framework??l?.framework}:{},...m?.kit||l?.kit?{kit:m?.kit??l?.kit}:{},...m?.supportTier?{supportTier:m.supportTier}:{},commands:{supported:[...m?.commands.supported??[]].sort(),unsupported:[...m?.commands.unsupported??[]].sort(),fleetStages:[...m?.commands.fleetStages??[]].sort()},importantFiles:[...new Set((m?.importantFiles??[]).map(a=>O(a,t$1,n)).filter(a=>a!==null))].sort()},intelligence:{...f?.generatedAt?{modelGeneratedAt:f.generatedAt}:{},...w?.generatedAt?{graphGeneratedAt:w.generatedAt}:{},...w?.source.hash?{graphModelHash:w.source.hash}:{},entityCount:g.entityCount,relationCount:g.relationCount,proofCount:g.proofCount,entitiesByKind:g.entitiesByKind,relationsByKind:g.relationsByKind,languages:g.languages,semantic:g.semantic,relatedProjects:g.relatedProjects,freshness:{model:S,graph:R,graphMatchesModel:b$1},topology:{...g.topology,dependencies:g.topology.dependencies.map(a=>({...a,evidence:a.evidence.map(h=>O(h,t$1,n)).filter(h=>h!==null)})),dependents:g.topology.dependents.map(a=>({...a,evidence:a.evidence.map(h=>O(h,t$1,n)).filter(h=>h!==null)}))},surfaces:ve(g.entities,t$1,n),diagnostics:[...j,...g.diagnostics].map(a=>({...a,message:P(a.message,t$1,n),...a.recommendation?{recommendation:P(a.recommendation,t$1,n)}:{}}))},evidence:{readOrder:[b,".workspai/PROJECT-GROUNDING.md",i.projectContextAgent,"AGENTS.md","workspace:.workspai/goals/index.json",`workspace:${i.goalPackLastRun}`,"workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json","workspace:.workspai/reports/workspace-skills-index.json",`command:workspai workspace graph search <task-query> --scope project:${p} --limit 12 --json`],projectProofArtifacts:[...new Set(g.proofArtifacts.map(a=>O(a,t$1,n)).filter(a=>a!==null))],relations:g.relations.map(a=>({id:a.id,from:a.from,to:a.to,kind:a.kind,derivation:a.derivation,trust:a.trust,confidence:a.confidence,proofIds:[...a.proofIds].sort()})),proofs:g.proofs.map(a=>Ae(a,t$1,n)).filter(a=>a!==null)},blockers:v,agentRouting:{enforcement:"required",mandatoryPreflight:{command:"workspai agent bootstrap --for-agent generic --strict --json",successCondition:"ready"},workspaceLocator:{command:"workspai project workspace status --json",successCondition:"resolved",outputClassification:"machine-local",persistence:"forbidden",disclosure:"forbidden",portableUriScheme:"workspace:"},workspaceEvidenceRequiredFor:["repository-analysis","architecture-analysis","change-impact","cross-project-change","contract-change","infrastructure-change","release-readiness"],requiredReadOrder:[b,"command:workspai agent bootstrap --for-agent generic --strict --json","command:workspai project workspace status --json",i.projectContextAgent,"workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json","workspace:.workspai/reports/workspace-skills-index.json",`command:workspai workspace graph search ${JSON.stringify(p)} --scope ${JSON.stringify(`project:${p}`)} --limit 12 --json`],degradedMode:{allowCompleteArchitectureClaims:false,requireDisclosure:true}},commands:{refresh:"workspai workspace intelligence run --for-agent generic --strict --json",verify:"workspai workspace verify --strict --json",graphSearch:`workspai workspace graph search ${JSON.stringify(p)} --scope ${JSON.stringify(`project:${p}`)} --limit 12 --json`,doctor:"workspai doctor project --json",workspaceStatus:"workspai project workspace status --json"}};if(U(W,[t$1,n]))throw new Error("Project context lens rejected a non-portable absolute path.");let r={...W,integrity:{algorithm:"sha256",...y?{modelHash:y}:{},payloadHash:Ce(W),portable:true,absolutePathsEmitted:false}};return a(r,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent"),r}function Te(e){let t=e.intelligence.relatedProjects.length>0?e.intelligence.relatedProjects.map(i=>`\`${i}\``).join(", "):"No proven cross-project relation is currently available.",n=e.intelligence.diagnostics.length>0?e.intelligence.diagnostics.slice(0,8).map(i=>`- **${i.severity} \xB7 ${i.code}:** ${i.message}`).join(`
|
|
2
2
|
`):"- No project-scoped graph diagnostic is currently recorded.",o=e.blockers.length>0?e.blockers.slice(0,12).map(i=>`- **${i.severity}${i.code?` \xB7 ${i.code}`:""}:** ${i.message}`).join(`
|
|
3
3
|
`):"- No current project-scoped blocker is recorded.";return `# Workspai project grounding
|
|
4
4
|
|
|
@@ -17,7 +17,8 @@ until this sequence is complete:
|
|
|
17
17
|
4. Read \`.workspai/reports/project-context-agent.json\`.
|
|
18
18
|
5. If the receipt reports an active Goal, read its immutable Goal Pack and agent
|
|
19
19
|
handoff before choosing or expanding work.
|
|
20
|
-
6.
|
|
20
|
+
6. Read the compact workspace Skills index and load only a matching playbook.
|
|
21
|
+
7. Query the bounded Workspace Graph with the user's actual task before opening broad
|
|
21
22
|
source, then inspect only returned proof paths and targeted live files.
|
|
22
23
|
|
|
23
24
|
Receipt policy:
|
|
@@ -94,7 +95,8 @@ Before broad repository discovery, architecture claims, planning, or mutation:
|
|
|
94
95
|
2. Run \`workspai agent bootstrap --for-agent generic --strict --json\`.
|
|
95
96
|
3. Follow the receipt's \`requiredReadOrder\` exactly.
|
|
96
97
|
4. If a Goal is active, read its immutable Goal Pack and handoff before acting.
|
|
97
|
-
5.
|
|
98
|
+
5. Read the compact workspace Skills index and load only a matching playbook.
|
|
99
|
+
6. Query the bounded Workspace Graph with the user's task, then inspect only returned proofs and targeted live source.
|
|
98
100
|
|
|
99
101
|
Receipt policy: \`ready\` may proceed; \`degraded\` must disclose limitations and may not claim complete architecture or verification; \`blocked\` must stop governed claims, execute \`nextActions\`, and rerun bootstrap.
|
|
100
102
|
|
|
@@ -108,9 +110,9 @@ ${pe}`;return n?`${o}
|
|
|
108
110
|
|
|
109
111
|
${n}
|
|
110
112
|
`:`${o}
|
|
111
|
-
`}async function
|
|
113
|
+
`}async function G(e,t){await k.mkdir(d.dirname(e),{recursive:true});let n=`${e}.${process.pid}.${le.randomUUID()}.tmp`;try{await k.writeFile(n,t,"utf8");try{await k.rename(n,e);}catch(o){let i=o.code;if(i!=="EEXIST"&&i!=="EPERM")throw o;await he.move(n,e,{overwrite:true});}}finally{await k.rm(n,{force:true}).catch(()=>{});}}async function fe(e,t){let n;try{n=await execa("git",["rev-parse","--show-toplevel"],{cwd:e,reject:false});}catch{return false}if(n?.exitCode!==0)return false;let o=n.stdout.trim();if(!o)return false;let i,c;try{[i,c]=await Promise.all([k.realpath(d.resolve(o)),k.realpath(e)]);}catch{return false}let s=d.resolve(c,t),l=d.relative(i,s).replace(/\\/g,"/");if(!l||d.isAbsolute(l)||l===".."||l.startsWith("../"))return false;let p;try{p=await execa("git",["cat-file","-e",`HEAD:${l}`],{cwd:i,reject:false});}catch{return false}if(p?.exitCode!==0)return false;let u;try{u=await execa("git",["ls-files","--deleted","--error-unmatch","--",`:(top)${l}`],{cwd:i,reject:false});}catch{return false}return u?.exitCode===0}async function ae(e,t){let n=d.join(e,".gitignore"),o=await k.readFile(n,"utf8").catch(l=>{if(l.code==="ENOENT")return "";throw l}),i=[g$1,h$1,b],c=o.split(/\r?\n/).filter(l=>l.trim()!=="# Workspai local project grounding"&&!i.includes(l.trim()));for(;c.length>0&&c[c.length-1]==="";)c.pop();t==="local"&&(c.length>0&&c.push(""),c.push("# Workspai local project grounding",...i));let s=c.length>0?`${c.join(`
|
|
112
114
|
`)}
|
|
113
|
-
`:"";s!==o&&await
|
|
115
|
+
`:"";s!==o&&await G(n,s);}var L=[{host:"claude",relativePath:"CLAUDE.md",importFromAgents:"@AGENTS.md",importFromGrounding:"@.workspai/PROJECT-GROUNDING.md"},{host:"gemini",relativePath:"GEMINI.md",importFromAgents:"@./AGENTS.md",importFromGrounding:"@./.workspai/PROJECT-GROUNDING.md"},{host:"qwen",relativePath:"QWEN.md",importFromAgents:"@AGENTS.md",importFromGrounding:"@.workspai/PROJECT-GROUNDING.md"},{host:"amazon-q",relativePath:".amazonq/rules/workspai-agent-entry.md",importFromAgents:"",importFromGrounding:""}];if(L.length!==g.length||L.some((e,t)=>e.relativePath!==g[t]))throw new Error("Project agent adapter paths must match the portable entry contract.");async function Ie(e,t){let n=t.split("/").slice(0,-1),o=e;for(let i of n){o=d.join(o,i);let c=await k.lstat(o).catch(s=>{if(s.code==="ENOENT")return null;throw s});if(!c)return null;if(c.isSymbolicLink()||!c.isDirectory())return d.relative(e,o).split(d.sep).join("/")}return null}function xe(e){let t=e.agentsAvailable?e.adapter.importFromAgents:e.adapter.importFromGrounding;return t?`${t}
|
|
114
116
|
|
|
115
117
|
# Workspai host binding \xB7 ${e.adapter.host}
|
|
116
118
|
|
|
@@ -131,12 +133,12 @@ Receipt policy: \`ready\` may proceed; \`degraded\` must disclose limitations; \
|
|
|
131
133
|
The workspace name is a logical identity, not a path. Resolve \`workspace:\` URIs at runtime with \`workspai project workspace status --json\`; its absolute paths are machine-local and must never be copied into shared output or portable artifacts. Live source owns exact implementation; Workspai evidence owns identity, topology, goals, readiness, and verification. Repository-authored rules remain authoritative for source changes after this entry gate.`}async function ie(e){let t=await Ie(e.projectPath,e.adapter.relativePath);if(t)return {reason:`${e.adapter.relativePath} has an unsafe repository-authored parent at ${t}.`};let n=d.join(e.projectPath,e.adapter.relativePath),o=await k.lstat(n).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(o?.isSymbolicLink())return {reason:`${e.adapter.relativePath} is a repository-authored symbolic link.`};let i=o?.isFile()===true,c=await k.readFile(n,"utf8").catch(u=>{if(u.code==="ENOENT")return "";throw u});if(e.mode==="managed"&&!i&&await fe(e.projectPath,e.adapter.relativePath))return {reason:`${e.adapter.relativePath} has an authored tracked deletion.`};let s=c.replace(q(d$2,e$1),"").replace(/\n{3,}/g,`
|
|
132
134
|
|
|
133
135
|
`).trim(),l=e.mode==="managed"?[s,`${d$2}
|
|
134
|
-
${
|
|
136
|
+
${xe(e).trim()}
|
|
135
137
|
${e$1}`].filter(Boolean).join(`
|
|
136
138
|
|
|
137
|
-
`):s;if(!l)return i&&await k.rm(n,{force:true}),{};let
|
|
138
|
-
`;return
|
|
139
|
-
`;return
|
|
140
|
-
`),await
|
|
141
|
-
`),await
|
|
142
|
-
`);let m=[i.projectWorkspaceLink,h$1,g$1,b];l&&m.push("AGENTS.md");for(let
|
|
139
|
+
`):s;if(!l)return i&&await k.rm(n,{force:true}),{};let p=`${l.trimEnd()}
|
|
140
|
+
`;return p!==c&&await G(n,p),e.mode==="managed"?{path:e.adapter.relativePath}:{}}function Ge(e){let t={id:"generic",discovery:"portable-fallback",entryFiles:[g$1],status:"ready",managed:e.mode==="managed"},o=["codex","kimi","grok","copilot","cursor","windsurf"].map(s=>({id:s,discovery:"native",entryFiles:["AGENTS.md"],status:e.agentsAvailable?"ready":"blocked",managed:e.mode==="managed"&&e.agentsAvailable,...e.agentsAvailable?{}:{reason:"AGENTS.md could not be managed without overriding authored repository state."}})),i=L.map(s=>{let l=e.adapters.get(s.host);return {id:s.host,discovery:"adapter",entryFiles:[s.relativePath],status:l?.path?"ready":e.mode==="managed"?"blocked":"degraded",managed:!!l?.path,...l?.path?{}:{reason:l?.reason??"Provider adapter generation is disabled by the project grounding policy."}}}),c=[t,...o,...i];return f.map(s=>c.find(l=>l.id===s))}async function ce(e,t,n){let o=d.join(e,"AGENTS.md"),i=await k.lstat(o).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(i?.isSymbolicLink())return;let c=i?.isFile()===true,s=await k.readFile(o,"utf8").catch(u=>{if(u.code==="ENOENT")return "";throw u});if(t==="managed"&&!n)throw new Error("Managed project grounding requires a project context.");if(t==="managed"&&!c&&await fe(e,"AGENTS.md"))return;let l=t==="managed"&&n?Ne(s,Se(n)):me(s);if(!l){c&&await k.rm(o,{force:true});return}let p=`${l.trimEnd()}
|
|
141
|
+
`;return p!==s&&await G(o,p),t==="managed"?o:void 0}async function We(e){let t$1=e.mode??"managed",n=d.resolve(e.workspacePath),o=d.resolve(e.projectPath);if(t$1==="off"){let g=t(o,"project.json").find(j=>H.existsSync(j)),v=g?await E(g):null,C=e.projectName??(typeof v?.name=="string"?v.name:void 0)??d.basename(o),R=ge(v,e.relationship??"managed"),S=await c({workspacePath:n,projectPath:o,projectName:C,relationship:R,now:e.now});return await ae(o,t$1),await ce(o,t$1),await Promise.all(L.map(j=>ie({projectPath:o,adapter:j,mode:t$1,agentsAvailable:false}))),await Promise.all([k.rm(d.join(o,h$1),{force:true}),k.rm(d.join(o,g$1),{force:true}),k.rm(d.join(o,b),{force:true})]),{mode:t$1,projectPath:o,linkPath:S.linkPath,writtenFiles:[i.projectWorkspaceLink]}}let i$2=await Re(e),c$1=i$2.workspace.relationship,s=await c({workspacePath:n,projectPath:o,projectName:i$2.project.name,relationship:c$1,workspaceName:i$2.workspace.name,relativePath:i$2.project.relativePath,now:e.now});await ae(o,t$1);let l=await ce(o,t$1,i$2),p=new Map;for(let g of L)p.set(g.host,await ie({projectPath:o,adapter:g,mode:t$1,agentsAvailable:!!l}));let u=Ge({mode:t$1,agentsAvailable:!!l,adapters:p}),f=d.join(o,h$1),w=d.join(o,g$1),y=d.join(o,b),b$1=i$1({context:i$2,hosts:u});await G(f,`${JSON.stringify(i$2,null,2)}
|
|
142
|
+
`),await G(w,`${Te(i$2).trimEnd()}
|
|
143
|
+
`),await G(y,`${JSON.stringify(b$1,null,2)}
|
|
144
|
+
`);let m=[i.projectWorkspaceLink,h$1,g$1,b];l&&m.push("AGENTS.md");for(let g of p.values())g.path&&m.push(g.path);return {mode:t$1,projectPath:o,linkPath:s.linkPath,groundingPath:w,contextPath:f,agentEntryPath:y,agentsPath:l,hostCoverage:u,writtenFiles:m}}async function et(e){let t=d.resolve(e.workspacePath),n=e.mode??"managed",o=await $e(t),i=[],c=[];for(let s of o.resolved)try{i.push(await We({workspacePath:t,projectPath:s.projectPath,projectName:s.name,relationship:s.relationship,mode:n,now:e.now}));}catch(l){c.push({name:s.name,reason:l instanceof Error?l.message:String(l)});}return {workspacePath:t,mode:n,projects:i,skipped:[...o.skipped,...c]}}async function $e(e){let t=d.resolve(e),n=await E(d.join(t,".workspai","workspace.contract.json")),o=[],i=[];for(let c of n?.projects??[]){let s=c.slug??c.relativePath??"unknown-project",l=typeof c.externalPath=="string"?d.resolve(c.externalPath):typeof c.relativePath=="string"&&!c.relativePath.startsWith("external/")?d.resolve(t,c.relativePath):null;if(!l||!H.existsSync(l)){i.push({name:s,reason:"project path is unavailable on this machine"});continue}o.push({name:s,projectPath:l,relationship:c.relationship??"managed"});}return {resolved:o,skipped:i}}export{ke as a,Ze as b,de as c,pe as d,Re as e,We as f,et as g,$e as h};
|
|
@@ -2,7 +2,7 @@ import {c as c$1}from'./chunk-HCFWT42C.js';import {a}from'./chunk-A5FBGRJA.js';i
|
|
|
2
2
|
`);}async function re(e,r){let t=p.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${e}.${process.pid}.${randomUUID()}.tmp`;try{await promises.writeFile(o,r);let a=await promises.open(o,"r");try{await te(a);}finally{await a.close();}try{await promises.rename(o,e);}catch(s){let i=s.code;if(i!=="EEXIST"&&i!=="EPERM")throw s;await ne.move(o,e,{overwrite:true});}}finally{await promises.rm(o,{force:true}).catch(()=>{});}}async function q(e){try{return {exists:true,content:await promises.readFile(e)}}catch(r){if(r.code==="ENOENT")return {exists:false};throw r}}async function Q(e,r){if(!r.exists){await promises.rm(e,{force:true});return}await re(e,r.content);}async function ue(e,r){let t=p.join(e,"workspaces.json.lock"),o=randomUUID();await promises.mkdir(e,{recursive:true});let a=Date.now(),s;for(;!s;)try{s=await promises.open(t,"wx"),await s.writeFile(`${JSON.stringify({pid:process.pid,lockId:o,createdAt:new Date().toISOString()})}
|
|
3
3
|
`),await te(s);}catch(i){if(i.code!=="EEXIST")throw i;let n=await promises.stat(t).catch(()=>null);if(n&&Date.now()-n.mtimeMs>ce){let d=await promises.readFile(t,"utf8").then(m=>JSON.parse(m)).catch(()=>null),u=Number(d?.pid),w=false;if(Number.isInteger(u)&&u>0)try{process.kill(u,0),w=true;}catch(m){w=m.code==="EPERM";}if(!w){await promises.rm(t,{force:true}).catch(()=>{});continue}}if(Date.now()-a>pe)throw new Error(`Timed out waiting for workspace registry lock: ${t}`);await new Promise(d=>setTimeout(d,25));}try{return await r()}finally{await s.close().catch(()=>{}),await promises.readFile(t,"utf8").then(n=>JSON.parse(n).lockId===o).catch(()=>false)&&await promises.rm(t,{force:true}).catch(()=>{});}}async function _(e){let r$1=q$1(),t=p.join(r$1,"workspaces.json"),o=p.join(r(),"workspaces.json"),a=[...new Set(s$1())];return ue(r$1,async()=>{let[s,i]=await Promise.all([q(t),q(o)]),n=await ee(a);await e(n);let d=b(n);try{await K(t,d),await K(o,d);}catch(u){let m=(await Promise.allSettled([Q(t,s),Q(o,i)])).filter(g=>g.status==="rejected").map(g=>g.reason);throw m.length>0?new AggregateError([u,...m],"Workspace registry transaction failed and could not be fully restored"):u}return d})}async function oe(e,r){let t=a(e);await _(o=>{let a=o.workspaces.find(s=>s.path===t);if(a){a.name=r,a.mode=a.mode||"full",a.projects=Array.isArray(a.projects)?a.projects:[];return}o.workspaces.push({name:r,path:t,mode:"full",projects:[]});});}async function ze(e){let r=a(e),o=(await ee()).workspaces.find(a=>a.path===r);return o?{...o,projects:o.projects.map(a=>({...a}))}:null}async function Ge(e,r){let t=a(e);await _(o=>{let a=o.workspaces.findIndex(i=>i.path===t);if(!r){a>=0&&o.workspaces.splice(a,1);return}let s=B(r);a>=0?o.workspaces[a]=s:o.workspaces.push(s);});}async function Me(e){let r=a(e);await _(t=>{t.workspaces=t.workspaces.filter(o=>o.path!==r);});}async function ke(e,r){try{await oe(e,r);}catch{console.warn(c.gray("Note: Could not register workspace in shared registry"));}}async function Ve(e,r=false){let t$1=a(e),o={workspacePath:t$1,workspaceFound:false,added:[],skipped:0};try{let a$1=await F(),s=a$1.workspaces.find(g=>g.path===t$1);if(!s){if(await ke(t$1,p.basename(p.resolve(e))),a$1=await F(),s=a$1.workspaces.find(g=>g.path===t$1),!s)return r||console.log("\u26A0\uFE0F Workspace could not be registered in registry"),o;r||console.log("\u2714 Registered workspace in shared registry");}Array.isArray(s.projects)||(s.projects=[]);let i=0,n=0,d=[],u=[],w=[e],m=new Set;for(;w.length>0;){let g=w.shift();if(!g||m.has(g))continue;m.add(g);let y=await promises.readdir(g,{withFileTypes:true});for(let h of y){if(!h.isDirectory()||h.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(h.name))continue;let j=p.join(g,h.name),f=a(j);try{let k=false;for(let $ of [...t(f,"context.json"),...t(f,"project.json")])try{await promises.access($),k=true;break}catch{}if(k){let $=p.basename(f),R=s.projects.some(C=>C.path===f);u.push({name:$,path:f}),R?n++:(s.projects.push({name:$,path:f}),i++,d.push(f),r||console.log(`\u2714 Added: ${p.relative(e,f)}`));continue}}catch{}w.push(j);}}return await _(g=>{let y=g.workspaces.find(f=>f.path===t$1);if(!y)return;let h=`${t$1}${p.sep}`,j=(y.projects||[]).filter(f=>f.path!==t$1&&!f.path.startsWith(h));y.projects=B({...y,projects:[...j,...u]}).projects;}),i>0?r||console.log(`
|
|
4
4
|
\u2705 Synced ${i} project(s) to registry`):r||console.log(`
|
|
5
|
-
\u2705 All projects already registered (${n} found)`),{workspacePath:t$1,workspaceFound:true,added:d,skipped:n}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function we(e,r,t){let o=a(e),a$1=a(t);await _(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let n=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};n>=0?i.projects[n]=d:i.projects.push(d);});}async function Ye(e,r,t){try{await we(e,r,t);}catch{}}async function He(e,r){let t=P("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(p.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(p.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-
|
|
5
|
+
\u2705 All projects already registered (${n} found)`),{workspacePath:t$1,workspaceFound:true,added:d,skipped:n}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function we(e,r,t){let o=a(e),a$1=a(t);await _(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let n=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};n>=0?i.projects[n]=d:i.projects.push(d);});}async function Ye(e,r,t){try{await we(e,r,t);}catch{}}async function He(e,r){let t=P("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(p.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(p.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-CKUQRSJF.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=fe();await promises.writeFile(p.join(e,"rapidkit"),s),await promises.chmod(p.join(e,"rapidkit"),493);let i=he();await promises.writeFile(p.join(e,"rapidkit.cmd"),i);let n=ye(r.name);await promises.writeFile(p.join(e,"README.md"),n),await promises.writeFile(p.join(e,".gitignore"),`# Workspai workspace
|
|
6
6
|
.env
|
|
7
7
|
.env.*
|
|
8
8
|
!.env.example
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-JEI6BTZI.js';import {a}from'./chunk-PXWKMPPI.js';import {c,e,d}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-JEI6BTZI.js';import {a}from'./chunk-PXWKMPPI.js';import {c,e,d}from'./chunk-YUGKQ44M.js';import {d as d$1,b}from'./chunk-O6R7SE6Y.js';import {g}from'./chunk-NBJ6AP7K.js';import {p as p$1,l}from'./chunk-NA2NXX5P.js';import {m,a as a$2}from'./chunk-KG3TUTXU.js';import {e as e$1}from'./chunk-CCDGHPEJ.js';import {b as b$2}from'./chunk-D65FCQIO.js';import {a as a$3}from'./chunk-AFIFZTOY.js';import v from'path';import b$1 from'fs-extra';function J(e$1){switch(e$1){case "why":return d;case "trace":return e;default:return c}}async function P(e,o,n){try{if(!await b$1.pathExists(e))return null;let r=await b$1.readJson(e);return o?b$2(o,r,e):n&&a$3(r,n,e),r}catch(r){if((o||n)&&await b$1.pathExists(e))throw r;return null}}function G(e,o){if(!e)return null;let n=o.trim().toLowerCase();return e.projects.find(r=>r.slug.toLowerCase()===n||r.relativePath.toLowerCase()===n)??null}function X(e,o,n){let r=n.trim().toLowerCase(),t=(l(e)?.nodes.map(a=>a.id)??e.projects.map(a=>a.name)).find(a=>a.toLowerCase()===r);if(t)return t;let d=e.projects.find(a=>[a.name,a.path,v.basename(a.path)].filter(u=>u.trim().length>0).some(u=>u.toLowerCase()===r));if(d)return d.name;let c=G(o,n);if(c){let a=e.projects.find(u=>u.path===c.relativePath||u.path.endsWith(`/${c.relativePath}`));if(a)return a.name}return n}function Y(e,o){if(!e)return [];let n=o.trim().toLowerCase(),r=new Set;for(let l of e.projects){l.contracts.dependsOn?.some(t=>t.toLowerCase()===n)&&r.add(l.slug);for(let t of l.contracts.consumes??[])for(let d of e.projects)d.contracts.publishes?.includes(t)&&d.slug===n&&r.add(l.slug);}return [...r].sort()}function q(e,o){if(!e)return [];let n=o.trim().toLowerCase();return e.steps.filter(r=>r.scope==="project"&&r.project?.toLowerCase()===n&&r.command?.display).map(r=>r.command.display).slice(0,8)}function p(e,o,n){return {id:e,title:o,body:n.trim()}}async function fe(e){let o=v.resolve(e.workspacePath),n=(e.now??new Date).toISOString(),r=e.model??await p$1({workspacePath:o,includeEvidence:true}),l$1=e.contract;if(l$1===void 0)try{l$1=(await m({workspacePath:o})).contract;}catch{l$1=null;}let t=e.verify;t===void 0&&(t=await P(v.join(o,d$1),d$1));let d=e.impact;if(d===void 0&&(d=await P(v.join(o,g),g)),e.target.kind==="release-blocked"){let s=t?.blockingReasons??[],i=(r.summary?.projectCount??r.projects.length)===0,g=[p("verdict",i?"Workspace scaffold posture":"Release verdict",t?i?`Scaffold posture: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Freshness: **${t.freshness.verdict}**. No registered projects yet \u2014 release gates apply after the first project is added.`:`Verdict: **${t.summary.verdict}** (exit ${t.summary.exitCode}). Risk: **${t.impact.risk}**. Freshness: **${t.freshness.verdict}**.`:"No workspace verify report found. Run `npx workspai workspace verify --json --write` first."),p("blockers",i?"Pre-project signals":"Blocking reasons",s.length?s.map(h=>`- ${h}`).join(`
|
|
2
2
|
`):i?"No pre-project signals in the latest verify report.":"No blocking reasons in the latest verify report.")];return t?.resolutionHints?.length&&g.push(p("resolution","Resolution hints",t.resolutionHints.map(h=>`- **${h.blockerId}** (${h.resolutionClass}): ${h.commandRetryHint??h.fixHints[0]?.detail??"See fix hints"}`).join(`
|
|
3
3
|
`))),{schemaVersion:a,generatedAt:n,workspacePath:o,target:e.target,summary:t?i?b(s.length,t.summary.verdict):s.length>0||t.summary.verdict==="blocked"?`Release blocked: ${t.summary.verdict} with ${s.length} blocking reason(s).`:t.summary.verdict==="needs-attention"?"Release needs attention: advisory or incomplete verification evidence remains; no blocking reason was reported.":`Release posture: ${t.summary.verdict}; no blocking reason was reported.`:"Release posture unknown \u2014 verify report missing.",sections:g,releaseVerdict:t?.summary.verdict,evidenceFreshness:t?.freshness.verdict,blocking:!!(t&&(t.summary.verdict==="blocked"||s.length>0)),releaseRisk:t?.impact.risk,blockingReasons:s,resolutionHints:t?.resolutionHints}}if(e.target.kind==="blocker"){let s=e.target,m=t?.resolutionHints?.find(g=>g.blockerId===s.blockerId),i=t?.blockingReasons.find(g=>g.includes(s.blockerId))??t?.blockingReasons[0];return {schemaVersion:a,generatedAt:n,workspacePath:o,target:s,summary:m?`Blocker ${s.blockerId}: ${m.resolutionClass}`:`Blocker ${s.blockerId} (no structured hint)`,sections:[p("reason","Blocking signal",i??"No matching blocking reason in verify."),p("hint","Resolution class",m?`${m.resolutionClass}
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {r as r$1}from'./chunk-VDFHUYAQ.js';import {a as a$1}from'./chunk-7ITSLGPZ.js';import {b,c as c$2}from'./chunk-WLFJHRB3.js';import {a as a$2}from'./chunk-GPGEJVVO.js';import {g}from'./chunk-WUB6QGC7.js';import {j,l as l$2}from'./chunk-NRVSDL4J.js';import {c as c$1,d}from'./chunk-OU7DF6MP.js';import {a}from'./chunk-WQX3JYEP.js';import {f as f$1,g as g$1,h as h$1}from'./chunk-O6R7SE6Y.js';import {k,l as l$1,h,m as m$1,n,p as p$2,q}from'./chunk-NBJ6AP7K.js';import {a as a$3}from'./chunk-A4BK7C7M.js';import {j as j$1,e as e$2}from'./chunk-N4QQADXX.js';import {m,p as p$1,s}from'./chunk-NA2NXX5P.js';import {l,o as o$1,p as p$3}from'./chunk-KG3TUTXU.js';import {c,e as e$1}from'./chunk-CCDGHPEJ.js';import {b as b$1}from'./chunk-D65FCQIO.js';import {e,f,o,p,n as n$1,m as m$2}from'./chunk-NZ3WZYD5.js';import {c as c$3}from'./chunk-X6TNBARH.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(e.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===e.intelligenceRun,`artifactPath must be ${e.intelligenceRun}`),r(t.preflight.length===n$1.length,`preflight must contain exactly ${n$1.length} entries`);for(let[d,n]of n$1.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,o[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===m$2.length,`stages must contain exactly ${m$2.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of m$2.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,p[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=e.intelligenceRun,Ee=f.intelligenceRun,L=we;function I(t){c$3({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return c(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t){let s$1=t.workspacePath,m$2=[],u=[],h$2=false,y=async(e,o$1)=>{let c=[...o[e]];if(h$2){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$2.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o$1();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$2.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$2.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$3=async(e,o)=>{let c=[...p[e].produces];if(h$2){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o=await l({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o.contract.projects.length} projects`}});let p$4,d$1=()=>{if(!p$4)throw new Error("canonical workspace model is unavailable");return p$4};await l$3("model",async()=>(p$4={...await p$1({workspacePath:s$1,includeEvidence:true}),build:m({mode:"full",engineStatus:"disabled"})},await s(p$4,s$1),{message:`${p$4.summary.projectCount} projects modeled`}));let n$1=ge.join(s$1,e.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$1)){let c=await k({workspacePath:s$1,model:d$1()});return await l$1(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$1),o=h(e);return o?(await l$1(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$3("diff",async()=>{let e$1=await m$1({workspacePath:s$1,fromPath:e.snapshot,model:d$1()});return await n(e$1,s$1),{message:e$1.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$3("impact",async()=>{let e$1=await p$2({workspacePath:s$1,fromPath:e.diff});return await q(e$1,s$1),{message:`${e$1.summary.risk} risk; ${e$1.summary.affectedProjects} affected`}}),await l$3("doctor-evidence",async()=>{let e=await r$1({workspace:s$1,json:true,quiet:true,profile:t.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$3("contract-evidence",async()=>{let e=await o$1({workspacePath:s$1,strict:true});return await p$3({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$3("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t.strict===true});return {blocked:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$3("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$3("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:e.impact});await g$1(e$1,s$1);let o=h$1(e$1,{strict:t.strict===true});return await j$1(s$1,e$2(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$3("context",async()=>{let e=await c$1({workspacePath:s$1,model:d$1(),agent:t.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$3("agent-sync",async()=>{let e=await l$2({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"}),o=false,c=await a$3(s$1);if(c.status==="miss"){if(c.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c.reason}).`);p$4={...await p$1({workspacePath:s$1,includeEvidence:true}),build:m({mode:"full",engineStatus:"disabled"})},await s(p$4,s$1);let f=await c$1({workspacePath:s$1,model:p$4,agent:t.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$2({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$3("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$2(e,s$1);let o=t.strict===true?u.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u.some(e=>e.status==="blocked"),G=h$2?"failed":me?"blocked":"passed",fe=h$2?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$2,status:G,exitCode:fe,stages:u,artifactPath:L};ue(b$1),await e$1(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await e$1(s$1,e.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
|
|
1
|
+
import {r as r$1}from'./chunk-VDFHUYAQ.js';import {a as a$1}from'./chunk-VRQLHCE2.js';import {b,c as c$2}from'./chunk-PPQL5UTI.js';import {a as a$2}from'./chunk-GPGEJVVO.js';import {g}from'./chunk-PKKP5H3T.js';import {j,l as l$2}from'./chunk-46USUSIK.js';import {c as c$1,d}from'./chunk-TVCJKE2U.js';import {a}from'./chunk-LNXIMF3O.js';import {f as f$1,g as g$1,h as h$1}from'./chunk-O6R7SE6Y.js';import {k,l as l$1,h,m as m$1,n,p as p$2,q}from'./chunk-NBJ6AP7K.js';import {a as a$3}from'./chunk-A4BK7C7M.js';import {j as j$1,e as e$2}from'./chunk-N4QQADXX.js';import {m,p as p$1,s}from'./chunk-NA2NXX5P.js';import {l,o as o$1,p as p$3}from'./chunk-KG3TUTXU.js';import {c,e as e$1}from'./chunk-CCDGHPEJ.js';import {b as b$1}from'./chunk-D65FCQIO.js';import {e,f,o,p,n as n$1,m as m$2}from'./chunk-NZ3WZYD5.js';import {c as c$3}from'./chunk-X6TNBARH.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(e.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===e.intelligenceRun,`artifactPath must be ${e.intelligenceRun}`),r(t.preflight.length===n$1.length,`preflight must contain exactly ${n$1.length} entries`);for(let[d,n]of n$1.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,o[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===m$2.length,`stages must contain exactly ${m$2.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of m$2.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,p[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=e.intelligenceRun,Ee=f.intelligenceRun,L=we;function I(t){c$3({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return c(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t){let s$1=t.workspacePath,m$2=[],u=[],h$2=false,y=async(e,o$1)=>{let c=[...o[e]];if(h$2){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$2.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o$1();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$2.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$2.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$3=async(e,o)=>{let c=[...p[e].produces];if(h$2){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$2=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o=await l({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o.contract.projects.length} projects`}});let p$4,d$1=()=>{if(!p$4)throw new Error("canonical workspace model is unavailable");return p$4};await l$3("model",async()=>(p$4={...await p$1({workspacePath:s$1,includeEvidence:true}),build:m({mode:"full",engineStatus:"disabled"})},await s(p$4,s$1),{message:`${p$4.summary.projectCount} projects modeled`}));let n$1=ge.join(s$1,e.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$1)){let c=await k({workspacePath:s$1,model:d$1()});return await l$1(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$1),o=h(e);return o?(await l$1(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$3("diff",async()=>{let e$1=await m$1({workspacePath:s$1,fromPath:e.snapshot,model:d$1()});return await n(e$1,s$1),{message:e$1.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$3("impact",async()=>{let e$1=await p$2({workspacePath:s$1,fromPath:e.diff});return await q(e$1,s$1),{message:`${e$1.summary.risk} risk; ${e$1.summary.affectedProjects} affected`}}),await l$3("doctor-evidence",async()=>{let e=await r$1({workspace:s$1,json:true,quiet:true,profile:t.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$3("contract-evidence",async()=>{let e=await o$1({workspacePath:s$1,strict:true});return await p$3({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$3("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t.strict===true});return {blocked:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$3("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$3("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:e.impact});await g$1(e$1,s$1);let o=h$1(e$1,{strict:t.strict===true});return await j$1(s$1,e$2(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$3("context",async()=>{let e=await c$1({workspacePath:s$1,model:d$1(),agent:t.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$3("agent-sync",async()=>{let e=await l$2({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"}),o=false,c=await a$3(s$1);if(c.status==="miss"){if(c.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c.reason}).`);p$4={...await p$1({workspacePath:s$1,includeEvidence:true}),build:m({mode:"full",engineStatus:"disabled"})},await s(p$4,s$1);let f=await c$1({workspacePath:s$1,model:p$4,agent:t.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$2({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$3("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$2(e,s$1);let o=t.strict===true?u.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u.some(e=>e.status==="blocked"),G=h$2?"failed":me?"blocked":"passed",fe=h$2?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$2,status:G,exitCode:fe,stages:u,artifactPath:L};ue(b$1),await e$1(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await e$1(s$1,e.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {f,e as e$2,g as g$1}from'./chunk-NVQUBUTY.js';import {b as b$4}from'./chunk-
|
|
1
|
+
import {f,e as e$2,g as g$1}from'./chunk-NVQUBUTY.js';import {b as b$4}from'./chunk-VDEFHP6I.js';import {b as b$7,a as a$3}from'./chunk-THIOE2PB.js';import {b as b$2}from'./chunk-B6FJ6RG6.js';import {a as a$2}from'./chunk-KCJ3VS6R.js';import {e,g,f as f$1,b as b$6,c as c$1,d as d$3}from'./chunk-PTNLVI62.js';import {d,b as b$1}from'./chunk-Y5YAP4F3.js';import {d as d$4}from'./chunk-KG3TUTXU.js';import {h,e as e$1,b as b$3,d as d$1}from'./chunk-X6TNBARH.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {b,a,c,d as d$2}from'./chunk-MOSXTVPU.js';import {b as b$5,k,j,m,i,t,s,q as q$1}from'./chunk-RJIYCDVC.js';import {promises}from'fs';import*as P from'fs-extra';import p from'path';import r from'chalk';import {execa}from'execa';function st(e){let n=e.projectCount??0,t=n===1?"project":"projects",a=e.pythonEngine==="installed"?`Python ${e.pythonVersion||"3.10+"} \xB7 ${e.installMethod||"local environment"}`:e.pythonEngine==="skipped"?"Python engine not installed":"Runtime-neutral foundation";return ["","\u2713 Workspace ready",`${e.workspaceName} \xB7 ${e.profile} \xB7 ${n} registered ${t}`,`Location ${e.workspacePath}`,`Runtime ${a}`,...e.note?[`Note ${e.note}`]:[],"","Workspace Intelligence"," \u2713 Contract and project registry"," \u2713 Canonical model and proof-backed graph"," \u2713 Agent context, grounding, and evidence index","","Next",` ${g$1(e.workspacePath)}`," npx workspai create"," npx workspai workspace intelligence run --for-agent generic --strict --json","","Evidence .workspai/reports/INDEX.json","Guide README.md",""]}function q(e){let n=st(e);for(let t of n)t==="\u2713 Workspace ready"?console.log(r.green.bold(t)):t==="Workspace Intelligence"||t==="Next"?console.log(r.cyan.bold(t)):t.startsWith(" \u2713")?console.log(r.green(t)):t.startsWith("Location")||t.startsWith("Runtime")?console.log(r.gray(t)):console.log(t);}function M(){return i()}var lt="transactions";function ct(){return p.join(q$1(),lt)}async function Ve(){let e=ct();return await b$7(e),a$3({journalDirectory:e})}async function Ge(e){for(let n of s())await e.captureFile(n);}async function ae(e){let n=await Ve();try{return await Ge(n),await n.captureOwnedTree(e),n}catch(t){return K(n,t)}}async function pt(e){let n=await Ve();try{await Ge(n),await n.captureOwnedTree(p.join(e,a)),await n.captureOwnedTree(p.join(e,".venv"));let t=[c,".gitignore",p.join(a,"workspace.json"),p.join(a,"toolchain.lock"),p.join(a,"policies.yml"),p.join(a,"cache-config.yml"),d$4,a$2,"pyproject.toml","poetry.toml","poetry.lock","rapidkit","rapidkit.cmd","README.md",".rapidkit-global"];for(let a of t)await n.captureFile(p.join(e,a));return n}catch(t){return K(n,t)}}async function z(e){await e.commit(),e.journalPath&&await promises.rm(p.dirname(e.journalPath),{recursive:true,force:true}).catch(n=>e$1.debug(`Could not remove committed lifecycle journal: ${n}`));}async function K(e,n){try{await e.rollback();}catch(t){throw new AggregateError([n,t],"Workspace lifecycle failed and rollback was incomplete.")}throw n}async function B(e,n,t,a,s){let l=d(n,h(),t,s?.pythonEngine?{coreStatus:s.pythonEngine,...s.pythonEngineReason?{coreReason:s.pythonEngineReason}:{},...a?{pythonVersion:a}:{}}:void 0);a&&!s?.pythonEngine&&(l.metadata||(l.metadata={}),l.metadata.python={pythonVersion:a}),await b$1(e,l);}async function G(e){await P.outputFile(p.join(e,".gitignore"),`.venv/
|
|
2
2
|
__pycache__/
|
|
3
3
|
*.pyc
|
|
4
4
|
.env
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-LNXIMF3O.js';import {c}from'./chunk-TFOOSYGO.js';import {p as p$1,h,i}from'./chunk-NA2NXX5P.js';import {a}from'./chunk-KG3TUTXU.js';import {e as e$1,d}from'./chunk-CCDGHPEJ.js';import {f,e}from'./chunk-NZ3WZYD5.js';import E from'path';import S from'fs-extra';var te=f.agentContext,se=e.agentContext;function ae(e){if(typeof e!="string"||!e.trim()||e==="true")return "generic";let r=e.trim().toLowerCase();return r==="codex"||r==="claude"||r==="cursor"||r==="gemini"||r==="qwen"||r==="kimi"||r==="grok"||r==="copilot"||r==="windsurf"||r==="amazon-q"||r==="orca"?r:"generic"}function L(e){return `npx --yes --package workspai workspai ${e}`.trim()}function j(e){return `npx workspai ${e}`.trim()}async function C(e,r,i){let s=E.join(e,r);if(!await S.pathExists(s))return null;try{let a=await S.readJson(s);return !a||a.schemaVersion!==i?null:a}catch{return null}}function p(e$1){return {id:e$1.id,scope:e$1.scope,display:j(e$1.args),execute:L(e$1.args),description:e$1.description,...e$1.project?{project:e$1.project}:{},freshness:h({id:`command.${e$1.id}`,label:`${e$1.id} command`,scope:"command",value:{display:j(e$1.args),execute:L(e$1.args)},...e$1.project?{project:e$1.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:e$1.generatedAt,now:e$1.now,sourceArtifact:e.model,sourcePath:`safeCommands.${e$1.id}`,reason:"Safe command surfaces are derived from workspace model command capabilities."}}).freshness}}function D(e,r){return `workspace run ${r} --scope project:${e.name}`}function ne(e){return (e.startsWith("project:")?e.slice(8):e).trim().toLowerCase()}function oe(e){return [e.name,e.path,E.basename(e.path),e.absolutePath].filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim().toLowerCase())}function ie(e,r,i){let s={generatedAt:e.generatedAt,now:i},a=[p({id:"workspace.model",scope:"workspace",args:"workspace model --json",description:"Read the canonical workspace intelligence model.",...s}),p({id:"workspace.graph.entities",scope:"workspace",args:"workspace graph entities --json",description:"Query proof-backed workspace entities without loading the full graph.",...s}),p({id:"workspace.graph.evidence",scope:"workspace",args:"workspace graph evidence <entity-or-relation> --json",description:"Resolve portable evidence for a graph entity or relation.",...s}),p({id:"workspace.graph.path",scope:"workspace",args:"workspace graph path <from> <to> --json",description:"Find a shortest proof-carrying path between workspace entities.",...s}),p({id:"workspace.doctor",scope:"workspace",args:"doctor workspace --json",description:"Check workspace health before claiming verification.",...s}),p({id:"workspace.pipeline",scope:"workspace",args:"pipeline --json",description:"Run the governed sync, doctor, analyze, readiness, and autopilot loop.",...s}),p({id:"workspace.contract.verify",scope:"workspace",args:"workspace contract verify --json",description:"Verify workspace contract and dependency edges.",...s}),p({id:"workspace.verify",scope:"workspace",args:"workspace verify --json",description:"Evaluate evidence freshness and verification gates before release decisions.",...s})],c=r?[r]:e.projects;for(let n of c)n.commands.fleetStages.includes("test")&&a.push(p({id:`project.${n.name}.test`,scope:"project",project:n.name,args:D(n,"test"),description:`Run tests for ${n.name} through workspace orchestration.`,...s})),n.commands.fleetStages.includes("build")&&a.push(p({id:`project.${n.name}.build`,scope:"project",project:n.name,args:D(n,"build"),description:`Build ${n.name} through workspace orchestration.`,...s}));return a}function ce(e){return e.commands.fleetStages.filter(r=>r==="test"||r==="build").map(r=>`workspace run ${r}`)}function de(e,r){if(!r?.startsWith("project:"))return;let i=ne(r);if(i)return e.projects.find(s=>oe(s).includes(i))}function me(e,r,i){let s=[...e.validation?.issues??[]];r?.startsWith("project:")&&!i&&s.push({severity:"error",code:"context.scope.project.missing",message:`Requested project scope was not found: ${r}`,target:r});let a=s.filter(n=>n.severity==="error").length,c=s.filter(n=>n.severity==="warning").length;return {status:a>0?"failed":c>0?"warning":"passed",errors:a,warnings:c,issues:s}}async function pe(e,r){let i=[],s=[];for(let[a,c]of Object.entries(e.evidence))c&&await d(r,c.path)!==null?i.push(`${a}: ${c.path}`):s.push(a);return {available:i.sort(),missing:s.sort()}}function le(e){let r=e.summary.projectCount,i=e.summary.runtimes.length?`${e.summary.runtimes.join(", ")} runtime coverage`:"no runtime coverage",s=e.identity.surfaces.length?e.identity.surfaces.join(", "):"no detected surfaces";return `${e.workspace.name} is a ${e.identity.workspaceType} with ${r} project${r===1?"":"s"}, ${i}, and ${s}.`}function ue(e){let r=["Do not claim a command passed unless a report or command output proves it.","Do not infer secrets or environment values from file names.","Do not change project scope without checking the selected project."];return e.contracts.exists||r.push("Workspace contract is missing; dependency and API edges may be incomplete."),e.summary.observedProjects>0&&r.push("Some projects are observed rather than first-class; command support may be partial."),r}async function xe(e$1){let r=e$1.model??await p$1({workspacePath:e$1.workspacePath,includeEvidence:e$1.includeEvidence===true,observableScanDepth:e$1.observableScanDepth,now:e$1.now}),i$1=ae(e$1.agent),s=de(r,e$1.scope),a=me(r,e$1.scope,s);if(e$1.strict===true&&a.status!=="passed"){let t=a.issues.map(u=>`${u.severity}:${u.code}:${u.target}`).join(", ");throw new Error(`Workspace context strict validation failed: ${t}`)}let c$1=e$1.now??new Date,n=r.facts??[],K=new Set((s?[s]:r.projects).map(t=>t.name)),F=n.filter(t=>t.project?K.has(t.project):true),H=(s?[s]:r.projects).map(t=>{let u=F.filter(d=>d.project===t.name);return {name:t.name,path:t.path,kind:t.kind,category:t.category,runtime:t.runtime,framework:t.frameworkDisplayName,...t.generator?{generator:t.generator}:{},createCapability:t.createCapability,supportTier:t.supportTier,safeCommands:ce(t),importantFiles:t.importantFiles,facts:u}}),A=await pe(r,e$1.workspacePath),R=E.join(e$1.workspacePath,e.knowledgeGraph),g=await S.pathExists(R)?await S.readJson(R).catch(()=>null):null,$=false;if(g?.schemaVersion===f.knowledgeGraph)try{c(g,r),$=true;}catch{}let M=le(r),I=ie(r,s,c$1),v=await C(e$1.workspacePath,e.impact,f.impact),l=await C(e$1.workspacePath,e.doctor,f.doctor),b$1=await C(e$1.workspacePath,e.analyze,f.analyze),k=await C(e$1.workspacePath,e.readiness,f.readiness),h$1=await C(e$1.workspacePath,e.verify,f.verify),w=await C(e$1.workspacePath,e.explain,f.explain),f$1=await C(e$1.workspacePath,e.diff,f.diff),B=v?.summary?{changed:v.summary.changed,risk:v.summary.risk,affectedProjects:v.summary.affectedProjects,blastRadius:v.summary.blastRadius,recommendedCommands:v.summary.recommendedCommands}:void 0,U=l?.summary?{verdict:l.summary.verdict,totalIssues:l.summary.totalIssues,advisoryFindings:l.summary.advisoryFindings,blockingFindings:l.summary.blockingFindings,unknownFindings:l.summary.unknownFindings,hasSystemErrors:l.summary.hasSystemErrors,topSignals:(()=>{let t=Array.isArray(l.projects)?l.projects:[],u=[];for(let d of t.slice(0,6)){let re=Array.isArray(d?.probes)?d.probes:[];for(let y of re.slice(0,10))(y?.status==="fail"||y?.severity==="error")&&u.push({label:y.label,scope:y.scope,issueClass:y.issueClass,status:y.status,severity:y.severity,recommendation:y.recommendation});}return u.slice(0,8)})()}:void 0,J=b$1?.summary?{score:b$1.summary.score,verdict:b$1.summary.verdict,findingCounts:b$1.summary.findings,topFindings:(Array.isArray(b$1.findings)?b$1.findings:[]).filter(d=>d?.severity==="fail"||d?.severity==="warn").slice(0,8).map(d=>({severity:d.severity,title:d.title,target:d.target,remediation:d.remediation}))}:void 0,X=k?{overallStatus:k.overallStatus,blocking:k.blocking,blockingReasons:k.blockingReasons,evidencePath:k.evidencePath,gates:Array.isArray(k.gates)?k.gates.slice(0,6).map(t=>({gate:t.gate,status:t.status,summary:t.summary})):void 0}:void 0,Q=h$1?.summary?{verdict:h$1.summary.verdict,exitCode:h$1.summary.exitCode,stepsFailed:h$1.summary.stepsFailed,stepsMissing:h$1.summary.stepsMissing,blockingReasons:h$1.blockingReasons,missingEvidence:h$1.missingEvidence}:void 0,Y=w?{summary:w.summary,blockingReasons:w.blockingReasons,releaseVerdict:w.releaseVerdict,evidenceFreshness:w.evidenceFreshness,sections:Array.isArray(w.sections)?w.sections.slice(0,4).map(t=>({id:t.id,title:t.title,body:t.body})):void 0}:void 0,Z=f$1?.summary?{changed:f$1.summary.changed,addedProjects:f$1.summary.addedProjects,removedProjects:f$1.summary.removedProjects,changedProjects:f$1.summary.changedProjects,workspaceChanges:f$1.summary.workspaceChanges,validationChanges:f$1.summary.validationChanges,gitChangedFiles:f$1.summary.gitChangedFiles}:void 0,ee=I.map(t=>h({id:`context.command.${t.id}`,label:`${t.id} safe command`,scope:"command",value:{display:t.display,execute:t.execute,scope:t.scope},...t.project?{project:t.project}:{},freshness:{kind:"derived",category:"structure",generatedAt:r.generatedAt,now:c$1,sourceArtifact:e.agentContext,sourcePath:`safeCommands.${t.id}`,reason:"Context safe commands are derived from workspace model command capabilities."}})),T=[...F,...ee],x=i({facts:T,generatedAt:c$1.toISOString(),now:c$1}),W=b();return {schemaVersion:te,generatedAt:c$1.toISOString(),agent:i$1,workspaceSummary:M,modelRef:e.model,knowledgeGraph:{artifact:e.knowledgeGraph,schemaVersion:f.knowledgeGraph,available:$,...typeof g?.quality?.entityCount=="number"?{entityCount:g.quality.entityCount}:{},...typeof g?.quality?.relationCount=="number"?{relationCount:g.quality.relationCount}:{},...typeof g?.quality?.proofCount=="number"?{proofCount:g.quality.proofCount}:{},queryCommands:[j("workspace graph search <query> --limit 12 --json"),j("workspace graph entities [kind] --json"),j("workspace graph evidence <entity-or-relation> --json"),j("workspace graph path <from> <to> --json")]},intelligenceChain:{schemaVersion:W.schemaVersion,contractPath:W.contractPath,currentStep:"context",canonicalReadOrder:[...W.consumers.agents.canonicalReadOrder]},workspace:{name:r.workspace.name,root:`workspace:${r.workspace.name}`,type:r.identity.workspaceType,...r.workspace.profile?{profile:r.workspace.profile}:{}},scope:{requested:e$1.scope??"workspace",...s?{activeProject:s.name}:{}},projects:H,safeCommands:I,facts:T,factFreshness:x,evidence:A,policies:{mode:r.policies.mode,source:r.policies.source},contracts:{exists:r.contracts.exists,path:r.contracts.workspaceContractPath},validation:a,agentInstructions:[`Read \`${e.agentIndex}\` first, then this context pack and linked evidence reports.`,"Use `workspace graph search <query> --limit 12 --json` for bounded, proof-backed retrieval before loading the full graph.",`Load \`${e.knowledgeGraph}\` only when a complete graph export is explicitly required.`,"Use this context as the workspace source of truth before inspecting random files.","Prefer workspace-level evidence over generic framework assumptions.","Use `display` commands when explaining steps to a human.","Use `execute` commands when launching commands from automation or tooling.","Treat `facts[].freshness.verifyBeforeUse` as a hard refresh requirement before using that fact in advice, fixes, or release decisions.","Do not carry extracted facts beyond their freshness contract; re-read or regenerate evidence when the contract says stale, unknown, live, or verify-before-use.","Keep project-scoped advice tied to the active project scope.","Regenerate stale grounding with `npx workspai workspace agent-sync --write --refresh-context`."],unsafeAssumptions:[...ue(r),...x.verifyBeforeUseFacts>0?[`${x.verifyBeforeUseFacts} fact(s) require verification before use; do not treat them as durable workspace structure.`]:[]],humanSummary:[M,`Evidence available: ${A.available.length}. Missing evidence groups: ${A.missing.join(", ")||"none"}.`,s?`Active project scope: ${s.name} (${s.frameworkDisplayName}).`:"Scope: whole workspace."].join(`
|
|
2
|
+
`),impactSummary:B,doctorSummary:U,analyzeSummary:J,readinessSummary:X,verifySummary:Q,explainSummary:Y,diffSummary:Z}}async function We(e,r){return e$1(r,se,a(e))}export{te as a,se as b,xe as c,We as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {l}from'./chunk-3VU7ROHY.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
|
-
import e from'path';import N from'fs-extra';import F from'chalk';async function K(n,o={}){let t=e.resolve(n),{WORKSPACE_CONTRACT_PATH:i,syncWorkspaceContract:c,verifyWorkspaceContract:m,writeWorkspaceContractVerifyEvidence:k}=await import('./workspace-contract-3BWIRSVQ.js'),p=await c({workspacePath:t,strict:true}),{syncWorkspaceReadme:f,WORKSPACE_README_PATH:d}=await import('./workspace-readme-
|
|
1
|
+
import e from'path';import N from'fs-extra';import F from'chalk';async function K(n,o={}){let t=e.resolve(n),{WORKSPACE_CONTRACT_PATH:i,syncWorkspaceContract:c,verifyWorkspaceContract:m,writeWorkspaceContractVerifyEvidence:k}=await import('./workspace-contract-3BWIRSVQ.js'),p=await c({workspacePath:t,strict:true}),{syncWorkspaceReadme:f,WORKSPACE_README_PATH:d}=await import('./workspace-readme-G7TZ3V5T.js'),h=await f({workspacePath:t,workspaceName:p.contract.workspace.name,profile:p.contract.workspace.profile??"minimal",projectCount:p.contract.projects.length}),{buildWorkspaceModel:u,writeWorkspaceModel:g}=await import('./workspace-model-ETCLINRB.js'),a=await u({workspacePath:t,includeEvidence:true}),P=await g(a,t),{buildWorkspaceImpact:W,buildWorkspaceModelSnapshot:C,diffWorkspaceModel:y,writeWorkspaceImpact:A,writeWorkspaceModelDiff:j,writeWorkspaceModelSnapshot:E}=await import('./workspace-intelligence-625UN27X.js'),{WORKSPACE_INTELLIGENCE_ARTIFACTS:s}=await import('./workspace-intelligence-runtime-registry-IW6J53LO.js'),R=e.join(t,s.snapshot),l=false;if(!await N.pathExists(R)){let r=await C({workspacePath:t,model:a});await E(r,t),l=true;}let S=await y({workspacePath:t,fromPath:s.snapshot,model:a}),b=await j(S,t),v=await W({workspacePath:t,fromPath:s.diff}),O=await A(v,t),T=await m({workspacePath:t,strict:true}),_=await k({workspacePath:t,result:T}),{syncWorkspaceAgentGrounding:M}=await import('./workspace-agent-sync-ZURWHL3H.js'),w=await M({workspacePath:t,model:a,write:true,refreshContext:true,strict:false,preset:"enterprise",targets:["all"],projectGrounding:o.projectGrounding??"managed"}),x=[i,(await import('./workspace-registry-summary-VSOBKAJG.js')).WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH,e.relative(t,h).split(e.sep).join("/")||d,e.relative(t,P).split(e.sep).join("/"),s.knowledgeGraph,...l?[s.snapshot]:[],e.relative(t,b).split(e.sep).join("/"),e.relative(t,O).split(e.sep).join("/"),e.relative(t,_).split(e.sep).join("/"),...w.writtenFiles].filter((r,I,G)=>G.indexOf(r)===I);return o.silent||console.log(F.gray(`\u2713 Workspace Intelligence synced \xB7 ${a.summary.projectCount} project(s) \xB7 model + graph + agent grounding`)),{workspacePath:t,projectCount:a.summary.projectCount,baselineCreated:l,writtenFiles:x,warnings:w.projectLenses?.skipped.map(r=>`${r.name}: ${r.reason}`)??[]}}async function D(n,o={}){let t=e.resolve(n),i=o.workspaceName??e.basename(t),{registerWorkspaceStrict:c}=await import('./workspace-FSOLFNAJ.js');return await c(t,i),K(t,{silent:o.silent})}export{K as a,D as b};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import {f as f$1,e as e$1}from'./chunk-ILIBOMYL.js';import {a,b}from'./chunk-QJCCZLOF.js';import {a as a$1}from'./chunk-27UR373Z.js';import {a as a$2}from'./chunk-T5YRFRJV.js';import {h,j as j$1}from'./chunk-ZCPT6KC3.js';import {e as e$2}from'./chunk-CCDGHPEJ.js';import {e,f}from'./chunk-NZ3WZYD5.js';import {j,s,t}from'./chunk-MOSXTVPU.js';import w from'fs';import c from'path';import i from'chalk';var L=new Set([".git",".workspai",".rapidkit",".venv","node_modules","dist","build","target","coverage","htmlcov",".next"]);async function D(e){try{return await w.promises.access(e,w.constants.F_OK),true}catch{return false}}async function z(e){try{let t=JSON.parse(await w.promises.readFile(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async function K(e){try{return await w.promises.readFile(e,"utf-8")}catch{return ""}}function B(e){return a(e)}async function U(e,t$1){return await M([...t(e,"project.json"),...t(e,"context.json")])?true:b(e)?false:c.resolve(e)===c.resolve(t$1)?h(e).length>0:h(e).length>0}async function V(e){let t=await a$1(e,{skipDirs:L,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:U}),r=(await a$2(e)).filter(o=>o.relationship==="adopted"||o.source==="adopted-local").map(o=>c.resolve(o.path)).filter(o=>w.existsSync(o)),s=[...new Set([...t.map(o=>c.resolve(o)),...r])];return s.length>0?s:b(e)?[]:h(e).length>0?[e]:[]}function q(e,t){return c.relative(e,t).replace(/\\/g,"/")||"."}async function A(e,t){for(let n of t)if(await D(c.join(e,n)))return true;return false}async function M(e){for(let t of e)if(await D(t))return true;return false}async function Q(e){if(await A(e,[".gitlab-ci.yml",".circleci/config.yml","azure-pipelines.yml","bitbucket-pipelines.yml","cloudbuild.yaml"]))return true;try{return (await w.promises.readdir(c.join(e,".github","workflows"),{withFileTypes:true})).some(n=>n.isFile()&&/\.(?:ya?ml)$/i.test(n.name)&&!n.name.startsWith("."))}catch{return false}}async function O(e){for(let t of e){let n=await z(t);if(n)return n}return null}async function X(e){return A(e,["health","health.ts","health.js","health.py","health.go","health.kt","health.rb","health.php","healthcheck","health-check","src/health.ts","src/health.js","src/health.py","src/health.go","src/health.kt","src/health.rb","src/health.php","src/healthcheck.ts","src/healthcheck.js","src/liveness.ts","src/readiness.ts","src/ping.ts"])}async function Y(e){if(await A(e,["tests","test","__tests__","src/__tests__","pytest.ini","vitest.config.ts","jest.config.ts"]))return true;let n=await z(c.join(e,"package.json")),r=n?.scripts&&typeof n.scripts=="object"?n.scripts:{};return typeof r.test=="string"&&r.test.trim().length>0}async function Z(e){let t=await z(c.join(e,"package.json")),n=t?.scripts&&typeof t.scripts=="object"?t.scripts:{};return Object.keys(n).sort()}function g(e,t,n,r,s,o,a){return {id:e,severity:t,target:n,title:r,detail:s,remediation:o,...a&&a.length>0?{files:[...a]}:{}}}function ee(e){let t=e.reduce((n,r)=>r.severity==="fail"?n+28:r.severity==="warn"?n+12:n+3,0);return Math.max(0,100-t)}async function ne(e,t$1){let n=await O(t(t$1,"project.json")),r=j$1(t$1,n),s=h(t$1),o=r.runtime==="unknown"?s[0]||"unknown":r.runtime,a=q(e,t$1),d=a,f=await Z(t$1),u=await M([...t(t$1,"project.json"),...t(t$1,"context.json")]),p=await Y(t$1),h$1=await A(t$1,["Dockerfile","dockerfile"]),k=await A(t$1,[".env.example","env.example","config/env.example"]),P=await Q(t$1),C=await X(t$1),m=[];return r.key==="unknown"&&m.push(g("project.stack.unknown","fail",d,"Project stack is unknown","Workspai cannot confidently classify this backend project.","Add .workspai/project.json metadata or import the project with `workspai import`.")),u||m.push(g("project.marker.missing","warn",d,"Workspai marker is missing","The project can be detected by files, but it is not registered with Workspai metadata.","Run `workspai import <path>` from a workspace or create the project through Workspai.")),p||m.push(g("project.tests.missing","warn",d,"Test entrypoint is missing","No common test folder, config, or package test script was found.","Add a test command so `workspai workspace run test --affected` can gate changes.")),k||m.push(g("project.env.example.missing","info",d,"Environment example is missing","No .env.example or env.example file was found.","Add an env example for onboarding and CI secret documentation.",[".env.example"])),P||m.push(g("project.ci.missing","warn",d,"Continuous integration is missing","No recognized CI/CD configuration file was detected for this project.","Add CI configuration so tests and checks run automatically for every change.",[".github/workflows/ci.yml"])),C||m.push(g("project.health.missing","info",d,"Health or readiness probe is missing","The project has no obvious health or readiness endpoint to support automated deployment and runtime checks.","Add a simple health endpoint and document it for readiness gates and observability.")),h$1||m.push(g("project.container.missing","info",d,"Container recipe is missing","No Dockerfile was found for this project.","Add a Dockerfile when the service is intended for containerized deployment.",["Dockerfile"])),{name:typeof n?.name=="string"&&n.name.trim()?n.name.trim():c.basename(t$1),path:t$1,relativePath:a,runtime:o,framework:r.key,confidence:r.confidence,supportTier:r.supportTier,hasRapidKitMarker:u,hasTests:p,hasDockerfile:h$1,hasEnvExample:k,hasCiConfig:P,hasHealthEndpoint:C,scripts:f,findings:m,score:ee(m)}}function te(e){return e.name.toLowerCase()}async function re(e){let t=new Map(e.map(s=>[te(s),s])),n=[];for(let s of e){let o=await z(c.join(s.path,"package.json")),a={...o?.dependencies??{},...o?.devDependencies??{},...o?.peerDependencies??{}};for(let f of Object.keys(a)){let u=f.replace(/^@[^/]+\//,"").toLowerCase(),p=t.get(u);p&&p.relativePath!==s.relativePath&&n.push({from:s.relativePath,to:p.relativePath,kind:"package"});}let d=await K(c.join(s.path,"pyproject.toml"));for(let f of e)f.relativePath!==s.relativePath&&d.includes(f.name)&&n.push({from:s.relativePath,to:f.relativePath,kind:"workspace-reference"});}let r=new Set;return n.filter(s=>{let o=`${s.from}\0${s.to}\0${s.kind}`;return r.has(o)?false:(r.add(o),true)})}function se(e,t){let n=new Map;for(let r of e)n.set(r.relativePath,{project:r.relativePath,directDependents:0,directDependencies:0});for(let r of t){let s=n.get(r.from),o=n.get(r.to);s&&(s.directDependencies+=1),o&&(o.directDependents+=1);}return Array.from(n.values()).sort((r,s)=>s.directDependents-r.directDependents||s.directDependencies-r.directDependencies)}async function oe(e){let t=await O(s(e,"workspace.json"));return typeof t?.profile=="string"?t.profile:null}function ie(e){return {fail:e.filter(t=>t.severity==="fail").length,warn:e.filter(t=>t.severity==="warn").length,info:e.filter(t=>t.severity==="info").length}}function ae(e){if(e.projectCount===0)return e.workspaceDetected?["Add your first project: npx workspai create project <name> --kit <kit>","Import an existing service: npx workspai import <path>"]:["Create a Workspai workspace: npx workspai create workspace my-workspace --profile polyglot","Import an existing service: npx workspai import ../service"];let t=[];return e.findings.some(n=>n.id==="workspace.marker.missing")&&t.push("Initialize workspace metadata with `workspai bootstrap --profile polyglot`."),e.findings.some(n=>n.id==="project.marker.missing")&&t.push("Register detected projects with `workspai import <path>` or recreate them via `workspai create project`."),e.findings.some(n=>n.id==="project.tests.missing")&&t.push("Add test entrypoints, then gate changes with `workspai workspace run test --affected --strict`."),e.findings.some(n=>n.id==="project.ci.missing")&&t.push("Add CI/CD configuration to catch regressions early and make workspace health checks actionable."),e.findings.some(n=>n.id==="project.health.missing")&&t.push("Add a health/readiness endpoint so runtime probes and deployment checks can verify service health."),e.hasGraph||t.push("Create `.workspai/workspace-dependency-graph.json` or use analyze output as the first graph seed."),t.push("Run `workspai autopilot release --mode audit --json` before release."),Array.from(new Set(t))}async function ve(e$3={}){let t=c.resolve(e$3.workspacePath||process.cwd());if(!await D(t))throw new Error(`Workspace path does not exist: ${t}`);let n=B(t)??t,r=j(n),s=await oe(n),o=await V(n),a=await Promise.all(o.map(l=>ne(n,l))),d=await re(a),f$2=se(a,d),u=[];r||u.push(g("workspace.marker.missing","warn",".","Workspace metadata is missing","The directory can be analyzed, but it is not a registered Workspai workspace.","Run `workspai create workspace` or `workspai bootstrap --profile polyglot` in a workspace root.")),a.length===0&&u.push(g("workspace.projects.missing","warn",".","No backend projects detected","Workspai did not find runtime markers or project metadata under this root.","Create a project with `workspai create project` or import one with `workspai import <path>`."));let p=[...u,...a.flatMap(l=>l.findings)],h=ie(p),k={};for(let l of a)k[l.runtime]=(k[l.runtime]||0)+1;let P=a.length>0?Math.round(a.reduce((l,y)=>l+y.score,0)/a.length):0,C=u.reduce((l,y)=>l+(y.severity==="fail"?20:y.severity==="warn"?8:2),0),m=Math.max(0,P-C),J=a.length===0&&h.fail===0&&p.length>0&&p.every(l=>l.id==="workspace.projects.missing"&&l.severity==="warn"),H=h.fail>0||e$3.strict&&h.warn>0&&!J?"blocked":h.warn>0?"needs-attention":"ready",j$1={schemaVersion:f.analyze,generatedAt:new Date().toISOString(),workspacePath:n,workspaceDetected:r,profile:s,summary:{score:m,verdict:H,projectCount:a.length,runtimeCount:Object.keys(k).length,findings:h},runtimes:k,projects:a,dependencyGraph:{status:d.length>0?"generated":"empty",edges:d,topImpactedProjects:f$2.slice(0,5)},findings:p,nextActions:ae({findings:p,projectCount:a.length,hasGraph:d.length>0,workspaceDetected:r}),enterpriseControls:{jsonReady:true,ciGateCommand:"workspai analyze --json --strict",releaseGateCommand:"workspai autopilot release --mode enforce --json",evidencePath:e.analyze}};if(e$3.output&&(await w.promises.mkdir(c.dirname(c.resolve(e$3.output)),{recursive:true}),await w.promises.writeFile(c.resolve(e$3.output),`${JSON.stringify(j$1,null,2)}
|
|
2
|
+
`)),!e$3.output&&r){let l=f$1(j$1,{commandId:"workspaceAnalyze",exitCode:j$1.summary.verdict==="blocked"?2:j$1.summary.verdict==="needs-attention"?1:0,generatedAt:j$1.generatedAt,blockers:j$1.findings.filter(y=>y.severity==="fail").map(y=>y.title).slice(0,12),runId:e$1()});await e$2(n,e.analyze,l);}return j$1}function be(e){let t=e.summary.verdict==="ready"?i.green:e.summary.verdict==="needs-attention"?i.yellow:i.red;if(console.log(i.bold(`
|
|
3
|
+
Workspai Workspace Analysis
|
|
4
|
+
`)),console.log(i.cyan("Workspace:"),e.workspacePath),console.log(i.cyan("Profile:"),e.profile||"not configured"),console.log(i.cyan("Score:"),`${e.summary.score}/100`),console.log(i.cyan("Verdict:"),t(e.summary.verdict)),console.log(i.gray(`Projects: ${e.summary.projectCount}, runtimes: ${e.summary.runtimeCount}, findings: ${e.summary.findings.fail} fail / ${e.summary.findings.warn} warn / ${e.summary.findings.info} info`)),e.projects.length>0){console.log(i.bold(`
|
|
5
|
+
Projects`));for(let n of e.projects){let r=n.score>=85?i.green("pass"):n.score>=65?i.yellow("watch"):i.red("risk");console.log(` ${n.relativePath} ${i.gray(`${n.runtime}/${n.framework}`)} ${r} ${n.score}/100`);}}if(e.dependencyGraph.status==="generated"&&(console.log(i.bold(`
|
|
6
|
+
Dependency Graph`)),console.log(i.gray(` edges: ${e.dependencyGraph.edges.length}`)),e.dependencyGraph.topImpactedProjects.length>0)){console.log(i.gray(" Top impacted projects:"));for(let n of e.dependencyGraph.topImpactedProjects.slice(0,3))console.log(` ${n.project} (${n.directDependents} dependents, ${n.directDependencies} dependencies)`);}if(e.findings.length>0){console.log(i.bold(`
|
|
7
|
+
Top Findings`));for(let n of e.findings.slice(0,8)){let r=n.severity==="fail"?i.red:n.severity==="warn"?i.yellow:i.gray;console.log(` ${r(n.severity.toUpperCase())} ${n.target}: ${n.title}`),console.log(i.gray(` ${n.remediation}`));}}console.log(i.bold(`
|
|
8
|
+
Next Actions`));for(let n of e.nextActions.slice(0,5))console.log(i.gray(` - ${n}`));console.log();}export{ve as a,be 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};
|
|
@@ -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-
|
|
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-TR6OFSJM.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-
|
|
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-3VU7ROHY.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {c as c$5}from'./chunk-DIJGQUEV.js';import {c}from'./chunk-MDF2FBLS.js';import {j,i,d as d$1,f as f$2,c as c$3,e as e$1,h}from'./chunk-KNTPDRZB.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-KNTPDRZB.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-SS7NJMFL.js';import {j,i,d as d$1,f as f$2,c as c$3,e as e$1,h}from'./chunk-3VU7ROHY.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-3VU7ROHY.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};
|