@vpxa/aikit 0.1.381 → 0.1.382

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/package.json +1 -1
  2. package/packages/claude-desktop/dist/manifest.json +1 -1
  3. package/packages/cli/dist/index.js +3 -3
  4. package/packages/cli/dist/{init-Be3nyugf.js → init-DMj2ctyd.js} +1 -1
  5. package/packages/cli/dist/{templates-CK9mSHyJ.js → templates-DLra78_O.js} +10 -10
  6. package/packages/server/dist/bin.js +1 -1
  7. package/packages/server/dist/{config-CTYSUkDf.js → config-CQKoGfwD.js} +1 -1
  8. package/packages/server/dist/{config-Bz8Uyzuq.js → config-DX1KYSbN.js} +1 -1
  9. package/packages/server/dist/{dashboard-static-BbHMHkQ3.js → dashboard-static-C6RP0VA7.js} +1 -1
  10. package/packages/server/dist/{dashboard-static-gAOiHHqI.js → dashboard-static-DdsIJd-u.js} +1 -1
  11. package/packages/server/dist/index.js +1 -1
  12. package/packages/server/dist/{register-tools-fdniAqWz.js → register-tools-C49Lkpvq.js} +121 -121
  13. package/packages/server/dist/{register-tools-0E-d3SIk.js → register-tools-i_1kjBhi.js} +135 -135
  14. package/packages/server/dist/{server-C4qsakCZ.js → server-CTUxU4KX.js} +6 -6
  15. package/packages/server/dist/{server-DHdcyAmX.js → server-Dm2u4PSm.js} +6 -6
  16. package/packages/server/dist/{server-http-DlTdz6ch.js → server-http-D8Wemu8Y.js} +1 -1
  17. package/packages/server/dist/{server-http-CC39yGVF.js → server-http-DcgFpWra.js} +1 -1
  18. package/packages/server/dist/{server-stdio-Colzu8Wb.js → server-stdio-Bpoo8KOT.js} +1 -1
  19. package/packages/server/dist/{server-stdio-CTbBp6wO.js → server-stdio-CskpvBew.js} +1 -1
  20. package/packages/server/dist/{settings-static-DV2hXZgq.js → settings-static-C0oT3Ctk.js} +1 -1
  21. package/packages/server/dist/{settings-static-PjpMR9Q7.js → settings-static-DVMG47Oh.js} +1 -1
  22. package/packages/server/dist/startup-maintenance-cbRSFMY5.js +21 -0
  23. package/packages/server/dist/startup-maintenance-kHH8tjds.js +20 -0
  24. package/packages/tools/dist/index.js +1 -1
  25. package/scaffold/dist/definitions/bodies.mjs +21 -16
  26. package/scaffold/dist/definitions/flows.mjs +5 -5
  27. package/scaffold/dist/definitions/protocols.mjs +11 -11
  28. package/scaffold/dist/definitions/skills/aikit.mjs +2 -158
  29. package/scaffold/dist/definitions/skills/c4-architecture.mjs +5 -5
  30. package/scaffold/dist/definitions/skills/docs.mjs +12 -10
  31. package/scaffold/dist/definitions/skills/multi-agents-development.mjs +4 -4
  32. package/scaffold/dist/definitions/skills/orchestrator.mjs +8 -3
  33. package/packages/server/dist/startup-maintenance-BnTozHs1.js +0 -21
  34. package/packages/server/dist/startup-maintenance-CxAICs-n.js +0 -20
@@ -1,111 +1,4 @@
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 prelude.workspaceCore is null → run \`onboard({ path, mode: 'generate' })\`, then \`status({ includePrelude: true })\` again.
26
- 3. **L0 session start**: Run \`status({ includePrelude: true })\` for compact workspace-core summary. Extract workspace shape, package map, tool surfaces, key entry points, constraints, and known pitfalls before broad retrieval. If L0 answers enough, skip \`scope_map\`/wide \`search\`. If a flow is active, workflow card loaded via flow context. ≤ 2,100 tokens.
27
- 4. search({ query: "SESSION CHECKPOINT", origin: "curated" }).
28
- 5. flow({ action: 'status' }) when active flow may exist — use L1 snapshot before broad retrieval.
29
- 6. scope_map({ task }) only when L0 + checkpoint do not identify a narrow workset.
30
-
31
- During:
32
- - Prefer search/file_summary/digest/symbol/trace/graph over raw reads.
33
- - Use stash for temporary findings; knowledge for durable decisions.
34
- - Run blast_radius before shared/public edits.
35
- - Validate with check + relevant test_run.
36
-
37
- End:
38
- - reindex after structural changes.
39
- - produce_knowledge for durable project updates.
40
- - session_digest({ persist: true }).
41
- - knowledge remember session checkpoint with done/decisions/next/blockers.
42
-
43
- ## Retrieval Ladder — Layered (L0-L3)
44
-
45
- > This table maps knowledge layers to tool needs. For the canonical quick-reference tool decision table, see \`aiKitToolPreference()\` in protocols.mjs.
46
-
47
- | Layer | Need | Tool |
48
- |-------|------|------|
49
- | **L0** | Session briefing (after onboard) | \`status({ includePrelude: true })\` (compact summary). Run \`onboard\` first if card missing. Consume before broad scans. |
50
- | **L0** | Architecture overview | \`architecture\` briefing card |
51
- | **L0** | Known issues | \`known-issues\` briefing card |
52
- | **L0** | Flow-specific context | \`workflow:<flow>\` briefing card |
53
- | **L1** | Active flow state | \`knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>' })\` |
54
- | **L2** | Prior decisions/conventions | \`search\` / \`knowledge\` |
55
- | **L2** | File structure | \`file_summary({ files, tier: 'T1' })\` |
56
- | **L2** | Exact relevant section | \`file_summary({ files, tier: 'T2' })\` |
57
- | **L2** | Many files | \`digest\` |
58
- | **L2** | Symbol defs/refs | \`symbol\` |
59
- | **L2** | Call/data flow | \`trace\` |
60
- | **L2** | Module/import relationships | \`graph\` |
61
- | **L2** | Impact | \`blast_radius\` |
62
- | **L2** | Type/lint/test | \`check\` / \`test_run\` |
63
- | **L3** | Evidence, provenance, conflict review | \`search\` with \`knowledge({ action: 'lesson' })\` — focused only |
64
- | **General** | Tool choice unknown | \`list_tools({ intent: "<task>" })\` (use intent param for planner-ranked results) or \`search({ query: "tool to <do X>" })\` |
65
-
66
- Raw read_file only for exact edit lines after compressed tools identify target.
67
-
68
- ## Context Reuse
69
-
70
- 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.
71
-
72
- ## Patterns
73
-
74
- - New area: search -> scope_map -> file_summary -> graph/trace -> stash.
75
- - Bug: search -> symbol -> trace -> file_summary -> test/check -> remember.
76
- - Refactor shared code: blast_radius -> checkpoint -> file_summary -> rename/codemod -> check -> test_run.
77
- - 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.
78
-
79
- ## Memory Discipline
80
-
81
- Store only high-signal facts:
82
- - Decisions and rationale.
83
- - Conventions that constrain future work.
84
- - Non-obvious root causes and fixes.
85
- - Checkpoints and blockers.
86
-
87
- Review decayed/stale entries periodically with knowledge({ action: 'flagged' }). Use lesson actions for reusable engineering lessons; load lesson-learned after implementation/review work.
88
-
89
- ## Flow + FORGE
90
-
91
- Flows guide multi-step work. Read active step before acting. FORGE handles tiering/evidence/gates; load references only when main skill is too thin.
92
-
93
- ### Layered Knowledge Protocol
94
- - **L0** → Generated briefing cards: load \`workspace-core\` at session start via \`status({ includePrelude: true })\` (compact summary). Requires \`onboard()\` first — if card null, run \`onboard\` before session start. Consume L0 as the default workspace map before \`search\`, \`scope_map\`, \`digest\`, or repeated \`file_summary\`; add \`workflow:<flow>\` if flow active, or one task card if no flow. Use \`file_summary({ tier: 'T1' })\` for structure, or \`file_summary({ tier: 'T2', query })\` for content only after L0 narrows the workset. Token-bounded.
95
- - **L1** → Flow working context. Withdraw before dispatch; reuse before broad retrieval.
96
- - **L2** → Canonical curated knowledge. Retrieve on demand; never preload broadly.
97
- - **L3** → Evidence/auto-knowledge. Inspect only for provenance, conflict, or promotion assessment.
98
-
99
- Reference docs:
100
- - references/coordination.md - queue, lanes, stash, checkpoints, signaling.
101
- - references/forge-protocol.md - tiering, evidence, gates.
102
- - references/search-patterns.md - search, trace, graph, compression recipes.
103
- - references/layered-knowledge-protocol.md - L0-L3 operating policy and hot path.
104
-
105
- ## Self-Dogfooding
106
-
107
- When developing AI Kit itself: regenerate scaffold output, run focused checks, rebuild, then reindex so future searches see new shape.
108
- `},{file:`references/coordination.md`,content:`# Coordination
1
+ var e=[{file:`SKILL.md`,content:"---\nname: aikit\ndescription: \"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.\"\nmetadata:\n category: cross-cutting\n domain: general\n applicability: always\n inputs: [codebase]\n outputs: [search-results, analysis, knowledge]\n relatedSkills: [session-handoff, present]\n---\n\n# @vpxa/aikit - AI Kit\n\nUse AI Kit as compression, memory, validation, and coordination layer. Each call should reduce uncertainty or token load.\n\n## Communicating With the User\n\n**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.\n\n## Session Loop\n\nStart:\n1. status({ includePrelude: true }).\n2. If `onboarded` is false or `prelude.onboardContext` / `structuredContent.onboard_context` is null → run `onboard({ path, mode: 'generate' })`, then `status({ includePrelude: true })` again.\n3. If `onboard_context.freshness.status` is `stale` or `unknown`, or `nextAction.kind === \"update_onboard\"` → run `onboard({ path, update: true })`, then `status({ includePrelude: true })` again.\n4. **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.\n5. search({ query: \"SESSION CHECKPOINT\", origin: \"curated\" }).\n6. flow({ action: 'status' }) when active flow may exist — use L1 snapshot before broad retrieval.\n7. scope_map({ task }) only when workspace context + checkpoint do not identify a narrow workset.\n\nDuring:\n- Prefer search/file_summary/digest/symbol/trace/graph over raw reads.\n- Use stash for temporary findings; knowledge for durable decisions.\n- Run blast_radius before shared/public edits.\n- Validate with check + relevant test_run.\n\nEnd:\n- reindex after structural changes.\n- produce_knowledge for durable project updates.\n- session_digest({ persist: true }).\n- knowledge remember session checkpoint with done/decisions/next/blockers.\n\n## Retrieval Ladder — Layered (Workspace Context + L1-L3)\n\n> This table maps knowledge layers to tool needs. For the canonical quick-reference tool decision table, see `aiKitToolPreference()` in protocols.mjs.\n\n| Layer | Need | Tool |\n|-------|------|------|\n| **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. |\n| **Workspace Context** | Architecture overview | `status({ includePrelude: true }).onboard_context.architecture`, then onboard `diagram.md` / `domains.md` when deeper detail is needed |\n| **Workspace Context** | Package map / repo shape | `status({ includePrelude: true }).onboard_context.packageMap`, then onboard `structure.md` / `dependencies.md` |\n| **Flow Context** | Flow-specific context | L1 flow snapshot via `knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>' })` |\n| **L1** | Active flow state | `knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>' })` |\n| **L2** | Prior decisions/conventions | `search` / `knowledge` |\n| **L2** | File structure | `file_summary({ files, tier: 'T1' })` |\n| **L2** | Exact relevant section | `file_summary({ files, tier: 'T2' })` |\n| **L2** | Many files | `digest` |\n| **L2** | Symbol defs/refs | `symbol` |\n| **L2** | Call/data flow | `trace` |\n| **L2** | Module/import relationships | `graph` |\n| **L2** | Impact | `blast_radius` |\n| **L2** | Type/lint/test | `check` / `test_run` |\n| **L3** | Evidence, provenance, conflict review | `search` with `knowledge({ action: 'lesson' })` — focused only |\n| **General** | Tool choice unknown | `list_tools({ intent: \"<task>\" })` (use intent param for planner-ranked results) or `search({ query: \"tool to <do X>\" })` |\n\nRaw read_file only for exact edit lines after compressed tools identify target.\n\n## Context Reuse\n\nBefore 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.\n\n## Patterns\n\n- New area: search -> scope_map -> file_summary -> graph/trace -> stash.\n- Bug: search -> symbol -> trace -> file_summary -> test/check -> remember.\n- Refactor shared code: blast_radius -> checkpoint -> file_summary -> rename/codemod -> check -> test_run.\n- 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.\n\n## Memory Discipline\n\nStore only high-signal facts:\n- Decisions and rationale.\n- Conventions that constrain future work.\n- Non-obvious root causes and fixes.\n- Checkpoints and blockers.\n\nReview decayed/stale entries periodically with knowledge({ action: 'flagged' }). Use lesson actions for reusable engineering lessons; load lesson-learned after implementation/review work.\n\n## Flow + FORGE\n\nFlows guide multi-step work. Read active step before acting. FORGE handles tiering/evidence/gates; load references only when main skill is too thin.\n\n### Layered Knowledge Protocol\n- **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.\n- **L1** → Flow working context. Withdraw before dispatch; reuse before broad retrieval.\n- **L2** → Canonical curated knowledge. Retrieve on demand; never preload broadly.\n- **L3** → Evidence/auto-knowledge. Inspect only for provenance, conflict, or promotion assessment.\n\nReference docs:\n- references/coordination.md - queue, lanes, stash, checkpoints, signaling.\n- references/forge-protocol.md - tiering, evidence, gates.\n- references/search-patterns.md - search, trace, graph, compression recipes.\n- references/layered-knowledge-protocol.md - workspace context + L1-L3 operating policy and hot path.\n\n## Self-Dogfooding\n\nWhen developing AI Kit itself: regenerate scaffold output, run focused checks, rebuild, then reindex so future searches see new shape.\n"},{file:`references/coordination.md`,content:`# Coordination
109
2
 
110
3
  Use coordination tools when work is parallel, long-running, or easy to repeat incorrectly.
111
4
 
@@ -200,53 +93,4 @@ file_summary (T1=structure, T2=content) or digest (multi-file synthesis). Read_f
200
93
  ## Rule of Thumb
201
94
 
202
95
  If you are about to read raw code, ask whether the answer is really about structure, relevance, flow, or relationships. AI Kit has a smaller tool for each of those.
203
- `},{file:`references/layered-knowledge-protocol.md`,content:`# Layered Knowledge Protocol
204
-
205
- AI Kit delivers knowledge through four layers:
206
-
207
- ## L0 — Generated Briefing Cards
208
-
209
- Fast, compact task setup loaded at session start.
210
-
211
- - **Auto-injected**: \`workspace-core\` (800-1200 tokens) — available via \`status({ includePrelude: true })\` after \`onboard()\` generates the card. If null → run \`onboard({ path, mode: 'generate' })\` then retry status.
212
- - **If flow active**: Load \`workflow:<flow>\` (500-900 tokens) via flow start refs (replaces task card)
213
- - **If no flow**: Optionally load one task card via \`file_summary\`
214
- - **Budget**: ≤ 2,100 tokens total
215
- - **Storage**: Generated workspace cache (path from server config)
216
- - **Card families**: \`workspace-core\`, \`architecture\`, \`testing-release\`, \`known-issues\`, \`workflow:<flow>\`
217
- - Session-start budget: workspace-core (800-1200 tokens) + 1 additional card ≤ 2,100 tokens total
218
- - Generated cache, not canonical — rebuildable from L2 canonical sources
219
-
220
- ## L1 — Flow Working Context
221
-
222
- Active run state and role-filtered dispatch context.
223
-
224
- - Withdraw via \`knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>', budget: 6000 })\`
225
- - Use withdrawn refs before calling \`file_summary\`, \`scope_map\`, \`blast_radius\`, or \`search\`
226
- - Each step has a declared \`contextProfile\` (implementer, reviewer, researcher, documenter, debugger)
227
-
228
- ## L2 — Canonical Curated Knowledge
229
-
230
- Durable workspace archive managed by CuratedKnowledgeManager.
231
-
232
- - Retrieve on demand via \`search()\` or \`knowledge({ action: 'read' })\`
233
- - Never preload broadly at session start when L1 refs are already supplied
234
- - Markdown is the canonical form; vector/FTS indexes are derived
235
-
236
- ## L3 — Evidence Archive
237
-
238
- High-volume observations, proofs, failures, and runtime traces.
239
-
240
- - Never auto-injected into session or step context
241
- - Inspect only for provenance verification, conflict review, or promotion assessment
242
- - Auto-knowledge extractors write to L3; they cannot navigate flow state or promote
243
-
244
- ## Retrieval Order
245
-
246
- 1. L0 (loaded cards at session start)
247
- 2. L1 (flow withdrawal when active)
248
- 3. L2 (on-demand canonical knowledge)
249
- 4. L3 (focused evidence retrieval only)
250
-
251
- No active flow → keep L1 absent; use L0 + on-demand L2; turn-local context only.
252
- `}];export{e as default};
96
+ `},{file:`references/layered-knowledge-protocol.md`,content:"# Layered Knowledge Protocol\n\nAI Kit delivers knowledge through startup workspace context plus L1-L3:\n\n## Workspace Context — Workspace Skill + Onboard Context\n\nFast, compact task setup loaded at session start.\n\n- **Auto-injected/discoverable**: `status({ includePrelude: true })` returns workspace skill preview/resource pointer and `onboard_context` after `onboard()` generates artifacts. If `onboard_context` is null → run `onboard({ path, mode: 'generate' })` then retry status. If `onboard_context.freshness.status` is `stale` or `unknown` → run `onboard({ path, update: true })` then retry status.\n- **Full workspace skill**: Read `aikit://skill/SKILL.md` only when full conventions, commands, or lessons are needed.\n- **Onboard files**: Use `onboard_context.recommendedReadOrder` and paths for `synthesis-guide.md`, `structure.md`, `dependencies.md`, `diagram.md`, `domains.md`, `entry-points.md`, and `code-map.md`.\n- **If flow active**: Load L1 via `knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>' })` and reuse supplied refs before broad retrieval.\n- **If no flow**: Optionally load one task card via `file_summary`\n- **Budget**: ≤ 2,100 tokens total\n- **Storage**: Workspace skill plus generated onboard artifacts under the status `onboardDir`\n- Generated workspace context, not canonical — rebuildable from L2 canonical sources and current repo analysis\n\n## L1 — Flow Working Context\n\nActive run state and role-filtered dispatch context.\n\n- Withdraw via `knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>', budget: 6000 })`\n- Use withdrawn refs before calling `file_summary`, `scope_map`, `blast_radius`, or `search`\n- Each step has a declared `contextProfile` (implementer, reviewer, researcher, documenter, debugger)\n\n## L2 — Canonical Curated Knowledge\n\nDurable workspace archive managed by CuratedKnowledgeManager.\n\n- Retrieve on demand via `search()` or `knowledge({ action: 'read' })`\n- Never preload broadly at session start when L1 refs are already supplied\n- Markdown is the canonical form; vector/FTS indexes are derived\n\n## L3 — Evidence Archive\n\nHigh-volume observations, proofs, failures, and runtime traces.\n\n- Never auto-injected into session or step context\n- Inspect only for provenance verification, conflict review, or promotion assessment\n- Auto-knowledge extractors write to L3; they cannot navigate flow state or promote\n\n## Retrieval Order\n\n1. Workspace context (workspace skill + onboard context at session start)\n2. L1 (flow withdrawal when active)\n3. L2 (on-demand canonical knowledge)\n4. L3 (focused evidence retrieval only)\n\nNo active flow → keep L1 absent; use workspace context + on-demand L2; turn-local context only.\n"}];export{e as default};
@@ -141,15 +141,15 @@ Default: Context + Container. Add Component only for a complex container and a c
141
141
  2. Identify audience and decision the diagram supports.
142
142
  3. **Gather evidence with AI Kit - check onboard cache FIRST:**
143
143
  a. **Check onboard cache:**
144
- - Run status({ includePrelude: true }) - if workspaceCore shows onboard data available:
145
- - Read cache from ~/.aikit/workspaces/<hash>/onboard/:
144
+ - Run status({ includePrelude: true }) - if structuredContent.onboard_context is present and onboard_context.freshness.status == "fresh":
145
+ - Use onboard_context.recommendedReadOrder and read cache files from onboardDir:
146
146
  - structure.md - module tree, layers, directory shape
147
147
  - dependencies.md - internal/external dependency graph
148
+ - diagram.md / domains.md - architecture boundaries
148
149
  - symbols.md - exported symbols, type signatures
149
150
  - entry-points.md - API surface, CLI entry points
150
- - Freshness: cache fresh if status().onboarded == true and index recent.
151
- For finer control: compare git diff --stat pending change count.
152
- Default: <50 pending changes -> serve from cache | >=50 -> refresh.
151
+ - Freshness: trust status().onboard_context.freshness.status, not timestamps inferred by the model.
152
+ If freshness is stale/unknown, run onboard({ path: ".", update: true }) and status again before using onboard files.
153
153
  b. **Use cache data for C4:**
154
154
  - Extract layers from structure analysis (layer-detector classifications)
155
155
  - Extract modules/containers from directory tree
@@ -155,8 +155,9 @@ Detailed workflow for acquiring and documenting project knowledge into \`docs/ar
155
155
 
156
156
  ### Phase 1: Scan and Read Intent (IR-aware)
157
157
 
158
- Pre-flight — load L0 + L1 context:
158
+ Pre-flight — load workspace context + L1 context:
159
159
  - \`status({ includePrelude: true })\`
160
+ - If \`onboard_context\` is missing, run \`onboard({ path: ".", mode: "generate" })\`; if \`onboard_context.freshness.status\` is \`stale\` or \`unknown\`, run \`onboard({ path: ".", update: true })\`; then status again.
160
161
  - \`knowledge({ action: 'withdraw', scope: 'flow', profile: 'documenter', budget: 6000 })\`
161
162
 
162
163
  Then check \`docs/.docs-state.json\` (the Committed Docs IR):
@@ -789,7 +790,7 @@ Use this template for any generated section that includes factual claims:
789
790
 
790
791
  ### Update Mode Template (\`docs/.docs-state.json\`)
791
792
 
792
- Committed state file for incremental documentation updates. L0 regeneratable cache,
793
+ Committed state file for incremental documentation updates. Workspace-context regeneratable cache,
793
794
  committed to git so clones have warm cache.
794
795
 
795
796
  **Design: extends existing schema (backward compatible).** NO parallel \`_lastSynced\` block.
@@ -798,7 +799,7 @@ Adds \`signatureHash\`, \`contractHash\` (optional), and \`syncedAt\` to the exi
798
799
  \`\`\`json
799
800
  {
800
801
  "version": "1.1",
801
- "layer": "l0",
802
+ "layer": "workspace-context",
802
803
  "timestamp": "ISO-8601",
803
804
  "lastCommitSha": "git rev-parse HEAD of last documented commit",
804
805
 
@@ -1732,7 +1733,7 @@ Orchestrate phased documentation generation with document-type-specific outputs
1732
1733
 
1733
1734
  Before executing the generation pipeline, load available context from across the infrastructure:
1734
1735
 
1735
- - L0: \`status({ includePrelude: true })\` — workspace context (lessons, conventions)
1736
+ - Workspace context: \`status({ includePrelude: true })\` — workspace skill, onboard context, lessons, conventions
1736
1737
  - L1: \`knowledge({ action: 'withdraw', scope: 'flow', profile: 'documenter', budget: 6000 })\` — flow context
1737
1738
  - L2: \`search({ origin: 'curated' })\` + \`knowledge({ action: 'lesson', subAction: 'list-lessons' })\` — curated knowledge
1738
1739
  - L3: Evidence archive (provenance only, never auto-injected)
@@ -1741,8 +1742,9 @@ Before executing the generation pipeline, load available context from across the
1741
1742
 
1742
1743
  ### Phase 1 — Docs IR Producer (deterministic)
1743
1744
 
1744
- Pre-flight: load L0 + L1 context from infrastructure.
1745
- - \`status({ includePrelude: true })\` — L0 prelude
1745
+ Pre-flight: load workspace context + L1 context from infrastructure.
1746
+ - \`status({ includePrelude: true })\` — workspace skill + onboard context prelude
1747
+ - If \`onboard_context\` is missing, generate onboard. If \`onboard_context.freshness.status\` is \`stale\` or \`unknown\`, update onboard, then status again.
1746
1748
  - \`knowledge({ action: 'withdraw', scope: 'flow', profile: 'documenter', budget: 6000 })\` — L1 flow context
1747
1749
 
1748
1750
  Step 1: Check \`docs/.docs-state.json\` (the Committed Docs IR):
@@ -1810,7 +1812,7 @@ Step 2: Doc inventory (always runs, not cached):
1810
1812
  - \`blast_radius({ files: changedFiles })\` — stale doc detection
1811
1813
 
1812
1814
  The IR (\`docs/.docs-state.json\`) stores:
1813
- - \`version\` + \`layer: "l0"\` (regeneratable cache, not curated; committed to git)
1815
+ - \`version\` + \`layer: "workspace-context"\` (regeneratable cache, not curated; committed to git)
1814
1816
  - \`lastCommitSha\` (committed = warm clones, no cold starts)
1815
1817
  - \`onboardRef\` (pointer to onboard cache, NO duplicated analysis data)
1816
1818
  - \`sourceFiles\` (per-file contentHash, signatureHash, contractHash, syncedAt, changeClass)
@@ -3304,7 +3306,7 @@ Each doc type uses specific tools. Load the tools before generating.
3304
3306
  Documentation is the bridge between AI Kit's layered knowledge and human readers.
3305
3307
 
3306
3308
  \`\`\`
3307
- L0 (Briefing Cards) ─→ docs/ — Human-readable summaries of workspace state
3309
+ Workspace skill + onboard context ─→ docs/ — Human-readable summaries of workspace state
3308
3310
 
3309
3311
  L1 (Flow Context) ───→ docs/architecture/flows/ — Flow design decisions → durable docs
3310
3312
  │ │
@@ -3315,7 +3317,7 @@ L3 (Evidence Archive) ──→ docs/reference/ — Verified claims with tool re
3315
3317
 
3316
3318
  | Layer | Docs Role | Action |
3317
3319
  |---|---|---|
3318
- | L0 | Regenerate via briefing-card-compiler when topics change | Card invalidation trigger |
3320
+ | Workspace context | Regenerate via onboard/status/skill compiler when topics change | Onboard + workspace skill freshness trigger |
3319
3321
  | L1 | Withdraw flow context, extract decisions/artifacts → docs/ | \`knowledge({action:'withdraw',scope:'flow'})\` |
3320
3322
  | L2 | Candidate for promotion from verified docs | Consolidation adjudication |
3321
3323
  | L3 | Evidence chain for every doc claim | \`knowledge({action:'lesson'})\` + receipts |
@@ -3439,7 +3441,7 @@ Report: "No documentation updates needed" + brief reason.
3439
3441
  - If \`syncedAt\` missing on doc → treat as stale (conservative), emit warning
3440
3442
  - If no recent lessons match → continue silently
3441
3443
  - Session dedup: maintain \`Set<string>\` of checked topic+entry IDs per session; skip if already checked
3442
- 2. **Load layered context**: \`status({ includePrelude: true })\` → L0. \`knowledge({ action: 'withdraw', scope: 'flow', profile: 'documenter', budget: 6000 })\` → L1.
3444
+ 2. **Load layered context**: \`status({ includePrelude: true })\` → fresh workspace context (generate/update onboard first if missing/stale/unknown). \`knowledge({ action: 'withdraw', scope: 'flow', profile: 'documenter', budget: 6000 })\` → L1.
3443
3445
  3. Gather intent/evidence from flow artifacts, git diff, blast_radius, produce_knowledge, analyze, changelog, or search.
3444
3446
  4. Classify target docs with Diataxis or extended doc type table.
3445
3447
  5. Map changed capability to doc action.
@@ -467,8 +467,8 @@ Every subagent prompt includes:
467
467
  2. Goal + acceptance criteria.
468
468
  3. Files/boundary + do-not-touch list.
469
469
  4. Compressed context: relevant snippets, conventions, decisions, active flow paths.
470
- 5. **L0/L1 refs**: Include \`selectedCardRefs\`, \`retrievedRefs\`, and L1 \`FlowContextSnapshotV1\` fields relevant to the role.
471
- 6. **Hard rule — no broad card reload**: Subagent must reuse supplied refs first. Must NOT independently reload \`workspace-core\`, architecture, testing-release, or known-issues cards when the dispatch already carries applicable refs.
470
+ 5. **Workspace/L1 refs**: Include supplied workspace skill/onboard context, \`retrievedRefs\`, and L1 \`FlowContextSnapshotV1\` fields relevant to the role.
471
+ 6. **Hard rule — no broad rediscovery**: Subagent must reuse supplied refs first. Must NOT independently rediscover workspace basics or reload architecture context when the dispatch already carries applicable refs.
472
472
  7. Constraints: skills to load, libraries/patterns, no present, no flow advance.
473
473
  8. FORGE: tier, task_id, evidence claims to add.
474
474
  9. Validation: expected check, test_run, or reason skipped.
@@ -480,10 +480,10 @@ Use references/implementer-prompt.md for implementation dispatches and reference
480
480
 
481
481
  Before dispatch:
482
482
  - knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>', budget: 6000 })
483
- - Include \`selectedCardRefs\` (L0 card refs) and \`retrievedRefs\` (from L1) in the dispatch envelope.
483
+ - Include supplied workspace/onboard context refs and \`retrievedRefs\` (from L1) in the dispatch envelope.
484
484
  - Add only missing snippets with file_summary/digest.
485
485
  - Paste context into dispatch; do not tell subagent to rediscover basics.
486
- - **Hard rule**: Subagent must reuse supplied L0/L1 refs before broad retrieval. Block if it reloads \`workspace-core\` or architecture cards independently.
486
+ - **Hard rule**: Subagent must reuse supplied workspace/L1 refs before broad retrieval. Block if it independently rediscovers workspace basics already present in the dispatch.
487
487
 
488
488
  After subagent work:
489
489
  - Store durable findings with knowledge({ action: 'remember', scope: 'flow', ... }).
@@ -27,14 +27,19 @@ YOU MUST FOLLOW THIS PROTOCOL ON EVERY TASK. You are an orchestrator, not an imp
27
27
 
28
28
  Execute these before ANY other work:
29
29
  1. \`flow({ action: 'status' })\` — Check active flow state.
30
- 2. \`status({ includePrelude: true })\` — Load L0 workspace context plus workspace skill summary.
31
- 3. If workspaceCore null → \`onboard({ path: "." })\` first, then status again.
32
- 4. \`skill({ name: 'aikit' })\` Load the AI Kit skill for tool routing, retrieval ladder, and communication patterns.
30
+ 2. \`status({ includePrelude: true })\` — Load workspace skill summary plus onboard context.
31
+ 3. If \`onboarded\` is false or \`onboard_context\` is null → \`onboard({ path: ".", mode: "generate" })\` first, then status again.
32
+ 4. If \`onboard_context.freshness.status\` is \`stale\` or \`unknown\`, or \`nextAction.kind === "update_onboard"\` \`onboard({ path: ".", update: true })\` first, then status again.
33
+ 5. \`skill({ name: 'aikit' })\` — Load the AI Kit skill for tool routing, retrieval ladder, and communication patterns.
33
34
 
34
35
  On platforms without native \`skill()\` support, the AI Kit instructions are already in your system prompt via other channels.
35
36
 
36
37
  **Workspace skill:** \`status({ includePrelude: true })\` gives you the compact summary. For full content (conventions, commands, lessons): read \`aikit://skill/SKILL.md\` MCP resource on demand.
37
38
 
39
+ ## User-Facing Presentation
40
+
41
+ Use \`present({ schemaVersion: 1, title, blocks })\` for almost every substantive response to the user. If the response is more than 3 sentences, contains a list/table/checklist/plan/status/verdict/summary/progress/evidence map, or asks for approval/choice, use \`present\`. Prefer \`present\` even without actions for read-only summaries; add \`actions\` for approvals, confirmations, and selections. Plain text only for tiny status updates or one simple question that fits in 3 short sentences.
42
+
38
43
  ## Delegation Rules
39
44
 
40
45
  **RULE 1 — Decompose everything.** Break every task into independent, parallelizable subtasks.
@@ -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,unlinkSync as ee,writeFileSync as te}from"node:fs";import{dirname as g,join as _,resolve as v}from"node:path";import{readFile as ne,writeFile as re}from"node:fs/promises";import{homedir as y}from"node:os";import{execFile as ie,execSync as b,spawn as ae}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 oe={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},se={working:1,episodic:2,semantic:4,procedural:12};function ce(e,t=oe){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 le(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},ue=`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 de(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 fe(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 pe(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 me(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 he(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 ge(e){return{...D,...e}}function O(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function _e(e){return e&&e in se?e:`working`}function k(e,t,n,r=D,i){let a=typeof r==`string`?_e(r):`working`,o=ge(typeof r==`string`?i:r),s=O(e,O(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*se[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function ve(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=k(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function ye(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=k(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function be(e,t){let n=ge(t);return e.memoryMetaList().map(t=>ve(e,t.entryId,n)??t).filter(e=>e.retentionScore<n.flagThreshold).sort((e,t)=>e.retentionScore-t.retentionScore)}const A={threshold:.7,maxCompare:50,autoThreshold:.95};function xe(e){let t=Math.min(1,Math.max(0,e?.threshold??A.threshold)),n=Math.min(1,Math.max(t,e?.autoThreshold??A.autoThreshold));return{threshold:t,maxCompare:Math.max(1,Math.trunc(e?.maxCompare??A.maxCompare)),autoThreshold:n}}function Se(e){let t=e.toLowerCase().match(/[a-z0-9]{2,}/g)??[];return new Set(t)}function j(e,t){let n=Se(e),r=Se(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 Ce(e,t,n=A){let r=xe(n);return t.slice(0,r.maxCompare).map(t=>({entryId:t.id,title:t.title,similarity:j(e,t.content),path:t.path})).filter(e=>e.similarity>=r.threshold).sort((e,t)=>t.similarity-e.similarity)}function we(e,t,n){e.memoryMetaCreate(t),e.memoryMetaSetSuperseded(t,n)}const Te=t(import.meta.url),Ee=import.meta.dirname??g(n(import.meta.url)),M=new Map;function N(e){let t=M.get(e);if(t!==void 0)return t;let n=_(Ee,`..`,`..`,e);if(d(_(n,`package.json`)))return M.set(e,n),n;try{let t=g(Te.resolve(`@aikit/${e}/package.json`));return M.set(e,t),t}catch{}let r=Ee;for(let t=0;t<6;t++){let t=_(r,`packages`,e);if(d(_(t,`package.json`)))return M.set(e,t),t;let n=g(r);if(n===r)break;r=n}return M.set(e,null),null}function De(e,t=`dist`){let n=N(e);if(!n)return null;let r=_(n,t);return d(r)?r:null}function Oe(e,t){let n=N(e);if(!n)return null;for(let e of t){let t=_(n,e);if(d(t))return t}return null}var P=S({DEFAULT_GROUP_CONFIG:()=>I,DEFAULT_PRUNE_CONFIG:()=>F,groupLessons:()=>He,pruneLessons:()=>Ve});const F={maxConfidence:15,minIdleDays:30,safetyDays:7,maxPrune:20,dryRun:!0},I={similarityThreshold:.7,minGroupSize:2,maxGroups:10,dryRun:!0},ke=new Set([`the`,`a`,`to`,`for`,`in`,`of`,`and`,`is`,`use`]);function Ae(e){return{maxConfidence:Math.min(100,Math.max(0,Math.trunc(e?.maxConfidence??F.maxConfidence))),minIdleDays:Math.max(1,Math.trunc(e?.minIdleDays??F.minIdleDays)),safetyDays:Math.max(0,Math.trunc(e?.safetyDays??F.safetyDays)),maxPrune:Math.max(1,Math.trunc(e?.maxPrune??F.maxPrune)),dryRun:e?.dryRun??F.dryRun}}function je(e){return{similarityThreshold:Math.min(1,Math.max(0,e?.similarityThreshold??I.similarityThreshold)),minGroupSize:Math.max(2,Math.trunc(e?.minGroupSize??I.minGroupSize)),maxGroups:Math.max(1,Math.trunc(e?.maxGroups??I.maxGroups)),dryRun:e?.dryRun??I.dryRun}}function Me(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}function Ne(e,t){let n=Math.max(Me(e),Me(t));return n===0?1/0:Math.max(0,Date.now()-n)/864e5}function Pe(e){return e.toLowerCase().match(/[a-z0-9]{2,}/g)??[]}function Fe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,60)}function Ie(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 Le(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)j(e[r],e[i])>=t&&(n[r].push(i),n[i].push(r));return n}function Re(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 ze(e){let t=new Map,n=new Map,r=0;for(let i of e)for(let e of Pe(i))ke.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?Fe(i[0]):Fe(e.flatMap(e=>Pe(e)).find(e=>!ke.has(e))??`lesson-group`)}async function Be(e,t,n){let r=_(e.curatedDir,t),i=await ne(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 re(r,Ie({...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 Ve(e,t,n,r){let i=Ae(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=Ne(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 He(e,t,n){let r=je(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=Re(Le(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:ze(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 Be(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 Ue=S({DEFAULT_PROMOTE_CONFIG:()=>L,adjudicateCandidate:()=>nt,checkPromotionGates:()=>et,collectWorkspaceLessons:()=>ot,demoteLesson:()=>lt,getGlobalCuratedDir:()=>z,promoteLessons:()=>ct,scanForDuplicates:()=>st,scorePromotionCandidate:()=>tt});const L={minWorkspaces:2,minAvgConfidence:80,similarityThreshold:.7,dryRun:!0};function We(e){return{minWorkspaces:Math.max(2,Math.trunc(e?.minWorkspaces??L.minWorkspaces)),minAvgConfidence:Math.min(100,Math.max(0,Math.trunc(e?.minAvgConfidence??L.minAvgConfidence))),similarityThreshold:Math.min(1,Math.max(0,e?.similarityThreshold??L.similarityThreshold)),dryRun:e?.dryRun??L.dryRun,layeredKnowledge:e?.layeredKnowledge??L.layeredKnowledge}}function Ge(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)j(e[r].insight,e[i].insight)>=t&&(n[r].push(i),n[i].push(r));return n}function Ke(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 qe(t){return new e(t,null,null)}function Je(e){return(e??``).replace(/\s+/g,` `).trim()}function Ye(e){let t=Je(e);return t.length<=80?t:`${t.slice(0,77).replace(/\s+\S*$/,``)}...`}function Xe(e){return de({title:Ye(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 R(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function Ze(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 Qe(e){switch(e){case`high`:return 10;case`medium`:return 6;case`low`:return 2}}function $e(e){let t=e.length/4;return t<=10?10:t<=25?8:t<=50?6:t<=100?4:t<=200?2:1}function et(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 tt(e,t){let n=R(t?.recurrence??1,1,10),r=R(t?.impact??5,1,10),i=R(e.foundIn.length,1,10),a=t?.observedAt?Ze(new Date(t.observedAt)):5,o=Qe(t?.actionability??`medium`),s=$e(e.insight);return{signals:{recurrence:n,impact:r,sourceDiversity:i,freshness:a,actionability:o,tokenCost:s},totalScore:n+r+i+a+o+s}}function nt(e,t,n,r,i){return t.passed?n&&r&&i&&n.some(e=>j(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 rt(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=Je(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 it(e){return(await rt(e,`global`)).map(e=>e.insight)}function at(e,t,n){return t.some(t=>j(t,e)>=n)}function z(){let e=_(o(),`global-knowledge`,`.ai`,`curated`);return d(e)||f(e,{recursive:!0}),e}async function ot(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 rt(qe(n),e.partition);r.length>0&&t.set(e.partition,r)}return t}function st(e,t=L,n){let r=We(t),i=[...e.values()].flat();if(i.length===0)return[];let a=Ke(Ge(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=et(c,e),r=tt(c,e),i=nt(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 ct(e,t,n=L){let r=We(n),i=[],a=await it(t);for(let n of e){if(!(r.layeredKnowledge?n.adjudication?.decision===`promote`:n.action===`promote`)||at(n.insight,a,r.similarityThreshold)||r.dryRun)continue;let e=await t.remember(Ye(n.insight),Xe(n),`lessons`,[`lesson`,`promoted`,`global`]);i.push(e.path),a.push(n.insight)}return{candidates:e,promoted:i}}async function lt(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 ut=S({createSamplingClient:()=>mt});const dt=a(`sampling`);function ft(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 pt(e){if(Array.isArray(e))return e.map(e=>pt(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 mt(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:ft(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:pt(i.content),model:i.model,stopReason:i.stopReason}}catch(e){throw dt.warn(`Sampling createMessage failed`,{error:String(e)}),e}}}}const ht=/^(export|import|function|class|interface|type|const|let|var|→|├|└|─|##)/,gt=/^(decision|rationale|status|context|consequence)/i,_t=/finding|recommendation|warning|error|issue/i,vt=/status|done|decision|blocker|next|file|created|modified/i,yt=/(score|relevance)/i,bt=/[/.]|\\.(ts|js)$/i;function B(e){return e.split(/\r?\n/u).map(e=>e.replace(/[ \t]+$/u,``)).join(`
7
- `).replace(/\n{3,}/gu,`
8
-
9
- `).trim()}function xt(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 V(e,t,n){return xt(e,Math.max(1,Math.floor(n*t)))}function H(e,t){if(e.length<50)return e;let n=B(t);return!n||n.length<e.length*.2?e:n}function St(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 Ct(e,t){e.includes(t)||e.push(t)}function wt(e){return H(e,V(St(e.split(/\r?\n/u),3,e=>ht.test(e)||e.startsWith(`- `)),.6,e.length))}function Tt(e){let t=e.split(/\r?\n/u),n=[];return t.forEach((e,t)=>{if(t<5||yt.test(e)||bt.test(e)||/^Content:/i.test(e)){if(/^Content:/i.test(e)){Ct(n,`Content: ${e.replace(/^Content:\s*/i,``).trim().slice(0,200)}`);return}Ct(n,e)}}),H(e,n.join(`
13
- `))}function Et(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(`* `)||gt.test(e))&&n.add(t)}),H(e,V(t.filter((e,t)=>n.has(t)).join(`
14
- `),.7,e.length))}function Dt(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)}),H(e,V(t.filter((e,t)=>n.has(t)).join(`
15
- `),.65,e.length))}function Ot(e){return H(e,V(e.split(/\r?\n/u).filter(e=>e.startsWith(`#`)||e.startsWith(`- `)||/\d/.test(e)||/\d+%/.test(e)||_t.test(e)).join(`
16
- `),.6,e.length))}function kt(e){return H(e,V(e.split(/\r?\n/u).filter(e=>e.startsWith(`- `)||e.startsWith(`* `)||vt.test(e)).join(`
17
- `),.5,e.length))}function At(e,t){switch(e){case`file-card`:return wt(t);case`search-result`:return Tt(t);case`decision`:return Et(t);case`pattern`:return Dt(t);case`analysis`:return Ot(t);case`step-summary`:return kt(t)}}const jt=/^### (Context|Insight|Evidence|Key|Finding|Result|Decision)/imu;function Mt(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),jt.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?B(a):xt(B(a),t)}function Nt(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 Pt=S({autoUpgradeScaffold:()=>en,checkForUpdates:()=>Kt,cleanupOldVersions:()=>J,getCurrentVersion:()=>K,getUpgradeState:()=>Qt});const Ft=`@vpxa/aikit`,It=`https://registry.npmjs.org/${Ft}/latest`,U=a(`server`);function Lt(){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 Rt=_(y(),`.aikit`),W=_(Rt,`current-version.json`),G=_(Rt,`versions`),zt=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/;function Bt(e){if(!zt.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}function K(){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 Vt(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 Ht(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 Ut(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)))){U.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),U.debug(`Renamed locked directory to ${t} — deferred cleanup`);try{h(t,{recursive:!0,force:!0})}catch{}}catch(t){U.debug(`Failed to rename locked directory`,{path:e,error:t instanceof Error?t.message:String(t)})}}async function Wt(e){Bt(e);let t=`v${e}`,n=_(G,`${t}-staging`),i=_(G,t);try{Ut(n),f(n,{recursive:!0}),b(`tar -xzf "${b(`npm pack ${Ft}@${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=`${W}.tmp`;te(o,JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)),m(o,W),J(e)}finally{Ut(n)}}function q(e){U.debug(`Updated to v${e}. Restarting server...`),setTimeout(()=>{process.exit(0)},300).unref()}function J(e){i(G,e??K())}async function Gt(){try{let e=p(W,`utf-8`),{version:t}=JSON.parse(e),n=await fetch(It,{signal:AbortSignal.timeout(1e4)});if(!n.ok)return;let r=(await n.json()).version;if(!r||r===t||!Ht(r,t))return;if(d(_(G,`v${r}`))){let e=`${W}.tmp`;te(e,JSON.stringify({version:r,installedAt:new Date().toISOString()},null,2)),m(e,W),U.debug(`Re-activated existing version v${r} — no download needed`),q(r);return}U.debug(`New version available: ${r}. Installing...`),await Wt(r),q(r)}catch(e){U.error(`Background update check failed: ${e instanceof Error?e.message:String(e)}`)}}let Y=null;function Kt(){return Y||(Y=qt().finally(()=>{Y=null}),Y)}async function qt(){if(d(W)){await Gt();return}let e=K();try{let t=await fetch(It,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return;let n=(await t.json()).version;if(!n)return;if(Vt(e,n)<0){U.debug(`Newer version available — installing`,{currentVersion:e,latestVersion:n});try{await Wt(n),q(n)}catch(e){U.warn(`Auto-install failed`,{error:e instanceof Error?e.message:String(e),latestVersion:n})}}}catch{}}function Jt(){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 Yt(){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 X=`idle`,Z=null,Xt=null,Zt=!1;function Qt(){return{state:X,error:Z}}function $t(){X=`idle`,Z=null}function en(){try{let e=K();if(Kt(),!Zt){Zt=!0;try{let e=Lt();e&&ae(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`]&&ee(e)}catch{}}let t=Jt(),n=Yt();if(!(t!=null&&t!==e)&&!(n!=null&&n!==e)||(Xt!==e&&($t(),Xt=e),X!==`idle`))return;X=`pending`,Z=null,U.debug(`Scaffold version mismatch — auto-upgrading`,{serverVersion:e,userScaffoldVersion:t,workspaceScaffoldVersion:n});let r=Lt();if(!r){X=`failed`,Z=`aikit CLI binary not found`,U.warn(`Cannot auto-upgrade: aikit CLI binary not found`);return}let i=y();ie(process.execPath,[r,`upgrade`],{cwd:i,timeout:3e4,windowsHide:!0},(t,n,a)=>{t?(X=`failed`,Z=t.message,U.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})):(X=`success`,Z=null,U.debug(`Auto-upgrade completed to version ${e}`))}).unref()}catch(e){X=`failed`,Z=e instanceof Error?e.message:String(e),U.warn(`Auto-upgrade check failed`,{error:Z})}}var tn=S({buildPreludeInjection:()=>on,generatePrelude:()=>an});function nn(e,t){return e.length<=t?e:e.slice(0,t)}function Q(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}function rn(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`);return e.length>400?`${e.slice(0,400)}\n...`:e}catch{}}return null}async function an(e,t,n=C,r){if(!e||!t)return null;try{let[i,a,o]=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=i.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);return{lessons:await Promise.all(s.map(async({entry:t,confidence:n})=>{let r=T((await e.read(t.path)).content);return{title:t.title,insight:nn(r.insight??``,150),confidence:n}})),conventions:a.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).filter(({entry:e})=>(e.contentPreview?.trim()??``).length>5).sort((e,t)=>Q(t.lastAccessedAt)-Q(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),checkpoint:o.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>Q(t.lastAccessedAt)-Q(e.lastAccessedAt)).map(({entry:e})=>nn(e.contentPreview,200))[0]??null,workspaceSkill:rn(r)}}catch{return null}}function on(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=Nt(t.title,t.insight,t.confidence,200);n.push(`• ${e}`),r++}e.workspaceSkill&&(n.push(`• Workspace: ${e.workspaceSkill.split(`
19
- `)[0]??``}`),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 sn(e,t){return t?{version:e,...u(t)}:{version:e}}function cn(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(()=>P),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(()=>Ue),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)`,sn(r,e))}}).catch(e=>$.warn(`Startup maintenance failed`,u(e)))}export{xe as A,me as B,De as C,Ce as D,A as E,C as F,oe as G,w as H,ue as I,ce as K,pe as L,be as M,ve as N,j as O,ye as P,E as R,Ve as S,N as T,fe as U,T as V,he as W,z as _,en as a,P as b,Qt as c,Mt as d,mt as f,lt as g,ot as h,tn as i,D as j,we as k,Pt as l,L as m,sn as n,J as o,ut as p,le as q,an as r,K as s,cn as t,At as u,ct as v,Oe as w,He as x,st as y,de as z};
@@ -1,20 +0,0 @@
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,unlinkSync as ee,writeFileSync as te}from"node:fs";import{dirname as _,join as v,resolve as y}from"node:path";import{readFile as ne,writeFile as re}from"node:fs/promises";import{execFile as ie,execSync as b,spawn as ae}from"node:child_process";import{homedir as x}from"node:os";const S={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},C={working:1,episodic:2,semantic:4,procedural:12};function oe(e,t=S){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 se(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},ce=`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 le(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 ue(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 de(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 fe(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 pe(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 me(e){return{...O,...e}}function he(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function ge(e){return e&&e in C?e:`working`}function _e(e,t,n,r=O,i){let a=typeof r==`string`?ge(r):`working`,o=me(typeof r==`string`?i:r),s=he(e,he(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*C[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function ve(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=_e(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function ye(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=_e(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function be(e,t){let n=me(t);return e.memoryMetaList().map(t=>ve(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 xe(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 A(e){let t=e.toLowerCase().match(/[a-z0-9]{2,}/g)??[];return new Set(t)}function j(e,t){let n=A(e),r=A(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 Se(e,t,n=k){let r=xe(n);return t.slice(0,r.maxCompare).map(t=>({entryId:t.id,title:t.title,similarity:j(e,t.content),path:t.path})).filter(e=>e.similarity>=r.threshold).sort((e,t)=>t.similarity-e.similarity)}function Ce(e,t,n){e.memoryMetaCreate(t),e.memoryMetaSetSuperseded(t,n)}const we=n(import.meta.url),M=import.meta.dirname??_(r(import.meta.url)),N=new Map;function P(e){let t=N.get(e);if(t!==void 0)return t;let n=v(M,`..`,`..`,e);if(f(v(n,`package.json`)))return N.set(e,n),n;try{let t=_(we.resolve(`@aikit/${e}/package.json`));return N.set(e,t),t}catch{}let r=M;for(let t=0;t<6;t++){let t=v(r,`packages`,e);if(f(v(t,`package.json`)))return N.set(e,t),t;let n=_(r);if(n===r)break;r=n}return N.set(e,null),null}function Te(e,t=`dist`){let n=P(e);if(!n)return null;let r=v(n,t);return f(r)?r:null}function Ee(e,t){let n=P(e);if(!n)return null;for(let e of t){let t=v(n,e);if(f(t))return t}return null}var De=e({DEFAULT_GROUP_CONFIG:()=>I,DEFAULT_PRUNE_CONFIG:()=>F,groupLessons:()=>Ve,pruneLessons:()=>Be});const F={maxConfidence:15,minIdleDays:30,safetyDays:7,maxPrune:20,dryRun:!0},I={similarityThreshold:.7,minGroupSize:2,maxGroups:10,dryRun:!0},Oe=new Set([`the`,`a`,`to`,`for`,`in`,`of`,`and`,`is`,`use`]);function ke(e){return{maxConfidence:Math.min(100,Math.max(0,Math.trunc(e?.maxConfidence??F.maxConfidence))),minIdleDays:Math.max(1,Math.trunc(e?.minIdleDays??F.minIdleDays)),safetyDays:Math.max(0,Math.trunc(e?.safetyDays??F.safetyDays)),maxPrune:Math.max(1,Math.trunc(e?.maxPrune??F.maxPrune)),dryRun:e?.dryRun??F.dryRun}}function Ae(e){return{similarityThreshold:Math.min(1,Math.max(0,e?.similarityThreshold??I.similarityThreshold)),minGroupSize:Math.max(2,Math.trunc(e?.minGroupSize??I.minGroupSize)),maxGroups:Math.max(1,Math.trunc(e?.maxGroups??I.maxGroups)),dryRun:e?.dryRun??I.dryRun}}function je(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}function Me(e,t){let n=Math.max(je(e),je(t));return n===0?1/0:Math.max(0,Date.now()-n)/864e5}function Ne(e){return e.toLowerCase().match(/[a-z0-9]{2,}/g)??[]}function Pe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,60)}function Fe(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 Ie(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)j(e[r],e[i])>=t&&(n[r].push(i),n[i].push(r));return n}function Le(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 Re(e){let t=new Map,n=new Map,r=0;for(let i of e)for(let e of Ne(i))Oe.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?Pe(i[0]):Pe(e.flatMap(e=>Ne(e)).find(e=>!Oe.has(e))??`lesson-group`)}async function ze(e,t,n){let r=v(e.curatedDir,t),i=await ne(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 re(r,Fe({...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 Be(e,t,n,r){let i=ke(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=Me(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 Ve(e,t,n){let r=Ae(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=Le(Ie(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:Re(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 ze(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 He=e({DEFAULT_PROMOTE_CONFIG:()=>L,adjudicateCandidate:()=>tt,checkPromotionGates:()=>$e,collectWorkspaceLessons:()=>ot,demoteLesson:()=>lt,getGlobalCuratedDir:()=>at,promoteLessons:()=>ct,scanForDuplicates:()=>st,scorePromotionCandidate:()=>et});const L={minWorkspaces:2,minAvgConfidence:80,similarityThreshold:.7,dryRun:!0};function Ue(e){return{minWorkspaces:Math.max(2,Math.trunc(e?.minWorkspaces??L.minWorkspaces)),minAvgConfidence:Math.min(100,Math.max(0,Math.trunc(e?.minAvgConfidence??L.minAvgConfidence))),similarityThreshold:Math.min(1,Math.max(0,e?.similarityThreshold??L.similarityThreshold)),dryRun:e?.dryRun??L.dryRun,layeredKnowledge:e?.layeredKnowledge??L.layeredKnowledge}}function We(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)j(e[r].insight,e[i].insight)>=t&&(n[r].push(i),n[i].push(r));return n}function Ge(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 Ke(e){return new t(e,null,null)}function qe(e){return(e??``).replace(/\s+/g,` `).trim()}function Je(e){let t=qe(e);return t.length<=80?t:`${t.slice(0,77).replace(/\s+\S*$/,``)}...`}function Ye(e){return le({title:Je(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 R(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}function Xe(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 Ze(e){switch(e){case`high`:return 10;case`medium`:return 6;case`low`:return 2}}function Qe(e){let t=e.length/4;return t<=10?10:t<=25?8:t<=50?6:t<=100?4:t<=200?2:1}function $e(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 et(e,t){let n=R(t?.recurrence??1,1,10),r=R(t?.impact??5,1,10),i=R(e.foundIn.length,1,10),a=t?.observedAt?Xe(new Date(t.observedAt)):5,o=Ze(t?.actionability??`medium`),s=Qe(e.insight);return{signals:{recurrence:n,impact:r,sourceDiversity:i,freshness:a,actionability:o,tokenCost:s},totalScore:n+r+i+a+o+s}}function tt(e,t,n,r,i){return t.passed?n&&r&&i&&n.some(e=>j(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 nt(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=qe(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 rt(e){return(await nt(e,`global`)).map(e=>e.insight)}function it(e,t,n){return t.some(t=>j(t,e)>=n)}function at(){let e=v(s(),`global-knowledge`,`.ai`,`curated`);return f(e)||p(e,{recursive:!0}),e}async function ot(e){let t=new Map;if(!c())return t;for(let e of l()){let n=v(e.workspacePath,`.ai`,`curated`);if(!f(n))continue;let r=await nt(Ke(n),e.partition);r.length>0&&t.set(e.partition,r)}return t}function st(e,t=L,n){let r=Ue(t),i=[...e.values()].flat();if(i.length===0)return[];let a=Ge(We(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=$e(c,e),r=et(c,e),i=tt(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 ct(e,t,n=L){let r=Ue(n),i=[],a=await rt(t);for(let n of e){if(!(r.layeredKnowledge?n.adjudication?.decision===`promote`:n.action===`promote`)||it(n.insight,a,r.similarityThreshold)||r.dryRun)continue;let e=await t.remember(Je(n.insight),Ye(n),`lessons`,[`lesson`,`promoted`,`global`]);i.push(e.path),a.push(n.insight)}return{candidates:e,promoted:i}}async function lt(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 ut=e({createSamplingClient:()=>mt});const dt=o(`sampling`);function ft(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 pt(e){if(Array.isArray(e))return e.map(e=>pt(e)).filter(e=>e.length>0).join(`
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 mt(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:ft(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:pt(i.content),model:i.model,stopReason:i.stopReason}}catch(e){throw dt.warn(`Sampling createMessage failed`,{error:String(e)}),e}}}}const ht=/^(export|import|function|class|interface|type|const|let|var|→|├|└|─|##)/,gt=/^(decision|rationale|status|context|consequence)/i,_t=/finding|recommendation|warning|error|issue/i,vt=/status|done|decision|blocker|next|file|created|modified/i,yt=/(score|relevance)/i,bt=/[/.]|\\.(ts|js)$/i;function z(e){return e.split(/\r?\n/u).map(e=>e.replace(/[ \t]+$/u,``)).join(`
6
- `).replace(/\n{3,}/gu,`
7
-
8
- `).trim()}function xt(e,t){if(e.length<=t)return e;let n=e.split(`
9
- `),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(`
10
- `):e.slice(0,t).trimEnd()}function B(e,t,n){return xt(e,Math.max(1,Math.floor(n*t)))}function V(e,t){if(e.length<50)return e;let n=z(t);return!n||n.length<e.length*.2?e:n}function St(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(`
11
- `)}function Ct(e,t){e.includes(t)||e.push(t)}function wt(e){return V(e,B(St(e.split(/\r?\n/u),3,e=>ht.test(e)||e.startsWith(`- `)),.6,e.length))}function Tt(e){let t=e.split(/\r?\n/u),n=[];return t.forEach((e,t)=>{if(t<5||yt.test(e)||bt.test(e)||/^Content:/i.test(e)){if(/^Content:/i.test(e)){Ct(n,`Content: ${e.replace(/^Content:\s*/i,``).trim().slice(0,200)}`);return}Ct(n,e)}}),V(e,n.join(`
12
- `))}function Et(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(`* `)||gt.test(e))&&n.add(t)}),V(e,B(t.filter((e,t)=>n.has(t)).join(`
13
- `),.7,e.length))}function Dt(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)}),V(e,B(t.filter((e,t)=>n.has(t)).join(`
14
- `),.65,e.length))}function Ot(e){return V(e,B(e.split(/\r?\n/u).filter(e=>e.startsWith(`#`)||e.startsWith(`- `)||/\d/.test(e)||/\d+%/.test(e)||_t.test(e)).join(`
15
- `),.6,e.length))}function kt(e){return V(e,B(e.split(/\r?\n/u).filter(e=>e.startsWith(`- `)||e.startsWith(`* `)||vt.test(e)).join(`
16
- `),.5,e.length))}function At(e,t){switch(e){case`file-card`:return wt(t);case`search-result`:return Tt(t);case`decision`:return Et(t);case`pattern`:return Dt(t);case`analysis`:return Ot(t);case`step-summary`:return kt(t)}}const jt=/^### (Context|Insight|Evidence|Key|Finding|Result|Decision)/imu;function Mt(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),jt.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?z(a):xt(z(a),t)}function Nt(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 Pt=e({autoUpgradeScaffold:()=>$t,checkForUpdates:()=>Kt,cleanupOldVersions:()=>q,getCurrentVersion:()=>G,getUpgradeState:()=>Zt});const Ft=`@vpxa/aikit`,It=`https://registry.npmjs.org/${Ft}/latest`,H=o(`server`);function Lt(){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 Rt=v(x(),`.aikit`),U=v(Rt,`current-version.json`),W=v(Rt,`versions`),zt=/^\d+\.\d+\.\d+(-[\w.+]+)?(\+[\w.]+)?$/;function Bt(e){if(!zt.test(e))throw Error(`Invalid semver version: ${JSON.stringify(e)}`)}function G(){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 Vt(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 Ht(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 Ut(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)))){H.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),H.debug(`Renamed locked directory to ${t} — deferred cleanup`);try{g(t,{recursive:!0,force:!0})}catch{}}catch(t){H.debug(`Failed to rename locked directory`,{path:e,error:t instanceof Error?t.message:String(t)})}}async function Wt(e){Bt(e);let t=`v${e}`,n=v(W,`${t}-staging`),r=v(W,t);try{Ut(n),p(n,{recursive:!0}),b(`tar -xzf "${b(`npm pack ${Ft}@${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=`${U}.tmp`;te(o,JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)),h(o,U),q(e)}finally{Ut(n)}}function K(e){H.debug(`Updated to v${e}. Restarting server...`),setTimeout(()=>{process.exit(0)},300).unref()}function q(e){a(W,e??G())}async function Gt(){try{let e=m(U,`utf-8`),{version:t}=JSON.parse(e),n=await fetch(It,{signal:AbortSignal.timeout(1e4)});if(!n.ok)return;let r=(await n.json()).version;if(!r||r===t||!Ht(r,t))return;if(f(v(W,`v${r}`))){let e=`${U}.tmp`;te(e,JSON.stringify({version:r,installedAt:new Date().toISOString()},null,2)),h(e,U),H.debug(`Re-activated existing version v${r} — no download needed`),K(r);return}H.debug(`New version available: ${r}. Installing...`),await Wt(r),K(r)}catch(e){H.error(`Background update check failed: ${e instanceof Error?e.message:String(e)}`)}}let J=null;function Kt(){return J||(J=qt().finally(()=>{J=null}),J)}async function qt(){if(f(U)){await Gt();return}let e=G();try{let t=await fetch(It,{signal:AbortSignal.timeout(1e4)});if(!t.ok)return;let n=(await t.json()).version;if(!n)return;if(Vt(e,n)<0){H.debug(`Newer version available — installing`,{currentVersion:e,latestVersion:n});try{await Wt(n),K(n)}catch(e){H.warn(`Auto-install failed`,{error:e instanceof Error?e.message:String(e),latestVersion:n})}}}catch{}}function Jt(){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 Yt(){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 Y=`idle`,X=null,Z=null,Xt=!1;function Zt(){return{state:Y,error:X}}function Qt(){Y=`idle`,X=null}function $t(){try{let e=G();if(Kt(),!Xt){Xt=!0;try{let e=Lt();e&&ae(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`]&&ee(e)}catch{}}let t=Jt(),n=Yt();if(!(t!=null&&t!==e)&&!(n!=null&&n!==e)||(Z!==e&&(Qt(),Z=e),Y!==`idle`))return;Y=`pending`,X=null,H.debug(`Scaffold version mismatch — auto-upgrading`,{serverVersion:e,userScaffoldVersion:t,workspaceScaffoldVersion:n});let r=Lt();if(!r){Y=`failed`,X=`aikit CLI binary not found`,H.warn(`Cannot auto-upgrade: aikit CLI binary not found`);return}let i=x();ie(process.execPath,[r,`upgrade`],{cwd:i,timeout:3e4,windowsHide:!0},(t,n,a)=>{t?(Y=`failed`,X=t.message,H.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})):(Y=`success`,X=null,H.debug(`Auto-upgrade completed to version ${e}`))}).unref()}catch(e){Y=`failed`,X=e instanceof Error?e.message:String(e),H.warn(`Auto-upgrade check failed`,{error:X})}}var en=e({buildPreludeInjection:()=>an,generatePrelude:()=>rn});function tn(e,t){return e.length<=t?e:e.slice(0,t)}function Q(e){if(!e)return 0;let t=Date.parse(e);return Number.isNaN(t)?0:t}function nn(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`);return e.length>400?`${e.slice(0,400)}\n...`:e}catch{}}return null}async function rn(e,t,n=w,r){if(!e||!t)return null;try{let[i,a,o]=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=i.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);return{lessons:await Promise.all(s.map(async({entry:t,confidence:n})=>{let r=E((await e.read(t.path)).content);return{title:t.title,insight:tn(r.insight??``,150),confidence:n}})),conventions:a.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).filter(({entry:e})=>(e.contentPreview?.trim()??``).length>5).sort((e,t)=>Q(t.lastAccessedAt)-Q(e.lastAccessedAt)).slice(0,2).map(({entry:e})=>({title:e.title,preview:e.contentPreview})),checkpoint:o.map(e=>({entry:e,lastAccessedAt:t.memoryMetaGet(e.path)?.lastAccessedAt??null})).sort((e,t)=>Q(t.lastAccessedAt)-Q(e.lastAccessedAt)).map(({entry:e})=>tn(e.contentPreview,200))[0]??null,workspaceSkill:nn(r)}}catch{return null}}function an(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=Nt(t.title,t.insight,t.confidence,200);n.push(`• ${e}`),r++}e.workspaceSkill&&(n.push(`• Workspace: ${e.workspaceSkill.split(`
18
- `)[0]??``}`),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
- `);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 on(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(()=>De),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(()=>He),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)`,on(r,e))}}).catch(e=>$.warn(`Startup maintenance failed`,d(e)))}export{xe as A,fe as B,Te as C,Se as D,k as E,w as F,S as G,T as H,ce as I,oe as K,de as L,be as M,ve as N,j as O,ye as P,D as R,Be as S,P as T,ue as U,E as V,pe as W,at as _,$t as a,De as b,Zt as c,Mt as d,mt as f,lt as g,ot as h,en as i,O as j,Ce as k,Pt as l,L as m,on as n,q as o,ut as p,se as q,rn as r,G as s,sn as t,At as u,ct as v,Ee as w,Ve as x,st as y,le as z};