@vpxa/aikit 0.1.383 → 0.1.385
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/package.json +1 -1
- package/packages/claude-desktop/dist/manifest.json +1 -1
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/{config-CQKoGfwD.js → config-BS9mkd50.js} +1 -1
- package/packages/server/dist/{config-DX1KYSbN.js → config-CkXCQx7E.js} +1 -1
- package/packages/server/dist/{dashboard-static-DdsIJd-u.js → dashboard-static-CVRj5Cbv.js} +1 -1
- package/packages/server/dist/{dashboard-static-C6RP0VA7.js → dashboard-static-q97RHnd3.js} +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{register-tools-RwhtWli2.js → register-tools-DQozoQCc.js} +141 -140
- package/packages/server/dist/{register-tools-BGFt0C77.js → register-tools-jeARoElg.js} +141 -140
- package/packages/server/dist/{server-CJw04C9E.js → server-BtBhCSgd.js} +2 -2
- package/packages/server/dist/{server-DxiekvQV.js → server-Dn5krTHS.js} +2 -2
- package/packages/server/dist/{server-http-DjE5LRrG.js → server-http-BXgL1pzw.js} +1 -1
- package/packages/server/dist/{server-http-CpGB2imV.js → server-http-NwhEoWbY.js} +1 -1
- package/packages/server/dist/{server-stdio-DTcX2U0-.js → server-stdio-0TjK5HFr.js} +1 -1
- package/packages/server/dist/{server-stdio-BN_gzRqw.js → server-stdio-DLsg8ccQ.js} +1 -1
- package/packages/server/dist/{settings-static-C0oT3Ctk.js → settings-static-HY0egyKG.js} +1 -1
- package/packages/server/dist/{settings-static-DVMG47Oh.js → settings-static-VnUkp9iU.js} +1 -1
- package/packages/server/dist/startup-maintenance-D7tKqECM.js +21 -0
- package/packages/server/dist/{startup-maintenance-kHH8tjds.js → startup-maintenance-QrloHssd.js} +6 -6
- package/packages/tools/dist/index.d.ts +60 -24
- package/packages/tools/dist/index.js +81 -76
- package/scaffold/dist/definitions/bodies.mjs +2 -1
- package/scaffold/dist/definitions/skills/aikit.mjs +121 -1
- package/scaffold/dist/definitions/skills/orchestrator.mjs +12 -1
- package/packages/server/dist/startup-maintenance-cbRSFMY5.js +0 -21
package/packages/server/dist/{startup-maintenance-kHH8tjds.js → startup-maintenance-QrloHssd.js}
RENAMED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-DT7IzrpZ.js";import{t}from"./curated-manager-D4MOFQ-t.js";import{createRequire as n}from"node:module";import{fileURLToPath as r}from"node:url";import{INSTALL_ARGS as i,cleanupOldVersions as a,createLogger as o,getGlobalDataDir as s,isUserInstalled as c,listWorkspaces as l,safeCwd as u,serializeError as d}from"../../core/dist/index.js";import{existsSync as f,mkdirSync as p,readFileSync as m,renameSync as h,rmSync as g,statSync as ee,unlinkSync as
|
|
2
|
-
`)}function
|
|
3
|
-
`)}\n\n${t}\n`}function ze(e,t){let n=e.map(()=>[]);for(let r=0;r<e.length;r+=1)for(let i=r+1;i<e.length;i+=1)
|
|
4
|
-
`),confidence:e.avgConfidence,tags:[`lesson`,`promoted`,`global`]})}function I(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function $e(e){let t=(Date.now()-e.getTime())/(1440*60*1e3);return t<=1?10:t<=7?8:t<=14?6:t<=21?4:t<=30?2:1}function et(e){switch(e){case`high`:return 10;case`medium`:return 6;case`low`:return 2}}function tt(e){let t=e.length/4;return t<=10?10:t<=25?8:t<=50?6:t<=100?4:t<=200?2:1}function nt(e,t){let n=[],r=!!t?.topicKey;n.push({name:`canonical-topic-key`,passed:r,reason:r?void 0:`No canonical topic key provided`});let i=!!(t?.evidenceRefs&&t.evidenceRefs.length>0);n.push({name:`evidence-attached`,passed:i,reason:i?void 0:`No evidence refs attached`});let a=!0,o;if(t?.observedAt){let e=Date.now()-new Date(t.observedAt).getTime();a=e<2592e6,o=a?void 0:`Observation older than 30 days (${Math.round(e/(1440*60*1e3))}d)`}n.push({name:`freshness`,passed:a,reason:o});let s=!t?.hasConflict;n.push({name:`no-unresolved-conflict`,passed:s,reason:s?void 0:`Has unresolved conflict`});let c=!0,l;t?.scope&&t?.targetScope&&(c=t.scope===t.targetScope,l=c?void 0:`Scope "${t.scope}" does not match target "${t.targetScope}"`),n.push({name:`scope-matches`,passed:c,reason:l});let u=!1;t?.actionability&&(u=t.actionability===`high`||t.actionability===`medium`),n.push({name:`actionability-clear`,passed:u,reason:u?void 0:`Actionability is "${t?.actionability??`not set`}"`});let d=!0,f;t?.tokenBudgetRemaining!==void 0&&t?.minTokenBudget!==void 0&&(d=t.tokenBudgetRemaining>=t.minTokenBudget,f=d?void 0:`Token budget ${t.tokenBudgetRemaining} < required ${t.minTokenBudget}`),n.push({name:`token-budget-available`,passed:d,reason:f});let p=n.filter(e=>!e.passed).map(e=>e.name);return{passed:p.length===0,gates:n,failedGates:p}}function rt(e,t){let n=I(t?.recurrence??1,1,10),r=I(t?.impact??5,1,10),i=I(e.foundIn.length,1,10),a=t?.observedAt?$e(new Date(t.observedAt)):5,o=et(t?.actionability??`medium`),s=tt(e.insight);return{signals:{recurrence:n,impact:r,sourceDiversity:i,freshness:a,actionability:o,tokenCost:s},totalScore:n+r+i+a+o+s}}function it(e,t,n,r,i){return t.passed?n&&r&&i&&n.some(e=>
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DT7IzrpZ.js";import{t}from"./curated-manager-D4MOFQ-t.js";import{createRequire as n}from"node:module";import{fileURLToPath as r}from"node:url";import{INSTALL_ARGS as i,cleanupOldVersions as a,createLogger as o,getGlobalDataDir as s,isUserInstalled as c,listWorkspaces as l,safeCwd as u,serializeError as d}from"../../core/dist/index.js";import{existsSync as f,mkdirSync as p,readFileSync as m,renameSync as h,rmSync as g,statSync as ee,unlinkSync as _,writeFileSync as v}from"node:fs";import{dirname as y,join as b,resolve as x}from"node:path";import{readFile as te,writeFile as ne}from"node:fs/promises";import{execFile as re,execSync as S,spawn as ie}from"node:child_process";import{homedir as C}from"node:os";const ae={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},oe={working:1,episodic:2,semantic:4,procedural:12};function se(e,t=ae){switch(e.tier){case`working`:if(e.accessCount>=t.workingToEpisodicAccesses)return`episodic`;break;case`episodic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences)return`semantic`;break;case`semantic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences+t.semanticToProceduralVerifications)return`procedural`;break;case`procedural`:break;default:break}}function ce(e,t,n){e.memoryMetaUpdateTier(t,n)}const w={confirmIncrement:10,contradictDecrement:20,weeklyDecay:2,implicitUseIncrement:3,staleThreshold:30,staleDays:21,decayFloor:10,autoArchiveDays:30,archiveThreshold:20},le=`lesson:auto-archive`;function T(e){return{confirmIncrement:Math.max(0,Math.trunc(e?.confirmIncrement??w.confirmIncrement)),contradictDecrement:Math.max(0,Math.trunc(e?.contradictDecrement??w.contradictDecrement)),weeklyDecay:Math.max(0,Math.trunc(e?.weeklyDecay??w.weeklyDecay)),implicitUseIncrement:Math.max(0,Math.trunc(e?.implicitUseIncrement??w.implicitUseIncrement)),staleThreshold:Math.min(100,Math.max(0,Math.trunc(e?.staleThreshold??w.staleThreshold))),staleDays:Math.max(1,Math.trunc(e?.staleDays??w.staleDays)),decayFloor:Math.min(100,Math.max(0,Math.trunc(e?.decayFloor??w.decayFloor))),autoArchiveDays:Math.max(1,Math.trunc(e?.autoArchiveDays??w.autoArchiveDays)),archiveThreshold:Math.min(100,Math.max(0,Math.trunc(e?.archiveThreshold??w.archiveThreshold)))}}function ue(e){return[`## Lesson: ${e.title}`,``,`**Confidence:** ${e.confidence}/100`,``,`### Context`,e.context,``,`### Insight`,e.insight,``,`### Evidence`,e.evidence].join(`
|
|
2
|
+
`)}function E(e){let t=e.match(/^## Lesson:\s+(.+)$/m),n=e.match(/\*\*Confidence:\*\*\s+(\d+)\/100/),r=e.match(/### Context\r?\n([\s\S]*?)(?=\r?\n### |$)/),i=e.match(/### Insight\r?\n([\s\S]*?)(?=\r?\n### |$)/),a=e.match(/### Evidence\r?\n([\s\S]*?)(?=\r?\n### |$)/);return{title:t?.[1]?.trim(),confidence:n?Number(n[1]):void 0,context:r?.[1]?.trim(),insight:i?.[1]?.trim(),evidence:a?.[1]?.trim()}}function de(e,t){let n=Math.min(100,Math.max(0,Math.trunc(t)));return/\*\*Confidence:\*\*/.test(e)?e.replace(/\*\*Confidence:\*\*\s+\d+\/100/,`**Confidence:** ${n}/100`):e.match(/^(## Lesson:[^\r\n]*)(\r?\n)/)?e.replace(/^(## Lesson:[^\r\n]*)(\r?\n)/,`$1$2$2**Confidence:** ${n}/100$2$2`):`**Confidence:** ${n}/100\n\n${e}`}function fe(e,t,n=w){let r=T(n);return t===`confirm`?Math.min(100,e+r.confirmIncrement):Math.max(0,e-r.contradictDecrement)}function D(e,t,n,r=w,i=Date.now()){let a=T(r),o=!!t,s=t?new Date(t):new Date(n),c=Math.max(0,i-s.getTime());o||(c=Math.min(c,336*60*60*1e3));let l=c/(10080*60*1e3),u=Math.floor(l)*a.weeklyDecay;return Math.max(a.decayFloor,e-u)}function pe(e,t=w,n=Date.now()){let r=T(t);if(D(e.confidence,e.lastAccessedAt,e.createdAt,t,n)>=r.staleThreshold)return!1;let i=e.lastAccessedAt?new Date(e.lastAccessedAt):new Date(e.createdAt);return Math.max(0,n-i.getTime())/(1e3*60*60*24)>=r.staleDays}function me(e,t=w,n=Date.now()){let r=T(t);if(D(e.confidence,e.lastAccessedAt,e.createdAt,t,n)>=r.archiveThreshold)return!1;let i=e.lastAccessedAt?new Date(e.lastAccessedAt):new Date(e.createdAt);return Math.max(0,n-i.getTime())/(1e3*60*60*24)>=r.autoArchiveDays}const O={stabilityHours:168,accessMultiplier:1.5,flagThreshold:.1,maxStabilityHours:8760};function he(e){return{...O,...e}}function ge(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function _e(e){return e&&e in oe?e:`working`}function ve(e,t,n,r=O,i){let a=typeof r==`string`?_e(r):`working`,o=he(typeof r==`string`?i:r),s=ge(e,ge(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*oe[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function ye(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=ve(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function be(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=ve(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function xe(e,t){let n=he(t);return e.memoryMetaList().map(t=>ye(e,t.entryId,n)??t).filter(e=>e.retentionScore<n.flagThreshold).sort((e,t)=>e.retentionScore-t.retentionScore)}const k={threshold:.7,maxCompare:50,autoThreshold:.95};function Se(e){let t=Math.min(1,Math.max(0,e?.threshold??k.threshold)),n=Math.min(1,Math.max(t,e?.autoThreshold??k.autoThreshold));return{threshold:t,maxCompare:Math.max(1,Math.trunc(e?.maxCompare??k.maxCompare)),autoThreshold:n}}function Ce(e){let t=e.toLowerCase().match(/[a-z0-9]{2,}/g)??[];return new Set(t)}function A(e,t){let n=Ce(e),r=Ce(t);if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=new Set([...n].filter(e=>r.has(e))),a=new Set([...n,...r]);return i.size/a.size}function we(e,t,n=k){let r=Se(n);return t.slice(0,r.maxCompare).map(t=>({entryId:t.id,title:t.title,similarity:A(e,t.content),path:t.path})).filter(e=>e.similarity>=r.threshold).sort((e,t)=>t.similarity-e.similarity)}function Te(e,t,n){e.memoryMetaCreate(t),e.memoryMetaSetSuperseded(t,n)}const Ee=n(import.meta.url),De=import.meta.dirname??y(r(import.meta.url)),j=new Map;function M(e){let t=j.get(e);if(t!==void 0)return t;let n=b(De,`..`,`..`,e);if(f(b(n,`package.json`)))return j.set(e,n),n;try{let t=y(Ee.resolve(`@aikit/${e}/package.json`));return j.set(e,t),t}catch{}let r=De;for(let t=0;t<6;t++){let t=b(r,`packages`,e);if(f(b(t,`package.json`)))return j.set(e,t),t;let n=y(r);if(n===r)break;r=n}return j.set(e,null),null}function Oe(e,t=`dist`){let n=M(e);if(!n)return null;let r=b(n,t);return f(r)?r:null}function ke(e,t){let n=M(e);if(!n)return null;for(let e of t){let t=b(n,e);if(f(t))return t}return null}var Ae=e({DEFAULT_GROUP_CONFIG:()=>P,DEFAULT_PRUNE_CONFIG:()=>N,groupLessons:()=>We,pruneLessons:()=>Ue});const N={maxConfidence:15,minIdleDays:30,safetyDays:7,maxPrune:20,dryRun:!0},P={similarityThreshold:.7,minGroupSize:2,maxGroups:10,dryRun:!0},je=new Set([`the`,`a`,`to`,`for`,`in`,`of`,`and`,`is`,`use`]);function Me(e){return{maxConfidence:Math.min(100,Math.max(0,Math.trunc(e?.maxConfidence??N.maxConfidence))),minIdleDays:Math.max(1,Math.trunc(e?.minIdleDays??N.minIdleDays)),safetyDays:Math.max(0,Math.trunc(e?.safetyDays??N.safetyDays)),maxPrune:Math.max(1,Math.trunc(e?.maxPrune??N.maxPrune)),dryRun:e?.dryRun??N.dryRun}}function Ne(e){return{similarityThreshold:Math.min(1,Math.max(0,e?.similarityThreshold??P.similarityThreshold)),minGroupSize:Math.max(2,Math.trunc(e?.minGroupSize??P.minGroupSize)),maxGroups:Math.max(1,Math.trunc(e?.maxGroups??P.maxGroups)),dryRun:e?.dryRun??P.dryRun}}function Pe(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}function Fe(e,t){let n=Math.max(Pe(e),Pe(t));return n===0?1/0:Math.max(0,Date.now()-n)/864e5}function Ie(e){return e.toLowerCase().match(/[a-z0-9]{2,}/g)??[]}function Le(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,60)}function Re(e,t){return`${[`---`,`title: "${e.title.replace(/"/g,`\\"`)}"`,`category: ${e.category}`,`tags: [${e.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${e.created}`,`updated: ${e.updated}`,`version: ${e.version}`,`origin: ${e.origin}`,`changelog:`,...e.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
|
|
3
|
+
`)}\n\n${t}\n`}function ze(e,t){let n=e.map(()=>[]);for(let r=0;r<e.length;r+=1)for(let i=r+1;i<e.length;i+=1)A(e[r],e[i])>=t&&(n[r].push(i),n[i].push(r));return n}function Be(e){let t=new Set,n=[];for(let r=0;r<e.length;r+=1){if(t.has(r))continue;let i=[r],a=[];for(t.add(r);i.length>0;){let n=i.pop();if(n!==void 0){a.push(n);for(let r of e[n])t.has(r)||(t.add(r),i.push(r))}}n.push(a)}return n}function Ve(e){let t=new Map,n=new Map,r=0;for(let i of e)for(let e of Ie(i))je.has(e)||(t.set(e,(t.get(e)??0)+1),n.has(e)||(n.set(e,r),r+=1));let i=[...t.entries()].sort((e,t)=>t[1]-e[1]||(n.get(e[0])??0)-(n.get(t[0])??0))[0];return i&&i[1]>1?Le(i[0]):Le(e.flatMap(e=>Ie(e)).find(e=>!je.has(e))??`lesson-group`)}async function He(e,t,n){let r=b(e.curatedDir,t),i=await te(r,`utf8`),{frontmatter:a,content:o}=e.parseFile(i),s=`group:${n}`;if(a.tags.includes(s))return;let c=new Date().toISOString(),l=(a.version??1)+1;await ne(r,Re({...a,tags:[...new Set([...a.tags,s])],updated:c,version:l,changelog:[...a.changelog??[],{version:l,date:c,reason:`Grouped lesson under ${n}`}]},o),`utf8`)}async function Ue(e,t,n,r){let i=Me(n),a=T(r??w),o=(await e.list({category:`lessons`})).filter(e=>e.tags.includes(`lesson`)),s=o.map(e=>{let n=t.memoryMetaGet(e.path);if(!n||n.supersededBy!=null)return null;let r=Fe(n.lastAccessedAt,n.createdAt??e.created);if(r<i.safetyDays)return null;let o=D(n.confidence,n.lastAccessedAt,n.createdAt,a);return o>=i.maxConfidence||r<i.minIdleDays?null:{path:e.path,effectiveConfidence:o}}).filter(e=>e!==null).sort((e,t)=>e.effectiveConfidence-t.effectiveConfidence||e.path.localeCompare(t.path)).slice(0,i.maxPrune);if(!i.dryRun)for(let e of s)t.memoryMetaSetSuperseded(e.path,`lesson:auto-prune`);return{pruned:s.map(e=>e.path),skipped:o.length-s.length,dryRun:i.dryRun}}async function We(e,t,n){let r=Ne(n),i=(await e.list({category:`lessons`})).filter(e=>{if(!e.tags.includes(`lesson`)||e.tags.some(e=>e.startsWith(`group:`)))return!1;let n=t.memoryMetaGet(e.path);return n?.supersededBy==null||n===void 0});if(i.length<r.minGroupSize)return{groupsCreated:0,lessonsGrouped:0,groups:[],dryRun:r.dryRun};let a=Be(ze(i.map(e=>e.title),r.similarityThreshold)).filter(e=>e.length>=r.minGroupSize).map(e=>{let t=e.map(e=>i[e]).sort((e,t)=>e.path.localeCompare(t.path));return{label:Ve(t.map(e=>e.title)),members:t.map(e=>e.path)}}).sort((e,t)=>t.members.length-e.members.length||e.members[0].localeCompare(t.members[0])).slice(0,r.maxGroups);if(!r.dryRun&&a.length>0){for(let t of a)for(let n of t.members)await He(e,n,t.label);await e.reindexAll()}return{groupsCreated:a.length,lessonsGrouped:a.reduce((e,t)=>e+t.members.length,0),groups:a,dryRun:r.dryRun}}var Ge=e({DEFAULT_PROMOTE_CONFIG:()=>F,adjudicateCandidate:()=>it,checkPromotionGates:()=>nt,collectWorkspaceLessons:()=>lt,demoteLesson:()=>ft,getGlobalCuratedDir:()=>ct,promoteLessons:()=>dt,scanForDuplicates:()=>ut,scorePromotionCandidate:()=>rt});const F={minWorkspaces:2,minAvgConfidence:80,similarityThreshold:.7,dryRun:!0};function Ke(e){return{minWorkspaces:Math.max(2,Math.trunc(e?.minWorkspaces??F.minWorkspaces)),minAvgConfidence:Math.min(100,Math.max(0,Math.trunc(e?.minAvgConfidence??F.minAvgConfidence))),similarityThreshold:Math.min(1,Math.max(0,e?.similarityThreshold??F.similarityThreshold)),dryRun:e?.dryRun??F.dryRun,layeredKnowledge:e?.layeredKnowledge??F.layeredKnowledge}}function qe(e,t){let n=e.map(()=>[]);for(let r=0;r<e.length;r+=1)for(let i=r+1;i<e.length;i+=1)A(e[r].insight,e[i].insight)>=t&&(n[r].push(i),n[i].push(r));return n}function Je(e){let t=new Set,n=[];for(let r=0;r<e.length;r+=1){if(t.has(r))continue;let i=[r],a=[];for(t.add(r);i.length>0;){let n=i.pop();if(n!==void 0){a.push(n);for(let r of e[n])t.has(r)||(t.add(r),i.push(r))}}n.push(a)}return n}function Ye(e){return new t(e,null,null)}function Xe(e){return(e??``).replace(/\s+/g,` `).trim()}function Ze(e){let t=Xe(e);return t.length<=80?t:`${t.slice(0,77).replace(/\s+\S*$/,``)}...`}function Qe(e){return ue({title:Ze(e.insight),context:`Observed across ${e.foundIn.length} workspaces: ${e.foundIn.join(`, `)}`,insight:e.insight,evidence:[`Promoted from workspaces: ${e.foundIn.join(`, `)}`,`Average confidence: ${e.avgConfidence}/100`,`Reason: ${e.reason}`].join(`
|
|
4
|
+
`),confidence:e.avgConfidence,tags:[`lesson`,`promoted`,`global`]})}function I(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function $e(e){let t=(Date.now()-e.getTime())/(1440*60*1e3);return t<=1?10:t<=7?8:t<=14?6:t<=21?4:t<=30?2:1}function et(e){switch(e){case`high`:return 10;case`medium`:return 6;case`low`:return 2}}function tt(e){let t=e.length/4;return t<=10?10:t<=25?8:t<=50?6:t<=100?4:t<=200?2:1}function nt(e,t){let n=[],r=!!t?.topicKey;n.push({name:`canonical-topic-key`,passed:r,reason:r?void 0:`No canonical topic key provided`});let i=!!(t?.evidenceRefs&&t.evidenceRefs.length>0);n.push({name:`evidence-attached`,passed:i,reason:i?void 0:`No evidence refs attached`});let a=!0,o;if(t?.observedAt){let e=Date.now()-new Date(t.observedAt).getTime();a=e<2592e6,o=a?void 0:`Observation older than 30 days (${Math.round(e/(1440*60*1e3))}d)`}n.push({name:`freshness`,passed:a,reason:o});let s=!t?.hasConflict;n.push({name:`no-unresolved-conflict`,passed:s,reason:s?void 0:`Has unresolved conflict`});let c=!0,l;t?.scope&&t?.targetScope&&(c=t.scope===t.targetScope,l=c?void 0:`Scope "${t.scope}" does not match target "${t.targetScope}"`),n.push({name:`scope-matches`,passed:c,reason:l});let u=!1;t?.actionability&&(u=t.actionability===`high`||t.actionability===`medium`),n.push({name:`actionability-clear`,passed:u,reason:u?void 0:`Actionability is "${t?.actionability??`not set`}"`});let d=!0,f;t?.tokenBudgetRemaining!==void 0&&t?.minTokenBudget!==void 0&&(d=t.tokenBudgetRemaining>=t.minTokenBudget,f=d?void 0:`Token budget ${t.tokenBudgetRemaining} < required ${t.minTokenBudget}`),n.push({name:`token-budget-available`,passed:d,reason:f});let p=n.filter(e=>!e.passed).map(e=>e.name);return{passed:p.length===0,gates:n,failedGates:p}}function rt(e,t){let n=I(t?.recurrence??1,1,10),r=I(t?.impact??5,1,10),i=I(e.foundIn.length,1,10),a=t?.observedAt?$e(new Date(t.observedAt)):5,o=et(t?.actionability??`medium`),s=tt(e.insight);return{signals:{recurrence:n,impact:r,sourceDiversity:i,freshness:a,actionability:o,tokenCost:s},totalScore:n+r+i+a+o+s}}function it(e,t,n,r,i){return t.passed?n&&r&&i&&n.some(e=>A(e,i.insight)>=r)?{decision:`supersede`,score:e.totalScore,reason:`Similar candidate already exists at L2`}:e.totalScore<20?{decision:`supersede`,score:e.totalScore,reason:`Score ${e.totalScore}/60 insufficient for promotion`}:e.totalScore<35?{decision:`hold-l3`,score:e.totalScore,reason:`Moderate score ${e.totalScore}/60, needs more evidence or recurrence`}:e.signals.recurrence<3&&e.signals.impact<8?{decision:`hold-l3`,score:e.totalScore,reason:`Low-impact repetition: recurrence=${e.signals.recurrence} < 3 despite score ${e.totalScore}/60`}:e.signals.recurrence<3&&e.signals.impact>=8?{decision:`promote`,score:e.totalScore,reason:`High-impact exception: impact=${e.signals.impact}, score=${e.totalScore}/60`}:{decision:`promote`,score:e.totalScore,reason:`Strong multi-signal score: ${e.totalScore}/60, recurrence=${e.signals.recurrence}, impact=${e.signals.impact}`}:{decision:`reject`,score:e.totalScore,reason:`Hard gates failed: ${t.failedGates.join(`, `)}`}}async function at(e,t){let n=await e.list({category:`lessons`,limit:1e3,orderBy:`updated`,order:`desc`});return(await Promise.all(n.map(async n=>{let r=await e.read(n.path),i=E(r.content),a=Xe(i.insight);return a?{workspace:t,path:n.path,title:i.title??r.title??n.title,insight:a,confidence:i.confidence??0}:null}))).filter(e=>e!==null)}async function ot(e){return(await at(e,`global`)).map(e=>e.insight)}function st(e,t,n){return t.some(t=>A(t,e)>=n)}function ct(){let e=b(s(),`global-knowledge`,`.ai`,`curated`);return f(e)||p(e,{recursive:!0}),e}async function lt(e){let t=new Map;if(!c())return t;for(let e of l()){let n=b(e.workspacePath,`.ai`,`curated`);if(!f(n))continue;let r=await at(Ye(n),e.partition);r.length>0&&t.set(e.partition,r)}return t}function ut(e,t=F,n){let r=Ke(t),i=[...e.values()].flat();if(i.length===0)return[];let a=Je(qe(i,r.similarityThreshold)),o=[];for(let e of a){let t=e.map(e=>i[e]),a=[...new Set(t.map(e=>e.workspace))].sort();if(a.length<r.minWorkspaces)continue;let s=Math.round(t.reduce((e,t)=>e+t.confidence,0)/t.length),c={insight:[...t].sort((e,t)=>t.confidence-e.confidence||e.title.localeCompare(t.title)||e.path.localeCompare(t.path))[0].insight,foundIn:a,avgConfidence:s,action:`skip`,reason:``};if(r.layeredKnowledge){let e=n?.get(c.insight),t=nt(c,e),r=rt(c,e),i=it(r,t,void 0,void 0,c);c.gateResult=t,c.scoringResult=r,c.adjudication=i,c.action=i.decision===`promote`?`promote`:`skip`,c.reason=i.reason}else c.action=s>=r.minAvgConfidence?`promote`:`skip`,c.reason=s>=r.minAvgConfidence?`Shared across ${a.length} workspaces`:`Below confidence threshold`;o.push(c)}return o.sort((e,t)=>Number(t.action===`promote`)-Number(e.action===`promote`)||t.foundIn.length-e.foundIn.length||t.avgConfidence-e.avgConfidence||e.insight.localeCompare(t.insight))}async function dt(e,t,n=F){let r=Ke(n),i=[],a=await ot(t);for(let n of e){if(!(r.layeredKnowledge?n.adjudication?.decision===`promote`:n.action===`promote`)||st(n.insight,a,r.similarityThreshold)||r.dryRun)continue;let e=await t.remember(Ze(n.insight),Qe(n),`lessons`,[`lesson`,`promoted`,`global`]);i.push(e.path),a.push(n.insight)}return{candidates:e,promoted:i}}async function ft(e,t){try{return await e.forget(t,`Demoted from global knowledge partition`),{removed:!0,path:t}}catch(e){if(e instanceof Error&&/not found/i.test(e.message))return{removed:!1,path:t};throw e}}var pt=e({createSamplingClient:()=>_t});const mt=o(`sampling`);function ht(e){if(!e.modelPreferences)return;let t={...e.modelPreferences.costPriority===void 0?{}:{costPriority:e.modelPreferences.costPriority},...e.modelPreferences.speedPriority===void 0?{}:{speedPriority:e.modelPreferences.speedPriority},...e.modelPreferences.intelligencePriority===void 0?{}:{intelligencePriority:e.modelPreferences.intelligencePriority}};return Object.keys(t).length>0?t:void 0}function gt(e){if(Array.isArray(e))return e.map(e=>gt(e)).filter(e=>e.length>0).join(`
|
|
5
5
|
`);if(e&&typeof e==`object`&&`type`in e){let t=e;if(t.type===`text`&&typeof t.text==`string`)return t.text}return JSON.stringify(e)}function _t(e){let t=e.server,n=typeof t?.createMessage==`function`;return{get available(){return n},async createMessage(e){if(!n)throw Error(`Sampling not available: client does not support createMessage`);let r=e.context?`${e.context}\n\n---\n\n${e.prompt}`:e.prompt;try{let n=t.createMessage({messages:[{role:`user`,content:{type:`text`,text:r}}],systemPrompt:e.systemPrompt,modelPreferences:ht(e),maxTokens:e.maxTokens??4e3}),i;if(e.timeoutMs&&e.timeoutMs>0){let t=new Promise((t,n)=>setTimeout(()=>n(Error(`Sampling createMessage timed out after ${e.timeoutMs}ms`)),e.timeoutMs));i=await Promise.race([n,t])}else i=await n;return{text:gt(i.content),model:i.model,stopReason:i.stopReason}}catch(e){throw mt.warn(`Sampling createMessage failed`,{error:String(e)}),e}}}}const vt=/^(export|import|function|class|interface|type|const|let|var|→|├|└|─|##)/,yt=/^(decision|rationale|status|context|consequence)/i,bt=/finding|recommendation|warning|error|issue/i,xt=/status|done|decision|blocker|next|file|created|modified/i,St=/(score|relevance)/i,Ct=/[/.]|\\.(ts|js)$/i;function L(e){return e.split(/\r?\n/u).map(e=>e.replace(/[ \t]+$/u,``)).join(`
|
|
6
6
|
`).replace(/\n{3,}/gu,`
|
|
7
7
|
|
|
@@ -14,7 +14,7 @@ import{t as e}from"./rolldown-runtime-DT7IzrpZ.js";import{t}from"./curated-manag
|
|
|
14
14
|
`),.65,e.length))}function jt(e){return z(e,R(e.split(/\r?\n/u).filter(e=>e.startsWith(`#`)||e.startsWith(`- `)||/\d/.test(e)||/\d+%/.test(e)||bt.test(e)).join(`
|
|
15
15
|
`),.6,e.length))}function Mt(e){return z(e,R(e.split(/\r?\n/u).filter(e=>e.startsWith(`- `)||e.startsWith(`* `)||xt.test(e)).join(`
|
|
16
16
|
`),.5,e.length))}function Nt(e,t){switch(e){case`file-card`:return Dt(t);case`search-result`:return Ot(t);case`decision`:return kt(t);case`pattern`:return At(t);case`analysis`:return jt(t);case`step-summary`:return Mt(t)}}const Pt=/^### (Context|Insight|Evidence|Key|Finding|Result|Decision)/imu;function Ft(e,t){let n=e.trim();if(!n||n.length<=t)return n;let r=n.split(/\\r?\\n/u),i=new Set;for(let e=0;e<r.length;e++)if(/^#{1,3}\s/mu.test(r[e])&&i.size===0){i.add(e);for(let t=e+1;t<r.length;t++)if(r[t].trim().length>0){i.add(t);break}}r.forEach((e,t)=>{if((/^\s*[-*]\s/mu.test(e)||/^\d+\.\s/mu.test(e))&&i.add(t),Pt.test(e)){i.add(t);let e=r[t+1]?.trim();e&&!/^[#>-]/.test(e)&&i.add(t+1)}/^(Confidence|Source|Tags?):/imu.test(e)&&i.add(t)}),n.length>t&&r.forEach((e,t)=>{i.has(t)||/\b(always|never|prefer|use|should|must|requires?|detected|confirmed|verified)\b/im.test(e)&&i.add(t)});let a=r.filter((e,t)=>i.has(t)).join(`
|
|
17
|
-
`).trim();return a.length<=t?L(a):wt(L(a),t)}function It(e,t,n,r){let i=t?.trim()??``,a=`(confidence: ${n}/100)`,o=`**${e}** ${a} — ${i}`.trim();if(o.length<=r)return o;let s=`**${e}** ${a}`;if(s.length<=r)return s;let c=r-a.length-8;return`**${e.length>c?`${e.slice(0,Math.max(0,c-3))}...`:e}** ${a}`}var Lt=e({autoUpgradeScaffold:()=>rn,checkForUpdates:()=>Yt,cleanupOldVersions:()=>G,getCurrentVersion:()=>U,getUpgradeState:()=>tn});const Rt=`@vpxa/aikit`,zt=`https://registry.npmjs.org/${Rt}/latest`,B=o(`server`);function Bt(){let e=_(r(import.meta.url));return[y(e,`..`,`..`,`..`,`bin`,`aikit.mjs`),y(e,`..`,`bin`,`aikit.mjs`),...process.argv[1]?[y(_(process.argv[1]),`aikit.mjs`)]:[]].find(e=>f(e))??null}const Vt=v(x(),`.aikit`),V=v(Vt,`current-version.json`),H=v(Vt,`versions`),Ht=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/;function Ut(e){if(!Ht.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}function U(){let e=y(_(r(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(m(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function Wt(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t>0?1:-1}return 0}function Gt(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){if((n[e]??0)>(r[e]??0))return!0;if((n[e]??0)<(r[e]??0))return!1}return!1}function Kt(e){if(!f(e))return;for(let t=1;t<=2;t++)try{g(e,{recursive:!0,force:!0});return}catch(n){if(!(n.code===`EPERM`||n.code===`EBUSY`||/EPERM|permission denied/i.test(String(n)))){B.debug(`Failed to remove directory`,{path:e,error:n instanceof Error?n.message:String(n),attempt:t});return}}let t=`${e}.orphaned.${Date.now()}`;try{h(e,t),B.debug(`Renamed locked directory to ${t} — deferred cleanup`);try{g(t,{recursive:!0,force:!0})}catch{}}catch(t){B.debug(`Failed to rename locked directory`,{path:e,error:t instanceof Error?t.message:String(t)})}}async function qt(e){Ut(e);let t=`v${e}`,n=v(H,`${t}-staging`),r=v(H,t);try{Kt(n),p(n,{recursive:!0}),b(`tar -xzf "${b(`npm pack ${Rt}@${e} 2>${process.platform===`win32`?`NUL`:`/dev/null`}`,{cwd:n,encoding:`utf-8`,timeout:6e4,windowsHide:!0}).trim()}"`,{cwd:n,encoding:`utf-8`,stdio:`pipe`,timeout:3e4,windowsHide:!0});let t=v(n,`package`);b(`npm ${i.join(` `)}`,{cwd:t,encoding:`utf-8`,stdio:`pipe`,timeout:12e4,windowsHide:!0});let a=v(t,`packages`,`server`,`dist`,`bin.js`);if(!f(a))throw Error(`Server entry not found at ${a}`);if(!f(v(t,`node_modules`)))throw Error(`node_modules not found — npm install may have failed`);f(r)&&g(r,{recursive:!0,force:!0}),h(t,r);let o=`${V}.tmp`;ne(o,JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)),h(o,V),G(e)}finally{Kt(n)}}function W(e){B.debug(`Updated to v${e}. Restarting server...`),setTimeout(()=>{process.exit(0)},300).unref()}function G(e){a(H,e??U())}async function Jt(){try{let e=m(V,`utf-8`),{version:t}=JSON.parse(e),n=await fetch(zt,{signal:AbortSignal.timeout(1e4)});if(!n.ok)return;let r=(await n.json()).version;if(!r||r===t||!Gt(r,t))return;if(f(v(H,`v${r}`))){let e=`${V}.tmp`;ne(e,JSON.stringify({version:r,installedAt:new Date().toISOString()},null,2)),h(e,V),B.debug(`Re-activated existing version v${r} — no download needed`),W(r);return}B.debug(`New version available: ${r}. Installing...`),await qt(r),W(r)}catch(e){B.error(`Background update check failed: ${e instanceof Error?e.message:String(e)}`)}}let K=null;function Yt(){return K||(K=Xt().finally(()=>{K=null}),K)}async function Xt(){if(f(V)){await Jt();return}let e=U();try{let t=await fetch(zt,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return;let n=(await t.json()).version;if(!n)return;if(Wt(e,n)<0){B.debug(`Newer version available — installing`,{currentVersion:e,latestVersion:n});try{await qt(n),W(n)}catch(e){B.warn(`Auto-install failed`,{error:e instanceof Error?e.message:String(e),latestVersion:n})}}}catch{}}function Zt(){try{let e=y(x(),`.copilot`,`.aikit-scaffold.json`);return f(e)?JSON.parse(m(e,`utf-8`)).version??null:null}catch{return null}}function Qt(){try{let e=u();if(!e)return null;let t=y(e,`.github`,`.aikit-scaffold.json`);return f(t)?JSON.parse(m(t,`utf-8`)).version??null:null}catch{return null}}let q=`idle`,J=null,$t=null,en=!1;function tn(){return{state:q,error:J}}function nn(){q=`idle`,J=null}function rn(){try{let e=U();if(Yt(),!en){en=!0;try{let e=Bt();e&&oe(process.execPath,[e,`migrate-launcher`],{cwd:x(),stdio:`ignore`,timeout:15e3,windowsHide:!0}).unref()}catch{}try{let e=y(x(),`.claude`,`mcp.json`);f(e)&&JSON.parse(m(e,`utf-8`))?.mcpServers?.[`AI Kit`]&&te(e)}catch{}}let t=Zt(),n=Qt();if(!(t!=null&&t!==e)&&!(n!=null&&n!==e)||($t!==e&&(nn(),$t=e),q!==`idle`))return;q=`pending`,J=null,B.debug(`Scaffold version mismatch — auto-upgrading`,{serverVersion:e,userScaffoldVersion:t,workspaceScaffoldVersion:n});let r=Bt();if(!r){q=`failed`,J=`aikit CLI binary not found`,B.warn(`Cannot auto-upgrade: aikit CLI binary not found`);return}let i=x();ae(process.execPath,[r,`upgrade`],{cwd:i,timeout:3e4,windowsHide:!0},(t,n,a)=>{t?(q=`failed`,J=t.message,B.warn(`Auto-upgrade failed`,{error:t.message,stack:t.stack,code:t.code,stdout:n?.slice(0,500),stderr:a?.slice(0,500),cwd:i,binPath:r,platform:process.platform})):(q=`success`,J=null,B.debug(`Auto-upgrade completed to version ${e}`))}).unref()}catch(e){q=`failed`,J=e instanceof Error?e.message:String(e),B.warn(`Auto-upgrade check failed`,{error:J})}}var an=e({buildOnboardContext:()=>hn,buildPreludeInjection:()=>vn,generatePrelude:()=>_n});function Y(e,t){return e.length<=t?e:e.slice(0,t)}function X(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}const on=2400,sn=new Set([`synthesis-guide.md`,`structure.md`,`dependencies.md`,`diagram.md`,`domains.md`,`entry-points.md`,`code-map.md`]),cn=[{id:`synthesis-guide`,file:`synthesis-guide.md`,title:`Synthesis Guide`,useFor:`project profile, recommended reading order, analysis index`,priority:1},{id:`structure`,file:`structure.md`,title:`Project Structure`,useFor:`package map, file layout, repo shape`,priority:2},{id:`dependencies`,file:`dependencies.md`,title:`Dependencies`,useFor:`external packages, internal import density, dependency hotspots`,priority:3},{id:`diagram`,file:`diagram.md`,title:`Architecture Diagram`,useFor:`C4 containers, package boundaries, architecture overview`,priority:4},{id:`domains`,file:`domains.md`,title:`Domains`,useFor:`service boundaries, domain clusters, ownership hints`,priority:5},{id:`entry-points`,file:`entry-points.md`,title:`Entry Points`,useFor:`CLI/server/API entry points before tracing code`,priority:6},{id:`code-map`,file:`code-map.md`,title:`Code Map`,useFor:`module graph, cross-package call edges, impact orientation`,priority:7},{id:`layers`,file:`layers.md`,title:`Layers`,useFor:`architectural layer classification`,priority:8},{id:`api-surface`,file:`api-surface.md`,title:`API Surface`,useFor:`public exports and API boundaries`,priority:9},{id:`type-inventory`,file:`type-inventory.md`,title:`Type Inventory`,useFor:`shared types and type-heavy modules`,priority:10}];function ln(e){return e.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``).trimStart()}function un(e,t){return e.length<=t?e:`${e.slice(0,t).trimEnd()}\n...`}function Z(e,t=12e3){try{return f(e)?m(e,`utf-8`).slice(0,t):null}catch{return null}}function dn(e){let t=Z(y(e,`.aikit-generated.json`),4e3);if(!t)return{exists:!1,valid:!1,generatedAt:null,schemaVersion:null};try{let e=JSON.parse(t);return{exists:!0,valid:!0,generatedAt:typeof e.generated_at==`string`?e.generated_at:null,schemaVersion:typeof e.schema_version==`number`?e.schema_version:null}}catch{return{exists:!0,valid:!1,generatedAt:null,schemaVersion:null}}}function Q(e,t){return e===`fresh`?{kind:`use`,command:null,reason:t}:{kind:`update_onboard`,command:`onboard({ path: ".", update: true })`,reason:t}}function fn(e){let t=new Date().toISOString(),n={generatedAt:e.generatedAt,lastIndexedAt:e.lastIndexedAt,manifestSchemaVersion:e.manifest.schemaVersion,missingResources:e.missingResources,checkedAt:t};if(e.missingResources.length>0)return{...n,status:`stale`,reason:`missing_required_files`,recommendedAction:Q(`stale`,`Required onboard files are missing; refresh onboard context before relying on it.`)};if(!e.manifest.exists)return{...n,status:`unknown`,reason:`missing_manifest`,recommendedAction:Q(`unknown`,`Onboard manifest is missing; update onboard context to restore freshness metadata.`)};if(!e.manifest.valid)return{...n,status:`unknown`,reason:`invalid_manifest`,recommendedAction:Q(`unknown`,`Onboard manifest is invalid; update onboard context before trusting it.`)};if(e.manifest.schemaVersion!==1)return{...n,status:`unknown`,reason:`legacy_manifest`,recommendedAction:Q(`unknown`,`Onboard manifest is from an older schema; update onboard context once.`)};if(!e.generatedAt||X(e.generatedAt)===0)return{...n,status:`unknown`,reason:`missing_generated_at`,recommendedAction:Q(`unknown`,`Onboard generation time is unavailable; update onboard context before trusting it.`)};let r=X(e.generatedAt);return X(e.lastIndexedAt)>r+3e5?{...n,status:`stale`,reason:`generated_before_index`,recommendedAction:Q(`stale`,`Repository index changed after onboard generation; update onboard context.`)}:{...n,status:`fresh`,reason:`fresh`,recommendedAction:Q(`fresh`,`Onboard context matches current freshness checks.`)}}function pn(e){if(!e)return[];let t=e.split(/\r?\n/),n=t.findIndex(e=>e.trim()===`### Project Profile`);if(n<0)return[];let r=[];for(let e of t.slice(n+1)){if(e.startsWith(`### `))break;let t=e.trim();t.startsWith(`- `)&&r.push(t)}return r.slice(0,6)}function mn(e){if(!e)return[];let t=new Set;for(let n of e.matchAll(/Container\([^,\n]+,\s*"([^"]+)"/g)){let e=n[1]?.trim();e&&t.add(e)}return[...t]}function hn(e,t={}){if(!e||!f(e))return null;let n=cn.flatMap(t=>{let n=y(e,t.file);return f(n)?[{id:t.id,title:t.title,path:n,sizeBytes:ee(n).size,useFor:t.useFor,priority:t.priority}]:[]}),r=y(e,`synthesis-guide.md`),i=y(e,`diagram.md`),a=dn(e),o=a.generatedAt,s=[...sn].filter(t=>!f(y(e,t))),c=fn({generatedAt:o,lastIndexedAt:t.lastIndexedAt??null,manifest:a,missingResources:s}),l=Z(r),u=mn(Z(i)),d=u.slice(0,40),p=u.length>d.length;return{dir:y(e),generatedAt:o,fresh:c.status===`fresh`,freshness:c,projectProfile:pn(l),recommendedReadOrder:[`synthesis-guide.md`,`structure.md`,`dependencies.md`,`diagram.md`,`domains.md`,`entry-points.md`,`code-map.md`],readInstruction:c.status===`fresh`?`Use fresh onboard context before broad source reads: start with synthesis-guide.md, use structure.md/dependencies.md for package map, diagram.md/domains.md for architecture, and code-map.md for module graph.`:`Update onboard context first with \`${c.recommendedAction.command}\`, then use synthesis-guide.md, structure.md/dependencies.md, diagram.md/domains.md, and code-map.md before broad source reads.`,resources:n,packageMap:{sourcePath:u.length>0?i:null,packages:d,totalPackages:u.length,truncated:p},architecture:{sourcePath:f(i)?i:null,summary:u.length>0?`C4 container diagram with ${u.length} package/container nodes.`:`Read diagram.md and domains.md for architecture boundaries.`,containers:d,totalContainers:u.length,truncated:p}}}function gn(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(!e)continue;let t=y(e,`SKILL.md`);if(f(t))try{let e=m(t,`utf-8`),n=ln(e)||e,r=un(n,on);return{preview:r,resource:{uri:`aikit://skill/SKILL.md`,path:t,sizeBytes:ee(t).size,previewChars:r.length,truncated:n.length>on}}}catch{}}return null}async function _n(e,t,n=C,r,i){if(!e||!t)return null;try{let[a,o,s]=await Promise.all([e.list({category:`lessons`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`conventions`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`session`,limit:200,orderBy:`updated`,order:`desc`})]),c=a.filter(e=>e.tags.includes(`lesson`)).map(e=>{let r=t.memoryMetaGet(e.path);return!r||r.supersededBy!=null?null:{entry:e,confidence:E(r.confidence,r.lastAccessedAt,r.createdAt,n)}}).filter(e=>e!==null).sort((e,t)=>t.confidence-e.confidence).slice(0,3),l=await Promise.all(c.map(async({entry:t,confidence:n})=>{let r=T((await e.read(t.path)).content);return{title:t.title,insight:Y(r.insight??``,150),confidence:n}})),u=o.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).filter(({entry:e})=>(e.contentPreview?.trim()??``).length>5).sort((e,t)=>X(t.lastAccessedAt)-X(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),d=s.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>X(t.lastAccessedAt)-X(e.lastAccessedAt)).map(({entry:e})=>Y(e.contentPreview,200))[0]??null,f=gn(r);return{lessons:l,conventions:u,checkpoint:d,workspaceSkill:f?.preview??null,workspaceSkillResource:f?.resource??null,onboardContext:i??null}}catch{return null}}function vn(e,t=600){if(!e)return{lines:[],totalChars:0,autoInjectCount:0};let n=[],r=0;for(let t of e.lessons){if(t.confidence<45)continue;let e=It(t.title,t.insight,t.confidence,200);n.push(`• ${e}`),r++}if(e.workspaceSkillResource?(n.push(`• Workspace skill: read ${e.workspaceSkillResource.uri} before repo work (${e.workspaceSkillResource.sizeBytes} bytes; status preview included).`),r++):e.workspaceSkill&&(n.push(`• Workspace skill preview: ${e.workspaceSkill.split(`
|
|
17
|
+
`).trim();return a.length<=t?L(a):wt(L(a),t)}function It(e,t,n,r){let i=t?.trim()??``,a=`(confidence: ${n}/100)`,o=`**${e}** ${a} — ${i}`.trim();if(o.length<=r)return o;let s=`**${e}** ${a}`;if(s.length<=r)return s;let c=r-a.length-8;return`**${e.length>c?`${e.slice(0,Math.max(0,c-3))}...`:e}** ${a}`}var Lt=e({autoUpgradeScaffold:()=>rn,checkForUpdates:()=>Yt,cleanupOldVersions:()=>G,getCurrentVersion:()=>U,getUpgradeState:()=>tn});const Rt=`@vpxa/aikit`,zt=`https://registry.npmjs.org/${Rt}/latest`,B=o(`server`);function Bt(){let e=y(r(import.meta.url));return[x(e,`..`,`..`,`..`,`bin`,`aikit.mjs`),x(e,`..`,`bin`,`aikit.mjs`),...process.argv[1]?[x(y(process.argv[1]),`aikit.mjs`)]:[]].find(e=>f(e))??null}const Vt=b(C(),`.aikit`),V=b(Vt,`current-version.json`),H=b(Vt,`versions`),Ht=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/;function Ut(e){if(!Ht.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}function U(){let e=x(y(r(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(m(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function Wt(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=(n[e]??0)-(r[e]??0);if(t!==0)return t>0?1:-1}return 0}function Gt(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){if((n[e]??0)>(r[e]??0))return!0;if((n[e]??0)<(r[e]??0))return!1}return!1}function Kt(e){if(!f(e))return;for(let t=1;t<=2;t++)try{g(e,{recursive:!0,force:!0});return}catch(n){if(!(n.code===`EPERM`||n.code===`EBUSY`||/EPERM|permission denied/i.test(String(n)))){B.debug(`Failed to remove directory`,{path:e,error:n instanceof Error?n.message:String(n),attempt:t});return}}let t=`${e}.orphaned.${Date.now()}`;try{h(e,t),B.debug(`Renamed locked directory to ${t} — deferred cleanup`);try{g(t,{recursive:!0,force:!0})}catch{}}catch(t){B.debug(`Failed to rename locked directory`,{path:e,error:t instanceof Error?t.message:String(t)})}}async function qt(e){Ut(e);let t=`v${e}`,n=b(H,`${t}-staging`),r=b(H,t);try{Kt(n),p(n,{recursive:!0}),S(`tar -xzf "${S(`npm pack ${Rt}@${e} 2>${process.platform===`win32`?`NUL`:`/dev/null`}`,{cwd:n,encoding:`utf-8`,timeout:6e4,windowsHide:!0}).trim()}"`,{cwd:n,encoding:`utf-8`,stdio:`pipe`,timeout:3e4,windowsHide:!0});let t=b(n,`package`);S(`npm ${i.join(` `)}`,{cwd:t,encoding:`utf-8`,stdio:`pipe`,timeout:12e4,windowsHide:!0});let a=b(t,`packages`,`server`,`dist`,`bin.js`);if(!f(a))throw Error(`Server entry not found at ${a}`);if(!f(b(t,`node_modules`)))throw Error(`node_modules not found — npm install may have failed`);f(r)&&g(r,{recursive:!0,force:!0}),h(t,r);let o=`${V}.tmp`;v(o,JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)),h(o,V),G(e)}finally{Kt(n)}}function W(e){B.debug(`Updated to v${e}. Restarting server...`),setTimeout(()=>{process.exit(0)},300).unref()}function G(e){a(H,e??U())}async function Jt(){try{let e=m(V,`utf-8`),{version:t}=JSON.parse(e),n=await fetch(zt,{signal:AbortSignal.timeout(1e4)});if(!n.ok)return;let r=(await n.json()).version;if(!r||r===t||!Gt(r,t))return;if(f(b(H,`v${r}`))){let e=`${V}.tmp`;v(e,JSON.stringify({version:r,installedAt:new Date().toISOString()},null,2)),h(e,V),B.debug(`Re-activated existing version v${r} — no download needed`),W(r);return}B.debug(`New version available: ${r}. Installing...`),await qt(r),W(r)}catch(e){B.error(`Background update check failed: ${e instanceof Error?e.message:String(e)}`)}}let K=null;function Yt(){return K||(K=Xt().finally(()=>{K=null}),K)}async function Xt(){if(f(V)){await Jt();return}let e=U();try{let t=await fetch(zt,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return;let n=(await t.json()).version;if(!n)return;if(Wt(e,n)<0){B.debug(`Newer version available — installing`,{currentVersion:e,latestVersion:n});try{await qt(n),W(n)}catch(e){B.warn(`Auto-install failed`,{error:e instanceof Error?e.message:String(e),latestVersion:n})}}}catch{}}function Zt(){try{let e=x(C(),`.copilot`,`.aikit-scaffold.json`);return f(e)?JSON.parse(m(e,`utf-8`)).version??null:null}catch{return null}}function Qt(){try{let e=u();if(!e)return null;let t=x(e,`.github`,`.aikit-scaffold.json`);return f(t)?JSON.parse(m(t,`utf-8`)).version??null:null}catch{return null}}let q=`idle`,J=null,$t=null,en=!1;function tn(){return{state:q,error:J}}function nn(){q=`idle`,J=null}function rn(){try{let e=U();if(Yt(),!en){en=!0;try{let e=Bt();e&&ie(process.execPath,[e,`migrate-launcher`],{cwd:C(),stdio:`ignore`,timeout:15e3,windowsHide:!0}).unref()}catch{}try{let e=x(C(),`.claude`,`mcp.json`);f(e)&&JSON.parse(m(e,`utf-8`))?.mcpServers?.[`AI Kit`]&&_(e)}catch{}}let t=Zt(),n=Qt();if(!(t!=null&&t!==e)&&!(n!=null&&n!==e)||($t!==e&&(nn(),$t=e),q!==`idle`))return;q=`pending`,J=null,B.debug(`Scaffold version mismatch — auto-upgrading`,{serverVersion:e,userScaffoldVersion:t,workspaceScaffoldVersion:n});let r=Bt();if(!r){q=`failed`,J=`aikit CLI binary not found`,B.warn(`Cannot auto-upgrade: aikit CLI binary not found`);return}let i=C();re(process.execPath,[r,`upgrade`],{cwd:i,timeout:3e4,windowsHide:!0},(t,n,a)=>{t?(q=`failed`,J=t.message,B.warn(`Auto-upgrade failed`,{error:t.message,stack:t.stack,code:t.code,stdout:n?.slice(0,500),stderr:a?.slice(0,500),cwd:i,binPath:r,platform:process.platform})):(q=`success`,J=null,B.debug(`Auto-upgrade completed to version ${e}`))}).unref()}catch(e){q=`failed`,J=e instanceof Error?e.message:String(e),B.warn(`Auto-upgrade check failed`,{error:J})}}var an=e({buildOnboardContext:()=>_n,buildPreludeInjection:()=>bn,generatePrelude:()=>yn});function Y(e,t){return e.length<=t?e:e.slice(0,t)}function X(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}const on=2400,sn=new Set([`synthesis-guide.md`,`structure.md`,`dependencies.md`,`diagram.md`,`domains.md`,`entry-points.md`,`code-map.md`]),cn=[{id:`synthesis-guide`,file:`synthesis-guide.md`,title:`Synthesis Guide`,useFor:`project profile, recommended reading order, analysis index`,priority:1},{id:`structure`,file:`structure.md`,title:`Project Structure`,useFor:`package map, file layout, repo shape`,priority:2},{id:`dependencies`,file:`dependencies.md`,title:`Dependencies`,useFor:`external packages, internal import density, dependency hotspots`,priority:3},{id:`diagram`,file:`diagram.md`,title:`Architecture Diagram`,useFor:`C4 containers, package boundaries, architecture overview`,priority:4},{id:`domains`,file:`domains.md`,title:`Domains`,useFor:`service boundaries, domain clusters, ownership hints`,priority:5},{id:`entry-points`,file:`entry-points.md`,title:`Entry Points`,useFor:`CLI/server/API entry points before tracing code`,priority:6},{id:`code-map`,file:`code-map.md`,title:`Code Map`,useFor:`module graph, cross-package call edges, impact orientation`,priority:7},{id:`layers`,file:`layers.md`,title:`Layers`,useFor:`architectural layer classification`,priority:8},{id:`api-surface`,file:`api-surface.md`,title:`API Surface`,useFor:`public exports and API boundaries`,priority:9},{id:`type-inventory`,file:`type-inventory.md`,title:`Type Inventory`,useFor:`shared types and type-heavy modules`,priority:10}];function ln(e){return e.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``).trimStart()}function un(e,t){return e.length<=t?e:`${e.slice(0,t).trimEnd()}\n...`}function Z(e,t=12e3){try{return f(e)?m(e,`utf-8`).slice(0,t):null}catch{return null}}function dn(e){let t=Z(x(e,`.aikit-generated.json`),4e3);if(!t)return{exists:!1,valid:!1,generatedAt:null,schemaVersion:null};try{let e=JSON.parse(t);return{exists:!0,valid:!0,generatedAt:typeof e.generated_at==`string`?e.generated_at:null,schemaVersion:typeof e.schema_version==`number`?e.schema_version:null}}catch{return{exists:!0,valid:!1,generatedAt:null,schemaVersion:null}}}function Q(e,t){return e===`fresh`?{kind:`use`,command:null,reason:t}:{kind:`update_onboard`,command:`onboard({ path: ".", update: true })`,reason:t}}function fn(e){let t=new Date().toISOString(),n={generatedAt:e.generatedAt,lastIndexedAt:e.lastIndexedAt,manifestSchemaVersion:e.manifest.schemaVersion,missingResources:e.missingResources,checkedAt:t};if(e.missingResources.length>0)return{...n,status:`stale`,reason:`missing_required_files`,recommendedAction:Q(`stale`,`Required onboard files are missing; refresh onboard context before relying on it.`)};if(!e.manifest.exists)return{...n,status:`unknown`,reason:`missing_manifest`,recommendedAction:Q(`unknown`,`Onboard manifest is missing; update onboard context to restore freshness metadata.`)};if(!e.manifest.valid)return{...n,status:`unknown`,reason:`invalid_manifest`,recommendedAction:Q(`unknown`,`Onboard manifest is invalid; update onboard context before trusting it.`)};if(e.manifest.schemaVersion!==1)return{...n,status:`unknown`,reason:`legacy_manifest`,recommendedAction:Q(`unknown`,`Onboard manifest is from an older schema; update onboard context once.`)};if(!e.generatedAt||X(e.generatedAt)===0)return{...n,status:`unknown`,reason:`missing_generated_at`,recommendedAction:Q(`unknown`,`Onboard generation time is unavailable; update onboard context before trusting it.`)};let r=X(e.generatedAt);return X(e.lastIndexedAt)>r+3e5?{...n,status:`stale`,reason:`generated_before_index`,recommendedAction:Q(`stale`,`Repository index changed after onboard generation; update onboard context.`)}:{...n,status:`fresh`,reason:`fresh`,recommendedAction:Q(`fresh`,`Onboard context matches current freshness checks.`)}}function pn(e){if(!e)return[];let t=e.split(/\r?\n/),n=t.findIndex(e=>e.trim()===`### Project Profile`);if(n<0)return[];let r=[];for(let e of t.slice(n+1)){if(e.startsWith(`### `))break;let t=e.trim();t.startsWith(`- `)&&r.push(t)}return r.slice(0,6)}function mn(e){if(!e)return[];let t=new Set;for(let n of e.matchAll(/Container\([^,\n]+,\s*"([^"]+)"/g)){let e=n[1]?.trim();e&&t.add(e)}return[...t]}function hn(e){if(!e)return[];let t=new Set,n=!1,r=!1,i=null;for(let a of e.split(/\r?\n/)){if(a.trim().startsWith("```")){n=!n;continue}if(!n)continue;let e=a.match(/^([A-Za-z0-9_.@-][^/\\]*)\/\s*$/);if(!r&&e?.[1]){i=e[1].trim(),r=!0;continue}if(!r)continue;let o=a.match(/^(?:│ {3}| {4})([A-Za-z0-9_.@-][^/\\]*?)\/\s*$/)?.[1]?.trim();o&&o!==i&&t.add(o)}return[...t]}function gn(e){if(!e)return null;let{resources:t,...n}=e;return{...n,resourceCount:t.length,resourceIds:t.map(e=>e.id)}}function _n(e,t={}){if(!e||!f(e))return null;let n=cn.flatMap(t=>{let n=x(e,t.file);return f(n)?[{id:t.id,title:t.title,path:n,sizeBytes:ee(n).size,useFor:t.useFor,priority:t.priority}]:[]}),r=x(e,`synthesis-guide.md`),i=x(e,`structure.md`),a=x(e,`diagram.md`),o=dn(e),s=o.generatedAt,c=[...sn].filter(t=>!f(x(e,t))),l=fn({generatedAt:s,lastIndexedAt:t.lastIndexedAt??null,manifest:o,missingResources:c}),u=Z(r),d=Z(i),p=mn(Z(a)),m=p.length>0?[]:hn(d),h=p.length>0?p:m,g=p.length>0?a:m.length>0?i:null,_=h.slice(0,40),v=h.length>_.length,y=p.slice(0,40),b=p.length>y.length;return{dir:x(e),generatedAt:s,fresh:l.status===`fresh`,freshness:l,projectProfile:pn(u),recommendedReadOrder:[`synthesis-guide.md`,`structure.md`,`dependencies.md`,`diagram.md`,`domains.md`,`entry-points.md`,`code-map.md`],readInstruction:l.status===`fresh`?`Use fresh onboard context before broad source reads: start with synthesis-guide.md, use structure.md/dependencies.md for package map, diagram.md/domains.md for architecture, and code-map.md for module graph.`:`Update onboard context first with \`${l.recommendedAction.command}\`, then use synthesis-guide.md, structure.md/dependencies.md, diagram.md/domains.md, and code-map.md before broad source reads.`,resources:n,packageMap:{sourcePath:g,packages:_,totalPackages:h.length,truncated:v},architecture:{sourcePath:f(a)?a:null,summary:p.length>0?`C4 container diagram with ${p.length} package/container nodes.`:`Read diagram.md and domains.md for architecture boundaries.`,containers:y,totalContainers:p.length,truncated:b}}}function vn(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(!e)continue;let t=x(e,`SKILL.md`);if(f(t))try{let e=m(t,`utf-8`),n=ln(e)||e,r=un(n,on);return{preview:r,resource:{uri:`aikit://skill/SKILL.md`,path:t,sizeBytes:ee(t).size,previewChars:r.length,truncated:n.length>on}}}catch{}}return null}async function yn(e,t,n=w,r,i){let a=vn(r),o={lessons:[],conventions:[],checkpoint:null,workspaceSkill:a?.preview??null,workspaceSkillResource:a?.resource??null,onboardContext:gn(i)};if(!e||!t)return o;try{let[r,i,a]=await Promise.all([e.list({category:`lessons`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`conventions`,limit:200,orderBy:`updated`,order:`desc`}),e.list({category:`session`,limit:200,orderBy:`updated`,order:`desc`})]),s=r.filter(e=>e.tags.includes(`lesson`)).map(e=>{let r=t.memoryMetaGet(e.path);return!r||r.supersededBy!=null?null:{entry:e,confidence:D(r.confidence,r.lastAccessedAt,r.createdAt,n)}}).filter(e=>e!==null).sort((e,t)=>t.confidence-e.confidence).slice(0,3),c=await Promise.all(s.map(async({entry:t,confidence:n})=>{let r=E((await e.read(t.path)).content);return{title:t.title,insight:Y(r.insight??``,150),confidence:n}})),l=i.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).filter(({entry:e})=>(e.contentPreview?.trim()??``).length>5).sort((e,t)=>X(t.lastAccessedAt)-X(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),u=a.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>X(t.lastAccessedAt)-X(e.lastAccessedAt)).map(({entry:e})=>Y(e.contentPreview,200))[0]??null;return{...o,lessons:c,conventions:l,checkpoint:u}}catch{return o}}function bn(e,t=600){if(!e)return{lines:[],totalChars:0,autoInjectCount:0};let n=[],r=0;for(let t of e.lessons){if(t.confidence<45)continue;let e=It(t.title,t.insight,t.confidence,200);n.push(`• ${e}`),r++}if(e.workspaceSkillResource?(n.push(`• Workspace skill: read ${e.workspaceSkillResource.uri} before repo work (${e.workspaceSkillResource.sizeBytes} bytes; status preview included).`),r++):e.workspaceSkill&&(n.push(`• Workspace skill preview: ${e.workspaceSkill.split(`
|
|
18
18
|
`)[0]??``}`),r++),e.onboardContext){let t=e.onboardContext.packageMap.totalPackages>0?` package map has ${e.onboardContext.packageMap.totalPackages} packages/containers;`:``;n.push(`• Onboard context:${t} ${e.onboardContext.readInstruction}`),r++}for(let t of e.conventions){let e=t.preview?.trim()||``;if(e){let r=e.length>120?`${e.slice(0,117)}...`:e;n.push(`• ${t.title}: ${r}`)}else n.push(`• ${t.title}`)}if(n.length===0)return{lines:[],totalChars:0,autoInjectCount:0};let i=[`━━ Knowledge ━━`,...n,`───`],a=i.join(`
|
|
19
19
|
`);if(a.length>t)for(;i.length>3&&a.length>t;)i.splice(1,1)[0]?.startsWith(`•`)&&r--;return{lines:i,totalChars:i.join(`
|
|
20
|
-
`).length,autoInjectCount:r}}const $=o(`server`);function
|
|
20
|
+
`).length,autoInjectCount:r}}const $=o(`server`);function xn(e,t){return t?{version:e,...d(t)}:{version:e}}function Sn(e,n,r){e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:r,prune:i,shouldRunStartupPrune:a,shouldRunWeeklyPromote:o}=await import(`../../tools/dist/index.js`),s=n();if(!s)return;try{let{readdirSync:e,rmSync:t,statSync:n,existsSync:r}=await import(`node:fs`),{join:i}=await import(`node:path`),{homedir:a}=await import(`node:os`),o=i(a(),`.aikit`,`workspaces`);if(r(o)){let a=Date.now(),s=e(o,{withFileTypes:!0}),c=0;for(let e of s){if(!e.isDirectory())continue;let s=i(o,e.name);try{if(a-n(s).mtimeMs<2592e6)continue;let e=i(s,`store`,`aikit.db`);if(!r(e)){t(s,{recursive:!0,force:!0}),c++;continue}n(e).size<1024&&(t(s,{recursive:!0,force:!0}),c++)}catch{}}c>0&&$.info(`Workspace directory GC complete`,{directoriesRemoved:c,directoriesRemaining:s.length-c})}}catch{}if(a()){let e=await i({});r(),e.totalBytesFreed>0&&$.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:n}=await Promise.resolve().then(()=>Ae),a=await n(s.curated,s.stateStore,{dryRun:!1});a.pruned.length>0&&$.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let o=await t(s.curated,s.stateStore,{dryRun:!1});(o.groupsCreated>0||o.lessonsGrouped>0)&&$.info(`Startup lesson grouping complete`,{groupsCreated:o.groupsCreated,lessonsGrouped:o.lessonsGrouped})}if(o()){let{DEFAULT_PROMOTE_CONFIG:n,collectWorkspaceLessons:r,getGlobalCuratedDir:i,promoteLessons:a,scanForDuplicates:o}=await Promise.resolve().then(()=>Ge),c=s.curated,l=new t(i(),c.store,c.embedder),u=await r(),d={...n,dryRun:!1},f=await a(o(u,d),l,d);e(),f.promoted.length>0&&$.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){$.warn(`Startup maintenance failed (non-critical)`,xn(r,e))}}).catch(e=>$.warn(`Startup maintenance failed`,d(e)))}export{Te as A,ue as B,Ue as C,k as D,M as E,be as F,me as G,E as H,w as I,ce as J,ae as K,le as L,O as M,xe as N,we as O,ye as P,fe as R,We as S,ke as T,T as U,pe as V,de as W,ft as _,an as a,ut as b,U as c,Nt as d,Ft as f,lt as g,F as h,yn as i,Se as j,A as k,tn as l,pt as m,xn as n,rn as o,_t as p,se as q,_n as r,G as s,Sn as t,Lt as u,ct as v,Oe as w,Ae as x,dt as y,D as z};
|
|
@@ -3581,20 +3581,41 @@ declare function addToWorkset(name: string, files: string[], cwd?: string): Work
|
|
|
3581
3581
|
*/
|
|
3582
3582
|
declare function removeFromWorkset(name: string, files: string[], cwd?: string): Workset | null;
|
|
3583
3583
|
//#endregion
|
|
3584
|
-
//#region packages/tools/src/workspace-skill-
|
|
3584
|
+
//#region packages/tools/src/workspace-skill-quality.d.ts
|
|
3585
|
+
type WorkspaceSkillQuality = 'pass' | 'warn' | 'fail';
|
|
3586
|
+
interface RenderedWorkspaceSkillValidation {
|
|
3587
|
+
quality: WorkspaceSkillQuality;
|
|
3588
|
+
errors: string[];
|
|
3589
|
+
warnings: string[];
|
|
3590
|
+
sections: string[];
|
|
3591
|
+
visibleLearnedSectionCount: number;
|
|
3592
|
+
hasFallbackGuidance: boolean;
|
|
3593
|
+
}
|
|
3585
3594
|
/**
|
|
3586
|
-
*
|
|
3587
|
-
* facts, promoted knowledge, and flow state.
|
|
3595
|
+
* Validate a rendered workspace skill artifact against all quality gates.
|
|
3588
3596
|
*
|
|
3589
|
-
*
|
|
3597
|
+
* Inspects the final rendered SKILL.md markdown, the references companion,
|
|
3598
|
+
* the compiler input, and the compiled section metadata to produce a
|
|
3599
|
+
* pass/warn/fail verdict.
|
|
3590
3600
|
*
|
|
3591
|
-
*
|
|
3592
|
-
* L0CardInput → generateWorkspaceSkill() → skills/<ws-name>/SKILL.md
|
|
3593
|
-
* WorkflowCardInput → generateFlowBriefing() → skills/<ws-name>/references/<flow-slug>.md
|
|
3601
|
+
* Pure function — no side effects, no I/O, no LLM calls.
|
|
3594
3602
|
*
|
|
3595
|
-
*
|
|
3596
|
-
*
|
|
3603
|
+
* @param args.skillMarkdown — The visible SKILL.md content
|
|
3604
|
+
* @param args.referencesMarkdown — The references/workspace-memory.md companion
|
|
3605
|
+
* @param args.input — The SkillInput used during compilation
|
|
3606
|
+
* @param args.includedSections — Sections that made it through budget selection
|
|
3607
|
+
* @param args.warnings — Warnings collected during compilation
|
|
3608
|
+
* @returns A structured validation result
|
|
3597
3609
|
*/
|
|
3610
|
+
declare function validateRenderedWorkspaceSkill(args: {
|
|
3611
|
+
skillMarkdown: string;
|
|
3612
|
+
referencesMarkdown: string;
|
|
3613
|
+
input: SkillInput;
|
|
3614
|
+
includedSections: SkillSection[];
|
|
3615
|
+
warnings: string[];
|
|
3616
|
+
}): RenderedWorkspaceSkillValidation;
|
|
3617
|
+
//#endregion
|
|
3618
|
+
//#region packages/tools/src/workspace-skill-compiler.d.ts
|
|
3598
3619
|
/**
|
|
3599
3620
|
* Resolve the skill directory for a workspace partition.
|
|
3600
3621
|
*/
|
|
@@ -3609,8 +3630,6 @@ interface SkillSectionBudget {
|
|
|
3609
3630
|
declare const SECTION_BUDGETS: SkillSectionBudget[];
|
|
3610
3631
|
/** Budgets for flow briefing reference files. Total ≤ 4680 chars. */
|
|
3611
3632
|
declare const FLOW_REFERENCE_SECTION_BUDGETS: SkillSectionBudget[];
|
|
3612
|
-
/** Names for each section id, used as markdown headings. */
|
|
3613
|
-
declare const SECTION_NAMES: Record<string, string>;
|
|
3614
3633
|
/** Maximum characters for a generated skill file (≈1200 tokens × 4 chars/token). */
|
|
3615
3634
|
declare const MAX_SKILL_CHARS = 4800;
|
|
3616
3635
|
/** Name of the workspace skill SKILL.md file. */
|
|
@@ -3639,6 +3658,8 @@ interface CompiledSkillBundle {
|
|
|
3639
3658
|
warnings: string[];
|
|
3640
3659
|
/** Content hash for staleness detection. */
|
|
3641
3660
|
contentHash: string;
|
|
3661
|
+
/** Validation result from rendered quality gate. */
|
|
3662
|
+
validation?: RenderedWorkspaceSkillValidation;
|
|
3642
3663
|
}
|
|
3643
3664
|
interface PromotedKnowledgeEntry {
|
|
3644
3665
|
title: string;
|
|
@@ -3730,18 +3751,6 @@ declare function generateWorkspaceSkill(input: SkillInput, version?: number): Co
|
|
|
3730
3751
|
* Generate a flow briefing reference file from flow execution state.
|
|
3731
3752
|
*/
|
|
3732
3753
|
declare function generateFlowBriefing(input: FlowBriefingInput, version?: number): string;
|
|
3733
|
-
/**
|
|
3734
|
-
* Check whether the skill content contains raw auto-observation noise.
|
|
3735
|
-
* Matches "Observation ", "type-test_failure", and similar patterns
|
|
3736
|
-
* that come from auto-knowledge extractors, not curated knowledge.
|
|
3737
|
-
*/
|
|
3738
|
-
declare function containsRawObservationNoise(content: string): boolean;
|
|
3739
|
-
/**
|
|
3740
|
-
* Check whether the skill content contains HTML truncation comments.
|
|
3741
|
-
* These are comments like `<!-- high-value-retrieval truncated ... -->`
|
|
3742
|
-
* that should never be visible in agent-facing output.
|
|
3743
|
-
*/
|
|
3744
|
-
declare function containsTruncationComments(content: string): boolean;
|
|
3745
3754
|
/**
|
|
3746
3755
|
* Check if a skill file is stale based on content-hash comparison,
|
|
3747
3756
|
* schema policy version, and quality rejection patterns.
|
|
@@ -3759,4 +3768,31 @@ declare function isSkillStale(skillContent: string, currentSourceHash: string):
|
|
|
3759
3768
|
*/
|
|
3760
3769
|
declare function parseSkillMetadata(content: string): SkillMetadata | null;
|
|
3761
3770
|
//#endregion
|
|
3762
|
-
|
|
3771
|
+
//#region packages/tools/src/workspace-skill-constants.d.ts
|
|
3772
|
+
/**
|
|
3773
|
+
* Shared constants and utilities for workspace skill compilation and quality validation.
|
|
3774
|
+
* Extracted to break circular dependency between workspace-skill-compiler.ts
|
|
3775
|
+
* and workspace-skill-quality.ts.
|
|
3776
|
+
*/
|
|
3777
|
+
/** Minimum confidence threshold for a learned entry to be included. */
|
|
3778
|
+
declare const MIN_LEARNED_CONFIDENCE = 60;
|
|
3779
|
+
/** Names for each section id, used as markdown headings. */
|
|
3780
|
+
declare const SECTION_NAMES: Record<string, string>;
|
|
3781
|
+
/** Section IDs that require source references (learned content). */
|
|
3782
|
+
declare const LEARNED_SECTION_IDS: Set<string>;
|
|
3783
|
+
/** Section IDs that are structural (do not require references). */
|
|
3784
|
+
declare const STRUCTURAL_SECTION_IDS: Set<string>;
|
|
3785
|
+
/** Pattern matching runtime or partition slugs used as workspace identity. */
|
|
3786
|
+
declare const RUNTIME_SLUG_RE: RegExp;
|
|
3787
|
+
/** Patterns that indicate a secret leak if found in rendered skill content. */
|
|
3788
|
+
declare const SECRET_PATTERNS: ReadonlyArray<RegExp>;
|
|
3789
|
+
/**
|
|
3790
|
+
* Check whether the skill content contains raw auto-observation noise.
|
|
3791
|
+
*/
|
|
3792
|
+
declare function containsRawObservationNoise(content: string): boolean;
|
|
3793
|
+
/**
|
|
3794
|
+
* Check whether the skill content contains HTML truncation comments.
|
|
3795
|
+
*/
|
|
3796
|
+
declare function containsTruncationComments(content: string): boolean;
|
|
3797
|
+
//#endregion
|
|
3798
|
+
export { type AikitNextHint, type AikitResponse, type AikitResponseMeta, type AikitToolError, type AikitToolErrorCode, type AuditCheck, type AuditData, type AuditOptions, type AuditRecommendation, type BenchmarkReport, type BlastNode, type ChangelogEntry, type ChangelogFormat, type ChangelogOptions, type ChangelogResult, type CheckOptions, type CheckResult, type CheckSummaryResult, type Checkpoint, type CheckpointSummary, type ClassifyTrigger, type CodemodChange, type CodemodOptions, type CodemodResult, type CodemodRule, type CommunityInfo, type CompactOptions, type CompactResult, type ComplianceReport, type ComplianceRule, type ComplianceScoreOptions, type ComplianceViolation, type CompressOutputOptions, type CompressionContext, type CompressionMode, type CompressionResult, type CompressionRule, type ConstraintRef, type CorpusStats, type DeadSymbol, type DeadSymbolOptions, type DeadSymbolResult, type Definition, type DelegateOptions, type DelegateResult, type DetectedRoute, type DiffChange, type DiffFile, type DiffHunk, type DiffParseOptions, type DiffReport, type DigestFieldEntry, type DigestOptions, type DigestResult, type DigestSource, type DogfoodLogEntry, type DogfoodLogGroupedEntry, type DogfoodLogOptions, type DogfoodLogResult, type Domain, type DomainAnalysisInput, type DomainClassification, type DomainType, type EncodeOperation, type EncodeOptions, type EncodeResult, type EnrichOptions, type EnrichStructureEntry, type EnrichSymbolEntry, type EnvInfoOptions, type EnvInfoResult, type EvalOptions, type EvalResult, type EvidenceEntry, type EvidenceMapAction, type EvidenceMapResult, type EvidenceMapState, type EvidenceStatus, type Example, type ExportMap, ExtractionCache, type ExtractionCacheEntry, FLOW_REFERENCE_SECTION_BUDGETS, FileCache, type FileCacheEntry, type FileCacheStats, type FileChange, type FileMetrics, type FileSummaryOptions, type FileSummaryResult, type FileSummaryToolCard, type FileSummaryToolOptions, type FileSummaryToolResult, type FindExamplesOptions, type FindExamplesResult, type FindOptions, type FindResult, type FindResults, type Finding, type FindingSeverity, type FlowBriefingInput, type ForgeClassifyCeremony, type ForgeClassifyOptions, type ForgeClassifyResult, type ForgeGroundOptions, type ForgeGroundResult, type ForgeTier, GIT_REF_SLUG_PATTERN, type GateConfig, type GateDecision, type GateResult, type GitContextOptions, type GitContextResult, type GraphAugmentOptions, type GraphAugmentedResult, type GraphQueryOptions, type GraphQueryResult, type GraphReviewReport, type GraphStats, type GuideRecommendation, type GuideResult, type GuidedTour, type GuidedTourOptions, type HealthCheck, type HealthResult, type HotspotEntry, type HttpMethod, type HttpRequestOptions, type HttpRequestResult, type ImportGraph, type ImportMap, type KnowledgeGraph, LEARNED_SECTION_IDS, LLMEnricher, type LaneDiffEntry, type LaneDiffResult, type LaneMergeResult, type LaneMeta, type LayerDetectionInput, type LayerType, type Lease, type LeaseConflict, type LegacyStashOptions, MAX_SKILL_CHARS, MIN_LEARNED_CONFIDENCE, type ManagedProcess, type MeasureOptions, type MeasureResult, type ModuleInsight, type OnboardMode, type OnboardOptions, type OnboardResult, type OnboardStepResult, type ParsedError, type ParsedGitStatus, type ParsedOutput, type ParsedTestResult, type ParsedTestSummary, type PipelineResult, type PromotedKnowledgeEntry, type PruneOptions, type PruneResult, type QueueItem, type QueueState, RUNTIME_SLUG_RE, type RefTelemetry, type RegexTestOptions, type RegexTestResult, type RenameChange, type RenameOptions, type RenameResult, type RenderedWorkspaceSkillValidation, type ReplayEntry, type ReplayOptions, type Resolution, type ResolutionMethod, type ResolutionOptions, type ResolvedImport, type RestorePoint, type ReverseGraph, type RouteDetectionResult, SECRET_PATTERNS, SECTION_BUDGETS, SECTION_NAMES, STRUCTURAL_SECTION_IDS, type SafetyGate, type SafetyGateResult, type ScanResult, type ScannedFile, type SchemaValidateOptions, type SchemaValidateResult, type ScopeMapEntry, type ScopeMapOptions, type ScopeMapResult, type SearchResponseData, type SearchResponseItem, type SearchSuccessResponseOptions, type SessionDigestOptions, type SessionDigestResult, type SkillInput, type SkillMatch, type SkillMetadata, type SkillSection, type SkillSectionBudget, type SkillTriggerExamples, type SkillTriggerMeta, type StashEntry, type StashStore, type SymbolGraphContext, type SymbolInfo, type SymbolOptions, type TestRunOptions, type TestRunResult, type TimeOptions, type TimeResult, type TimeoutAction, type TourStep, type TraceNode, type TraceOptions, type TraceResult, type TransformOptions, type TransformResult, type TypedUnknownSeed, type UnknownType, type ValidationError, WORKSPACE_SKILL_FILENAME, WORKSPACE_SKILL_SCHEMA_VERSION, type WatchEvent, type WatchHandle, type WatchOptions, type WebFetchMode, type WebFetchOptions, type WebFetchResult, type WebSearchOptions, type WebSearchResult, type WebSearchResultItem, type Workset, type WorksetStore, type WorkspaceSkillQuality, acquireLease, addToWorkset, analyzeDiff, analyzeDomain, analyzeDomains, analyzeFile, audit, autoClaimTestFailures, benchmarkFiles, benchmarkTokenReduction, bookendReorder, bpeSurprise, buildExportMap, buildImportGraph, buildImportMap, buildNodeNameMap, buildReverseGraph, callId, changelog, check, checkEmptyGraph, checkMissingFields, checkSchemaVersion, checkpointDiff, checkpointGC, checkpointHistory, checkpointLatest, checkpointList, checkpointLoad, checkpointSave, classifyDomain, classifyDomains, classifyExitCode, cleanOrphanPartitions, codemod, compact, compressOutput, compressTerminalOutput, computeFlowSourceHash, computeSourceHash, containsRawObservationNoise, containsTruncationComments, cosineSimilarity, createRestorePoint, createSearchErrorResponse, createSearchSuccessResponse, dataTransform, delegate, delegateListModels, deleteWorkset, detectLayer, detectLayers, detectOutputTool, detectRoutes, diffParse, digest, dogfoodLog, edgeId, encode, ensureLegacyStashImported, envInfo, errorResponse, escapeRegExp, estimateGraphTokens, estimateTokens, evaluate, evidenceMap, extractImports, extractRoutesFromFile, fileId, fileSummary, fileSummaryTool, find, findDanglingEdges, findDeadSymbols, findDuplicateIds, findExamples, findOrphanNodes, findSelfLoops, findTour, forgeClassify, forgeGround, formatBytes, formatChangelog, formatDomainReport, formatEmptyResult, formatTour, formatToursIndex, generateFlowBriefing, generateGuidedTours, generateWorkspaceSkill, getRefTelemetry, getRegisteredRules, getReversibleContext, getReversibleContextFresh, getWorkset, gitAvailable, gitCommitToRef, gitContext, gitExec, graphAugmentSearch, graphQuery, groupByDomain, guide, hasReversibleContext, headTailTruncate, health, httpRequest, inferNextjsRoutes, isReversibleContextRef, isSkillStale, laneCreate, laneDiff, laneDiscard, laneList, laneMerge, laneStatus, listActiveLeases, listRestorePoints, listWorksets, markPromoteRun, markPruneRun, matchSkills, measure, measureCorpus, normalizePath, normalizeSkillInput, okResponse, onboard, orderByDependency, paragraphTruncate, parseBiome, parseGitStatus, parseOutput, parseSearchResults, parseSkillMetadata, parseTsc, parseVitest, processList, processLogs, processStart, processStatus, processStop, processStopAll, prune, queueClear, queueCreate, queueDag, queueDelete, queueDone, queueFail, queueGet, queueList, queueNext, queuePush, regexTest, registerRule, registerRules, releaseLease, removeFromWorkset, rename, replayAppend, replayCapture, replayClear, replayList, replayTrim, resetGitCache, resetRefTelemetry, resolveImportPath, resolveNodeName, resolvePath, resolveSkillDir, resolveSymbol, resolveSymbols, resolveWorkspaceDir, restoreFromPoint, reviewGraph, runPipeline, saveWorkset, scanCodebase, schemaValidate, scopeMap, scoreCompliance, scoreLine, scoreLines, segment, sessionDigest, sessionDigestSampling, shannonEntropy, shouldRunStartupPrune, shouldRunWeeklyPromote, slugForRef, stashClear, stashDelete, stashGet, stashList, stashSet, storeReversibleContext, summarizeCheckResult, symbol, symbolId, testRun, timeUtils, trace, transformCommunities, traverseBlastRadius, truncateToTokenBudget, validateRenderedWorkspaceSkill, watchList, watchStart, watchStop, webFetch, webSearch, workspacePath };
|