@ngockhoale/ukit 3.5.1 → 3.5.2

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.
@@ -0,0 +1,274 @@
1
+ // Edit graph: compact per-file mirror/test/import edges, written next to the other
2
+ // index artifacts so an edit hook can read ONE small file instead of imports.json.
3
+ // Measured 218 ms graph step per one-file refresh on this repo; a per-file token cache was tried and gave no measurable total gain.
4
+ import fs from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+
8
+ export const EDIT_GRAPH_FILE = 'edit-graph.json';
9
+ const SCHEMA = 1;
10
+ const CAP = 5;
11
+ const MIN_TWIN = 200;
12
+ const MAX_HASH = 512 * 1024;
13
+ const MAX_LOAD = 2 * 1024 * 1024;
14
+ const CODE_EXT = new Set('js mjs cjs ts tsx jsx vue sh py go java cs php rb rs json yaml yml'.split(' '));
15
+ const GENERIC = new Set('index main utils types config constants helpers'.split(' '));
16
+
17
+ const norm = (p) => String(p ?? '').trim().replace(/\\/g, '/').replace(/^(\.\/)+/, '');
18
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
19
+ const extOf = (p) => path.posix.extname(p).slice(1).toLowerCase();
20
+ const uniq = (list) => [...new Set(list)];
21
+ const cap = (list) => uniq(list).sort(cmp).slice(0, CAP);
22
+ const pairKey = (a, b) => (a < b ? `${a}\0${b}` : `${b}\0${a}`);
23
+
24
+ // Real test file: test-looking path, never under fixtures/mocks.
25
+ export function isTestPath(p) {
26
+ const l = norm(p).toLowerCase();
27
+ if (/(^|\/)(fixtures|__fixtures__|__mocks__)\//.test(l)) return false;
28
+ return /(^|\/)(__tests__|tests?|specs?)\//.test(l) || /\.(test|spec)\.[cm]?[jt]sx?$|\.(test|spec)\.vue$/.test(l);
29
+ }
30
+
31
+ const SRC_RE = /\.([cm]?[jt]sx?|vue)$/;
32
+ export const isTestSource = (p) => isTestPath(p) && SRC_RE.test(norm(p));
33
+
34
+ export function stemOf(p) {
35
+ const base = path.posix.basename(p, path.posix.extname(p)).toLowerCase();
36
+ if (base === 'index') return path.posix.basename(path.posix.dirname(p)).toLowerCase();
37
+ return base.replace(/(?:\.test|\.spec)+$/, '').replace(/[-_.](test|spec)$/, '');
38
+ }
39
+
40
+ // One "mention" = a whole identifier/path-segment token equal to a source stem.
41
+ export function tokenCounts(content) {
42
+ const m = new Map();
43
+ for (const t of String(content).toLowerCase().match(/[a-z0-9_$][a-z0-9_$-]*/g) ?? []) m.set(t, (m.get(t) ?? 0) + 1);
44
+ return m;
45
+ }
46
+
47
+ // {testPath: count} for a non-generic source stem; tokens: Map<testPath, Map<token,count>>.
48
+ export function mentionCountsFor(source, tokens) {
49
+ const stem = stemOf(norm(source));
50
+ const out = {};
51
+ if (GENERIC.has(stem) || stem.length < 5) return out;
52
+ for (const [t, m] of tokens) if (m.has(stem)) out[t] = m.get(stem);
53
+ return out;
54
+ }
55
+
56
+ export function findTwinGroups(entries) {
57
+ const groups = new Map();
58
+ for (const e of entries ?? []) {
59
+ const p = norm(e?.path);
60
+ if (!p || !e.hash || !(e.size >= MIN_TWIN)) continue;
61
+ if (/(^|\/)(fixtures|__fixtures__)\//.test(p) || /(^|\/)docs\/archive\//.test(p)) continue;
62
+ const key = `${e.size}:${e.hash}`;
63
+ if (!groups.has(key)) groups.set(key, new Set());
64
+ groups.get(key).add(p);
65
+ }
66
+ const top = (p) => (p.includes('/') ? p.split('/')[0] : '.');
67
+ return [...groups.values()]
68
+ .map((set) => [...set].sort(cmp))
69
+ .filter((g) => g.length >= 2 && g.length <= 4
70
+ && (g.some((p) => CODE_EXT.has(extOf(p))) || new Set(g.map(top)).size >= 2))
71
+ .sort((a, b) => cmp(a[0], b[0]));
72
+ }
73
+
74
+ export function rankTestsForSource({ source, stemMatches = [], importingTests = [], mentionCounts = {} } = {}) {
75
+ const base = path.posix.basename(norm(source), path.posix.extname(norm(source))).toLowerCase();
76
+ const generic = GENERIC.has(base) || base.length < 5;
77
+ const count = (t) => Number((mentionCounts instanceof Map ? mentionCounts.get(t) : mentionCounts?.[t]) ?? 0);
78
+ const rows = new Map();
79
+ const add = (t, tier) => { if (!rows.has(t) || rows.get(t).tier > tier) rows.set(t, { t, tier }); };
80
+ for (const t of stemMatches) add(t, 0);
81
+ for (const t of importingTests) add(t, 1);
82
+ if (!generic) {
83
+ const names = mentionCounts instanceof Map ? [...mentionCounts.keys()] : Object.keys(mentionCounts ?? {});
84
+ for (const t of names) if (count(t) > 0) add(t, 2);
85
+ }
86
+ return [...rows.values()]
87
+ .sort((a, b) => a.tier - b.tier || (a.tier === 2 ? count(b.t) - count(a.t) : 0) || cmp(a.t, b.t))
88
+ .map((r) => r.t);
89
+ }
90
+
91
+ function cleanPair(raw) {
92
+ const clean = (v) => {
93
+ if (typeof v !== 'string') return null;
94
+ const p = norm(v);
95
+ if (!p || p.startsWith('/') || /^[a-zA-Z]:/.test(p) || p.split('/').includes('..')) return null;
96
+ return p;
97
+ };
98
+ const a = clean(raw?.source);
99
+ const b = clean(raw?.mirror);
100
+ return a && b && a !== b ? [a, b] : null;
101
+ }
102
+
103
+ async function readHints(root, readFile) {
104
+ try {
105
+ const cfg = JSON.parse(String(await readFile(path.join(root, '.ukit', 'storage', 'config.json'))));
106
+ const h = cfg?.memory?.editHints ?? {};
107
+ return {
108
+ mirrors: Array.isArray(h.mirrors) ? h.mirrors : [],
109
+ ignore: Array.isArray(h.ignoreMirrors) ? h.ignoreMirrors.filter((v) => typeof v === 'string').map(norm) : [],
110
+ };
111
+ } catch {
112
+ return { mirrors: [], ignore: [] };
113
+ }
114
+ }
115
+
116
+ async function pool(items, limit, worker, signal) {
117
+ let next = 0;
118
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
119
+ while (next < items.length && !signal?.aborted) await worker(items[next++]);
120
+ }));
121
+ }
122
+
123
+ export async function buildEditGraph({
124
+ rootDir, files = [], imports = [], declaredMirrors = [], previousGraph = null,
125
+ indexDigest = null, readFile = (p) => fs.readFile(p), signal = null,
126
+ } = {}) {
127
+ const root = path.resolve(rootDir ?? '.');
128
+ const hints = await readHints(root, readFile);
129
+ const ignored = new Set(hints.ignore);
130
+ const sizes = new Map();
131
+ for (const f of files) {
132
+ const p = norm(typeof f === 'string' ? f : f?.path ?? f?.filePath);
133
+ if (p) sizes.set(p, Number(f?.size ?? 0));
134
+ }
135
+
136
+ const bySize = new Map();
137
+ for (const [p, s] of sizes) {
138
+ if (s < MIN_TWIN || s > MAX_HASH) continue;
139
+ if (!bySize.has(s)) bySize.set(s, []);
140
+ bySize.get(s).push(p);
141
+ }
142
+ const candidates = [...bySize.values()].filter((l) => l.length > 1).flat().sort(cmp);
143
+ const entries = [];
144
+ await pool(candidates, 16, async (p) => {
145
+ try {
146
+ entries.push({ path: p, size: sizes.get(p), hash: crypto.createHash('sha256').update(await readFile(path.join(root, p))).digest('hex') });
147
+ } catch { /* unreadable: no twin evidence */ }
148
+ }, signal);
149
+ if (signal?.aborted) throw new Error('edit-graph build aborted');
150
+
151
+ const pairs = new Map();
152
+ const put = (a, b, k) => {
153
+ if (a === b || !sizes.has(a) || !sizes.has(b) || ignored.has(a) || ignored.has(b)) return;
154
+ const key = pairKey(a, b);
155
+ if (!pairs.has(key) || k === 'declared') pairs.set(key, k);
156
+ };
157
+ for (const g of findTwinGroups(entries)) {
158
+ for (let i = 0; i < g.length; i++) for (let j = i + 1; j < g.length; j++) put(g[i], g[j], 'twin');
159
+ }
160
+ for (const raw of [...declaredMirrors, ...hints.mirrors]) {
161
+ const pair = cleanPair(raw);
162
+ if (pair) put(pair[0], pair[1], 'declared');
163
+ }
164
+ for (const [p, v] of Object.entries(previousGraph?.files ?? {})) {
165
+ for (const m of Array.isArray(v?.m) ? v.m : []) {
166
+ if ((m?.k === 'twin' || m?.k === 'drifted') && typeof m.p === 'string' && !pairs.has(pairKey(p, m.p))) put(p, m.p, 'drifted');
167
+ }
168
+ }
169
+
170
+ const acc = new Map();
171
+ const slot = (p) => {
172
+ if (!acc.has(p)) acc.set(p, { m: [], t: [], i: new Set(), d: new Set() });
173
+ return acc.get(p);
174
+ };
175
+ for (const [key, k] of pairs) {
176
+ const [a, b] = key.split('\0');
177
+ slot(a).m.push({ p: b, k });
178
+ slot(b).m.push({ p: a, k });
179
+ }
180
+ const edges = imports instanceof Map
181
+ ? [...imports].flatMap(([from, tos]) => [...tos].map((to) => ({ from, to })))
182
+ : imports;
183
+ for (const e of edges) {
184
+ const from = norm(e?.from);
185
+ const to = norm(e?.to);
186
+ if (from && to && from !== to && sizes.has(from) && sizes.has(to)) {
187
+ slot(from).d.add(to);
188
+ slot(to).i.add(from);
189
+ }
190
+ }
191
+ // Tests per source: stem match, importing tests, then whole-token mentions
192
+ // (same evidence the history bench replays).
193
+ const testPaths = [...sizes.keys()].filter((p) => isTestSource(p) && sizes.get(p) <= MAX_HASH).sort(cmp);
194
+ const tokens = new Map();
195
+ await pool(testPaths, 16, async (p) => {
196
+ try { tokens.set(p, tokenCounts(await readFile(path.join(root, p)))); } catch { /* unreadable */ }
197
+ }, signal);
198
+ if (signal?.aborted) throw new Error('edit-graph build aborted');
199
+ const byStem = new Map();
200
+ for (const t of testPaths) byStem.set(stemOf(t), [...(byStem.get(stemOf(t)) ?? []), t]);
201
+ for (const src of [...sizes.keys()].sort(cmp)) {
202
+ if (isTestPath(src) || !SRC_RE.test(src)) continue;
203
+ const ranked = rankTestsForSource({
204
+ source: src,
205
+ stemMatches: byStem.get(stemOf(src)) ?? [],
206
+ importingTests: [...(acc.get(src)?.i ?? [])].filter(isTestPath),
207
+ mentionCounts: mentionCountsFor(src, tokens),
208
+ }).slice(0, CAP);
209
+ if (ranked.length) slot(src).t = ranked;
210
+ }
211
+
212
+ const out = {};
213
+ for (const p of [...acc.keys()].sort(cmp)) {
214
+ const s = acc.get(p);
215
+ const m = s.m.sort((x, y) => cmp(x.p, y.p) || cmp(x.k, y.k)).slice(0, CAP);
216
+ const entry = { m, t: s.t, i: cap([...s.i]), d: cap([...s.d]) };
217
+ if (m.length || entry.t.length || entry.i.length || entry.d.length) out[p] = entry;
218
+ }
219
+ return { schemaVersion: SCHEMA, generatedAt: new Date().toISOString(), indexDigest, files: out };
220
+ }
221
+
222
+ const graphPath = (rootDir) => path.join(path.resolve(rootDir), '.cache', 'index', EDIT_GRAPH_FILE);
223
+
224
+ export async function writeEditGraph(rootDir, graph) {
225
+ const target = graphPath(rootDir);
226
+ const tmp = `${target}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;
227
+ await fs.mkdir(path.dirname(target), { recursive: true });
228
+ try {
229
+ await fs.writeFile(tmp, JSON.stringify(graph));
230
+ await fs.rename(tmp, target);
231
+ } catch (error) {
232
+ await fs.rm(tmp, { force: true }).catch(() => {});
233
+ throw error;
234
+ }
235
+ }
236
+
237
+ export async function loadEditGraph(rootDir, { signal } = {}) {
238
+ try {
239
+ if (signal?.aborted) return null;
240
+ const file = graphPath(rootDir);
241
+ if ((await fs.stat(file)).size > MAX_LOAD) return null;
242
+ const graph = JSON.parse(await fs.readFile(file, { encoding: 'utf8', signal }));
243
+ const ok = graph && graph.schemaVersion === SCHEMA && graph.files && typeof graph.files === 'object' && !Array.isArray(graph.files);
244
+ return ok ? graph : null;
245
+ } catch {
246
+ return null;
247
+ }
248
+ }
249
+
250
+ export function neighboursOf(graph, filePath) {
251
+ const e = graph?.files && Object.hasOwn(graph.files, norm(filePath)) ? graph.files[norm(filePath)] : null;
252
+ const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : []);
253
+ return {
254
+ mirrors: (Array.isArray(e?.m) ? e.m : []).filter((x) => typeof x?.p === 'string').map((x) => ({ path: x.p, kind: x.k })),
255
+ tests: strs(e?.t),
256
+ importers: strs(e?.i),
257
+ imports: strs(e?.d),
258
+ };
259
+ }
260
+
261
+ // Index-build entry: rebuild only when the artifact is missing or its digest is
262
+ // stale. Never throws, so a graph failure cannot fail the index build.
263
+ // `inputs` may be a function so the (costly) import resolution runs only on rebuild.
264
+ export async function ensureEditGraph({ rootDir, indexDigest, inputs, signal } = {}) {
265
+ try {
266
+ const previousGraph = await loadEditGraph(rootDir);
267
+ if (previousGraph && indexDigest && previousGraph.indexDigest === indexDigest) return previousGraph;
268
+ const graph = await buildEditGraph({ rootDir, indexDigest, previousGraph, signal, ...(typeof inputs === 'function' ? await inputs() : inputs) });
269
+ await writeEditGraph(rootDir, graph);
270
+ return graph;
271
+ } catch {
272
+ return null;
273
+ }
274
+ }
@@ -4,6 +4,12 @@ import crypto from 'node:crypto';
4
4
  import { execFile, spawnSync } from 'node:child_process';
5
5
  import { withFileLock } from '../../runtime/token-utils.mjs';
6
6
  import { withAsyncLock } from '../../runtime/async-lock.mjs';
7
+ // edit-graph.mjs is optional: a partial install must not lose the whole index core.
8
+ let editGraphModule;
9
+ function loadEditGraphModule() {
10
+ editGraphModule ??= import('../edit-graph.mjs').catch(() => null);
11
+ return editGraphModule;
12
+ }
7
13
 
8
14
  // One wall-clock ceiling for the WHOLE discovery phase: both `git ls-files`
9
15
  // enumerations AND the non-git fallback walk share this single budget. Every
@@ -599,6 +605,7 @@ async function buildCodeIndexInner({ rootDir = process.cwd(), changedFiles = nul
599
605
  [INDEX_ARTIFACTS.relations]: relations.length,
600
606
  },
601
607
  });
608
+ await refreshEditGraph(absoluteRoot, sourceFingerprint.digest, fileRecords, codeFiles, imports, importAliasContext, signal);
602
609
 
603
610
  return {
604
611
  indexDir,
@@ -1192,6 +1199,7 @@ async function tryIncrementalIndexUpdate({ absoluteRoot, indexDir, changedPaths,
1192
1199
  clearIndexArtifactCache(absoluteRoot);
1193
1200
  RELATED_TEST_LOOKUP_CACHE.delete(absoluteRoot);
1194
1201
  }
1202
+ await refreshEditGraph(absoluteRoot, refreshedFingerprint.digest, mergedFileRecords, codeFiles, imports, importAliasContext, signal);
1195
1203
 
1196
1204
  return {
1197
1205
  indexDir,
@@ -3236,6 +3244,23 @@ function areBugIndexSnapshotsEqual(previousSnapshot, nextSnapshot) {
3236
3244
  && previousSnapshot.size === nextSnapshot.size;
3237
3245
  }
3238
3246
 
3247
+ // Edit graph (mirror/test/import edges): rebuilt only when missing or its digest
3248
+ // differs from the index fingerprint. Never fails the index build.
3249
+ async function refreshEditGraph(rootDir, indexDigest, fileRecords, codeFiles, imports, aliasContext, signal) {
3250
+ const graphModule = await loadEditGraphModule();
3251
+ if (!graphModule) return;
3252
+ await graphModule.ensureEditGraph({
3253
+ rootDir,
3254
+ indexDigest,
3255
+ signal,
3256
+ inputs: () => ({
3257
+ files: fileRecords,
3258
+ imports: buildResolvedImportMap(rootDir, imports, new Set(codeFiles.map((f) => f.filePath)), aliasContext),
3259
+ declaredMirrors: IMPACT_MIRROR_PAIRS,
3260
+ }),
3261
+ });
3262
+ }
3263
+
3239
3264
  async function writeArtifact(rootDir, artifactName, payload) {
3240
3265
  const artifactPath = getArtifactPath(rootDir, artifactName);
3241
3266
  const temporaryPath = `${artifactPath}.tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
@@ -5217,7 +5242,17 @@ export async function resolveImpactContext({
5217
5242
  const callItems = safeItems(callsArtifact);
5218
5243
  const importItems = safeItems(importsArtifact);
5219
5244
  const risk = classifyImpactRisk(normalizedChangedFiles);
5220
- const mirrorCounterparts = findMirrorCounterparts(normalizedChangedFiles).slice(0, budget.maxMirrors);
5245
+ const graphModule = await loadEditGraphModule();
5246
+ const editGraph = graphModule ? await graphModule.loadEditGraph(absoluteRoot) : null;
5247
+ const mirrorCounterparts = [...findMirrorCounterparts(normalizedChangedFiles)];
5248
+ for (const changed of normalizedChangedFiles) {
5249
+ for (const mirror of graphModule?.neighboursOf(editGraph, changed).mirrors ?? []) {
5250
+ if (!mirrorCounterparts.some((m) => m.filePath === mirror.path && m.source === changed)) {
5251
+ mirrorCounterparts.push({ filePath: mirror.path, reason: `edit-graph ${mirror.kind} mirror`, source: changed });
5252
+ }
5253
+ }
5254
+ }
5255
+ mirrorCounterparts.splice(budget.maxMirrors);
5221
5256
  const changedFileSet = new Set(normalizedChangedFiles);
5222
5257
  const changedSymbolSet = new Set(normalizedChangedSymbols);
5223
5258
  const changedRecords = callItems.filter((item) => {
@@ -239,14 +239,17 @@ async function main() {
239
239
  }
240
240
  const projectRoot = process.env.CLAUDE_PROJECT_DIR || process.cwd();
241
241
  const runtimeConfig = await readRuntimeSafePatchConfig(projectRoot);
242
- const result = await verifyPostEdit({
243
- projectRoot,
244
- payload: parseJsonInput(await readStdin(), {}),
245
- });
242
+ const payload = parseJsonInput(await readStdin(), {});
243
+ const result = await verifyPostEdit({ projectRoot, payload });
246
244
  if (json) {
247
245
  process.stdout.write(`${JSON.stringify(result)}\n`);
248
246
  } else if (result.status === 'ok') {
249
- process.stdout.write(`[ukit-safe-patch] ${result.message}\n`);
247
+ // A plain-text line would make the chain's merged stdout invalid JSON and Claude Code
248
+ // would drop a later step's additionalContext (edit-hint). omp's bridge appends step
249
+ // stdout verbatim to the tool result, so omp keeps the plain line.
250
+ const line = `[ukit-safe-patch] ${result.message}`;
251
+ if (payload?.ukit_harness === 'omp' || process.env.UKIT_HARNESS === 'omp') process.stdout.write(`${line}\n`);
252
+ else emitSystemMessage(line);
250
253
  } else if (result.status === 'advisory') {
251
254
  process.stderr.write(`[ukit-safe-patch] ${result.message}\n`);
252
255
  process.stderr.write('[ukit-safe-patch] handoff authoring advisory — change is already written; continue updating docs/AI_HANDOFF/.\n');
@@ -62,6 +62,7 @@ if (!intent && !targetFile) {
62
62
  }
63
63
 
64
64
  await printContextResult(result, { rootDir, showOutline });
65
+ if (targetFile) await printEditHint({ rootDir, targetFile, intent });
65
66
  }
66
67
 
67
68
  catch (error) {
@@ -69,6 +70,22 @@ catch (error) {
69
70
  process.exit(1);
70
71
  }
71
72
 
73
+ // Computed after (never inside) the result cache so memory edits are never stale.
74
+ async function printEditHint({ rootDir, targetFile, intent }) {
75
+ try {
76
+ const { editHintFor } = await import('../runtime/memory-lanes.mjs');
77
+ let target = targetFile;
78
+ if (path.isAbsolute(target)) {
79
+ target = path.relative(path.resolve(rootDir), target).split(path.sep).join('/');
80
+ if (!target || target.startsWith('..') || path.isAbsolute(target)) return; // outside the project: silent
81
+ }
82
+ const hint = await editHintFor({ projectRoot: rootDir, target, query: intent });
83
+ if (hint.text) console.log(hint.text);
84
+ } catch {
85
+ // Hints are advisory; never fail the helper.
86
+ }
87
+ }
88
+
72
89
  async function ensureFreshIndex({ rootDir, logPrefix }) {
73
90
  if (typeof indexCore.ensureIndexFresh === 'function') {
74
91
  return indexCore.ensureIndexFresh({ rootDir, logPrefix });
@@ -170,8 +170,29 @@ function splitTopLevelJsonObjects(text) {
170
170
 
171
171
  function coalesceJsonStdout(text) {
172
172
  if (typeof text !== 'string' || text.length === 0) return text;
173
- const docs = splitTopLevelJsonObjects(text);
174
- if (!docs || docs.length < 2) return text;
173
+ const split = splitTopLevelJsonObjects(text);
174
+ // Mixed stream: single-line JSON documents plus plain text lines. Only when every
175
+ // JSON line is PostToolUse context-only (and at least one exists) is the text folded
176
+ // into the document's additionalContext; anything else (deny + log line) stays byte-exact.
177
+ let plain = [];
178
+ let docs = split;
179
+ if (!split) {
180
+ docs = [];
181
+ for (const line of text.split('\n')) {
182
+ if (!line.trim()) continue;
183
+ let obj = null;
184
+ if (line.trimStart().startsWith('{')) { try { obj = JSON.parse(line); } catch { obj = null; } }
185
+ if (obj && typeof obj === 'object' && !Array.isArray(obj)) docs.push(obj); else plain.push(line.trim());
186
+ }
187
+ // A pretty-printed JSON fragment is not a log line: leave the stream untouched.
188
+ // Bracketed log prefixes such as "[ukit-safe-patch] OK" stay plain text.
189
+ if (plain.some((l) => /^[{}[\]],?$/.test(l) || l.startsWith('{') || /^"[^"]*"\s*(:|,?$)/.test(l))) return text;
190
+ const verdictFree = (d) => !('decision' in d) && d.continue !== false && !('stopReason' in d)
191
+ && (!d.hookSpecificOutput || (d.hookSpecificOutput.hookEventName === 'PostToolUse'
192
+ && !('permissionDecision' in d.hookSpecificOutput) && !('decision' in d.hookSpecificOutput)));
193
+ if (!plain.length || !docs.some((d) => d.hookSpecificOutput) || !docs.every(verdictFree)) return text;
194
+ }
195
+ if (!docs || (docs.length < 2 && !plain.length)) return text;
175
196
  const merged = {};
176
197
  const messages = [];
177
198
  for (const d of docs) {
@@ -180,12 +201,25 @@ function coalesceJsonStdout(text) {
180
201
  if (typeof value === 'string' && value) messages.push(value);
181
202
  continue;
182
203
  }
204
+ if (key === 'hookSpecificOutput' && value && typeof value === 'object' && merged.hookSpecificOutput
205
+ && typeof merged.hookSpecificOutput === 'object') {
206
+ // Two steps may each carry context: join with a newline, never let the later win.
207
+ const prev = merged.hookSpecificOutput;
208
+ const joined = [prev.additionalContext, value.additionalContext].filter((t) => typeof t === 'string' && t);
209
+ merged.hookSpecificOutput = { ...prev, ...value, ...(joined.length ? { additionalContext: joined.join('\n') } : {}) };
210
+ continue;
211
+ }
183
212
  if (key === 'continue' && merged.continue === false) continue;
184
213
  if (key === 'decision' && merged.decision === 'block') continue;
185
214
  if (key === 'reason' && merged.decision === 'block' && d.decision !== 'block') continue;
186
215
  merged[key] = value;
187
216
  }
188
217
  }
218
+ if (plain.length) {
219
+ // Plain lines are trimmed and placed before the documents' context (original order/indentation not preserved).
220
+ const h = merged.hookSpecificOutput;
221
+ h.additionalContext = [...plain, h.additionalContext].filter((t) => typeof t === 'string' && t).join('\n');
222
+ }
189
223
  if (messages.length) merged.systemMessage = messages.join('\n');
190
224
  return `${JSON.stringify(merged)}\n`;
191
225
  }
@@ -195,13 +229,37 @@ function coalesceJsonStdout(text) {
195
229
  // enough — a child killed mid-write can carry the marker in a truncated
196
230
  // capture, and calling that a decision would exempt a genuinely-skipped gate
197
231
  // from the fail-closed verdict. A real decision is a clean exit-0 verdict.
232
+ // WP-C: behaviour is exactly as at HEAD (any clean marker-carrying entry owns
233
+ // stdout) except for ONE shape: stdout whose every document parses and is a
234
+ // PostToolUse context-only `hookSpecificOutput` (additionalContext, no
235
+ // permissionDecision/decision). That is advisory context, not a verdict, and
236
+ // must merge with other steps' output instead of ending the chain.
237
+ function isPostToolUseContextOnly(stdout) {
238
+ const docs = typeof stdout === 'string' ? splitTopLevelJsonObjects(stdout) : null;
239
+ return Boolean(docs) && docs.length > 0 && docs.every((d) => {
240
+ const h = d?.hookSpecificOutput;
241
+ return h && typeof h === 'object' && h.hookEventName === 'PostToolUse'
242
+ && !('permissionDecision' in h) && !('decision' in h)
243
+ && !('decision' in d) && d.continue !== false && !('stopReason' in d);
244
+ });
245
+ }
246
+
198
247
  function emitsPermissionDecision(entry) {
199
248
  return Boolean(entry)
200
249
  && !entry.killed
201
250
  && entry.code === 0
202
251
  && entry.failureKind === 'ok'
203
252
  && typeof entry.stdout === 'string'
204
- && entry.stdout.includes('"hookSpecificOutput"');
253
+ && entry.stdout.includes('"hookSpecificOutput"')
254
+ && !isPostToolUseContextOnly(entry.stdout);
255
+ }
256
+
257
+ // Emit-time owner lookup: HEAD's loose marker lookup, skipping only a CLEAN
258
+ // PostToolUse context-only entry; unclean marker-carrying entries stay candidates.
259
+ function isDecisionOwnerCandidate(r) {
260
+ if (!r || typeof r.stdout !== 'string' || !r.stdout.includes('"hookSpecificOutput"')) return false;
261
+ const clean = !r.killed && r.code === 0 && r.failureKind === 'ok';
262
+ return !(clean && isPostToolUseContextOnly(r.stdout));
205
263
  }
206
264
 
207
265
  function recordTiming(projectRoot, payload, timing) {
@@ -786,8 +844,7 @@ try {
786
844
  // non-zero decision emitter stays routed through the code-2/fail-closed
787
845
  // paths below, per SPEC §FR-001); the strict predicate decides whether that
788
846
  // entry may claim stdout outright.
789
- const decisionResult = chain.results.find((r) =>
790
- typeof r.stdout === 'string' && r.stdout.includes('"hookSpecificOutput"'));
847
+ const decisionResult = chain.results.find(isDecisionOwnerCandidate);
791
848
  const decisionOwnsVerdict = emitsPermissionDecision(decisionResult);
792
849
  const last = decisionResult ?? chain.results[chain.results.length - 1];
793
850