llm-wiki-kit 0.2.7 → 0.2.8
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 +3 -0
- package/docs/integrations/claude-code.md +2 -1
- package/docs/integrations/codex.md +3 -1
- package/docs/manual.md +5 -1
- package/docs/operations.md +3 -1
- package/docs/security.md +1 -1
- package/docs/troubleshooting.md +1 -1
- package/package.json +1 -1
- package/src/compact-capture.js +214 -0
- package/src/hook.js +7 -4
- package/src/install.js +43 -10
package/README.md
CHANGED
|
@@ -90,6 +90,7 @@ The installed hooks:
|
|
|
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
|
+
- before compaction, classify the current turn and save a redacted checkpoint for meaningful or durable work; durable candidates also get a maintenance queue item
|
|
93
94
|
- allow tool calls to proceed without secret/PII-based hook blocking
|
|
94
95
|
- update `llm-wiki/outputs/questions/YYYY-MM-DD-live-qa.md` only for meaningful work turns
|
|
95
96
|
- avoid automatic `wiki/queries/` and `wiki/decisions/` promotion in the default answer-first mode
|
|
@@ -100,6 +101,7 @@ The installed hooks:
|
|
|
100
101
|
|
|
101
102
|
If you need to think about saving every answer manually, the setup has failed.
|
|
102
103
|
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.
|
|
103
105
|
|
|
104
106
|
## Operational Commands
|
|
105
107
|
|
|
@@ -171,6 +173,7 @@ llm-wiki hook claude Stop
|
|
|
171
173
|
## Security Defaults
|
|
172
174
|
|
|
173
175
|
- Full raw transcript capture is disabled by default.
|
|
176
|
+
- PreCompact may read a small bounded transcript tail to create a redacted checkpoint, but it does not store the full transcript or raw `transcript_path`.
|
|
174
177
|
- Tool calls are not blocked only because inputs look sensitive.
|
|
175
178
|
- Authentication values such as tokens, passwords, and private keys are redacted before durable summaries are written.
|
|
176
179
|
- Hook payloads are stored only as redacted event envelopes.
|
|
@@ -44,11 +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`
|
|
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.
|
|
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
53
|
|
|
53
54
|
After installation or update, run:
|
|
54
55
|
|
|
@@ -33,7 +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`
|
|
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.
|
|
37
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/`.
|
|
38
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.
|
|
39
40
|
- `Stop` clears the per-session turn buffer after recording. `SubagentStop` leaves the parent turn buffer available for the final stop event.
|
|
@@ -43,6 +44,7 @@ Hook payloads are stored as small redacted event envelopes rather than full tran
|
|
|
43
44
|
Set `LLM_WIKI_KIT_AUTO_PROJECT_UPDATE=0` only while diagnosing automatic managed-template refresh behavior.
|
|
44
45
|
Set `LLM_WIKI_KIT_UPDATE_NOTICE=0` only while suppressing the cached passive runtime update status.
|
|
45
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.
|
|
46
48
|
|
|
47
49
|
Run these after install:
|
|
48
50
|
|
package/docs/manual.md
CHANGED
|
@@ -63,6 +63,7 @@ llm-wiki/
|
|
|
63
63
|
설치된 hook은 다음 일을 자동으로 수행한다.
|
|
64
64
|
|
|
65
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 후보를 남긴다.
|
|
66
67
|
- prompt/tool/result summary를 redaction한 뒤 turn buffer에 기록한다.
|
|
67
68
|
- 의미 있는 작업 turn만 `outputs/questions/YYYY-MM-DD-live-qa.md`에 live Q&A로 남긴다.
|
|
68
69
|
- 기본 answer-first mode에서는 `wiki/queries/`와 `wiki/decisions/`를 매 turn 자동 생성하지 않는다.
|
|
@@ -384,10 +385,12 @@ Claude Code handled events:
|
|
|
384
385
|
- `Stop`
|
|
385
386
|
- `SessionEnd`
|
|
386
387
|
|
|
387
|
-
Hook payload는 full transcript가 아니라 작은 redacted event envelope다. context output도 field별 redaction을 거친다.
|
|
388
|
+
Hook payload는 full transcript가 아니라 작은 redacted event envelope다. context output도 field별 redaction을 거친다. `PreCompact`는 checkpoint 생성을 위해 작은 bounded transcript tail만 읽을 수 있고, 저장 전 인증값과 raw `transcript_path`를 redaction한다.
|
|
388
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
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 한도를 조정한다.
|
|
393
|
+
|
|
391
394
|
## Security Defaults
|
|
392
395
|
|
|
393
396
|
기본 정책은 aggressive blocking보다 useful local work wiki를 우선한다.
|
|
@@ -396,6 +399,7 @@ Context를 반환하는 Codex/Claude hook event는 기능을 제거하지 않는
|
|
|
396
399
|
- token, password, bearer credential, private key, `.env` 원문 같은 authentication value는 durable summary에 쓰기 전 redaction한다.
|
|
397
400
|
- phone number, email, date, business identifier는 local work context로 유용할 수 있어 기본 보존한다.
|
|
398
401
|
- full raw transcript capture는 기본 기능이 아니다.
|
|
402
|
+
- `PreCompact` checkpoint는 bounded redacted transcript tail만 사용할 수 있으며 full transcript와 raw `transcript_path`는 저장하지 않는다.
|
|
399
403
|
- `llm-wiki lint`는 wiki 안의 secret-like content를 error로 보고한다.
|
|
400
404
|
|
|
401
405
|
민감한 raw command output, log, screenshot, transcript를 저장해야 할 때는 먼저 redaction한다. 인증값은 wiki, report, live Q&A, command history에 남기지 않는다.
|
package/docs/operations.md
CHANGED
|
@@ -143,7 +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`. `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. `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
|
+
|
|
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.
|
|
147
149
|
|
|
148
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.
|
|
149
151
|
|
package/docs/security.md
CHANGED
|
@@ -13,4 +13,4 @@ Before writing durable summaries, the runtime redacts authentication values such
|
|
|
13
13
|
|
|
14
14
|
Manual and hook context output also runs through redaction before returning excerpts or search hits. `llm-wiki lint` reports remaining secret-like wiki content as an error so it can be removed or rewritten before it becomes reusable project memory.
|
|
15
15
|
|
|
16
|
-
Hook payloads are stored as small event envelopes, not full raw transcripts. Full transcript capture is intentionally not implemented as a default. If a project needs
|
|
16
|
+
Hook payloads are stored as small event envelopes, not full raw transcripts. Full transcript capture is intentionally not implemented as a default. `PreCompact` may read a small bounded transcript tail for a redacted checkpoint, but it does not store the raw transcript path or full transcript. If a project needs raw transcript capture, add a project-local policy and a redaction path first.
|
package/docs/troubleshooting.md
CHANGED
|
@@ -242,7 +242,7 @@ If the queue is always empty during ordinary Q&A, that is normal. If you expecte
|
|
|
242
242
|
|
|
243
243
|
The hook does not block tool calls only because inputs look sensitive. Durable summaries redact authentication values before writing, while ordinary work context such as dates, phone numbers, emails, and business identifiers is preserved by default.
|
|
244
244
|
|
|
245
|
-
Hook payloads are stored as small redacted event envelopes rather than full transcripts. Manual and hook context output is redacted before wiki excerpts or search hits are returned.
|
|
245
|
+
Hook payloads are stored as small redacted event envelopes rather than full transcripts. `PreCompact` checkpoints may include a bounded redacted transcript tail, but the full transcript and raw `transcript_path` are not stored. Manual and hook context output is redacted before wiki excerpts or search hits are returned.
|
|
246
246
|
|
|
247
247
|
## Duplicate Pages Appear
|
|
248
248
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { open, stat } from 'fs/promises';
|
|
2
|
+
import { relative } from 'path';
|
|
3
|
+
import { classifyTurn } from './capture-policy.js';
|
|
4
|
+
import { recordMaintenanceForEntry } from './maintenance.js';
|
|
5
|
+
import { appendContextNote, appendLiveQa, appendWikiLog } from './project.js';
|
|
6
|
+
import { redactText, summarizeForStorage } from './redaction.js';
|
|
7
|
+
import { buildEntryFromState } from './state.js';
|
|
8
|
+
|
|
9
|
+
const DEFAULT_PRECOMPACT_TAIL_BYTES = 32 * 1024;
|
|
10
|
+
const MAX_PRECOMPACT_TAIL_BYTES = 256 * 1024;
|
|
11
|
+
const ENFORCEMENT_MODES = new Set(['limited', 'soft', 'off']);
|
|
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
|
+
export function preCompactEnforcementMode(env = process.env) {
|
|
28
|
+
const value = String(env.LLM_WIKI_KIT_PRECOMPACT_ENFORCEMENT || 'limited').toLowerCase();
|
|
29
|
+
return ENFORCEMENT_MODES.has(value) ? value : 'limited';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function preCompactTranscriptTailBytes(env = process.env) {
|
|
33
|
+
const raw = env.LLM_WIKI_KIT_PRECOMPACT_TRANSCRIPT_TAIL_BYTES;
|
|
34
|
+
if (raw === undefined || raw === '') return DEFAULT_PRECOMPACT_TAIL_BYTES;
|
|
35
|
+
const parsed = Number(raw);
|
|
36
|
+
if (!Number.isFinite(parsed) || parsed < 0) return DEFAULT_PRECOMPACT_TAIL_BYTES;
|
|
37
|
+
return Math.min(Math.floor(parsed), MAX_PRECOMPACT_TAIL_BYTES);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function compactSummaryText(payload) {
|
|
41
|
+
return summarizeForStorage(
|
|
42
|
+
payload.compact_summary ||
|
|
43
|
+
payload.compactSummary ||
|
|
44
|
+
payload.summary ||
|
|
45
|
+
payload.message ||
|
|
46
|
+
'',
|
|
47
|
+
4000
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function transcriptPath(payload) {
|
|
52
|
+
return payload.transcript_path || payload.transcriptPath || '';
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function redactTranscriptPath(text, path) {
|
|
56
|
+
let output = String(text || '');
|
|
57
|
+
if (path) output = output.split(path).join('[REDACTED:transcript-path]');
|
|
58
|
+
output = output.replace(/("transcript_path"\s*:\s*)"[^"]*"/gi, '$1"[REDACTED:transcript-path]"');
|
|
59
|
+
output = output.replace(/('transcript_path'\s*:\s*)'[^']*'/gi, "$1'[REDACTED:transcript-path]'");
|
|
60
|
+
output = output.replace(/\btranscript_path\s*=\s*[^\s"'`]+/gi, 'transcript_path=[REDACTED:transcript-path]');
|
|
61
|
+
return output;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function readTranscriptTail(path, maxBytes) {
|
|
65
|
+
if (!path) return { ok: false, reason: 'missing-transcript-path', text: '' };
|
|
66
|
+
if (maxBytes <= 0) return { ok: false, reason: 'transcript-tail-disabled', text: '' };
|
|
67
|
+
|
|
68
|
+
let handle = null;
|
|
69
|
+
try {
|
|
70
|
+
const info = await stat(path);
|
|
71
|
+
if (!info.isFile()) return { ok: false, reason: 'transcript-not-file', text: '' };
|
|
72
|
+
const length = Math.min(info.size, maxBytes);
|
|
73
|
+
const start = Math.max(0, info.size - length);
|
|
74
|
+
const buffer = Buffer.alloc(length);
|
|
75
|
+
handle = await open(path, 'r');
|
|
76
|
+
await handle.read(buffer, 0, length, start);
|
|
77
|
+
const text = summarizeForStorage(redactTranscriptPath(buffer.toString('utf8'), path), 4000);
|
|
78
|
+
return {
|
|
79
|
+
ok: true,
|
|
80
|
+
text,
|
|
81
|
+
bytesRead: length,
|
|
82
|
+
truncated: info.size > maxBytes,
|
|
83
|
+
};
|
|
84
|
+
} catch (error) {
|
|
85
|
+
return {
|
|
86
|
+
ok: false,
|
|
87
|
+
reason: summarizeForStorage(error?.code || error?.message || 'read-failed', 200),
|
|
88
|
+
text: '',
|
|
89
|
+
};
|
|
90
|
+
} finally {
|
|
91
|
+
await handle?.close().catch(() => {});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function appendToField(current, addition) {
|
|
96
|
+
const existing = String(current || '').trim();
|
|
97
|
+
if (!existing || existing === '(not captured)') return addition;
|
|
98
|
+
return `${existing}\n${addition}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function entryWithTranscriptTail(entry, tail) {
|
|
102
|
+
const next = { ...entry };
|
|
103
|
+
if (tail.ok && tail.text) {
|
|
104
|
+
const marker = tail.truncated
|
|
105
|
+
? 'PreCompact transcript tail (redacted bounded excerpt; earlier transcript omitted):'
|
|
106
|
+
: 'PreCompact transcript tail (redacted bounded excerpt):';
|
|
107
|
+
next.result = appendToField(next.result, `${marker}\n${tail.text}`);
|
|
108
|
+
next.followUp = appendToField(
|
|
109
|
+
next.followUp,
|
|
110
|
+
'Compact checkpoint includes only a bounded redacted transcript tail, not the raw transcript path or full transcript.'
|
|
111
|
+
);
|
|
112
|
+
} else if (tail.reason && tail.reason !== 'missing-transcript-path') {
|
|
113
|
+
next.followUp = appendToField(
|
|
114
|
+
next.followUp,
|
|
115
|
+
`Transcript tail unavailable during PreCompact (${tail.reason}); checkpoint used turn state only.`
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
return next;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function failureOutput(provider, eventName, message, mode) {
|
|
122
|
+
if (mode === 'off') return {};
|
|
123
|
+
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}`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function handlePreCompactCapture(projectRoot, provider, eventName, payload) {
|
|
134
|
+
const mode = preCompactEnforcementMode();
|
|
135
|
+
const failures = [];
|
|
136
|
+
const tail = await readTranscriptTail(transcriptPath(payload), preCompactTranscriptTailBytes());
|
|
137
|
+
const stateEntry = await buildEntryFromState(projectRoot, payload, payload.last_assistant_message || payload.response || '');
|
|
138
|
+
const entry = entryWithTranscriptTail(stateEntry, tail);
|
|
139
|
+
const classification = classifyTurn(entry, eventName);
|
|
140
|
+
|
|
141
|
+
await appendContextNote(
|
|
142
|
+
projectRoot,
|
|
143
|
+
eventName,
|
|
144
|
+
[
|
|
145
|
+
`PreCompact classification: ${classification.kind}.`,
|
|
146
|
+
tail.ok ? `Transcript tail bytes read: ${tail.bytesRead}.` : `Transcript tail: ${tail.reason || 'not available'}.`,
|
|
147
|
+
'Turn state is intentionally kept for the later Stop/SessionEnd hook.',
|
|
148
|
+
].join('\n')
|
|
149
|
+
).catch((error) => {
|
|
150
|
+
failures.push(`context note failed: ${error?.message || error}`);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
let liveQaPath = null;
|
|
154
|
+
if (classification.archive) {
|
|
155
|
+
const checkpointEntry = {
|
|
156
|
+
...entry,
|
|
157
|
+
followUp: appendToField(
|
|
158
|
+
entry.followUp,
|
|
159
|
+
classification.suggestDurable
|
|
160
|
+
? 'PreCompact saved this checkpoint and queued durable wiki review; merge reusable facts into existing wiki pages after the current answer.'
|
|
161
|
+
: 'PreCompact saved this checkpoint before context compaction; reusable facts should be merged only when appropriate.'
|
|
162
|
+
),
|
|
163
|
+
};
|
|
164
|
+
try {
|
|
165
|
+
liveQaPath = await appendLiveQa(projectRoot, checkpointEntry);
|
|
166
|
+
} catch (error) {
|
|
167
|
+
failures.push(`live Q&A checkpoint failed: ${error?.message || error}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (liveQaPath && ['suggest-durable', 'explicit-durable'].includes(classification.kind)) {
|
|
172
|
+
try {
|
|
173
|
+
const result = await recordMaintenanceForEntry(projectRoot, entry, {
|
|
174
|
+
source: liveQaPath,
|
|
175
|
+
eventName,
|
|
176
|
+
reason: 'PreCompact durable candidate checkpoint needs review after context compaction.',
|
|
177
|
+
});
|
|
178
|
+
if (result.created === false && result.reason) {
|
|
179
|
+
failures.push(`maintenance queue failed: ${result.reason}`);
|
|
180
|
+
}
|
|
181
|
+
} catch (error) {
|
|
182
|
+
failures.push(`maintenance queue failed: ${error?.message || error}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (liveQaPath) {
|
|
187
|
+
await appendWikiLog(
|
|
188
|
+
projectRoot,
|
|
189
|
+
`precompact checkpoint; archive=${relative(projectRoot, liveQaPath)}; classification=${classification.kind}`
|
|
190
|
+
).catch((error) => {
|
|
191
|
+
failures.push(`wiki log failed: ${error?.message || error}`);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (failures.length > 0) {
|
|
196
|
+
return failureOutput(
|
|
197
|
+
provider,
|
|
198
|
+
eventName,
|
|
199
|
+
`LLM Wiki PreCompact preservation did not complete. ${failures.join('; ')}`,
|
|
200
|
+
mode
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return {};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export async function recordPostCompactSummary(projectRoot, eventName, payload) {
|
|
208
|
+
const summary = compactSummaryText(payload);
|
|
209
|
+
await appendContextNote(
|
|
210
|
+
projectRoot,
|
|
211
|
+
eventName,
|
|
212
|
+
summary ? `Compact summary:\n${redactText(summary, 4000)}` : 'Compact summary was not provided.'
|
|
213
|
+
);
|
|
214
|
+
}
|
package/src/hook.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { findProjectRoot } from './fs-utils.js';
|
|
2
2
|
import { classifyTurn, formatDurableCaptureGuidance, hasDetectedDurableWikiChange, isLegacyEagerCaptureMode } from './capture-policy.js';
|
|
3
|
-
import { bootstrapProject,
|
|
3
|
+
import { bootstrapProject, appendLiveQa, appendSessionEnvelope, appendWikiLog, buildContextBrief, writeDecisionPage, writeQueryPage } from './project.js';
|
|
4
|
+
import { compactSummaryText, handlePreCompactCapture, recordPostCompactSummary } from './compact-capture.js';
|
|
4
5
|
import { recoverStaleTurnStates, recordMaintenanceForEntry } from './maintenance.js';
|
|
5
6
|
import { applyProjectTemplateUpdate, inspectProjectState } from './project-state.js';
|
|
6
7
|
import { recordProject } from './projects.js';
|
|
@@ -156,11 +157,13 @@ export async function handleHook(provider, explicitEvent) {
|
|
|
156
157
|
}
|
|
157
158
|
|
|
158
159
|
if (eventName === 'PreCompact' || eventName === 'PostCompact') {
|
|
159
|
-
await appendContextNote(projectRoot, eventName, 'Compaction lifecycle event captured by llm-wiki-kit.');
|
|
160
160
|
if (eventName === 'PostCompact') {
|
|
161
|
-
|
|
161
|
+
const summary = compactSummaryText(payload);
|
|
162
|
+
await recordPostCompactSummary(projectRoot, eventName, payload);
|
|
163
|
+
const context = await hookContext(projectRoot, eventName, await buildContextBrief(projectRoot, eventName, summary), payload);
|
|
164
|
+
return contextOutput(eventName, context);
|
|
162
165
|
}
|
|
163
|
-
return
|
|
166
|
+
return handlePreCompactCapture(projectRoot, provider, eventName, payload);
|
|
164
167
|
}
|
|
165
168
|
|
|
166
169
|
if (eventName === 'Stop' || eventName === 'SubagentStop' || eventName === 'SessionEnd') {
|
package/src/install.js
CHANGED
|
@@ -19,6 +19,8 @@ import { bootstrapProject } from './project.js';
|
|
|
19
19
|
import { recordProject } from './projects.js';
|
|
20
20
|
import { binPath, detectInstallSource, packageRoot, runtimeVersion } from './version.js';
|
|
21
21
|
|
|
22
|
+
const SESSION_START_MATCHER = 'startup|resume|clear|compact';
|
|
23
|
+
|
|
22
24
|
export function hookCommand(provider, eventName, options = {}) {
|
|
23
25
|
return commandForNodeScript(binPath, ['hook', provider, eventName], options);
|
|
24
26
|
}
|
|
@@ -125,11 +127,23 @@ async function reconcileWindowsCommand() {
|
|
|
125
127
|
|
|
126
128
|
function addHook(hooks, eventName, command, options = {}) {
|
|
127
129
|
hooks[eventName] = Array.isArray(hooks[eventName]) ? hooks[eventName] : [];
|
|
128
|
-
const
|
|
130
|
+
const existing = hooks[eventName].find((entry) => (
|
|
129
131
|
Array.isArray(entry?.hooks) &&
|
|
130
132
|
entry.hooks.some((hook) => hook?.type === 'command' && hook?.command === command)
|
|
131
133
|
));
|
|
132
|
-
if (
|
|
134
|
+
if (existing) {
|
|
135
|
+
let changed = false;
|
|
136
|
+
if (options.matcher && existing.matcher !== options.matcher) {
|
|
137
|
+
existing.matcher = options.matcher;
|
|
138
|
+
changed = true;
|
|
139
|
+
}
|
|
140
|
+
const hook = existing.hooks.find((item) => item?.type === 'command' && item?.command === command);
|
|
141
|
+
if (hook && options.commandWindows && hook.commandWindows !== options.commandWindows) {
|
|
142
|
+
hook.commandWindows = options.commandWindows;
|
|
143
|
+
changed = true;
|
|
144
|
+
}
|
|
145
|
+
return changed;
|
|
146
|
+
}
|
|
133
147
|
const entry = {
|
|
134
148
|
hooks: [
|
|
135
149
|
{
|
|
@@ -186,12 +200,21 @@ function unsupportedKitClaudeEvents(hooks, supportedEvents) {
|
|
|
186
200
|
.sort();
|
|
187
201
|
}
|
|
188
202
|
|
|
189
|
-
function
|
|
190
|
-
return
|
|
203
|
+
function expectedMatcher(eventName) {
|
|
204
|
+
return eventName === 'SessionStart' ? SESSION_START_MATCHER : undefined;
|
|
191
205
|
}
|
|
192
206
|
|
|
193
|
-
function
|
|
194
|
-
return
|
|
207
|
+
function hookCommandMatches(hook, command) {
|
|
208
|
+
return hook?.command === command || hook?.commandWindows === command;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function hookEventIsCurrent(entries, eventName, command) {
|
|
212
|
+
const matcher = expectedMatcher(eventName);
|
|
213
|
+
return Array.isArray(entries) && entries.some((entry) => (
|
|
214
|
+
(!matcher || entry.matcher === matcher) &&
|
|
215
|
+
Array.isArray(entry?.hooks) &&
|
|
216
|
+
entry.hooks.some((hook) => hook?.type === 'command' && hookCommandMatches(hook, command))
|
|
217
|
+
));
|
|
195
218
|
}
|
|
196
219
|
|
|
197
220
|
export async function install(options = {}) {
|
|
@@ -221,7 +244,7 @@ export async function install(options = {}) {
|
|
|
221
244
|
changed.push('codex:replaced');
|
|
222
245
|
}
|
|
223
246
|
for (const eventName of CODEX_EVENTS) {
|
|
224
|
-
const matcher = eventName
|
|
247
|
+
const matcher = expectedMatcher(eventName);
|
|
225
248
|
const command = hookCommand('codex', eventName, { platform });
|
|
226
249
|
const commandWindows = isWindows({ platform }) ? hookCommand('codex', eventName, { platform: 'win32' }) : undefined;
|
|
227
250
|
if (addHook(codex.hooks, eventName, command, { matcher, commandWindows })) {
|
|
@@ -251,7 +274,7 @@ export async function install(options = {}) {
|
|
|
251
274
|
changed.push(...removedUnsupported.map((eventName) => `claude:removed-unsupported:${eventName}`));
|
|
252
275
|
}
|
|
253
276
|
for (const eventName of claudeEvents) {
|
|
254
|
-
const matcher = eventName
|
|
277
|
+
const matcher = expectedMatcher(eventName);
|
|
255
278
|
if (addHook(claude.hooks, eventName, hookCommand('claude', eventName, { platform }), { matcher })) {
|
|
256
279
|
claudeChanged = true;
|
|
257
280
|
changed.push(`claude:${eventName}`);
|
|
@@ -312,9 +335,18 @@ export async function status(options = {}) {
|
|
|
312
335
|
const claude = await readJson(claudeSettingsPath, {});
|
|
313
336
|
const claudeDetection = detectClaudeVersion();
|
|
314
337
|
const claudeEvents = supportedClaudeEvents(claudeDetection);
|
|
315
|
-
const
|
|
338
|
+
const codexMissingEvents = CODEX_EVENTS.filter((eventName) => !hookEventIsCurrent(
|
|
339
|
+
codex.hooks?.[eventName] || [],
|
|
340
|
+
eventName,
|
|
341
|
+
hookCommand('codex', eventName, { platform })
|
|
342
|
+
));
|
|
343
|
+
const claudeMissingEvents = claudeEvents.filter((eventName) => !hookEventIsCurrent(
|
|
344
|
+
claude.hooks?.[eventName] || [],
|
|
345
|
+
eventName,
|
|
346
|
+
hookCommand('claude', eventName, { platform })
|
|
347
|
+
));
|
|
316
348
|
const claudeUnsupportedKitEvents = unsupportedKitClaudeEvents(claude.hooks || {}, claudeEvents);
|
|
317
|
-
const codexInstalled =
|
|
349
|
+
const codexInstalled = codexMissingEvents.length === 0;
|
|
318
350
|
const claudeInstalled = claudeMissingEvents.length === 0 && claudeUnsupportedKitEvents.length === 0;
|
|
319
351
|
const discoveredCommandPaths = await findCommandPaths('llm-wiki', { platform });
|
|
320
352
|
const commandPath = discoveredCommandPaths[0] || null;
|
|
@@ -344,6 +376,7 @@ export async function status(options = {}) {
|
|
|
344
376
|
claudeVersion: claudeDetection.version || 'unknown',
|
|
345
377
|
claudeModernHooks: claudeDetection.modern,
|
|
346
378
|
claudeSupportedEvents: claudeEvents,
|
|
379
|
+
codexMissingEvents,
|
|
347
380
|
claudeMissingEvents,
|
|
348
381
|
claudeUnsupportedKitEvents,
|
|
349
382
|
hooksCurrent: codexInstalled && claudeInstalled,
|