@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
|
@@ -169,7 +169,8 @@ Use web_fetch/http first. On auth failure, load repo-access; if exhausted, use A
|
|
|
169
169
|
- After read-only/epilogue-only flows: no reindex (0 token cost). remember decisions as normal.
|
|
170
170
|
- If re-onboard/reindex fails: log warning, surface in flow status, do not block.
|
|
171
171
|
- Flow-derived promotion: evidence-backed promotion candidates from final consolidation; confidence alone never promotes.
|
|
172
|
-
- session_digest({ persist: true })
|
|
172
|
+
- session_digest({ persist: true }).
|
|
173
|
+
- **Contribute durable knowledge**: After meaningful work, persist user preferences, repo conventions, architecture invariants, pitfalls, and lessons via \`knowledge({ action: "remember|lesson", ... })\` with appropriate categories and tags. Without curation the workspace skill stays at structural-only — curated facts make it self-improving.`,Planner:`${r()}
|
|
173
174
|
|
|
174
175
|
> **Reminder:** Follow ## MANDATORY FIRST ACTION from your shared base protocol.
|
|
175
176
|
|
|
@@ -1,4 +1,124 @@
|
|
|
1
|
-
var e=[{file:`SKILL.md`,content
|
|
1
|
+
var e=[{file:`SKILL.md`,content:`---
|
|
2
|
+
name: aikit
|
|
3
|
+
description: "Use the @vpxa/aikit AI Kit MCP server for codebase search, context compression, validation, and persistent memory. Load at session start or before using aikit_* tools. This skill teaches tool judgment: minimize raw reads, choose the smallest useful retrieval path, and persist decisions that matter."
|
|
4
|
+
metadata:
|
|
5
|
+
category: cross-cutting
|
|
6
|
+
domain: general
|
|
7
|
+
applicability: always
|
|
8
|
+
inputs: [codebase]
|
|
9
|
+
outputs: [search-results, analysis, knowledge]
|
|
10
|
+
relatedSkills: [session-handoff, present]
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
# @vpxa/aikit - AI Kit
|
|
14
|
+
|
|
15
|
+
Use AI Kit as compression, memory, validation, and coordination layer. Each call should reduce uncertainty or token load.
|
|
16
|
+
|
|
17
|
+
## Communicating With the User
|
|
18
|
+
|
|
19
|
+
**Use \`present({ schemaVersion: 1, title, blocks })\` for ALL non-trivial output.** This is the preferred way to show summaries, results, evidence maps, task plans, reviews, comparisons, dashboards, charts, timelines, and batch results to the user. Plain text is only for 1-2 sentence status updates or simple questions. The \`present\` tool renders rich, structured output that the user can interact with.
|
|
20
|
+
|
|
21
|
+
## Session Loop
|
|
22
|
+
|
|
23
|
+
Start:
|
|
24
|
+
1. status({ includePrelude: true }).
|
|
25
|
+
2. If \`onboarded\` is false or \`prelude.onboardContext\` / \`structuredContent.onboard_context\` is null → run \`onboard({ path, mode: 'generate' })\`, then \`status({ includePrelude: true })\` again.
|
|
26
|
+
3. If \`onboard_context.freshness.status\` is \`stale\` or \`unknown\`, or \`nextAction.kind === "update_onboard"\` → run \`onboard({ path, update: true })\`, then \`status({ includePrelude: true })\` again.
|
|
27
|
+
4. **Workspace context start**: Extract workspace skill + fresh onboard context from status: \`workspace_skill.uri\`, \`prelude.workspaceSkillResource\`, \`onboard_context.freshness\`, \`onboard_context.packageMap\`, \`onboard_context.architecture\`, and \`onboard_context.recommendedReadOrder\`. Read \`aikit://skill/SKILL.md\` when full repo-specific guidance is needed. Use fresh onboard context before broad retrieval. ≤ 2,100 tokens.
|
|
28
|
+
5. search({ query: "SESSION CHECKPOINT", origin: "curated" }).
|
|
29
|
+
6. flow({ action: 'status' }) when active flow may exist — use L1 snapshot before broad retrieval.
|
|
30
|
+
7. scope_map({ task }) only when workspace context + checkpoint do not identify a narrow workset.
|
|
31
|
+
|
|
32
|
+
During:
|
|
33
|
+
- Prefer search/file_summary/digest/symbol/trace/graph over raw reads.
|
|
34
|
+
- Use stash for temporary findings; knowledge for durable decisions.
|
|
35
|
+
- Run blast_radius before shared/public edits.
|
|
36
|
+
- Validate with check + relevant test_run.
|
|
37
|
+
|
|
38
|
+
End:
|
|
39
|
+
- reindex after structural changes.
|
|
40
|
+
- produce_knowledge for durable project updates.
|
|
41
|
+
- session_digest({ persist: true }).
|
|
42
|
+
- knowledge remember session checkpoint with done/decisions/next/blockers.
|
|
43
|
+
|
|
44
|
+
## Retrieval Ladder — Layered (Workspace Context + L1-L3)
|
|
45
|
+
|
|
46
|
+
> This table maps knowledge layers to tool needs. For the canonical quick-reference tool decision table, see \`aiKitToolPreference()\` in protocols.mjs.
|
|
47
|
+
|
|
48
|
+
| Layer | Need | Tool |
|
|
49
|
+
|-------|------|------|
|
|
50
|
+
| **Workspace Context** | Workspace skill + fresh onboard context | \`status({ includePrelude: true })\`; read \`aikit://skill/SKILL.md\` only when full guidance is needed. Run \`onboard({ path, mode: 'generate' })\` if \`onboard_context\` is missing; run \`onboard({ path, update: true })\` if \`onboard_context.freshness.status\` is \`stale\` or \`unknown\`. Consume fresh context before broad scans. |
|
|
51
|
+
| **Workspace Context** | Architecture overview | \`status({ includePrelude: true }).onboard_context.architecture\`, then onboard \`diagram.md\` / \`domains.md\` when deeper detail is needed |
|
|
52
|
+
| **Workspace Context** | Package map / repo shape | \`status({ includePrelude: true }).onboard_context.packageMap\`, then onboard \`structure.md\` / \`dependencies.md\` |
|
|
53
|
+
| **Flow Context** | Flow-specific context | L1 flow snapshot via \`knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>' })\` |
|
|
54
|
+
| **L1** | Active flow state | \`knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>' })\` |
|
|
55
|
+
| **L2** | Prior decisions/conventions | \`search\` / \`knowledge\` |
|
|
56
|
+
| **L2** | File structure | \`file_summary({ files, tier: 'T1' })\` |
|
|
57
|
+
| **L2** | Exact relevant section | \`file_summary({ files, tier: 'T2' })\` |
|
|
58
|
+
| **L2** | Many files | \`digest\` |
|
|
59
|
+
| **L2** | Symbol defs/refs | \`symbol\` |
|
|
60
|
+
| **L2** | Call/data flow | \`trace\` |
|
|
61
|
+
| **L2** | Module/import relationships | \`graph\` |
|
|
62
|
+
| **L2** | Impact | \`blast_radius\` |
|
|
63
|
+
| **L2** | Type/lint/test | \`check\` / \`test_run\` |
|
|
64
|
+
| **L3** | Evidence, provenance, conflict review | \`search\` with \`knowledge({ action: 'lesson' })\` — focused only |
|
|
65
|
+
| **General** | Tool choice unknown | \`list_tools({ intent: "<task>" })\` (use intent param for planner-ranked results) or \`search({ query: "tool to <do X>" })\` |
|
|
66
|
+
|
|
67
|
+
Raw read_file only for exact edit lines after compressed tools identify target.
|
|
68
|
+
|
|
69
|
+
## Context Reuse
|
|
70
|
+
|
|
71
|
+
Before rereading path/topic, search exact path/topic first. If response gives ctxc_..., reuse with file_summary({ ref }) or file_summary({ ref, query }). Use enrich: true on tools that support it after first pass.
|
|
72
|
+
|
|
73
|
+
## Patterns
|
|
74
|
+
|
|
75
|
+
- New area: search -> scope_map -> file_summary -> graph/trace -> stash.
|
|
76
|
+
- Bug: search -> symbol -> trace -> file_summary -> test/check -> remember.
|
|
77
|
+
- Refactor shared code: blast_radius -> checkpoint -> file_summary -> rename/codemod -> check -> test_run.
|
|
78
|
+
- Web/API: web_search/web_fetch/http; browser only when JS/auth interaction needed. Browser snapshots now use ~200-400 tokens, making them practical for quick page state checks.
|
|
79
|
+
|
|
80
|
+
## Memory Discipline
|
|
81
|
+
|
|
82
|
+
Store only high-signal facts:
|
|
83
|
+
- Decisions and rationale.
|
|
84
|
+
- Conventions that constrain future work.
|
|
85
|
+
- Non-obvious root causes and fixes.
|
|
86
|
+
- Checkpoints and blockers.
|
|
87
|
+
|
|
88
|
+
Review decayed/stale entries periodically with knowledge({ action: 'flagged' }). Use lesson actions for reusable engineering lessons; load lesson-learned after implementation/review work.
|
|
89
|
+
|
|
90
|
+
### Contribute Durable Knowledge
|
|
91
|
+
|
|
92
|
+
The workspace skill auto-improves from curated knowledge. After meaningful work, persist durable facts:
|
|
93
|
+
- User preferences or collaboration style → \`knowledge({ action: "remember", category: "context", tags: ["user-preference", "collaboration"] })\`
|
|
94
|
+
- Repo conventions or constraints → \`knowledge({ action: "remember", category: "conventions", tags: ["repo-rule", "constraint"] })\`
|
|
95
|
+
- Architecture invariants → \`knowledge({ action: "remember", category: "context", tags: ["architecture-memory", "invariant"] })\`
|
|
96
|
+
- Recurring pitfalls or prevention rules → \`knowledge({ action: "lesson", subAction: "create", context: "...", insight: "...", evidence: "..." })\` with tag \`pitfall\` or \`prevention\`
|
|
97
|
+
- Tool-use or retrieval patterns → \`knowledge({ action: "remember", category: "patterns", tags: ["tool-use", "retrieval"] })\`
|
|
98
|
+
- Stable engineering lessons → \`knowledge({ action: "lesson", ... })\` with confidence >= 60
|
|
99
|
+
|
|
100
|
+
The skill regenerates when promoted knowledge changes. Without curation, the skill stays at structural-only.
|
|
101
|
+
|
|
102
|
+
## Flow + FORGE
|
|
103
|
+
|
|
104
|
+
Flows guide multi-step work. Read active step before acting. FORGE handles tiering/evidence/gates; load references only when main skill is too thin.
|
|
105
|
+
|
|
106
|
+
### Layered Knowledge Protocol
|
|
107
|
+
- **Workspace Context** → Workspace skill + fresh onboard context: load via \`status({ includePrelude: true })\`. Requires \`onboard()\` first — if \`onboard_context\` is null, run \`onboard\`; if \`onboard_context.freshness.status\` is \`stale\` or \`unknown\`, run \`onboard({ path, update: true })\`. Consume the workspace skill preview/resource pointer and fresh onboard package map/architecture/read-order before \`search\`, \`scope_map\`, \`digest\`, or repeated \`file_summary\`. Use \`file_summary({ tier: 'T1' })\` for structure, or \`file_summary({ tier: 'T2', query })\` for content only after status/onboard context narrows the workset. Token-bounded.
|
|
108
|
+
- **L1** → Flow working context. Withdraw before dispatch; reuse before broad retrieval.
|
|
109
|
+
- **L2** → Canonical curated knowledge. Retrieve on demand; never preload broadly.
|
|
110
|
+
- **L3** → Evidence/auto-knowledge. Inspect only for provenance, conflict, or promotion assessment.
|
|
111
|
+
|
|
112
|
+
Reference docs:
|
|
113
|
+
- references/coordination.md - queue, lanes, stash, checkpoints, signaling.
|
|
114
|
+
- references/forge-protocol.md - tiering, evidence, gates.
|
|
115
|
+
- references/search-patterns.md - search, trace, graph, compression recipes.
|
|
116
|
+
- references/layered-knowledge-protocol.md - workspace context + L1-L3 operating policy and hot path.
|
|
117
|
+
|
|
118
|
+
## Self-Dogfooding
|
|
119
|
+
|
|
120
|
+
When developing AI Kit itself: regenerate scaffold output, run focused checks, rebuild, then reindex so future searches see new shape.
|
|
121
|
+
`},{file:`references/coordination.md`,content:`# Coordination
|
|
2
122
|
|
|
3
123
|
Use coordination tools when work is parallel, long-running, or easy to repeat incorrectly.
|
|
4
124
|
|
|
@@ -77,4 +77,15 @@ Every subagent dispatch MUST include:
|
|
|
77
77
|
|
|
78
78
|
STOP → ASSESS (\`git diff --stat\` + \`check({})\`) → CONTAIN (1-3 files: fix, widespread: stash) → RECOVER (stash first) → DOCUMENT (remember what went wrong).
|
|
79
79
|
|
|
80
|
-
Max 2 retries per task. Same failure twice → stop loop, change plan
|
|
80
|
+
Max 2 retries per task. Same failure twice → stop loop, change plan.
|
|
81
|
+
|
|
82
|
+
## Contribute Durable Knowledge
|
|
83
|
+
|
|
84
|
+
After meaningful work, persist facts that make the workspace skill self-improving:
|
|
85
|
+
- **User preferences** → \`knowledge({ action: "remember", category: "context", tags: ["user-preference"] })\`
|
|
86
|
+
- **Repo conventions** → \`knowledge({ action: "remember", category: "conventions", tags: ["repo-rule"] })\`
|
|
87
|
+
- **Architecture invariants** → \`knowledge({ action: "remember", category: "context", tags: ["architecture-memory"] })\`
|
|
88
|
+
- **Pitfalls/prevention** → \`knowledge({ action: "lesson", ..., tags: ["pitfall"] })\`
|
|
89
|
+
- **Tool-use/retrieval patterns** → \`knowledge({ action: "remember", category: "patterns", tags: ["tool-use"] })\`
|
|
90
|
+
|
|
91
|
+
The workspace skill regenerates from curated knowledge. Without deliberate curation, the skill stays at structural-only (package name + build commands). The promotion engine observes tool use and can auto-promote conventions, but manual curation produces the highest-quality skill sections.`}];export{e as default};
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{t as e}from"./bin.js";import{createRequire as t}from"node:module";import{fileURLToPath as n}from"node:url";import{INSTALL_ARGS as r,cleanupOldVersions as i,createLogger as a,getGlobalDataDir as o,isUserInstalled as s,listWorkspaces as c,safeCwd as l,serializeError as u}from"../../core/dist/index.js";import{existsSync as d,mkdirSync as f,readFileSync as p,renameSync as m,rmSync as h,statSync as ee,unlinkSync as te,writeFileSync as ne}from"node:fs";import{dirname as g,join as _,resolve as v}from"node:path";import{readFile as re,writeFile as ie}from"node:fs/promises";import{homedir as y}from"node:os";import{execFile as ae,execSync as b,spawn as oe}from"node:child_process";var x=Object.defineProperty,S=(e,t)=>{let n={};for(var r in e)x(n,r,{get:e[r],enumerable:!0});return t||x(n,Symbol.toStringTag,{value:`Module`}),n};const se={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},ce={working:1,episodic:2,semantic:4,procedural:12};function le(e,t=se){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 ue(e,t,n){e.memoryMetaUpdateTier(t,n)}const C={confirmIncrement:10,contradictDecrement:20,weeklyDecay:2,implicitUseIncrement:3,staleThreshold:30,staleDays:21,decayFloor:10,autoArchiveDays:30,archiveThreshold:20},de=`lesson:auto-archive`;function w(e){return{confirmIncrement:Math.max(0,Math.trunc(e?.confirmIncrement??C.confirmIncrement)),contradictDecrement:Math.max(0,Math.trunc(e?.contradictDecrement??C.contradictDecrement)),weeklyDecay:Math.max(0,Math.trunc(e?.weeklyDecay??C.weeklyDecay)),implicitUseIncrement:Math.max(0,Math.trunc(e?.implicitUseIncrement??C.implicitUseIncrement)),staleThreshold:Math.min(100,Math.max(0,Math.trunc(e?.staleThreshold??C.staleThreshold))),staleDays:Math.max(1,Math.trunc(e?.staleDays??C.staleDays)),decayFloor:Math.min(100,Math.max(0,Math.trunc(e?.decayFloor??C.decayFloor))),autoArchiveDays:Math.max(1,Math.trunc(e?.autoArchiveDays??C.autoArchiveDays)),archiveThreshold:Math.min(100,Math.max(0,Math.trunc(e?.archiveThreshold??C.archiveThreshold)))}}function fe(e){return[`## Lesson: ${e.title}`,``,`**Confidence:** ${e.confidence}/100`,``,`### Context`,e.context,``,`### Insight`,e.insight,``,`### Evidence`,e.evidence].join(`
|
|
3
|
-
`)}function T(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 pe(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 me(e,t,n=C){let r=w(n);return t===`confirm`?Math.min(100,e+r.confirmIncrement):Math.max(0,e-r.contradictDecrement)}function E(e,t,n,r=C,i=Date.now()){let a=w(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 he(e,t=C,n=Date.now()){let r=w(t);if(E(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 ge(e,t=C,n=Date.now()){let r=w(t);if(E(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 D={stabilityHours:168,accessMultiplier:1.5,flagThreshold:.1,maxStabilityHours:8760};function _e(e){return{...D,...e}}function ve(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function ye(e){return e&&e in ce?e:`working`}function be(e,t,n,r=D,i){let a=typeof r==`string`?ye(r):`working`,o=_e(typeof r==`string`?i:r),s=ve(e,ve(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*ce[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function xe(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=be(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function Se(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=be(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function Ce(e,t){let n=_e(t);return e.memoryMetaList().map(t=>xe(e,t.entryId,n)??t).filter(e=>e.retentionScore<n.flagThreshold).sort((e,t)=>e.retentionScore-t.retentionScore)}const O={threshold:.7,maxCompare:50,autoThreshold:.95};function we(e){let t=Math.min(1,Math.max(0,e?.threshold??O.threshold)),n=Math.min(1,Math.max(t,e?.autoThreshold??O.autoThreshold));return{threshold:t,maxCompare:Math.max(1,Math.trunc(e?.maxCompare??O.maxCompare)),autoThreshold:n}}function k(e){let t=e.toLowerCase().match(/[a-z0-9]{2,}/g)??[];return new Set(t)}function A(e,t){let n=k(e),r=k(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 Te(e,t,n=O){let r=we(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 Ee(e,t,n){e.memoryMetaCreate(t),e.memoryMetaSetSuperseded(t,n)}const De=t(import.meta.url),Oe=import.meta.dirname??g(n(import.meta.url)),j=new Map;function M(e){let t=j.get(e);if(t!==void 0)return t;let n=_(Oe,`..`,`..`,e);if(d(_(n,`package.json`)))return j.set(e,n),n;try{let t=g(De.resolve(`@aikit/${e}/package.json`));return j.set(e,t),t}catch{}let r=Oe;for(let t=0;t<6;t++){let t=_(r,`packages`,e);if(d(_(t,`package.json`)))return j.set(e,t),t;let n=g(r);if(n===r)break;r=n}return j.set(e,null),null}function ke(e,t=`dist`){let n=M(e);if(!n)return null;let r=_(n,t);return d(r)?r:null}function Ae(e,t){let n=M(e);if(!n)return null;for(let e of t){let t=_(n,e);if(d(t))return t}return null}var je=S({DEFAULT_GROUP_CONFIG:()=>P,DEFAULT_PRUNE_CONFIG:()=>N,groupLessons:()=>Ge,pruneLessons:()=>We});const N={maxConfidence:15,minIdleDays:30,safetyDays:7,maxPrune:20,dryRun:!0},P={similarityThreshold:.7,minGroupSize:2,maxGroups:10,dryRun:!0},Me=new Set([`the`,`a`,`to`,`for`,`in`,`of`,`and`,`is`,`use`]);function Ne(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 Pe(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 Fe(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}function Ie(e,t){let n=Math.max(Fe(e),Fe(t));return n===0?1/0:Math.max(0,Date.now()-n)/864e5}function Le(e){return e.toLowerCase().match(/[a-z0-9]{2,}/g)??[]}function Re(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,60)}function ze(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(`
|
|
4
|
-
`)}\n\n${t}\n`}function Be(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 Ve(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 He(e){let t=new Map,n=new Map,r=0;for(let i of e)for(let e of Le(i))Me.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?Re(i[0]):Re(e.flatMap(e=>Le(e)).find(e=>!Me.has(e))??`lesson-group`)}async function Ue(e,t,n){let r=_(e.curatedDir,t),i=await re(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 ie(r,ze({...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 We(e,t,n,r){let i=Ne(n),a=w(r??C),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=Ie(n.lastAccessedAt,n.createdAt??e.created);if(r<i.safetyDays)return null;let o=E(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 Ge(e,t,n){let r=Pe(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=Ve(Be(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:He(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 Ue(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 Ke=S({DEFAULT_PROMOTE_CONFIG:()=>F,adjudicateCandidate:()=>L,checkPromotionGates:()=>rt,collectWorkspaceLessons:()=>lt,demoteLesson:()=>ft,getGlobalCuratedDir:()=>ct,promoteLessons:()=>dt,scanForDuplicates:()=>ut,scorePromotionCandidate:()=>it});const F={minWorkspaces:2,minAvgConfidence:80,similarityThreshold:.7,dryRun:!0};function qe(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 Je(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 Ye(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 Xe(t){return new e(t,null,null)}function Ze(e){return(e??``).replace(/\s+/g,` `).trim()}function Qe(e){let t=Ze(e);return t.length<=80?t:`${t.slice(0,77).replace(/\s+\S*$/,``)}...`}function $e(e){return fe({title:Qe(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(`
|
|
5
|
-
`),confidence:e.avgConfidence,tags:[`lesson`,`promoted`,`global`]})}function I(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function et(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 tt(e){switch(e){case`high`:return 10;case`medium`:return 6;case`low`:return 2}}function nt(e){let t=e.length/4;return t<=10?10:t<=25?8:t<=50?6:t<=100?4:t<=200?2:1}function rt(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 it(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?et(new Date(t.observedAt)):5,o=tt(t?.actionability??`medium`),s=nt(e.insight);return{signals:{recurrence:n,impact:r,sourceDiversity:i,freshness:a,actionability:o,tokenCost:s},totalScore:n+r+i+a+o+s}}function L(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=T(r.content),a=Ze(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=_(o(),`global-knowledge`,`.ai`,`curated`);return d(e)||f(e,{recursive:!0}),e}async function lt(e){let t=new Map;if(!s())return t;for(let e of c()){let n=_(e.workspacePath,`.ai`,`curated`);if(!d(n))continue;let r=await at(Xe(n),e.partition);r.length>0&&t.set(e.partition,r)}return t}function ut(e,t=F,n){let r=qe(t),i=[...e.values()].flat();if(i.length===0)return[];let a=Ye(Je(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=rt(c,e),r=it(c,e),i=L(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=qe(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(Qe(n.insight),$e(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=S({createSamplingClient:()=>_t});const mt=a(`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(`
|
|
6
|
-
`);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 R(e){return e.split(/\r?\n/u).map(e=>e.replace(/[ \t]+$/u,``)).join(`
|
|
7
|
-
`).replace(/\n{3,}/gu,`
|
|
8
|
-
|
|
9
|
-
`).trim()}function wt(e,t){if(e.length<=t)return e;let n=e.split(`
|
|
10
|
-
`),r=[],i=0;for(let e of n){let n=r.length===0?e.length:e.length+1;if(i+n>t)break;r.push(e),i+=n}return r.length>0?r.join(`
|
|
11
|
-
`):e.slice(0,t).trimEnd()}function z(e,t,n){return wt(e,Math.max(1,Math.floor(n*t)))}function B(e,t){if(e.length<50)return e;let n=R(t);return!n||n.length<e.length*.2?e:n}function Tt(e,t,n){let r=new Set;for(let n=0;n<Math.min(t,e.length);n+=1)r.add(n);return e.forEach((e,t)=>{n(e,t)&&r.add(t)}),e.filter((e,t)=>r.has(t)).join(`
|
|
12
|
-
`)}function Et(e,t){e.includes(t)||e.push(t)}function Dt(e){return B(e,z(Tt(e.split(/\r?\n/u),3,e=>vt.test(e)||e.startsWith(`- `)),.6,e.length))}function Ot(e){let t=e.split(/\r?\n/u),n=[];return t.forEach((e,t)=>{if(t<5||St.test(e)||Ct.test(e)||/^Content:/i.test(e)){if(/^Content:/i.test(e)){Et(n,`Content: ${e.replace(/^Content:\s*/i,``).trim().slice(0,200)}`);return}Et(n,e)}}),B(e,n.join(`
|
|
13
|
-
`))}function kt(e){let t=e.split(/\r?\n/u),n=new Set;for(let e=0;e<t.length&&t[e].trim()!==``;e+=1)n.add(e);return t.forEach((e,t)=>{(e.startsWith(`- `)||e.startsWith(`* `)||yt.test(e))&&n.add(t)}),B(e,z(t.filter((e,t)=>n.has(t)).join(`
|
|
14
|
-
`),.7,e.length))}function At(e){let t=e.split(/\r?\n/u),n=new Set,r=!1;for(let e=0;e<Math.min(2,t.length);e+=1)n.add(e);return t.forEach((e,t)=>{if(e.startsWith("```")){n.add(t),r=!r;return}(r||e.startsWith(`##`)||e.startsWith(`- `)||e.startsWith(`* `))&&n.add(t)}),B(e,z(t.filter((e,t)=>n.has(t)).join(`
|
|
15
|
-
`),.65,e.length))}function jt(e){return B(e,z(e.split(/\r?\n/u).filter(e=>e.startsWith(`#`)||e.startsWith(`- `)||/\d/.test(e)||/\d+%/.test(e)||bt.test(e)).join(`
|
|
16
|
-
`),.6,e.length))}function Mt(e){return B(e,z(e.split(/\r?\n/u).filter(e=>e.startsWith(`- `)||e.startsWith(`* `)||xt.test(e)).join(`
|
|
17
|
-
`),.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(`
|
|
18
|
-
`).trim();return a.length<=t?R(a):wt(R(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=S({autoUpgradeScaffold:()=>rn,checkForUpdates:()=>Yt,cleanupOldVersions:()=>K,getCurrentVersion:()=>W,getUpgradeState:()=>tn});const Rt=`@vpxa/aikit`,zt=`https://registry.npmjs.org/${Rt}/latest`,V=a(`server`);function Bt(){let e=g(n(import.meta.url));return[v(e,`..`,`..`,`..`,`bin`,`aikit.mjs`),v(e,`..`,`bin`,`aikit.mjs`),...process.argv[1]?[v(g(process.argv[1]),`aikit.mjs`)]:[]].find(e=>d(e))??null}const Vt=_(y(),`.aikit`),H=_(Vt,`current-version.json`),U=_(Vt,`versions`),Ht=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/;function Ut(e){if(!Ht.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}function W(){let e=v(g(n(import.meta.url)),`..`,`..`,`..`,`package.json`);try{return JSON.parse(p(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(!d(e))return;for(let t=1;t<=2;t++)try{h(e,{recursive:!0,force:!0});return}catch(n){if(!(n.code===`EPERM`||n.code===`EBUSY`||/EPERM|permission denied/i.test(String(n)))){V.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{m(e,t),V.debug(`Renamed locked directory to ${t} — deferred cleanup`);try{h(t,{recursive:!0,force:!0})}catch{}}catch(t){V.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=_(U,`${t}-staging`),i=_(U,t);try{Kt(n),f(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=_(n,`package`);b(`npm ${r.join(` `)}`,{cwd:t,encoding:`utf-8`,stdio:`pipe`,timeout:12e4,windowsHide:!0});let a=_(t,`packages`,`server`,`dist`,`bin.js`);if(!d(a))throw Error(`Server entry not found at ${a}`);if(!d(_(t,`node_modules`)))throw Error(`node_modules not found — npm install may have failed`);d(i)&&h(i,{recursive:!0,force:!0}),m(t,i);let o=`${H}.tmp`;ne(o,JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)),m(o,H),K(e)}finally{Kt(n)}}function G(e){V.debug(`Updated to v${e}. Restarting server...`),setTimeout(()=>{process.exit(0)},300).unref()}function K(e){i(U,e??W())}async function Jt(){try{let e=p(H,`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(d(_(U,`v${r}`))){let e=`${H}.tmp`;ne(e,JSON.stringify({version:r,installedAt:new Date().toISOString()},null,2)),m(e,H),V.debug(`Re-activated existing version v${r} — no download needed`),G(r);return}V.debug(`New version available: ${r}. Installing...`),await qt(r),G(r)}catch(e){V.error(`Background update check failed: ${e instanceof Error?e.message:String(e)}`)}}let q=null;function Yt(){return q||(q=Xt().finally(()=>{q=null}),q)}async function Xt(){if(d(H)){await Jt();return}let e=W();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){V.debug(`Newer version available — installing`,{currentVersion:e,latestVersion:n});try{await qt(n),G(n)}catch(e){V.warn(`Auto-install failed`,{error:e instanceof Error?e.message:String(e),latestVersion:n})}}}catch{}}function Zt(){try{let e=v(y(),`.copilot`,`.aikit-scaffold.json`);return d(e)?JSON.parse(p(e,`utf-8`)).version??null:null}catch{return null}}function Qt(){try{let e=l();if(!e)return null;let t=v(e,`.github`,`.aikit-scaffold.json`);return d(t)?JSON.parse(p(t,`utf-8`)).version??null:null}catch{return null}}let J=`idle`,Y=null,$t=null,en=!1;function tn(){return{state:J,error:Y}}function nn(){J=`idle`,Y=null}function rn(){try{let e=W();if(Yt(),!en){en=!0;try{let e=Bt();e&&oe(process.execPath,[e,`migrate-launcher`],{cwd:y(),stdio:`ignore`,timeout:15e3,windowsHide:!0}).unref()}catch{}try{let e=v(y(),`.claude`,`mcp.json`);d(e)&&JSON.parse(p(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),J!==`idle`))return;J=`pending`,Y=null,V.debug(`Scaffold version mismatch — auto-upgrading`,{serverVersion:e,userScaffoldVersion:t,workspaceScaffoldVersion:n});let r=Bt();if(!r){J=`failed`,Y=`aikit CLI binary not found`,V.warn(`Cannot auto-upgrade: aikit CLI binary not found`);return}let i=y();ae(process.execPath,[r,`upgrade`],{cwd:i,timeout:3e4,windowsHide:!0},(t,n,a)=>{t?(J=`failed`,Y=t.message,V.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})):(J=`success`,Y=null,V.debug(`Auto-upgrade completed to version ${e}`))}).unref()}catch(e){J=`failed`,Y=e instanceof Error?e.message:String(e),V.warn(`Auto-upgrade check failed`,{error:Y})}}var an=S({buildOnboardContext:()=>gn,buildPreludeInjection:()=>yn,generatePrelude:()=>vn});function on(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 sn=2400,cn=new Set([`synthesis-guide.md`,`structure.md`,`dependencies.md`,`diagram.md`,`domains.md`,`entry-points.md`,`code-map.md`]),ln=[{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 un(e){return e.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``).trimStart()}function dn(e,t){return e.length<=t?e:`${e.slice(0,t).trimEnd()}\n...`}function Z(e,t=12e3){try{return d(e)?p(e,`utf-8`).slice(0,t):null}catch{return null}}function fn(e){let t=Z(v(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 pn(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 mn(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 hn(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 gn(e,t={}){if(!e||!d(e))return null;let n=ln.flatMap(t=>{let n=v(e,t.file);return d(n)?[{id:t.id,title:t.title,path:n,sizeBytes:ee(n).size,useFor:t.useFor,priority:t.priority}]:[]}),r=v(e,`synthesis-guide.md`),i=v(e,`diagram.md`),a=fn(e),o=a.generatedAt,s=[...cn].filter(t=>!d(v(e,t))),c=pn({generatedAt:o,lastIndexedAt:t.lastIndexedAt??null,manifest:a,missingResources:s}),l=Z(r),u=hn(Z(i)),f=u.slice(0,40),p=u.length>f.length;return{dir:v(e),generatedAt:o,fresh:c.status===`fresh`,freshness:c,projectProfile:mn(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:f,totalPackages:u.length,truncated:p},architecture:{sourcePath:d(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:f,totalContainers:u.length,truncated:p}}}function _n(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(!e)continue;let t=v(e,`SKILL.md`);if(d(t))try{let e=p(t,`utf-8`),n=un(e)||e,r=dn(n,sn);return{preview:r,resource:{uri:`aikit://skill/SKILL.md`,path:t,sizeBytes:ee(t).size,previewChars:r.length,truncated:n.length>sn}}}catch{}}return null}async function vn(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:on(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})=>on(e.contentPreview,200))[0]??null,f=_n(r);return{lessons:l,conventions:u,checkpoint:d,workspaceSkill:f?.preview??null,workspaceSkillResource:f?.resource??null,onboardContext:i??null}}catch{return null}}function yn(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(`
|
|
19
|
-
`)[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(`
|
|
20
|
-
`);if(a.length>t)for(;i.length>3&&a.length>t;)i.splice(1,1)[0]?.startsWith(`•`)&&r--;return{lines:i,totalChars:i.join(`
|
|
21
|
-
`).length,autoInjectCount:r}}const $=a(`server`);function bn(e,t){return t?{version:e,...u(t)}:{version:e}}function xn(t,n,r){t.then(async()=>{try{let{markPromoteRun:t,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(()=>je),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(()=>Ke),c=s.curated,l=new e(i(),c.store,c.embedder),u=await r(),d={...n,dryRun:!1},f=await a(o(u,d),l,d);t(),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)`,bn(r,e))}}).catch(e=>$.warn(`Startup maintenance failed`,u(e)))}export{Ee as A,fe as B,We as C,O as D,M as E,Se as F,ge as G,T as H,C as I,ue as J,se as K,de as L,D as M,Ce as N,Te as O,xe as P,me as R,Ge as S,Ae as T,w as U,he as V,pe as W,ft as _,an as a,ut as b,W as c,Nt as d,Ft as f,lt as g,F as h,vn as i,we as j,A as k,tn as l,pt as m,bn as n,rn as o,_t as p,le as q,gn as r,K as s,xn as t,Lt as u,ct as v,ke as w,je as x,dt as y,E as z};
|