llm-wiki-kit 0.2.8 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -86,11 +86,12 @@ Use Claude Code or Codex normally.
86
86
 
87
87
  The installed hooks:
88
88
 
89
- - inject functional compact context at session start, instructions loaded, prompt submit, and post-compact time. The hook still uses `wiki/memory.md`, `wiki/index.md`, relevant wiki search results, maintenance signals, and update status; it formats only the useful parts so user-visible hook context does not look like a raw debug dump.
89
+ - inject functional compact context at session start, instructions loaded, and prompt submit. The hook still uses `wiki/memory.md`, `wiki/index.md`, relevant wiki search results, maintenance signals, update status, and any compact recovery packet; it formats only the useful parts so user-visible hook context does not look like a raw debug dump.
90
90
  - remove Codex-facing legacy `oh-my-codex:wiki`/`omx_wiki` surfaces at session start so `llm-wiki/` remains the active wiki implementation
91
91
  - record small redacted raw event envelopes and per-turn state
92
92
  - capture decision points, debugging findings, changed files, and verification notes
93
93
  - before compaction, classify the current turn and save a redacted checkpoint for meaningful or durable work; durable candidates also get a maintenance queue item
94
+ - after compaction, store the redacted compact summary only; if pre-compact preservation failed, prepare a recovery packet for the next legal model-visible context hook
94
95
  - allow tool calls to proceed without secret/PII-based hook blocking
95
96
  - update `llm-wiki/outputs/questions/YYYY-MM-DD-live-qa.md` only for meaningful work turns
96
97
  - avoid automatic `wiki/queries/` and `wiki/decisions/` promotion in the default answer-first mode
@@ -101,7 +102,7 @@ The installed hooks:
101
102
 
102
103
  If you need to think about saving every answer manually, the setup has failed.
103
104
  If wiki maintenance delays the actual answer, the setup is being used wrong. The default capture mode is `LLM_WIKI_KIT_CAPTURE_MODE=answer-first`; the old eager query/decision capture path remains only as deprecated compatibility mode via `LLM_WIKI_KIT_CAPTURE_MODE=legacy-eager`.
104
- Pre-compact preservation uses `LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT=limited|soft|off` with default `limited`. It reads only a bounded transcript tail controlled by `LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES`; the raw transcript path and authentication values are redacted before any checkpoint is written.
105
+ Pre-compact preservation always lets compaction proceed. `LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT=off` suppresses failure warnings; `limited` and `soft` both emit a non-blocking warning if checkpoint storage fails. The hook reads only a bounded transcript tail controlled by `LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES`; the raw transcript path and authentication values are redacted before any checkpoint or recovery packet is written.
105
106
 
106
107
  ## Operational Commands
107
108
 
@@ -44,12 +44,12 @@ The hook records redacted turn summaries but does not deny tool calls only becau
44
44
 
45
45
  At `SessionStart`/`InstructionsLoaded`, the hook first attempts a safe managed-template refresh, recovers stale turn state into `outputs/maintenance/queue.md`, performs a cached npm update notice check for npm installs, then injects functional compact context. The context still uses `llm-wiki/wiki/memory.md`, `llm-wiki/wiki/index.md`, relevant wiki/search state, operating rules, maintenance signals, passive runtime update status, and managed-template cleanup notes; the hook formats those signals so they are usable if shown in the Claude Code UI. At `UserPromptSubmit`, it recovers stale turn state, searches wiki pages with MiniSearch or substring fallback, expands one-hop wikilinks, redacts context fields, performs the same cached update notice check, and injects the smallest useful functional compact context set. Update notice cache is scoped by npm command, and maintenance reminders are shown only when the prompt is wiki/maintenance related or matches a queue topic.
46
46
 
47
- `PostToolUse` and `PostToolBatch` record redacted tool summaries in the same turn buffer. `PreCompact` classifies the current turn before compaction: simple turns record only a context note, meaningful work writes a live Q&A checkpoint, and durable candidates write both a checkpoint and a maintenance queue item. The checkpoint can include only a bounded redacted transcript tail, never the full raw transcript or raw `transcript_path`. `PostCompact` stores the redacted compact summary as a context note and returns fresh wiki context. In the default `answer-first` mode, `SubagentStop` does not create live Q&A, query, decision, or maintenance files. `Stop` and `SessionEnd` append live Q&A only for meaningful work turns and do not auto-create `wiki/queries/` or `wiki/decisions/`. If the user explicitly asked to record or document durable knowledge and no durable wiki update is detected, `Stop`/`SessionEnd` queue a pending maintenance item for agent review. `Stop` and `SessionEnd` then clear the per-session turn buffer; `SubagentStop` does not.
47
+ `PostToolUse` and `PostToolBatch` record redacted tool summaries in the same turn buffer. `PreCompact` classifies the current turn before compaction: simple turns record only a context note, meaningful work writes a live Q&A checkpoint, and durable candidates write both a checkpoint and a maintenance queue item. The checkpoint can include only a bounded redacted transcript tail, never the full raw transcript or raw `transcript_path`. Compaction is not blocked; if checkpoint storage fails, the hook records a compact recovery packet for the next legal context-injection event. `PostCompact` stores the redacted compact summary as a context note and prepares any pending recovery packet without returning model-visible context directly. In the default `answer-first` mode, `SubagentStop` does not create live Q&A, query, decision, or maintenance files. `Stop` and `SessionEnd` append live Q&A only for meaningful work turns and do not auto-create `wiki/queries/` or `wiki/decisions/`. If the user explicitly asked to record or document durable knowledge and no durable wiki update is detected, `Stop`/`SessionEnd` queue a pending maintenance item for agent review. `Stop` and `SessionEnd` then clear the per-session turn buffer; `SubagentStop` does not.
48
48
 
49
49
  Set `LLM_WIKI_KIT_AUTO_PROJECT_UPDATE=0` only while diagnosing automatic managed-template refresh behavior.
50
50
  Set `LLM_WIKI_KIT_UPDATE_NOTICE=0` only while suppressing the cached passive runtime update status.
51
51
  Set `LLM_WIKI_KIT_CAPTURE_MODE=legacy-eager` only as deprecated compatibility mode for the old eager query/decision capture behavior.
52
- Set `LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT=limited|soft|off` to tune pre-compact failure handling; default `limited` blocks only when checkpoint/queue preservation fails on providers with block support. `LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES` controls the bounded tail size.
52
+ Set `LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT=off` to suppress pre-compact failure warnings; `limited` and `soft` both keep compaction moving and emit a non-blocking warning when checkpoint/queue preservation fails. `LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES` controls the bounded tail size.
53
53
 
54
54
  After installation or update, run:
55
55
 
@@ -33,8 +33,8 @@ Expected behavior:
33
33
  - `UserPromptSubmit` recovers stale turn state, searches project wiki pages with MiniSearch or substring fallback, expands one-hop wikilinks, redacts context fields, performs the same cached update notice check, and injects the smallest useful functional compact context set. Update notice cache is scoped by npm command, and maintenance reminders are shown only when the prompt is wiki/maintenance related or matches a queue topic.
34
34
  - `PreToolUse` records redacted tool summaries without blocking tool calls.
35
35
  - `PostToolUse` records redacted tool summaries in a turn buffer.
36
- - `PreCompact` classifies the current turn before compaction. Simple turns record only a context note; meaningful work writes a live Q&A checkpoint; durable candidates write both a checkpoint and a maintenance queue item. The checkpoint can include only a bounded redacted transcript tail, never the full raw transcript or raw `transcript_path`.
37
- - `PostCompact` stores the redacted compact summary as a context note and returns fresh wiki context.
36
+ - `PreCompact` classifies the current turn before compaction. Simple turns record only a context note; meaningful work writes a live Q&A checkpoint; durable candidates write both a checkpoint and a maintenance queue item. The checkpoint can include only a bounded redacted transcript tail, never the full raw transcript or raw `transcript_path`. Compaction is not blocked; if checkpoint storage fails, the hook records a compact recovery packet for the next legal context-injection event.
37
+ - `PostCompact` stores the redacted compact summary as a context note and prepares any pending compact recovery packet. It does not return `hookSpecificOutput.additionalContext`, because Codex `PostCompact` only supports common output fields.
38
38
  - In the default `answer-first` mode, `SubagentStop` does not create live Q&A, query, decision, or maintenance files. `Stop` appends live Q&A only for meaningful work turns and does not auto-create `wiki/queries/` or `wiki/decisions/`.
39
39
  - If the user explicitly asked to record or document durable knowledge and no durable wiki update is detected, `Stop` queues a pending maintenance item for agent review.
40
40
  - `Stop` clears the per-session turn buffer after recording. `SubagentStop` leaves the parent turn buffer available for the final stop event.
@@ -44,7 +44,7 @@ Hook payloads are stored as small redacted event envelopes rather than full tran
44
44
  Set `LLM_WIKI_KIT_AUTO_PROJECT_UPDATE=0` only while diagnosing automatic managed-template refresh behavior.
45
45
  Set `LLM_WIKI_KIT_UPDATE_NOTICE=0` only while suppressing the cached passive runtime update status.
46
46
  Set `LLM_WIKI_KIT_CAPTURE_MODE=legacy-eager` only as deprecated compatibility mode for the old eager query/decision capture behavior.
47
- Set `LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT=limited|soft|off` to tune pre-compact failure handling; default `limited` blocks only on supported providers when checkpoint/queue preservation fails. `LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES` controls the bounded tail size.
47
+ Set `LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT=off` to suppress pre-compact failure warnings; `limited` and `soft` both keep compaction moving and emit a non-blocking warning when checkpoint/queue preservation fails. `LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES` controls the bounded tail size.
48
48
 
49
49
  Run these after install:
50
50
 
package/docs/manual.md CHANGED
@@ -62,8 +62,8 @@ llm-wiki/
62
62
 
63
63
  설치된 hook은 다음 일을 자동으로 수행한다.
64
64
 
65
- - session start, prompt submit, post compact 시점에 functional compact context를 주입한다. `wiki/memory.md`, `wiki/index.md`, 관련 wiki 검색 결과, maintenance signal, update status 계속 사용하되 사용자 화면에 보일 수 있는 hook context는 필요한 정보 중심으로 정제한다.
66
- - pre compact 시점에는 현재 turn을 분류하고, simple turn은 context note만 남기며, meaningful/durable turn은 redacted live Q&A checkpoint와 필요한 maintenance queue 후보를 남긴다.
65
+ - session start, instructions loaded, prompt submit 시점에 functional compact context를 주입한다. `wiki/memory.md`, `wiki/index.md`, 관련 wiki 검색 결과, maintenance signal, update status, compact recovery packet은 계속 사용하되 사용자 화면에 보일 수 있는 hook context는 필요한 정보 중심으로 정제한다.
66
+ - pre compact 시점에는 현재 turn을 분류하고, simple turn은 context note만 남기며, meaningful/durable turn은 redacted live Q&A checkpoint와 필요한 maintenance queue 후보를 남긴다. 저장 실패 시에도 compact는 진행시키고, 중요한 내용만 recovery packet으로 준비한다.
67
67
  - prompt/tool/result summary를 redaction한 뒤 turn buffer에 기록한다.
68
68
  - 의미 있는 작업 turn만 `outputs/questions/YYYY-MM-DD-live-qa.md`에 live Q&A로 남긴다.
69
69
  - 기본 answer-first mode에서는 `wiki/queries/`와 `wiki/decisions/`를 매 turn 자동 생성하지 않는다.
@@ -387,9 +387,9 @@ Claude Code handled events:
387
387
 
388
388
  Hook payload는 full transcript가 아니라 작은 redacted event envelope다. context output도 field별 redaction을 거친다. `PreCompact`는 checkpoint 생성을 위해 작은 bounded transcript tail만 읽을 수 있고, 저장 전 인증값과 raw `transcript_path`를 redaction한다.
389
389
 
390
- Context를 반환하는 Codex/Claude hook event는 기능을 제거하지 않는다. memory hot index, navigation index, relevant wiki hits, link expansion, maintenance signal, passive runtime update status 계속 사용할 수 있고, 사용자 화면에 보일 수 있는 `additionalContext`만 functional compact context로 정제한다. `llm-wiki context` CLI의 full debug 출력은 이 hook formatting 정책과 별도로 유지한다.
390
+ Context를 반환하는 Codex/Claude hook event는 기능을 제거하지 않는다. memory hot index, navigation index, relevant wiki hits, link expansion, maintenance signal, passive runtime update status, compact recovery packet을 계속 사용할 수 있고, 사용자 화면에 보일 수 있는 `additionalContext`만 functional compact context로 정제한다. `PostCompact`는 compact summary 저장과 recovery packet 준비만 수행하고 model-visible context를 직접 반환하지 않는다. `llm-wiki context` CLI의 full debug 출력은 이 hook formatting 정책과 별도로 유지한다.
391
391
 
392
- Pre-compact 보존은 기본 `LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT=limited`로 동작한다. `limited`는 checkpoint/queue 저장 실패 시 block을 지원하는 provider에서만 compact block을 시도하고, 그 외에는 failure context를 남긴다. `soft`는 block하지 않고, `off`는 실패 output을 억제한다. `LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES`로 transcript tail byte 한도를 조정한다.
392
+ Pre-compact 보존은 compact를 block하지 않는다. `LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT=off`는 실패 warning을 억제하고, `limited`/`soft`는 checkpoint/queue 저장 실패 시 non-blocking warning만 남긴다. `LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES`로 transcript tail byte 한도를 조정한다.
393
393
 
394
394
  ## Security Defaults
395
395
 
@@ -143,9 +143,9 @@ After a plain `npm install -g llm-wiki-kit@latest`, existing hooks keep working
143
143
 
144
144
  Daily use should be Claude Code/Codex first. The user should not need to run a chain of `llm-wiki` commands while working. Hooks inject context automatically, but the current user answer takes priority over wiki cleanup. The active agent updates durable wiki pages when reusable project knowledge appears and the turn's importance or user consent justifies persistence. Hook context policy is function-first: memory, search, maintenance, and update signals remain available, while user-visible context is formatted as functional compact context instead of a raw dump.
145
145
 
146
- In the default `LLM_WIKI_KIT_CAPTURE_MODE=answer-first` mode, `Stop` and `SessionEnd` append live Q&A only for meaningful work turns. They do not auto-create `wiki/queries/` or `wiki/decisions/`. If the user explicitly asked for recording/documentation and no durable wiki update is detected, a pending cleanup candidate is written to `llm-wiki/outputs/maintenance/queue.md`. `PreCompact` performs the same answer-first classification before context compaction: simple turns get only a context note, archive-worthy turns get a live Q&A checkpoint, and durable candidates get a checkpoint plus queue item. `SessionStart` and `UserPromptSubmit` also recover stale per-turn state into the same queue when the previous stop hook did not complete. `SessionStart` injects a one-item queue summary; `UserPromptSubmit` injects a soft reminder only when the prompt is wiki/maintenance related or matches a queue topic. This is a recovery and reminder layer, not a full transcript capture path.
146
+ In the default `LLM_WIKI_KIT_CAPTURE_MODE=answer-first` mode, `Stop` and `SessionEnd` append live Q&A only for meaningful work turns. They do not auto-create `wiki/queries/` or `wiki/decisions/`. If the user explicitly asked for recording/documentation and no durable wiki update is detected, a pending cleanup candidate is written to `llm-wiki/outputs/maintenance/queue.md`. `PreCompact` performs the same answer-first classification before context compaction: simple turns get only a context note, archive-worthy turns get a live Q&A checkpoint, and durable candidates get a checkpoint plus queue item. If checkpoint storage fails, compaction still proceeds and the hook prepares an important-only compact recovery packet for the next legal context-injection event. `SessionStart` and `UserPromptSubmit` also recover stale per-turn state into the same queue when the previous stop hook did not complete. `SessionStart` injects a one-item queue summary; `UserPromptSubmit` injects a soft reminder only when the prompt is wiki/maintenance related or matches a queue topic. This is a recovery and reminder layer, not a full transcript capture path.
147
147
 
148
- Pre-compact preservation defaults to `LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT=limited`. In that mode, checkpoint/queue write failures can block compact only on providers that support hook blocking; otherwise the hook returns best-effort failure context. `soft` never blocks, and `off` suppresses failure output. `LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES` controls the small bounded transcript tail used for checkpoint context. Authentication values and the raw transcript path are redacted before storage.
148
+ Pre-compact preservation defaults to `LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT=limited`, but compaction is never blocked by llm-wiki-kit. `limited` and `soft` emit non-blocking failure warnings, and `off` suppresses failure output. `LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES` controls the small bounded transcript tail used for checkpoint context. Authentication values and the raw transcript path are redacted before storage.
149
149
 
150
150
  `LLM_WIKI_KIT_CAPTURE_MODE=legacy-eager` keeps the old eager live Q&A/query/decision/maintenance behavior for compatibility only. New projects should rely on the answer-first default.
151
151
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "llm-wiki-kit",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "description": "Hook-first living LLM Wiki runtime for Codex and Claude Code.",
5
5
  "type": "module",
6
6
  "files": [
@@ -4,26 +4,12 @@ import { classifyTurn } from './capture-policy.js';
4
4
  import { recordMaintenanceForEntry } from './maintenance.js';
5
5
  import { appendContextNote, appendLiveQa, appendWikiLog } from './project.js';
6
6
  import { redactText, summarizeForStorage } from './redaction.js';
7
- import { buildEntryFromState } from './state.js';
7
+ import { buildEntryFromState, clearCompactRecovery, readCompactRecovery, writeCompactRecovery } from './state.js';
8
8
 
9
9
  const DEFAULT_PRECOMPACT_TAIL_BYTES = 32 * 1024;
10
10
  const MAX_PRECOMPACT_TAIL_BYTES = 256 * 1024;
11
11
  const ENFORCEMENT_MODES = new Set(['limited', 'soft', 'off']);
12
12
 
13
- function contextOutput(eventName, context) {
14
- if (!context) return {};
15
- return {
16
- hookSpecificOutput: {
17
- hookEventName: eventName,
18
- additionalContext: context,
19
- },
20
- };
21
- }
22
-
23
- function providerSupportsBlock(provider) {
24
- return String(provider || '').toLowerCase() === 'claude';
25
- }
26
-
27
13
  export function preCompactEnforcementMode(env = process.env) {
28
14
  const value = String(env.LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT || 'limited').toLowerCase();
29
15
  return ENFORCEMENT_MODES.has(value) ? value : 'limited';
@@ -118,16 +104,77 @@ function entryWithTranscriptTail(entry, tail) {
118
104
  return next;
119
105
  }
120
106
 
121
- function failureOutput(provider, eventName, message, mode) {
107
+ function captured(value) {
108
+ const text = String(value || '').trim();
109
+ return text && text !== '(not captured)' ? text : '';
110
+ }
111
+
112
+ function sanitizeFailureText(projectRoot, value) {
113
+ let text = String(value || '');
114
+ if (projectRoot) text = text.split(projectRoot).join('[REDACTED:project-root]');
115
+ return summarizeForStorage(text, 1200);
116
+ }
117
+
118
+ function sanitizeFailures(projectRoot, failures) {
119
+ return failures.map((failure) => sanitizeFailureText(projectRoot, failure));
120
+ }
121
+
122
+ function formatRecoveryContext(recovery) {
123
+ const entry = recovery?.entry || {};
124
+ const lines = [
125
+ 'LLM Wiki compact recovery:',
126
+ '- PreCompact preservation could not finish before compaction. Use this fallback context only for important lost details.',
127
+ `- classification: ${recovery?.classification || 'unknown'}`,
128
+ ];
129
+ if (recovery?.postCompactSummary) {
130
+ lines.push(`- compact summary: ${summarizeForStorage(recovery.postCompactSummary, 600)}`);
131
+ }
132
+ if (recovery?.failures) {
133
+ lines.push(`- preservation failure: ${summarizeForStorage(recovery.failures, 600)}`);
134
+ }
135
+ const fields = [
136
+ ['question', 'question', 900],
137
+ ['work', 'work', 1200],
138
+ ['result', 'result', 1400],
139
+ ['changedFiles', 'changed files', 700],
140
+ ['verification', 'verification', 700],
141
+ ['followUp', 'follow-up', 700],
142
+ ];
143
+ for (const [key, label, limit] of fields) {
144
+ const value = captured(entry[key]);
145
+ if (value) lines.push(`\n${label}:\n${summarizeForStorage(value, limit)}`);
146
+ }
147
+ return summarizeForStorage(lines.join('\n'), 5000);
148
+ }
149
+
150
+ async function recordCompactRecoveryFailure(projectRoot, payload, entry, classification, failures) {
151
+ const recovery = {
152
+ created_at: new Date().toISOString(),
153
+ updated_at: new Date().toISOString(),
154
+ classification: classification.kind,
155
+ failures: summarizeForStorage(failures.join('; '), 1200),
156
+ entry: {
157
+ topic: summarizeForStorage(entry.topic, 300),
158
+ question: summarizeForStorage(entry.question, 1000),
159
+ work: summarizeForStorage(entry.work, 1600),
160
+ result: summarizeForStorage(entry.result, 1800),
161
+ changedFiles: summarizeForStorage(entry.changedFiles, 900),
162
+ verification: summarizeForStorage(entry.verification, 900),
163
+ followUp: summarizeForStorage(entry.followUp, 900),
164
+ firstTimestamp: entry.firstTimestamp,
165
+ session: entry.session,
166
+ },
167
+ };
168
+ recovery.context = formatRecoveryContext(recovery);
169
+ await writeCompactRecovery(projectRoot, payload, recovery);
170
+ }
171
+
172
+ function failureOutput(message, mode) {
122
173
  if (mode === 'off') return {};
123
174
  const reason = summarizeForStorage(message, 1200);
124
- if (mode === 'limited' && providerSupportsBlock(provider)) {
125
- return {
126
- decision: 'block',
127
- reason,
128
- };
129
- }
130
- return contextOutput(eventName, `LLM Wiki PreCompact preservation warning:\n${reason}`);
175
+ return {
176
+ systemMessage: `LLM Wiki PreCompact preservation warning: ${reason}`,
177
+ };
131
178
  }
132
179
 
133
180
  export async function handlePreCompactCapture(projectRoot, provider, eventName, payload) {
@@ -193,12 +240,16 @@ export async function handlePreCompactCapture(projectRoot, provider, eventName,
193
240
  }
194
241
 
195
242
  if (failures.length > 0) {
196
- return failureOutput(
197
- provider,
198
- eventName,
199
- `LLM Wiki PreCompact preservation did not complete. ${failures.join('; ')}`,
200
- mode
201
- );
243
+ let safeFailures = sanitizeFailures(projectRoot, failures);
244
+ if (classification.archive) {
245
+ try {
246
+ await recordCompactRecoveryFailure(projectRoot, payload, entry, classification, safeFailures);
247
+ } catch (error) {
248
+ failures.push(`compact recovery marker failed: ${error?.message || error}`);
249
+ safeFailures = sanitizeFailures(projectRoot, failures);
250
+ }
251
+ }
252
+ return failureOutput(`LLM Wiki PreCompact preservation did not complete. ${safeFailures.join('; ')}`, mode);
202
253
  }
203
254
 
204
255
  return {};
@@ -212,3 +263,30 @@ export async function recordPostCompactSummary(projectRoot, eventName, payload)
212
263
  summary ? `Compact summary:\n${redactText(summary, 4000)}` : 'Compact summary was not provided.'
213
264
  );
214
265
  }
266
+
267
+ export async function finalizeCompactRecovery(projectRoot, payload) {
268
+ const recovery = await readCompactRecovery(projectRoot, payload);
269
+ if (!recovery) return null;
270
+ const summary = compactSummaryText(payload);
271
+ const next = {
272
+ ...recovery,
273
+ updated_at: new Date().toISOString(),
274
+ postCompactSummary: summary || recovery.postCompactSummary || '',
275
+ ready: true,
276
+ };
277
+ next.context = formatRecoveryContext(next);
278
+ await writeCompactRecovery(projectRoot, payload, next);
279
+ await appendContextNote(
280
+ projectRoot,
281
+ 'PostCompact',
282
+ 'Prepared compact recovery packet for the next legal model-visible hook context.'
283
+ ).catch(() => {});
284
+ return next;
285
+ }
286
+
287
+ export async function consumeCompactRecoveryContext(projectRoot, payload) {
288
+ const recovery = await readCompactRecovery(projectRoot, payload);
289
+ if (!recovery) return '';
290
+ await clearCompactRecovery(projectRoot, payload);
291
+ return recovery.context || formatRecoveryContext(recovery);
292
+ }
package/src/hook.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { findProjectRoot } from './fs-utils.js';
2
2
  import { classifyTurn, formatDurableCaptureGuidance, hasDetectedDurableWikiChange, isLegacyEagerCaptureMode } from './capture-policy.js';
3
3
  import { bootstrapProject, appendLiveQa, appendSessionEnvelope, appendWikiLog, buildContextBrief, writeDecisionPage, writeQueryPage } from './project.js';
4
- import { compactSummaryText, handlePreCompactCapture, recordPostCompactSummary } from './compact-capture.js';
4
+ import { consumeCompactRecoveryContext, finalizeCompactRecovery, handlePreCompactCapture, recordPostCompactSummary } from './compact-capture.js';
5
5
  import { recoverStaleTurnStates, recordMaintenanceForEntry } from './maintenance.js';
6
6
  import { applyProjectTemplateUpdate, inspectProjectState } from './project-state.js';
7
7
  import { recordProject } from './projects.js';
@@ -35,8 +35,16 @@ function toolSummary(payload) {
35
35
  return `${toolName}: ${summarizeForStorage(input, 1200)}`;
36
36
  }
37
37
 
38
- function contextOutput(eventName, context) {
38
+ function supportsAdditionalContext(provider, eventName) {
39
+ const normalized = String(provider || '').toLowerCase();
40
+ if (normalized === 'codex') return ['SessionStart', 'UserPromptSubmit'].includes(eventName);
41
+ if (normalized === 'claude') return ['SessionStart', 'InstructionsLoaded', 'UserPromptSubmit'].includes(eventName);
42
+ return ['SessionStart', 'InstructionsLoaded', 'UserPromptSubmit'].includes(eventName);
43
+ }
44
+
45
+ function contextOutput(provider, eventName, context) {
39
46
  if (!context) return {};
47
+ if (!supportsAdditionalContext(provider, eventName)) return {};
40
48
  return {
41
49
  hookSpecificOutput: {
42
50
  hookEventName: eventName,
@@ -129,21 +137,30 @@ export async function handleHook(provider, explicitEvent) {
129
137
  }
130
138
 
131
139
  if (eventName === 'SessionStart' || eventName === 'InstructionsLoaded') {
132
- const context = await hookContext(projectRoot, eventName, await buildContextBrief(projectRoot, 'SessionStart'), payload);
133
- return contextOutput(eventName, context);
140
+ const recovery = supportsAdditionalContext(provider, eventName)
141
+ ? await consumeCompactRecoveryContext(projectRoot, payload).catch(() => '')
142
+ : '';
143
+ const context = await hookContext(
144
+ projectRoot,
145
+ eventName,
146
+ [recovery, await buildContextBrief(projectRoot, 'SessionStart')].filter(Boolean).join('\n\n'),
147
+ payload
148
+ );
149
+ return contextOutput(provider, eventName, context);
134
150
  }
135
151
 
136
152
  if (eventName === 'UserPromptSubmit') {
137
153
  const prompt = promptText(payload);
138
154
  await rememberQuestion(projectRoot, payload, prompt);
139
155
  const guidance = formatDurableCaptureGuidance(prompt);
156
+ const recovery = await consumeCompactRecoveryContext(projectRoot, payload).catch(() => '');
140
157
  const context = await hookContext(
141
158
  projectRoot,
142
159
  eventName,
143
- [await buildContextBrief(projectRoot, eventName, prompt), guidance].filter(Boolean).join('\n\n'),
160
+ [recovery, await buildContextBrief(projectRoot, eventName, prompt), guidance].filter(Boolean).join('\n\n'),
144
161
  payload
145
162
  );
146
- return contextOutput(eventName, context);
163
+ return contextOutput(provider, eventName, context);
147
164
  }
148
165
 
149
166
  if (eventName === 'PreToolUse') {
@@ -158,10 +175,9 @@ export async function handleHook(provider, explicitEvent) {
158
175
 
159
176
  if (eventName === 'PreCompact' || eventName === 'PostCompact') {
160
177
  if (eventName === 'PostCompact') {
161
- const summary = compactSummaryText(payload);
162
178
  await recordPostCompactSummary(projectRoot, eventName, payload);
163
- const context = await hookContext(projectRoot, eventName, await buildContextBrief(projectRoot, eventName, summary), payload);
164
- return contextOutput(eventName, context);
179
+ await finalizeCompactRecovery(projectRoot, payload).catch(() => {});
180
+ return {};
165
181
  }
166
182
  return handlePreCompactCapture(projectRoot, provider, eventName, payload);
167
183
  }
package/src/state.js CHANGED
@@ -38,6 +38,22 @@ export async function clearTurnState(projectRoot, payload) {
38
38
  await unlink(statePath(projectRoot, payload)).catch(() => {});
39
39
  }
40
40
 
41
+ export function compactRecoveryPath(projectRoot, payload) {
42
+ return join(kitDataDir(), 'compact-recovery', `${sessionKey(projectRoot, payload)}.json`);
43
+ }
44
+
45
+ export async function readCompactRecovery(projectRoot, payload) {
46
+ return readJson(compactRecoveryPath(projectRoot, payload), null);
47
+ }
48
+
49
+ export async function writeCompactRecovery(projectRoot, payload, recovery) {
50
+ await writeJson(compactRecoveryPath(projectRoot, payload), recovery);
51
+ }
52
+
53
+ export async function clearCompactRecovery(projectRoot, payload) {
54
+ await unlink(compactRecoveryPath(projectRoot, payload)).catch(() => {});
55
+ }
56
+
41
57
  export async function rememberQuestion(projectRoot, payload, prompt) {
42
58
  const state = await readTurnState(projectRoot, payload);
43
59
  const clean = summarizeForStorage(prompt, 3000);