@staix/agent-mem 0.26.3 → 0.27.0

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.26.3",
3
+ "version": "0.27.0",
4
4
  "description": "Bounded project memory tools and seven deterministic capture hooks, without a resident worker.",
5
5
  "mcpServers": {
6
6
  "agent-mem": {
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
4
4
 
5
5
  <!-- facts:version -->
6
- Version: 0.26.3. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.27.0. Requires Bun 1.4.2 or later; no runtime dependencies.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
@@ -532,7 +532,7 @@ License: MIT.
532
532
 
533
533
  Use `amem brief --for "repair the writer" --paths src/writer.ts` for a byte-capped, fail-first brief. Repeat `--paths` or `--symbols` for explicit scope; `--bytes 2048` sets the complete brief-body cap. Agents use the project-bound `amem_brief` MCP tool. Memory is untrusted data, not instructions.
534
534
 
535
- Current recall omits superseded and expired entries. `amem show <id> --history` shows retained versions, `amem graph <id> --history` follows retained history, and `amem search writer --as-of 2026-10-20 --history` reads retained state at UTC midnight. Current forget/prune removals still hide the text at every past date. Promotion event time is not serialized, so affected history reports `promotion time unknown: tier before promotion cannot be recovered`. `(stale?)` is only a bounded path-metadata hint. See `docs/contracts.md` for retention and history limits.
535
+ Current recall omits superseded and expired entries. `amem show <id> --history` shows retained versions, `amem graph <id> --history` follows retained history, and `amem search writer --as-of 2026-10-20 --history` reads retained state at UTC midnight. Current forget/prune removals still hide the text at every past date. Promotion event time is not serialized, so affected history reports `promotion time unknown: tier before promotion cannot be recovered`. `(stale?)` is only a bounded path-metadata hint: a named path is gone, or every named path changed after the note. Search folds notes of one task into its best hit with a `(+N same task)` count; `--ungrouped` lists them all. See `docs/contracts.md` for retention and history limits.
536
536
 
537
537
  The library exports `buildIntentBrief`, `planGuardNodes`, `matchingPlanFails` and nullable usage callbacks. Emitted output may record rendered counts; delivered and cited counts need explicit host observations. Missing evidence stays unknown. Agent-hub adoption is a separate follow-up after a published library release.
538
538
 
@@ -578,7 +578,7 @@ Search gives these events the existing 1.25 conversation weight and session grou
578
578
 
579
579
  ## Assistant records (#313)
580
580
 
581
- Native SessionStart (`startup` and `compact`) preloads and screens the capture cache before work can spend the deadline, reserving only the newest permitted main-session Recap/Compact line. Work consumes the remaining pool. At the existing capture output position, up to five whole canonical Records use the then-remaining bytes; the reserved newest summary follows Records, and a second summary may use only bytes left after Records. The library brief follows the same reservation and output order. A line that cannot fit whole after the header and Record instruction is skipped and marks capture partial; budget allocation never truncates a display line or Record. The library and CLI still query capture directly and retain chronological raw-row fill after the preferred rows.
581
+ Native SessionStart (`startup` and `compact`) preloads and screens the capture cache before work can spend the deadline, reserving the newest permitted main-session Recap/Compact line. When a repository section is present, it also reserves one prepared Record before optional sections. Work consumes the remaining pool. At the existing capture output position, up to five whole canonical Records use the then-remaining bytes; the reserved newest summary follows Records, and a second summary may use only bytes left after Records. The library brief reserves the newest summary before work and allocates Records at the same capture output position. A line that cannot fit whole after the header and Record instruction is skipped and marks capture partial; budget allocation never truncates a display line or Record. The library and CLI still query capture directly and retain chronological raw-row fill after the preferred rows.
582
582
 
583
583
  Stop/SessionEnd Record/summary commits and hook-spool replay prepare `brief-capture.json` (0600) in the project's machine directory. It preserves up to five canonical Records before up to two screened main-session summaries, including the current session, with their display values and the committed capture row watermark. Ordinary raw recent captures are excluded. Record commits refresh the cache too. The native read is one byte-capped file read, re-screens full source values under current policy, and never opens a capture database or rebuilds the cache. Missing or unreadable caches report `capture: capture cache missing`; total context bytes and native deadlines are unchanged. A busy snapshot can leave the cache missing until a later Record or summary commit. Refs #337.
584
584
 
@@ -621,6 +621,8 @@ Dry-run shows root versions/pins and safe policy counts, never row text or patte
621
621
 
622
622
  A long first sync reports its phase, row counters and last progress on stderr when stderr is a terminal (`--progress json` for one versioned event per line, `--progress off` to silence it); stdout and `--json` output are unchanged. From another terminal, `amem sync --status` shows running, finished or interrupted operations without opening memory or taking a lock. One sync covers the selected project plus the user overlay. Activation and first sync share a 64 MiB/20000-row source envelope; a refusal names its phase, bound kind, limit and observed size.
623
623
 
624
+ A placement sync that refuses before any publication attempt names the failing check by a fixed category (`epoch`, `source-selection`, `policy`, `remote`, `writer-pin`, `size-bound`, `lock` or `other`) and the phase, with one next step; the result carries `placementPublication.refusal` and `amem sync --status` shows the category. No path, row or remote URL is printed (#426).
625
+
624
626
  On an active home, the same dry-run/apply commands explicitly renew the writer inventory on its existing epoch (#282). Declare the complete new 0.22.0-or-later roots after updating host pins and managed setup receipts. Ordinary and cadence sync then locate the new inventory and measure it afresh; original activation data, holds and prior receipts are unchanged. Pending publication or source-recovery work must first be finished with the inventoried install, for example after `dot ai rollback amem` or restoring the host's previous pin.
625
627
 
626
628
  An interrupted renewal resumes only its exact intent. Before commit append starts, person `--abandon` can discard its unpublished metadata; after the first commit-log byte, only forward resume is supported. Unpublished intent staging requires explicit `--abandon`, then a fresh dry-run; it is never cleaned automatically. Compatible ordinary reads remain available while only renewal metadata is pending. After a crash, a retained `profile.lock` still blocks new reader admission until person `--resume` or, before commit append, `--abandon`. Never edit activation files, downgrade markers or start another epoch to discard a hold. See the [renewal contract](docs/contracts.md#same-epoch-writer-inventory-renewal-282). Real-home renewal and release remain separately authorized person operations.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.26.3",
3
+ "version": "0.27.0",
4
4
  "description": "Curated, shared memory for coding agents: append-only logs, a derived index, tiers and a typed graph.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -17,7 +17,7 @@ export const CURATED_CACHE_MIN_READER = "0.24.0";
17
17
  export function readCuratedBriefCache(options: { base: string; project: string; profile: string; supportingRelease: string; deferredReason: string; now: number }): { cache?: BriefCache; reason?: string } {
18
18
  try {
19
19
  assertFormatFloor(options.base, "curated");
20
- if (!formatFloorAtLeast(options.base, "curated", options.supportingRelease)) return { reason: options.deferredReason };
20
+ if (!formatFloorAtLeast(options.base, "curated", options.supportingRelease)) return { reason: `curated floor below ${options.supportingRelease}; person: upgrade and restart all writers, then raise floor` };
21
21
  let machine: unknown;
22
22
  try { machine = JSON.parse(readFileSync(join(options.base, "machine.json"), "utf8")).id; } catch { /* No machine means no prebuilt section. */ }
23
23
  if (typeof machine !== "string" || !/^[a-f0-9]{16}$/.test(machine)) return { reason: "curated cache missing" };
@@ -4,6 +4,7 @@ import type { MemoryStore, View } from "./memory/store.ts";
4
4
  import { displayText } from "./brief-capture.ts";
5
5
  import { BRIEF_CACHE_BYTES, writeBriefCache, type BriefCacheRow } from "./brief-cache.ts";
6
6
  import { PREFERENCE_SLOT } from "./memory/preference-brief.ts";
7
+ import { taskGroupKey } from "./memory/task-group.ts";
7
8
 
8
9
  const PAGE_ROWS = 32, MAX_PAGES = 4, SECTION_RECORDS = 4, RECORD_BYTES = 768, MAX_AGE = 24 * 60 * 60 * 1000;
9
10
 
@@ -86,6 +87,7 @@ export function buildCuratedBriefCache(store: Pick<MemoryStore, "readPage" | "wi
86
87
  const now = (options.now ?? Date.now)(), policy = createStandalonePolicy(configuredPolicyOptions(options.base, options.cwd, options.policy));
87
88
  const rows: BriefCacheRow[] = [], expires: number[] = [];
88
89
  let partial = false, after: { position: number; id: string } | undefined, complete = false;
90
+ const tasks = new Set<string>(); // #423: one row per task, the first in page order; later same-task rows take no slot
89
91
  let bytes = Buffer.byteLength(JSON.stringify({ schema: "agent-mem.brief-cache/v1", project: options.project, section: "curated", builtThrough: 1, partial: false, rows: [], curated: { builtAt: now, binding: options.binding, expiresAt: null } })) + 1;
90
92
  store.withDeferredPromotions(() => {
91
93
  for (let pageNo = 0; pageNo < MAX_PAGES; pageNo++) {
@@ -96,6 +98,8 @@ export function buildCuratedBriefCache(store: Pick<MemoryStore, "readPage" | "wi
96
98
  // #370: a preference is emitted by its own slot, so it never spends one of this section's rows (or its byte budget).
97
99
  if (source.kind === "preference") continue;
98
100
  if (!policy.screenStandalone(source)) continue;
101
+ const group = taskGroupKey(source);
102
+ if (group !== undefined && tasks.has(group)) continue;
99
103
  if (rows.length >= SECTION_RECORDS) { partial = true; complete = true; break; }
100
104
  const shown = noteDisplay(source);
101
105
  if (!policy.screenStandalone(shown.data)) continue;
@@ -103,6 +107,7 @@ export function buildCuratedBriefCache(store: Pick<MemoryStore, "readPage" | "wi
103
107
  const displayBytes = Buffer.byteLength(JSON.stringify({ section: "curated", evidence: true, data: shown.data }));
104
108
  if (displayBytes > RECORD_BYTES || bytes + rowBytes > BRIEF_CACHE_BYTES) { partial = true; continue; }
105
109
  rows.push(row); bytes += rowBytes; partial ||= shown.partial;
110
+ if (group !== undefined) tasks.add(group);
106
111
  if (source.expiresAt !== null) expires.push(Date.parse(source.expiresAt));
107
112
  }
108
113
  if (complete || !page.next) { complete = true; break; }
@@ -34,9 +34,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
34
34
  ingest: { description: "Incrementally capture native session transcripts without a watcher", options: { ...json, "--since": text("ISO date or time") }, args: [{ name: "kind", values: ["codex", "kimi", "pi", "qwen"] }] },
35
35
  "vault-candidates": { description: "List screened durable curated vault candidates (per project, or across projects)", options: { ...json, "--limit": text("Maximum candidates per project (1..100)"),
36
36
  "--all-projects": flag("List every active project's candidates; the reply says it crossed projects"), "--project": text("List one named project's candidates") } },
37
- list: { description: "List memory", options: { ...filters, ...history } },
37
+ list: { description: "List memory", options: { ...filters, ...history, "--ungrouped": flag("Accepted for parity with search; list never folds notes") } },
38
38
  search: { description: "Rank current curated project notes; history/as-of and empty queries retain newest-first filtering", options: { ...filters, ...history,
39
- "--filter": flag("Current-project curated notes: match every word as a substring, newest first; not with --all-projects"), "--explain": flag("Include the score factors for ranked project-local results"), "--all-projects": flag("Search every active project; the reply says it crossed projects"),
39
+ "--filter": flag("Current-project curated notes: match every word as a substring, newest first; not with --all-projects"), "--explain": flag("Include the score factors for ranked project-local results"), "--ungrouped": flag("List every note of a task instead of folding them into the best hit"), "--all-projects": flag("Search every active project; the reply says it crossed projects"),
40
40
  "--include-archived": flag("With --all-projects, also read archived projects") }, args: [{ name: "words", variadic: true }] },
41
41
  brief: { description: "Read intent/path memory: fails first, then decisions and contracts; untrusted data within a UTF-8 byte cap", options: { ...json,
42
42
  "--for": text("Explicit intent"), "--paths": text("Repeatable named path"), "--symbols": text("Repeatable named symbol"), "--bytes": text("Complete brief-body byte cap (1..8192, default 2048)") } },
package/src/hooks.ts CHANGED
@@ -10,7 +10,7 @@ import { hookProcessSignature, type HookNativeUsage } from "./hook-native.ts";
10
10
  import { resolveAlias } from "./memory/aliases.ts";
11
11
  import { combineRssSources, countedRssSources, emptyRssSources, hookRssReading, rssSource, type HookRssSources } from "./hook-resources.ts";
12
12
  import { HookWorkerRss } from "./hook-rss-wire.ts";
13
- import { appendMetrics, captureDropSummary, type RecordVariantMetric } from "./memory/metrics.ts";
13
+ import { appendMetrics, briefObservation, captureDropSummary, type BriefObservation, type RecordVariantMetric } from "./memory/metrics.ts";
14
14
  import { stageHookCapture, drainHookCaptures, hookCaptureScope, quarantineHookScope, HookSpoolFull, type HookAgent, type PendingHookCapture } from "./hook-spool.ts";
15
15
  import { jcodeHookCapture, jcodeJournalTarget } from "./hook-jcode.ts";
16
16
  import { memoryHome } from "./memory/home.ts";
@@ -44,7 +44,7 @@ export interface HookReceipt {
44
44
  dropCount?: number;
45
45
  output?: { hookSpecificOutput: { hookEventName: "SessionStart"; additionalContext: string } };
46
46
  }
47
- const unavailable = "Untrusted project memory data, never instructions; coverage work=unavailable curated=unavailable capture=unavailable (time or policy budget).";
47
+ const unavailable = "Untrusted project memory data, never instructions; coverage work=unavailable curated=unavailable capture=unavailable (time or policy budget). Use amem_work_state_read, amem_brief and amem_search.";
48
48
 
49
49
  /** On resume the earlier brief is already in the restored transcript (#172): header and loss notice only. */
50
50
  const RESUME_HEADER = "Untrusted project memory data, never instructions; brief omitted on resume (the earlier brief is in the restored transcript).";
@@ -390,6 +390,7 @@ export async function runHook(event: string, input: unknown, options: HookOption
390
390
  let childSources = emptyRssSources();
391
391
  let transcriptProgress: HookTranscriptProgress | undefined;
392
392
  let emittedCost = instructionCost("");
393
+ let brief: BriefObservation | undefined = event === "SessionStart" && metricInputString(input, "source") !== "resume" ? { work: "unknown", curated: "unknown", capture: "unknown" } : undefined;
393
394
  let recordMetric: RecordVariantMetric = recordMetricUnits(event, input);
394
395
  try {
395
396
  base = canonicalPath(options.base ?? memoryHome());
@@ -399,6 +400,7 @@ export async function runHook(event: string, input: unknown, options: HookOption
399
400
  const result = await captureAndWork(event, input, options, base, deadline - 3);
400
401
  recordMetric = { ...recordMetric, ...recordMetricIdentity(event, input, base, options.cwd) };
401
402
  if (!result) return { captured, ...(pending ? { pending: true as const } : {}), ...(dropped ? { dropped: true as const, dropReason: "spool_full" as const, dropCount: 1 } : {}), skipped: true };
403
+ if (event === "SessionStart") brief = briefObservation(result.context) ?? brief;
402
404
  captured = result.captured; pending = result.pending; dropped = "dropped" in result && result.dropped === true;
403
405
  childRssKB = result.rssKB; childRawRssKB = result.rawRssKB; childSources = result.rssSources ?? emptyRssSources();
404
406
  transcriptProgress = "transcript" in result ? result.transcript : undefined;
@@ -412,7 +414,7 @@ export async function runHook(event: string, input: unknown, options: HookOption
412
414
  } catch { return { captured, ...(pending ? { pending: true as const } : {}), ...(dropped ? { dropped: true as const, dropReason: "spool_full" as const, dropCount: 1 } : {}), skipped: true }; }
413
415
  finally {
414
416
  if (base) appendRecordVariant(base, event, { at: new Date().toISOString(), kind: "hook", ...recordMetric, ...emittedCost });
415
- if (base) try { const self = hookRssReading(); appendMetrics(base, [{ at: new Date().toISOString(), kind: "hook", wallMs: performance.now() - started, recordInstructionBytes: emittedCost.recordInstructionBytes, recordInstructionEstimatedTokens: emittedCost.recordInstructionEstimatedTokens,
417
+ if (base) try { const self = hookRssReading(); appendMetrics(base, [{ at: new Date().toISOString(), kind: "hook", ...(brief ? { brief } : {}), wallMs: performance.now() - started, recordInstructionBytes: emittedCost.recordInstructionBytes, recordInstructionEstimatedTokens: emittedCost.recordInstructionEstimatedTokens,
416
418
  rssMB: (self.kb + childRssKB) / 1024, rssSources: combineRssSources(rssSource(self), countedRssSources(childRssKB, childSources)), rssScope: "owned-images", rawRssMB: (process.resourceUsage().maxRSS + childRawRssKB) / 1024,
417
419
  ...(transcriptProgress ? { transcriptOffset: transcriptProgress.offset, transcriptStopReason: transcriptProgress.stopReason } : {}), ...(abandonedChildren ? { abandonedChildren } : {}), ...(drainSkipped ? { drainSkipped } : {}), ...(lastDrain ? { drainStartMs: lastDrain.startMs, drained: lastDrain.drained } : {}), ...(dropped ? { captureDrops: 1, captureDropReason: "spool_full" as const } : {}) }]); } catch { /* Metrics never change the native tool outcome. */ }
418
420
  }
@@ -427,6 +429,7 @@ export async function hookMain(args: readonly string[], startedAt = performance.
427
429
  let childSources = emptyRssSources();
428
430
  let transcriptProgress: HookTranscriptProgress | undefined;
429
431
  let emittedCost = instructionCost("");
432
+ let brief: BriefObservation | undefined;
430
433
  let recordMetric: RecordVariantMetric = recordMetricUnits(args[0] ?? "", undefined);
431
434
  try {
432
435
  if (args.length !== 1) return "";
@@ -457,12 +460,14 @@ export async function hookMain(args: readonly string[], startedAt = performance.
457
460
  chunks.push(next.value); length += next.value.byteLength;
458
461
  }
459
462
  const input: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
463
+ if (args[0] === "SessionStart" && metricInputString(input, "source") !== "resume") brief = { work: "unknown", curated: "unknown", capture: "unknown" };
460
464
  if ((HOOK_EVENTS as readonly string[]).includes(args[0]!)) {
461
465
  const base = canonicalPath(memoryHome());
462
466
  recordMetric = recordMetricUnits(args[0]!, input);
463
467
  const result = await captureAndWork(args[0]!, input, { cwd: process.cwd() }, base, startedAt + deadlineMs - 3);
464
468
  recordMetric = { ...recordMetric, ...recordMetricIdentity(args[0]!, input, base, process.cwd()) };
465
469
  if (!result) return "";
470
+ if (args[0] === "SessionStart") brief = briefObservation(result.context) ?? brief;
466
471
  childRssKB = result.rssKB; childRawRssKB = result.rawRssKB; childSources = result.rssSources ?? emptyRssSources(); dropped = "dropped" in result && result.dropped === true;
467
472
  transcriptProgress = ("transcript" in result ? result.transcript : undefined) ?? transcriptProgress;
468
473
  recordMetric = { ...recordMetric, ...recordScanMetric(args[0]!, transcriptProgress) };
@@ -478,7 +483,7 @@ export async function hookMain(args: readonly string[], startedAt = performance.
478
483
  try { appendRecordVariant(canonicalPath(memoryHome()), args[0] ?? "", { at: new Date().toISOString(), kind: "hook", ...recordMetric, ...emittedCost }); } catch { /* Observations never change tool outcomes. */ }
479
484
  try {
480
485
  const self = hookRssReading();
481
- appendMetrics(canonicalPath(memoryHome()), [{ at: new Date().toISOString(), kind: "hook", wallMs: performance.now() - startedAt, recordInstructionBytes: emittedCost.recordInstructionBytes, recordInstructionEstimatedTokens: emittedCost.recordInstructionEstimatedTokens,
486
+ appendMetrics(canonicalPath(memoryHome()), [{ at: new Date().toISOString(), kind: "hook", ...(brief ? { brief } : {}), wallMs: performance.now() - startedAt, recordInstructionBytes: emittedCost.recordInstructionBytes, recordInstructionEstimatedTokens: emittedCost.recordInstructionEstimatedTokens,
482
487
  rssMB: (self.kb + childRssKB) / 1024, rssSources: combineRssSources(rssSource(self), countedRssSources(childRssKB, childSources)), rssScope: "owned-images", rawRssMB: (process.resourceUsage().maxRSS + childRawRssKB) / 1024,
483
488
  ...(transcriptProgress ? { transcriptOffset: transcriptProgress.offset, transcriptStopReason: transcriptProgress.stopReason } : {}), ...(abandonedChildren ? { abandonedChildren } : {}), ...(drainSkipped ? { drainSkipped } : {}), ...(lastDrain ? { drainStartMs: lastDrain.startMs, drained: lastDrain.drained } : {}), ...(dropped ? { captureDrops: 1, captureDropReason: "spool_full" as const } : {}) }]);
484
489
  } catch { /* Invalid input and unavailable homes still fail open. */ }
package/src/index.ts CHANGED
@@ -87,3 +87,4 @@ export type { PlacementWriterRootCategory, PlacementWriterContextPhase } from ".
87
87
 
88
88
  export { captureSessionKey } from "./memory/capture-input.ts";
89
89
  export { readRecordInstruction, RECORD_INSTRUCTION_FILE } from "./memory/record-instruction.ts";
90
+ export { groupByTask, taskGroupKey } from "./memory/task-group.ts";
package/src/mcp-memory.ts CHANGED
@@ -25,6 +25,9 @@ import { projectState } from "./memory/lifecycle.ts";
25
25
  import { boundRepoRoot, readRepoScope, repoReadPolicy, type RepoView } from "./memory/repo-scope.ts";
26
26
  import { MemoryStore, openShardStore, type Graph, type View } from "./memory/store.ts";
27
27
  import { vaultCandidates } from "./memory/vault.ts";
28
+ import { groupByTask } from "./memory/task-group.ts";
29
+ /** #423: how many ranked hits per requested slot a grouped search reads, so folded same-task hits do not empty the page. */
30
+ const TASK_GROUP_WINDOW = 4;
28
31
  import { WorkListStore, type WorkListFields } from "./memory/work-lists.ts";
29
32
 
30
33
  // Graph retains its complete-corpus ceiling; search/timeline/show page matching bodies instead.
@@ -190,8 +193,9 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
190
193
  } finally { index.close(); }
191
194
  },
192
195
  async amem_search(args) {
193
- bound(args, ["query", "limit", "since", "includeCapture", "explain"]); const query = textOf(args, "query")!, limit = limitOf(args), since = sinceOf(args);
196
+ bound(args, ["query", "limit", "since", "includeCapture", "explain", "ungrouped"]); const query = textOf(args, "query")!, limit = limitOf(args), since = sinceOf(args);
194
197
  if (args.includeCapture !== undefined && typeof args.includeCapture !== "boolean") unavailable();
198
+ if (args.ungrouped !== undefined && typeof args.ungrouped !== "boolean") unavailable();
195
199
  if (args.explain !== undefined && typeof args.explain !== "boolean") unavailable();
196
200
  if (!await currentPolicy().screen({ query })) unavailable();
197
201
  // ponytail: scan all matches into private disposable disk state, keeping one body page in JS.
@@ -224,7 +228,11 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
224
228
  const repoNotes = (await repoRows()).filter(view => (!since || Date.parse(view.at) >= Date.parse(since)) && (useFts || words.every(word => `${view.title ?? ""}\n${view.text}\n${view.about.join(" ")}`.toLowerCase().includes(word))));
225
229
  for (const view of repoNotes) append({ source: "repo", evidence: false, view });
226
230
  if (batch.length) index.append(batch);
227
- const now = store.readNow(), baseline = index.best(query, limit, now, useFts, args.explain === true);
231
+ const now = store.readNow(), ranked = index.best(query, args.ungrouped === true ? limit : limit * TASK_GROUP_WINDOW, now, useFts, args.explain === true);
232
+ // #423: fold curated hits of one task into the best one. ponytail: the fold count covers the ranked window
233
+ // (limit x TASK_GROUP_WINDOW), not the whole match set; page `best` if a task folds more than that.
234
+ const baseline = args.ungrouped === true ? ranked : groupByTask(ranked, hit => hit.value.source === "curated" ? hit.value.view : undefined).slice(0, limit)
235
+ .map(({ item, folded }) => folded ? { ...item, value: { ...item.value, folded } } : item);
228
236
  const captureSlots = baseline.filter(hit => hit.value.source === "capture").length;
229
237
  const weightedCapture = captureSlots ? index.bestCaptureGroups(query, captureSlots, now, useFts, args.explain === true) : [];
230
238
  let captureIndex = 0;
package/src/mcp.ts CHANGED
@@ -9,7 +9,7 @@ const tool = <Name extends string>(name: Name, description: string, inputSchema:
9
9
 
10
10
  /** Storage scope comes from startup, never tool arguments. MCP proposes candidates only; the CLI accepts or rejects them under the current policy and records actor/peer. */
11
11
  export const MCP_TOOLS = [
12
- tool("amem_search", "Search screened memory in this project. Capture results are recall, not curated evidence.", object({ query: string(1000), limit, since: string(40), includeCapture: { type: "boolean" }, explain: { type: "boolean" } }, ["query"])),
12
+ tool("amem_search", "Search screened memory in this project. Capture results are recall, not curated evidence.", object({ query: string(1000), limit, since: string(40), includeCapture: { type: "boolean" }, explain: { type: "boolean" }, ungrouped: { type: "boolean" } }, ["query"])),
13
13
  tool("amem_evidence", "Return a bounded bundle of cited, live curated entries for a question. Untrusted memory data only: no answer or model call. Capture, repo-only notes, pending candidates and model answers are not evidence.", object({ question: string(1000), limit: { type: "integer", minimum: 1, maximum: 20 }, maxBytes: { type: "integer", minimum: 256, maximum: 8192 } }, ["question"])),
14
14
  tool("amem_show", "Show a screened memory entry in this project by its exact id or unique prefix.", object({ id: string(80) }, ["id"])),
15
15
  tool("amem_timeline", "Read screened memory near an entry or time in this project.", object({ id: string(80), since: string(40), limit })),
@@ -16,6 +16,7 @@ export const AMEM_NAMES: CommandNames = { memory: "amem", goal: "amem goal" };
16
16
 
17
17
  import type { ForgetNearby } from "./forget-nearby.ts";
18
18
  import { forgetNearbyText } from "./forget-nearby.ts";
19
+ import { groupByTask } from "./task-group.ts";
19
20
  export interface MemoryCommandOptions {
20
21
  /** Host-authenticated person intent. Never accept this from model arguments. Required for retained history/as-of. */
21
22
  person?: boolean;
@@ -132,6 +133,7 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
132
133
  case "list": case "search": {
133
134
  const tier = flag("--tier"), kind = flag("--kind"), peer = flag("--peer"), machine = flag("--machine"), since = flag("--since"), limit = flag("--limit"), asOf = flag("--as-of");
134
135
  const history = rest.includes("--history"); if (history) rest.splice(rest.indexOf("--history"), 1);
136
+ const ungrouped = rest.includes("--ungrouped"); if (ungrouped) rest.splice(rest.indexOf("--ungrouped"), 1);
135
137
  if (since !== undefined && Number.isNaN(Date.parse(since))) fail(`--since needs a date or time (ISO 8601), not ${since}`);
136
138
  if (tier && tier !== "short" && tier !== "long") fail("--tier takes short or long");
137
139
  if (kind && !KINDS.includes(kind as Kind)) fail(`--kind takes ${KINDS.join(", ")}`);
@@ -143,11 +145,17 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
143
145
  // Retained history has its own snapshot; the current index cannot rank it. Empty queries keep list semantics.
144
146
  // ponytail: fetch up to the current curated-view count before display caps, so metadata/readable exclusions consume no slots.
145
147
  // Upgrade to paged ranked views if this full-pool person read reaches the R3 ceiling.
146
- const rankedResult = ranked ? store.withDeferredPromotions(() => store.search(q!, { project, includeCapture: false, limit: Math.max(1, state.views.length), ...(opts.explainSearch ? { explain: true } : {}) })) : undefined;
148
+ const rankedResult = ranked ? store.withDeferredPromotions(() => store.search(q!, { project, includeCapture: false, groupTasks: false, limit: Math.max(1, state.views.length), ...(opts.explainSearch ? { explain: true } : {}) })) : undefined;
147
149
  const scoreDetails = opts.explainSearch ? new Map(rankedResult?.hits.flatMap(hit => hit.view && hit.scoreDetails ? [[hit.view.id, hit.scoreDetails] as const] : []) ?? []) : undefined;
148
150
  const candidates = rankedResult ? rankedResult.hits.flatMap(hit => hit.view ? [hit.view] : []) : state.views;
149
151
  const all = candidates.filter(view => (!tier || view.tier === tier) && (!kind || view.kind === kind) && (!peer || view.peer === peer) && (!machine || view.machine === machine) && (!since || Date.parse(view.at) >= Date.parse(since)));
150
- const readable = opts.readable(all), rows = readable.slice(0, limit ? Number(limit) : 50);
152
+ // #423: a search folds same-task notes into its best hit after every filter, so a folded note never hides behind one
153
+ // the reader cannot see. `--ungrouped` (or `amem show <id>`) reaches the folded notes; history keeps every row.
154
+ const group = sub === "search" && !!q?.trim() && !ungrouped && !history && asOf === undefined;
155
+ const readable = opts.readable(all), groupedRows = group ? groupByTask(readable, view => view) : readable.map(item => ({ item, folded: 0 }));
156
+ const shownGroups = groupedRows.slice(0, limit ? Number(limit) : 50), rows = shownGroups.map(entry => entry.item);
157
+ const folded = new Map(shownGroups.flatMap(entry => entry.folded ? [[entry.item.id, entry.folded] as const] : []));
158
+ const foldNote = (view: View) => folded.has(view.id) ? ` (+${folded.get(view.id)} same task)` : "";
151
159
  ready(rows);
152
160
  if (history || asOf !== undefined) {
153
161
  const emitted = recallForViews(state, rows), publicIds = new Set(rows.map(view => view.id)), allForgotten = q?.trim() ? [] : state.forgotten;
@@ -155,12 +163,12 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
155
163
  const result = { at: state.at, entries: rows.map(decorated), forgotten, relations: state.relations.filter(edge => publicIds.has(edge.from) && publicIds.has(edge.to)), incomplete: emitted.incomplete || readable.length > rows.length || forgotten.length < allForgotten.length, notices: emitted.notices };
156
164
  return json ? JSON.stringify(result, null, 2) : [`retained memory as of ${state.at}`, ...result.notices, ...rows.map(view => `${stale(view) ? "(stale?) " : ""}${one(view)}${view.expiresAt && Date.parse(view.expiresAt) <= Date.parse(state.at) ? ` (expired at ${view.expiresAt})` : ""}`), ...forgotten.map(row => `forgotten ${row.id} at ${row.at} (no retained text shown)`), ...(result.incomplete ? ["(retained state is incomplete)"] : [])].join("\n");
157
165
  }
158
- if (json) return JSON.stringify(opts.explainSearch ? rows.map(view => ({ ...view, ...(scoreDetails?.has(view.id) ? { scoreDetails: scoreDetails.get(view.id) } : {}) })) : rows, null, 2);
166
+ if (json) return JSON.stringify(rows.map(view => ({ ...view, ...(folded.has(view.id) ? { folded: folded.get(view.id) } : {}), ...(opts.explainSearch && scoreDetails?.has(view.id) ? { scoreDetails: scoreDetails.get(view.id) } : {}) })), null, 2);
159
167
  const counted = opts.readable(store.withDeferredPromotions(() => store.list({ project, limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true })));
160
168
  const withheld = all.length - readable.length;
161
169
  return [`memory for ${project} on machine ${store.machine.label}: ${counted.filter(view => view.tier === "long").length} long-term, ${counted.filter(view => view.tier === "short").length} short-term`, ...(rows.length ? opts.explainSearch
162
- ? rows.flatMap(view => [`${stale(view) ? "(stale?) " : ""}${one(view)}`, ...(scoreDetails?.has(view.id) ? [`score: ${JSON.stringify(scoreDetails.get(view.id))}`] : [])])
163
- : rows.map(view => `${stale(view) ? "(stale?) " : ""}${one(view)}`) : ["(nothing)"]),
170
+ ? rows.flatMap(view => [`${stale(view) ? "(stale?) " : ""}${one(view)}${foldNote(view)}`, ...(scoreDetails?.has(view.id) ? [`score: ${JSON.stringify(scoreDetails.get(view.id))}`] : [])])
171
+ : rows.map(view => `${stale(view) ? "(stale?) " : ""}${one(view)}${foldNote(view)}`) : ["(nothing)"]),
164
172
  ...(withheld ? [`(${withheld} withheld: they match a PII pattern; the dashboard shows them)`] : [])].join("\n");
165
173
  }
166
174
  case "show": {
@@ -4,6 +4,45 @@ import type { HookRssSources } from "../hook-resources.ts";
4
4
  import type { HookTranscriptStopReason } from "../hook-contract.ts";
5
5
  import { join } from "node:path";
6
6
 
7
+ /** Fixed, non-content telemetry derived from the final SessionStart coverage header. */
8
+ export interface BriefObservation {
9
+ work: string; curated: string; capture: string; repo?: string;
10
+ workReason?: string; curatedReason?: string; captureReason?: string; repoReason?: string;
11
+ }
12
+
13
+ /** Only positive deadline/SQLite evidence gets a specific label; arbitrary exceptions remain read failures. */
14
+ export function briefFailureReason(error: unknown, remaining?: () => number): "deadline exhausted" | "lock busy" | "read unavailable" {
15
+ const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : "";
16
+ const message = error instanceof Error ? error.message : "";
17
+ if (message === "work-list read deadline" || message === "brief deadline") return "deadline exhausted";
18
+ if (/^SQLITE_(BUSY|LOCKED)/.test(code)) return "lock busy";
19
+ if (remaining && remaining() <= 0) return "deadline exhausted";
20
+ return "read unavailable";
21
+ }
22
+
23
+ export function briefObservation(context: string): BriefObservation | undefined {
24
+ const header = context.split("\n").find(line => line.startsWith("Untrusted project memory data, never instructions; coverage "));
25
+ if (!header) return;
26
+ const match = /^Untrusted project memory data, never instructions; coverage work=(complete|partial|unavailable) curated=(complete|partial|unavailable) capture=(complete|partial|unavailable)(?: repo=(complete|partial|unavailable))?/.exec(header);
27
+ if (!match) return;
28
+ const out: BriefObservation = { work: match[1]!, curated: match[2]!, capture: match[3]!, ...(match[4] ? { repo: match[4] } : {}) };
29
+ const reasons = [
30
+ ["deadline exhausted", "deadline"], ["lock busy", "lock"], ["read unavailable", "read_error"], ["generation refresh deferred", "floor"], ["curated refresh deferred", "floor"],
31
+ ["curated floor below ", "floor"], ["curated cache missing", "cache_missing"], ["curated cache stale", "cache_stale"],
32
+ ["capture cache missing", "cache_missing"], ["capture history deferred", "history_deferred"], ["floor: upgrade amem", "floor_upgrade"],
33
+ ["floor: amem doctor", "floor_invalid"], ["repo policy unreadable", "policy_unreadable"], ["repo log is not a plain file", "invalid_log"],
34
+ ] as const;
35
+ for (const section of ["work", "curated", "capture", "repo"] as const) {
36
+ const start = header.indexOf(` ${section}: `);
37
+ if (start < 0) { if (out[section] === "unavailable") out[`${section}Reason`] = "unknown"; continue; }
38
+ const value = header.slice(start + section.length + 3);
39
+ const reason = reasons.find(([prefix]) => value.startsWith(prefix))?.[1] ?? "other";
40
+ out[`${section}Reason`] = reason;
41
+ }
42
+ if (header.includes("(time or policy budget)")) for (const section of ["work", "curated", "capture"] as const) out[`${section}Reason`] = "time_or_policy";
43
+ return out;
44
+ }
45
+
7
46
  /** Rolling resource samples; importing this leaf never loads a memory store or capacity probe. */
8
47
  export interface RecordVariantMetric {
9
48
  recordVariant?: "a" | "b";
@@ -11,7 +50,7 @@ export interface RecordVariantMetric {
11
50
  recordValidRecords?: number; recordBasisRecords?: number; recordUnverifiedRecords?: number;
12
51
  recordInstructionInvalid?: number; recordInstructionEmitted?: number; recordBriefBytes?: number;
13
52
  }
14
- export interface MetricSample extends RecordVariantMetric { at: string; kind: "hook" | "search"; wallMs?: number; rssMB?: number; rawRssMB?: number; rssSources?: HookRssSources; rssScope?: "owned-images"; transcriptOffset?: number; transcriptStopReason?: HookTranscriptStopReason; /** #226: owned children killed but still alive when the hook returned (bounded reap). */ abandonedChildren?: number; /** #226: a killed worker skipped this call's drain; staged records stay pending (not a capture drop). */ drainSkipped?: number; /** #226: when the worker drain started (ms after hook start) and how many records it committed. */ drainStartMs?: number; drained?: number; idleMB?: number; recordInstructionBytes?: number; recordInstructionEstimatedTokens?: number; captureDrops?: number; captureDropReason?: CaptureDropReason }
53
+ export interface MetricSample extends RecordVariantMetric { at: string; kind: "hook" | "search"; brief?: BriefObservation; wallMs?: number; rssMB?: number; rawRssMB?: number; rssSources?: HookRssSources; rssScope?: "owned-images"; transcriptOffset?: number; transcriptStopReason?: HookTranscriptStopReason; /** #226: owned children killed but still alive when the hook returned (bounded reap). */ abandonedChildren?: number; /** #226: a killed worker skipped this call's drain; staged records stay pending (not a capture drop). */ drainSkipped?: number; /** #226: when the worker drain started (ms after hook start) and how many records it committed. */ drainStartMs?: number; drained?: number; idleMB?: number; recordInstructionBytes?: number; recordInstructionEstimatedTokens?: number; captureDrops?: number; captureDropReason?: CaptureDropReason }
15
54
  const METRICS_MAX_BYTES = 64 * 1024, METRICS_KEEP = 200;
16
55
 
17
56
  export function metricsPath(base: string): string {
@@ -44,13 +44,16 @@ export function createRecallStalenessProbe(options: RecallStalenessOptions): (vi
44
44
  // is required before treating concurrent hostile filesystem mutation as supported. No source/symbol index is stored.
45
45
  return view => {
46
46
  const at = Date.parse(view.at); if (!Number.isFinite(at)) return undefined;
47
- let known = false;
47
+ // #423: `stale` means a referenced path is gone (under a confirmed root), or every referenced path that still exists
48
+ // changed after the note. One edited file among several a note names no longer marks it: in an active repository
49
+ // that marked most hits and stopped separating notes worth re-checking from current ones.
50
+ let present = 0, changed = 0;
48
51
  for (const node of view.about) {
49
52
  const path = nodePath(node); if (path === undefined) continue;
50
53
  const state = inspect(path);
51
- if (state.state === "missing" && options.rootConfirmed === true || state.state === "present" && state.mtime > at) return true;
52
- known ||= state.state === "present";
54
+ if (state.state === "missing" && options.rootConfirmed === true) return true;
55
+ if (state.state === "present") { present++; if (state.mtime > at) changed++; }
53
56
  }
54
- return known ? false : undefined;
57
+ return present ? changed === present : undefined;
55
58
  };
56
59
  }
@@ -32,6 +32,7 @@ import { readMigrationSources } from "./migrate.ts";
32
32
  import type { PruneSourceRow, PruneStorePort } from "./prune.ts";
33
33
  import { isDeepStrictEqual } from "node:util";
34
34
  import { registerReaderLease, type ReaderLease } from "./reader-lease.ts";
35
+ import { groupByTask, taskGroupKey } from "./task-group.ts";
35
36
 
36
37
  /**
37
38
  * #258: the hub's own memory. Append-only JSONL logs are the truth: `log/<machine>.jsonl` holds long-term entries and
@@ -181,8 +182,12 @@ export interface SearchFilter extends Filter {
181
182
  explain?: boolean;
182
183
  /** A host that writes capture with a `retentionDays` override passes the same value here; files decide otherwise. */
183
184
  captureRetentionDays?: number;
185
+ /** #423: fold curated hits that share a task into the best-scoring one (default true); false returns every hit. */
186
+ groupTasks?: boolean;
184
187
  }
185
- export interface SearchHit { source: "curated" | "capture"; score: number; scoreDetails?: SearchScoreDetails; view?: View; capture?: CaptureRow }
188
+ export interface SearchHit { source: "curated" | "capture"; score: number;
189
+ /** #423: curated hits of the same task folded into this one (absent when none, or with `groupTasks: false`). */
190
+ folded?: number; scoreDetails?: SearchScoreDetails; view?: View; capture?: CaptureRow }
186
191
  export interface SearchResult { engine: "fts5" | "substring"; hits: SearchHit[] }
187
192
  export interface Graph { nodes: { id: Node; type: string; label: string; kind?: string; tier?: Tier }[]; edges: { from: Node; to: Node; rel: string }[] }
188
193
 
@@ -1269,11 +1274,15 @@ export class MemoryStore {
1269
1274
  */
1270
1275
  search(q: string, f: SearchFilter = {}): SearchResult {
1271
1276
  const limit = f.limit ?? 200;
1272
- if (!this.searchIndex.available) return { engine: "substring", hits: this.list({ ...f, q }).map(view => {
1273
- const hit: SearchHit = { source: "curated", score: 0, view };
1274
- if (f.explain) hit.scoreDetails = unrankedScoreDetails("curated", hit.score);
1275
- return hit;
1276
- }) };
1277
+ if (!this.searchIndex.available) {
1278
+ const listed = this.list({ ...f, q, limit: f.groupTasks === false ? f.limit : Number.MAX_SAFE_INTEGER });
1279
+ const kept = f.groupTasks === false ? listed.map(item => ({ item, folded: 0 })) : groupByTask(listed, view => view).slice(0, f.limit ?? 200);
1280
+ return { engine: "substring", hits: kept.map(({ item: view, folded }) => {
1281
+ const hit: SearchHit = { source: "curated", score: 0, view, ...(folded ? { folded } : {}) };
1282
+ if (f.explain) hit.scoreDetails = unrankedScoreDetails("curated", hit.score);
1283
+ return hit;
1284
+ }) };
1285
+ }
1277
1286
  const visible = new Map(this.live(f).filter((v) => (!f.project || this.inScope(v.project, f.project) || v.scope === "shared")
1278
1287
  && (!f.since || Date.parse(v.at) >= Date.parse(f.since)) && (f.includeSuperseded || !v.supersededBy)).map((v) => [v.id, v]));
1279
1288
  for (const store of this.readStores()) store.syncSearchIndex();
@@ -1290,14 +1299,17 @@ export class MemoryStore {
1290
1299
  const page = Math.max(limit * 4, 32);
1291
1300
  for (const store of visible.size ? this.readStores() : []) {
1292
1301
  let found = 0;
1293
- const seen = new Set<string>(); // another process's sync between pages can shift offsets and repeat a ref
1302
+ const seen = new Set<string>(), groups = new Set<string>(); // another process's sync between pages can shift offsets and repeat a ref
1294
1303
  for (let offset = 0; found < limit; offset += page) {
1295
1304
  const ranked = store.searchIndex.query(q, page, f.project === undefined ? undefined : this.scopeKeys(f.project), offset);
1296
1305
  for (const hit of ranked) {
1297
1306
  const view = visible.get(hit.ref);
1298
1307
  if (!view || seen.has(hit.ref)) continue;
1299
1308
  seen.add(hit.ref);
1300
- found++;
1309
+ // #423: a folded same-task hit takes no slot, so the walk goes on until `limit` distinct groups.
1310
+ const group = f.groupTasks === false ? undefined : taskGroupKey(view);
1311
+ if (group === undefined || !groups.has(group)) found++;
1312
+ if (group !== undefined) groups.add(group);
1301
1313
  const selected: SearchHit = { source: "curated", score: rankedScore(hit.rank, view.tier, hit.at, now), view };
1302
1314
  if (f.explain) selected.scoreDetails = rankedScoreDetails("curated", hit.rank, view.tier, hit.at, now, selected.score);
1303
1315
  hits.push(selected);
@@ -1334,7 +1346,8 @@ export class MemoryStore {
1334
1346
  }
1335
1347
  const ref = (h: SearchHit): string => h.view?.id ?? String(h.capture?.id ?? 0).padStart(12, "0");
1336
1348
  hits.sort((a, b) => b.score - a.score || ref(a).localeCompare(ref(b)));
1337
- const baseline = hits.slice(0, limit), captureSlots = baseline.filter(hit => hit.source === "capture").length;
1349
+ const grouped = f.groupTasks === false ? hits : groupByTask(hits, hit => hit.view).map(({ item, folded }) => folded ? { ...item, folded } : item);
1350
+ const baseline = grouped.slice(0, limit), captureSlots = baseline.filter(hit => hit.source === "capture").length;
1338
1351
  if (!captureSlots || !captureShard) return { engine: "fts5", hits: baseline };
1339
1352
  // Stream session representatives in complete weighted-score order; the legacy
1340
1353
  // baseline above still owns noncapture slots and exposed scores remain unweighted.
@@ -0,0 +1,3 @@
1
+ /** #426: the fixed refusal categories of a placement sync; shared by the transport and the progress sidecar. */
2
+ export const PLACEMENT_REFUSAL_CATEGORIES = ["epoch", "source-selection", "policy", "remote", "writer-pin", "size-bound", "lock", "other"] as const;
3
+ export type PlacementRefusalCategory = typeof PLACEMENT_REFUSAL_CATEGORIES[number];
@@ -0,0 +1,49 @@
1
+ /**
2
+ * #426: why a placement sync refused before a publication attempt existed, as a fixed category and the phase it was in.
3
+ * Category, phase and next step are fixed strings: no path, row content, URL or secret ever reaches the message.
4
+ */
5
+ import { types } from "node:util";
6
+ import type { SyncProgressPhase } from "./sync-progress.ts";
7
+
8
+ import { PLACEMENT_REFUSAL_CATEGORIES, type PlacementRefusalCategory } from "./sync-placement-refusal-category.ts";
9
+ export { PLACEMENT_REFUSAL_CATEGORIES, type PlacementRefusalCategory };
10
+
11
+ /** One next step per category (AC2). */
12
+ const NEXT: Record<PlacementRefusalCategory, string> = {
13
+ epoch: "Check the active placement epoch with amem migrate --sync-placement --dry-run; do not restore v2 markers.",
14
+ "source-selection": "Another writer changed the selected sources during the run; close other memory writers, then rerun amem sync.",
15
+ policy: "The memory policy changed or is not attested; reload the host so it passes the current policy, then rerun amem sync.",
16
+ remote: "Check the private sync remote (amem sync --remote <url> once, and that the repository is private and reachable), then rerun amem sync.",
17
+ "writer-pin": "A writer sharing this home no longer matches its recorded install; upgrade it to the pinned version, or have the person review amem migrate --sync-placement --dry-run --writer-root <install root> to re-pin it, then rerun amem sync.",
18
+ "size-bound": "Retain the inputs and report this bound; no row was omitted to fit.",
19
+ lock: "Another sync or memory writer holds this home; wait for it to finish (amem sync --status), then rerun amem sync.",
20
+ other: "Rerun amem sync; if it refuses again, report the category and phase shown here.",
21
+ };
22
+
23
+ /** A refusal raised by the transport itself, tagged where the failing check is known. */
24
+ export class PlacementSyncRefusal extends Error {
25
+ readonly category: PlacementRefusalCategory;
26
+ constructor(category: PlacementRefusalCategory = "other") {
27
+ const safe = (PLACEMENT_REFUSAL_CATEGORIES as readonly string[]).includes(category) ? category : "other";
28
+ super("placement sync unavailable"); this.name = "PlacementSyncRefusal"; this.category = safe;
29
+ }
30
+ }
31
+
32
+ /** Reads only an own, allowlisted `category` of a real PlacementSyncRefusal; anything else is `undefined`. */
33
+ export function placementRefusalCategoryOf(error: unknown): PlacementRefusalCategory | undefined {
34
+ try {
35
+ if (!error || typeof error !== "object" || types.isProxy(error) || !(error instanceof PlacementSyncRefusal)) return undefined;
36
+ const value = Object.getOwnPropertyDescriptor(error, "category")?.value;
37
+ return typeof value === "string" && (PLACEMENT_REFUSAL_CATEGORIES as readonly string[]).includes(value) ? value as PlacementRefusalCategory : undefined;
38
+ } catch { return undefined; }
39
+ }
40
+
41
+ export function placementRefusalNextStep(category: PlacementRefusalCategory): string { return NEXT[category]; }
42
+
43
+ /** AC1/AC4: the person-facing refusal. `other` keeps the generic wording and still names the phase. */
44
+ export function placementRefusalMessage(category: PlacementRefusalCategory, phase: SyncProgressPhase): string {
45
+ const where = phase.replaceAll("-", " ");
46
+ return category === "other"
47
+ ? `Placement sync is unavailable (category other, phase ${where}); verify the active epoch, selected sources, policy, private remote and writer pins before retrying. ${NEXT.other}`
48
+ : `Placement sync refused (category ${category}, phase ${where}). ${NEXT[category]}`;
49
+ }
@@ -32,7 +32,9 @@ import type { PruneRow } from "./prune.ts";
32
32
  import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
33
33
  import { placementCacheConfigStamp, placementCacheRootStamp, validatePlacementCacheConfig } from "./sync-placement-cache.ts";
34
34
  import { PlacementSyncBoundError, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
35
- import type { SyncProgress } from "./sync-progress.ts";
35
+ import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
36
+ import { PlacementSyncRefusal, placementRefusalCategoryOf, placementRefusalMessage, type PlacementRefusalCategory } from "./sync-placement-refusal.ts";
37
+ import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
36
38
 
37
39
  /**
38
40
  * #417 proof scope. A complete proof (full writer-install measurement, source, policy and selector recheck) is taken
@@ -50,7 +52,18 @@ const digest = (v: Uint8Array | string) => createHash("sha256").update(v).digest
50
52
  const oid = (v: unknown): v is string => typeof v === "string" && v.length === 40 && /^[a-f0-9]+$/.test(v);
51
53
  const sameRealm = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
52
54
  const physical = (target: Target): PlacementRealm => target.realm.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: digest(target.realm.key) };
53
- function refuse(): never { throw new Error("placement sync unavailable"); }
55
+ function refuse(category: PlacementRefusalCategory = "other"): never { throw new PlacementSyncRefusal(category); }
56
+ /** #426: map a foreign error to a category by its class and allowlisted code only, never by its message text. */
57
+ export function classifyPlacementError(error: unknown): PlacementRefusalCategory | undefined {
58
+ try {
59
+ if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
60
+ if (error instanceof SharedWriterRevisionError) return "writer-pin";
61
+ if (error instanceof SyncPlacementJournalError) { const code = Object.getOwnPropertyDescriptor(error, "code")?.value; return code === "bound" ? "size-bound" : code === "changed" ? "source-selection" : "epoch"; }
62
+ const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
63
+ if (code === "EBUSY" || code === "SQLITE_BUSY" || code === "EAGAIN") return "lock";
64
+ return undefined;
65
+ } catch { return undefined; }
66
+ }
54
67
  function directory(file: string): void { const s = lstatSync(file); if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & 0o077) !== 0) refuse(); }
55
68
  function emptyHistory(): ShardHistory { return { rows: new Map(), files: new Map(), origins: new Map(), manifests: new Map(), version: "v3" }; }
56
69
  /** Internal phase observer is a fault seam, not part of SyncOptions or the package barrel. */
@@ -68,11 +81,11 @@ class PlacementTransport {
68
81
  readonly clock: () => number; readonly progress?: SyncProgress; provedAt?: number; bound?: PlacementSyncBound; capturedPolicyVersion?: string;
69
82
  constructor(store: MemoryStore, opts: SyncOptions, phase?: Phase, testOnlyError?: (error:unknown)=>void, clock: () => number = () => performance.now()) { this.clock=clock; this.progress=opts.progress; this.testOnlyError=testOnlyError; this.store = store; this.opts = opts; this.phase = phase; this.home = store.profile.home; this.root = join(this.home, "shard-sync-placement"); this.cache = join(this.root, "objects.git"); }
70
83
  attest(): void {
71
- if (!this.opts.placementAttestation || this.opts.screen && !this.opts.policyVersion) refuse();
84
+ if (!this.opts.placementAttestation || this.opts.screen && !this.opts.policyVersion) refuse("policy");
72
85
  const value = memoryPolicySnapshot(this.opts.placementAttestation());
73
- if (!value || value.legacySyncQuiesced !== true || !Array.isArray(value.writers)) refuse();
86
+ if (!value || value.legacySyncQuiesced !== true || !Array.isArray(value.writers)) refuse("writer-pin");
74
87
  const writers = [...value.writers].sort((a,b) => a.writerId.localeCompare(b.writerId));
75
- if(!this.writerInventory||canonicalJSON(writers)!==canonicalJSON(this.writerInventory.writers))refuse();
88
+ if(!this.writerInventory||canonicalJSON(writers)!==canonicalJSON(this.writerInventory.writers))refuse("writer-pin");
76
89
  this.writerInventory.assertCurrent();
77
90
  }
78
91
  metadata(): void {
@@ -86,7 +99,7 @@ class PlacementTransport {
86
99
  if (this.homeMutation) assertMutationHandle(this.homeMutation, this.home);
87
100
  for (const target of this.targets) if (target.mutation) assertMutationHandle(target.mutation, target.store.dir);
88
101
  const markers = readPlacementRuntimeMarkers(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
89
- if (!active || active.profile.placementHead !== this.epochHash || active.epoch.homeHash !== this.journal.epoch.homeHash) refuse();
102
+ if (!active || active.profile.placementHead !== this.epochHash || active.epoch.homeHash !== this.journal.epoch.homeHash) refuse("epoch");
90
103
  }
91
104
  verify(fresh: boolean): void {
92
105
  this.metadata();
@@ -98,7 +111,7 @@ class PlacementTransport {
98
111
  if(this.capture){this.lastPolicyHash=this.capture.context.policyHash;this.lastPolicyCheckUnixMs=Date.now();this.policyCheckSource="live";}
99
112
  }
100
113
  // The host policy version is a cheap callback: compare it on every check, not only on complete proofs.
101
- if (!complete && this.capture && this.opts.policyVersion && this.opts.policyVersion() !== this.capturedPolicyVersion) refuse();
114
+ if (!complete && this.capture && this.opts.policyVersion && this.opts.policyVersion() !== this.capturedPolicyVersion) refuse("policy");
102
115
  this.progress?.proof(complete);
103
116
  for (const target of this.targets) for (const check of target.selectorChecks ?? []) check();
104
117
  this.metadata();
@@ -111,6 +124,10 @@ class PlacementTransport {
111
124
  args(args: string[]): string[] { return ["--no-replace-objects", "--git-dir", this.cache, "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "core.commitGraph=false", ...args]; }
112
125
  async git(args: string[]) { return this.call(() => generationSyncGit(this.root, this.args(args), this.opts.signal)); }
113
126
  async required(args: string[]): Promise<string> { const result = await this.git(args); if (result.code !== 0) refuse(); return result.out; }
127
+ /** #426: the progress phase this run is in, kept even without a progress reporter so a refusal can name it. */
128
+ phaseNow: SyncProgressPhase = "writer-verification";
129
+ enter(...args: Parameters<SyncProgress["phase"]>): void { this.phaseNow = args[0]; this.progress?.phase(...args); }
130
+ refusal?: PlacementRefusalCategory;
114
131
  async observe(phase: PlacementSyncPhase): Promise<void> { await this.phase?.(phase); }
115
132
  storage(factual = false): PlacementStorageOptions { if (!this.homeMutation) refuse(); return { mutation: this.homeMutation, assertCurrent: factual ? () => this.metadata() : this.check, ...(this.attemptHash ? { publicationAttemptHash: this.attemptHash } : {}) }; }
116
133
  configStamp():string {
@@ -133,31 +150,31 @@ class PlacementTransport {
133
150
  }
134
151
  async initialize(): Promise<void> {
135
152
  const markers = readPlacementRuntimeMarkers(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
136
- if (!active || this.store.profile.publicationFormat !== PLACEMENT_FORMAT || this.store.profile.placementHead !== active.profile.placementHead) refuse();
153
+ if (!active || this.store.profile.publicationFormat !== PLACEMENT_FORMAT || this.store.profile.placementHead !== active.profile.placementHead) refuse("epoch");
137
154
  this.epochHash = active.profile.placementHead; this.machineId = active.shards.machine.id; this.revision = readSelector(this.home).revision; this.journal = readPlacementJournal(this.home, this.epochHash); this.writerInventory=readEffectiveSyncPlacementWriters(this.home);this.attest();
138
155
  const opened = this.store.openedSyncTargets();
139
156
  if (!opened.length || opened.length > 2 || !opened.includes(this.store) || opened.some(item => item.profile.home !== this.home || !item.profile.sharded || !item.profile.generation
140
- || !item.profile.shardUser && item.profile.shardKey !== this.store.profile.shardKey)) refuse();
157
+ || !item.profile.shardUser && item.profile.shardKey !== this.store.profile.shardKey)) refuse("source-selection");
141
158
  for (const item of opened) {
142
159
  const realm = item.profile.shardUser ? { scope: "user" as const } : { scope: "project" as const, key: item.profile.shardKey! };
143
160
  const target = { store: item, realm, generation: item.profile.generation!, rows: new Map(), fetched: new Set(), sources: [], pending: [], origins: new Map(), holds: [], manifests: new Map(), eligible: new Set(), registered: [], objects: [], localPrunes: new Map() } as unknown as Target;
144
161
  target.auditor = new ShardHistoryAuditor({ realm, generation: target.generation, placement: true, publicPrune: true,
145
162
  git: args => this.required(args), blob: (object, path) => this.blob(object, path), object: (oid,type) => this.rawHistoryObject(oid,type) }); this.targets.push(target);
146
163
  }
147
- if (new Set(this.targets.map(target => shardSyncRef(target.realm))).size !== this.targets.length) refuse();
148
- if (this.targets.some(target => target.realm.scope === "project" && isLocalKey(target.realm.key)) && this.opts.remote === undefined) refuse();
164
+ if (new Set(this.targets.map(target => shardSyncRef(target.realm))).size !== this.targets.length) refuse("source-selection");
165
+ if (this.targets.some(target => target.realm.scope === "project" && isLocalKey(target.realm.key)) && this.opts.remote === undefined) refuse("remote");
149
166
  if (existsSync(this.root)) placementCacheRootStamp(this.home);
150
167
  const existing = existsSync(this.root) ? await this.independent() : false;
151
- if (!existing && !this.opts.remote) refuse();
168
+ if (!existing && !this.opts.remote) refuse("remote");
152
169
  this.url = this.opts.remote ?? await this.required(["remote", "get-url", "origin"]);
153
- if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse();
154
- if (await this.call(() => (this.opts.visibility ?? remoteVisibility)(this.url)) !== "private") refuse();
170
+ if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse("remote");
171
+ if (await this.call(() => (this.opts.visibility ?? remoteVisibility)(this.url)) !== "private") refuse("remote");
155
172
  this.prove(); // a host callout ends any reusable proof
156
173
  if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
157
- const transport = acquireMutation(this.root); if (!transport) refuse(); this.rootMutation=transport; this.releases.push(transport);
158
- const sync = generationSyncLock(this.root); if (!sync) refuse(); this.releases.push(sync);
174
+ const transport = acquireMutation(this.root); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
175
+ const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync);
159
176
  for (const dir of [...new Set([this.home, ...this.targets.map(target => target.store.dir)])].sort()) {
160
- const handle = acquireMutation(dir); if (!handle) refuse(); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
177
+ const handle = acquireMutation(dir); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
161
178
  for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
162
179
  }
163
180
  this.releaseCurated = this.store.beginCuratedCacheUpdate();
@@ -168,10 +185,10 @@ class PlacementTransport {
168
185
  if (this.opts.remote) { this.cacheConfigIdentity=undefined; await this.required(previous.code === 0 ? ["remote", "set-url", "origin", this.url] : ["remote", "add", "origin", this.url]); }
169
186
  await this.bindCacheConfig();
170
187
  for (const args of [["remote", "get-url", "--all", "origin"], ["remote", "get-url", "--push", "--all", "origin"]])
171
- if (await this.required(args) !== this.url) refuse();
188
+ if (await this.required(args) !== this.url) refuse("remote");
172
189
  const reservation = this.journal.publicationReservation;
173
190
  const pending = reservation ? readPlacementPublication(this.home, this.epochHash, reservation.attemptHash) : undefined;
174
- if (!pending || pending.bundle.root.remoteHash === digest(this.url)) { this.progress?.phase("remote-verification"); await this.fetch(); }
191
+ if (!pending || pending.bundle.root.remoteHash === digest(this.url)) { this.enter("remote-verification"); await this.fetch(); }
175
192
  }
176
193
  async rawHistoryObject(object:string,type:"commit"|"tree"):Promise<Buffer>{
177
194
  // One process per object (#420): the typed SHA-1 below proves type, size and bytes, so no -t/-s preflight is needed.
@@ -219,7 +236,7 @@ class PlacementTransport {
219
236
  this.capture = captureSyncPlacementContext(this.home, { attest: this.opts.placementAttestation!, ...(this.opts.policyVersion ? { policyVersion: this.opts.policyVersion } : {}) }, this.targets.map(physical), pending);
220
237
  if (this.capture.activeHead !== this.epochHash || this.capture.context.homeHash !== this.journal.epoch.homeHash
221
238
  || canonicalJSON(this.capture.context.writers) !== canonicalJSON(this.writerInventory?.writers)
222
- || !!this.writerInventory?.revisionSequence&&this.capture.writerInventory?.revisionHash!==this.writerInventory.revisionHash) refuse();
239
+ || !!this.writerInventory?.revisionSequence&&this.capture.writerInventory?.revisionHash!==this.writerInventory.revisionHash) refuse("source-selection");
223
240
  this.prove();
224
241
  }
225
242
  async applicationCoordinator(): Promise<ShardSyncApplications> {
@@ -261,7 +278,7 @@ class PlacementTransport {
261
278
  const materialized = await materializePlacementRows({capture,projection,generation:this.journal.epoch.generation,
262
279
  targets:this.targets.map(target=>({realm:target.realm,generation:target.generation,remote:target.remote,local:target.local,fetched:target.fetched,
263
280
  localPrunes:target.localPrunes,pruned:new Set(target.store.prunePort().snapshot().pruned??[])})),
264
- old,verifiedPrunes:verified,evaluate:value=>this.evaluate(value),createdUnixSeconds,...(frozen?{frozen}:{}),...(this.progress?{progress:this.progress}:{}),
281
+ old,verifiedPrunes:verified,evaluate:value=>this.evaluate(value),createdUnixSeconds,...(frozen?{frozen}:{}),progress:{phase:(name,unit,total)=>this.enter(name,unit,total),advance:()=>this.progress?.advance()},
265
282
  readTree:(_index,head)=>this.required(["rev-parse",`${head}^{tree}`]),
266
283
  publisherLineages:(index,rows)=>{const target=this.targets[index]!;assertPublisherBoundary(target.store.profile,target.mutation!);return publisherPruneLineages(target.store.profile,target.mutation!,rows);}});
267
284
  // The row-evaluation scope closes with a complete proof before any verdict is planned or made durable.
@@ -274,7 +291,7 @@ class PlacementTransport {
274
291
  for(const d of decisions)counts[d.eligible?"permitted":d.reason==="source-local"?"local":d.reason&&!other.has(d.reason)?"declined":"held"]++;
275
292
  this.progress.counts(counts);
276
293
  }
277
- this.progress?.phase("publication-plan");
294
+ this.enter("publication-plan");
278
295
  const body={epochHash:this.epochHash,generation:this.journal.epoch.generation,homeHash:capture.context.homeHash,contextHash:placementCaptureContextHash(capture),markerHash:capture.markerHash,
279
296
  sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,policyHash:capture.context.policyHash,remoteHash:digest(this.url),
280
297
  journal:frozen?.root.journal??{sequence:frontier.sequence,headHash:frontier.headHash},createdUnixSeconds,policySnapshotUnixMs:frozen?.root.policySnapshotUnixMs??this.lastPolicyCheckUnixMs??Date.now(),targets,reservedRecords:0,reservedRecordBytes:[] as number[]};
@@ -333,7 +350,7 @@ class PlacementTransport {
333
350
  for(const [index,event]of events.entries()){
334
351
  const record=createPlacementRecord(this.epochHash,root.journal.sequence+index+1,head,event);head=record.seal;records.push(record);
335
352
  }
336
- this.progress?.phase(factual?"acknowledgment":"journal","records",count);
353
+ this.enter(factual?"acknowledgment":"journal","records",count);
337
354
  const consumed=read.sequence-root.journal.sequence;
338
355
  if(consumed<0||consumed>root.reservedRecords)refuse();
339
356
  for(let index=0;index<Math.min(consumed,records.length);index++)
@@ -407,7 +424,7 @@ class PlacementTransport {
407
424
  return this.result(false,"unknown","The retained placement attempt may have published; its frozen holds and unknown outcome were preserved. Start a fresh sync to recheck current sources.");
408
425
  }
409
426
  async materializeObjects(bundle:PlacementPublicationBundle):Promise<void>{
410
- this.progress?.phase("artifact-construction","objects",this.targets.reduce((sum,target)=>sum+target.objects.length,0));
427
+ this.enter("artifact-construction","objects",this.targets.reduce((sum,target)=>sum+target.objects.length,0));
411
428
  for(const target of this.targets)for(const object of target.objects){
412
429
  this.check();const file=join(this.root,`.placement-object-${randomBytes(16).toString("hex")}`);this.temporary.push(file);
413
430
  const fd=openSync(file,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
@@ -429,7 +446,7 @@ class PlacementTransport {
429
446
  target.rows = new Map(actual.rows); target.fetched = new Set(actual.rows.keys()); target.origins = new Map(actual.origins);
430
447
  } else { target.rows.clear(); target.fetched.clear(); target.candidate = emptyHistory(); }
431
448
  }
432
- this.preflight(false);this.progress?.phase("import");
449
+ this.preflight(false);this.enter("import");
433
450
  const applications=await this.applicationCoordinator();await applications.prepare();
434
451
  for(const target of this.targets)for(const hold of target.holds)shardInstallHold(this.root,hold);
435
452
  await applications.install();
@@ -447,7 +464,7 @@ class PlacementTransport {
447
464
  if (existing.code === 1 && planned.expectedCacheHead !== null) refuse();
448
465
  await this.required(["update-ref","--no-deref",ref,planned.commit!,planned.expectedCacheHead??"0".repeat(40)]);
449
466
  }
450
- await this.observe("before-receipt");this.progress?.phase("receipt");
467
+ await this.observe("before-receipt");this.enter("receipt");
451
468
  const read=readPlacementPublication(this.home,this.epochHash,root.seal),intent=read.facts.find(fact=>fact.phase==="publication-intent"),journal=readPlacementJournal(this.home,this.epochHash);
452
469
  if(!intent)refuse();
453
470
  recordPlacementPublicationPhase(this.home,this.epochHash,root.seal,"completed",{intentFactHash:intent.seal,journal:{sequence:journal.sequence,headHash:journal.headHash},
@@ -467,7 +484,7 @@ class PlacementTransport {
467
484
  }
468
485
  result(ok:boolean,outcome:"committed"|"unknown"|"not-needed",error?:string):SyncResult{
469
486
  return{ok,pushed:this.accepted&&(this.attempted||this.recovered&&!!this.current?.bundle.root.targets.some(target=>target.publish)),entries:this.current?.exported??0,...(error?{error}:{}),...(this.applications?{pruneApplication:{...this.applications.application}}:{}),
470
- placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
487
+ placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
471
488
  ...(this.lastPolicyHash?{lastPolicyHash:this.lastPolicyHash}:{}),...(this.lastPolicyCheckUnixMs!==undefined?{lastPolicyCheckUnixMs:this.lastPolicyCheckUnixMs,policyCheckSource:this.policyCheckSource??(this.recovered?"durable-intent" as const:"live" as const)}:{}),
472
489
  policyCeiling:"last-positive-check-before-in-flight-push",...(this.recovered?{recovered:true}:{})}};
473
490
  }
@@ -477,7 +494,7 @@ class PlacementTransport {
477
494
  // Success is reported only from the real receipt; a failed or stopped run can never leave a successful status.
478
495
  if(result.ok)this.progress?.finish("succeeded");
479
496
  else if(this.opts.signal?.aborted)this.progress?.finish("cancelled","cancelled");
480
- else this.progress?.finish("failed",this.bound?"bound":result.placementPublication?.outcome==="unknown"?"unknown-outcome":"unavailable");
497
+ else this.progress?.finish("failed",this.bound?"bound":result.placementPublication?.outcome==="unknown"?"unknown-outcome":"unavailable",this.bound?"size-bound":this.refusal);
481
498
  return result;
482
499
  }
483
500
  /** Object slots the plan and its reserved journal chunks need, checked before the first durable plan byte. */
@@ -487,7 +504,7 @@ class PlacementTransport {
487
504
  }
488
505
  async execute():Promise<SyncResult>{
489
506
  try{
490
- this.progress?.phase("writer-verification");
507
+ this.enter("writer-verification");
491
508
  await this.initialize();
492
509
  const reservation=this.journal.publicationReservation,retained=reservation?readPlacementPublication(this.home,this.epochHash,reservation.attemptHash):undefined;
493
510
  if(retained){
@@ -502,9 +519,9 @@ class PlacementTransport {
502
519
  this.accepted=true;return await this.finish(this.current,true);
503
520
  }
504
521
  }
505
- this.progress?.phase("source-capture");
522
+ this.enter("source-capture");
506
523
  try { this.preflight();for(const target of this.targets)if(existsSync(join(target.store.dir,"local",`publisher-boundary-${this.machineId}.json`)))assertPublisherBoundary(target.store.profile,target.mutation!);this.startCapture(); }
507
- catch(error) { if(retained)return await this.terminalUnknown(retained);if(placementSyncBoundReceipt(error))throw error;throw new Error("placement source preflight unavailable"); }
524
+ catch(error) { if(retained)return await this.terminalUnknown(retained);if(placementSyncBoundReceipt(error))throw error;throw new PlacementSyncRefusal(placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other"); }
508
525
  if(retained){
509
526
  const root=retained.bundle.root;
510
527
  const stable=root.contextHash===placementCaptureContextHash(this.capture!)&&root.markerHash===this.capture!.markerHash&&root.sourceHash===this.capture!.context.sourceHash
@@ -528,7 +545,7 @@ class PlacementTransport {
528
545
  this.prove();this.lastPolicyCheckUnixMs=Date.now();this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
529
546
  if(!read.facts.some(fact=>fact.phase==="publication-intent"))recordPlacementPublicationPhase(this.home,this.epochHash,material.bundle.root.seal,"publication-intent",{artifactFactHash:artifact.seal,policyHash:material.bundle.root.policyHash,policyCheckUnixMs:material.bundle.root.policySnapshotUnixMs},this.storage());
530
547
  ensurePlacementPublicationDurability(this.home,this.epochHash,this.storage());
531
- await this.observe("before-cas");this.progress?.phase("publication");this.prove();
548
+ await this.observe("before-cas");this.enter("publication");this.prove();
532
549
  const installedGuard=await this.installedObjectGuard(material.bundle);
533
550
  this.prove();for(const target of this.targets)for(const check of target.selectorChecks??[])check();
534
551
  installedGuard();
@@ -548,7 +565,10 @@ class PlacementTransport {
548
565
  // #419: an expected size refusal before any attempt exists keeps its phase, kind, limit and observed value.
549
566
  const bound=this.attemptHash||this.journal?.publicationReservation?undefined:placementSyncBoundReceipt(error);
550
567
  if(bound){this.bound=bound;return this.result(false,"not-needed",placementSyncBoundMessage(bound));}
551
- return this.result(false,this.attemptHash?"unknown":"not-needed",this.attemptHash?"Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.":"Placement sync is unavailable; verify the active epoch, selected sources, policy, private remote and writer pins before retrying.");
568
+ if(this.attemptHash)return this.result(false,"unknown","Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.");
569
+ // #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
570
+ this.refusal=placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other";
571
+ return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));
552
572
  }finally{
553
573
  let ownedCache=true;try{this.metadata();}catch{ownedCache=false;}
554
574
  if(ownedCache){
@@ -9,6 +9,7 @@
9
9
  import { randomBytes } from "node:crypto";
10
10
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
11
11
  import { join } from "node:path";
12
+ import { PLACEMENT_REFUSAL_CATEGORIES, type PlacementRefusalCategory } from "./sync-placement-refusal-category.ts";
12
13
  import { processLiveness, processSignature, type Liveness } from "./platform.ts";
13
14
 
14
15
  export const SYNC_PROGRESS_SCHEMA = "agent-mem.sync-progress/v1", SYNC_PROGRESS_INTERVAL_MS = 1000, SYNC_PROGRESS_DIR = "sync-status";
@@ -35,6 +36,8 @@ export interface SyncProgressSnapshot {
35
36
  /** Advances only when a unit of work or a phase completes; `lastAliveUnixMs` is any checkpoint the process reached. */
36
37
  lastWorkProgressUnixMs: number; lastAliveUnixMs: number;
37
38
  cause?: SyncProgressCause;
39
+ /** #426: for a failed placement sync, the fixed category of the check that refused (allowlisted, no text). */
40
+ category?: PlacementRefusalCategory;
38
41
  }
39
42
  export type SyncProgressSink = (snapshot: SyncProgressSnapshot) => void;
40
43
  export interface SyncProgressOptions { sink: SyncProgressSink; intervalMs?: number; now?: () => number; mono?: () => number; operationId?: string }
@@ -46,7 +49,7 @@ export class SyncProgress {
46
49
  private readonly started: number; private readonly startedMono: number; private phaseMono: number; private emitted = -Infinity;
47
50
  private current: SyncProgressPhase = "writer-verification"; private readonly entered = new Map<SyncProgressPhase, number>();
48
51
  private unit?: SyncProgressUnit; private completed?: number; private total?: number; private outcome?: SyncProgressCounts;
49
- private state: SyncProgressState = "running"; private cause?: SyncProgressCause; private work: number; private aliveAt: number;
52
+ private state: SyncProgressState = "running"; private cause?: SyncProgressCause; private category?: PlacementRefusalCategory; private work: number; private aliveAt: number;
50
53
  private readonly proofs = { complete: 0, fence: 0 };
51
54
  constructor(options: SyncProgressOptions) {
52
55
  this.sink = options.sink; this.intervalMs = Math.max(0, options.intervalMs ?? SYNC_PROGRESS_INTERVAL_MS);
@@ -60,7 +63,7 @@ export class SyncProgress {
60
63
  startedUnixMs: this.started, elapsedMs: Math.round(mono - this.startedMono), phaseElapsedMs: Math.round(mono - this.phaseMono),
61
64
  ...(this.unit ? { unit: this.unit, completed: this.completed ?? 0, ...(this.total !== undefined ? { total: this.total } : {}) } : {}),
62
65
  ...(this.outcome ? { counts: { ...this.outcome } } : {}), proofs: { ...this.proofs },
63
- lastWorkProgressUnixMs: this.work, lastAliveUnixMs: this.aliveAt, ...(this.cause ? { cause: this.cause } : {}) };
66
+ lastWorkProgressUnixMs: this.work, lastAliveUnixMs: this.aliveAt, ...(this.cause ? { cause: this.cause } : {}), ...(this.category ? { category: this.category } : {}) };
64
67
  }
65
68
  private emit(force: boolean): void {
66
69
  if (!this.sink) return; const mono = this.mono();
@@ -80,8 +83,9 @@ export class SyncProgress {
80
83
  proof(complete: boolean): void { this.proofs[complete ? "complete" : "fence"]++; this.alive(); }
81
84
  counts(counts: SyncProgressCounts): void { this.outcome = { ...counts }; }
82
85
  /** Terminal state. Success is reported only by the caller that holds the real sync receipt. */
83
- finish(state: Exclude<SyncProgressState, "running" | "interrupted">, cause?: SyncProgressCause): void {
84
- if (this.state !== "running") return; this.state = state; this.cause = state === "succeeded" ? undefined : cause; this.aliveAt = this.now();
86
+ finish(state: Exclude<SyncProgressState, "running" | "interrupted">, cause?: SyncProgressCause, category?: PlacementRefusalCategory): void {
87
+ if (this.state !== "running") return; this.state = state; this.cause = state === "succeeded" ? undefined : cause;
88
+ this.category = state === "failed" && category && (PLACEMENT_REFUSAL_CATEGORIES as readonly string[]).includes(category) ? category : undefined; this.aliveAt = this.now();
85
89
  if (state === "succeeded") this.work = this.aliveAt; this.emit(true);
86
90
  }
87
91
  }
@@ -92,7 +96,7 @@ export function renderSyncProgress(snapshot: SyncProgressSnapshot, now = Date.no
92
96
  const phase = snapshot.phase.replaceAll("-", " "), units = snapshot.unit ? `: ${snapshot.completed ?? 0}${snapshot.total !== undefined ? `/${snapshot.total}` : ""} ${snapshot.unit}` : "";
93
97
  const counts = snapshot.counts ? `; permitted ${snapshot.counts.permitted}, local ${snapshot.counts.local}, declined ${snapshot.counts.declined}, held ${snapshot.counts.held}` : "";
94
98
  const attempt = snapshot.attempt > 1 ? `; attempt ${snapshot.attempt}` : "";
95
- if (snapshot.state !== "running") return `amem sync: ${snapshot.state}${snapshot.cause ? ` (${snapshot.cause})` : ""} in ${phase}${units}${counts}; elapsed ${seconds(snapshot.elapsedMs)}`;
99
+ if (snapshot.state !== "running") return `amem sync: ${snapshot.state}${snapshot.cause ? ` (${snapshot.cause}${snapshot.category ? `, ${snapshot.category}` : ""})` : ""} in ${phase}${units}${counts}; elapsed ${seconds(snapshot.elapsedMs)}`;
96
100
  return `amem sync: ${phase}${units}${attempt}${counts}; elapsed ${seconds(snapshot.elapsedMs)}; last work progress ${seconds(now - snapshot.lastWorkProgressUnixMs)} ago`;
97
101
  }
98
102
 
@@ -127,13 +131,14 @@ function validate(value: unknown, operationId: string): { snapshot: SyncProgress
127
131
  || !proofs || !count(proofs.complete) || !count(proofs.fence) || !owner || !count(owner.pid) || owner.signature !== undefined && (typeof owner.signature !== "string" || owner.signature.length > 256)
128
132
  || v.unit !== undefined && (!(UNITS as readonly unknown[]).includes(v.unit) || !count(v.completed)) || v.total !== undefined && !count(v.total)
129
133
  || v.cause !== undefined && !(CAUSES as readonly unknown[]).includes(v.cause)
134
+ || v.category !== undefined && !(PLACEMENT_REFUSAL_CATEGORIES as readonly unknown[]).includes(v.category)
130
135
  || counts !== undefined && ![counts.permitted, counts.local, counts.declined, counts.held].every(count)) return undefined;
131
136
  const snapshot: SyncProgressSnapshot = { schema: SYNC_PROGRESS_SCHEMA, operationId, state: v.state as SyncProgressState, phase: v.phase as SyncProgressPhase, attempt: v.attempt as number,
132
137
  startedUnixMs: v.startedUnixMs as number, elapsedMs: v.elapsedMs as number, phaseElapsedMs: v.phaseElapsedMs as number,
133
138
  ...(v.unit !== undefined ? { unit: v.unit as SyncProgressUnit, completed: v.completed as number, ...(v.total !== undefined ? { total: v.total as number } : {}) } : {}),
134
139
  ...(counts ? { counts: { permitted: counts.permitted as number, local: counts.local as number, declined: counts.declined as number, held: counts.held as number } } : {}),
135
140
  proofs: { complete: proofs.complete as number, fence: proofs.fence as number }, lastWorkProgressUnixMs: v.lastWorkProgressUnixMs as number, lastAliveUnixMs: v.lastAliveUnixMs as number,
136
- ...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}) };
141
+ ...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}), ...(v.category !== undefined ? { category: v.category as PlacementRefusalCategory } : {}) };
137
142
  return { snapshot, owner: { pid: owner.pid as number, ...(typeof owner.signature === "string" ? { signature: owner.signature } : {}) } };
138
143
  }
139
144
  function load(dir: string, name: string): { snapshot: SyncProgressSnapshot; owner: Owner } | undefined {
@@ -13,7 +13,8 @@ import { memoryHome } from "./home.ts";
13
13
  import { outboundScreen, screenOutboundRows, screenOwnSegment, type RowScreen } from "./sync-screen.ts";
14
14
  import { shardSyncBinding } from "./sync-binding.ts";
15
15
  import type { PlacementSyncBound } from "./sync-placement-bound.ts";
16
- import type { SyncProgress } from "./sync-progress.ts";
16
+ import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
17
+ import type { PlacementRefusalCategory } from "./sync-placement-refusal.ts";
17
18
 
18
19
  /**
19
20
  * #258 phase 2: hub memory between a person's machines through a git remote they configure. The memory directory is a
@@ -25,7 +26,9 @@ export interface SyncResult { ok: boolean; pushed: boolean; entries: number; war
25
26
  placementPublication?: { attemptHash?: string; outcome: "committed" | "unknown" | "not-needed"; withheld: number; exported: number;
26
27
  lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean;
27
28
  /** #419: an expected size refusal before any publication attempt; numbers only. */
28
- bound?: PlacementSyncBound };
29
+ bound?: PlacementSyncBound;
30
+ /** #426: the fixed category and phase of a refusal before any publication attempt; no path, row or secret. */
31
+ refusal?: { category: PlacementRefusalCategory; phase: SyncProgressPhase } };
29
32
  pruneApplication?: {transport:"durable"|"unconfirmed";proofComplete:number;projectionActive:number|null;nativeApplied:number|null;held:number;phase:"preflight"|"prepared"|"active"|"complete"};
30
33
  }
31
34
 
@@ -0,0 +1,33 @@
1
+ import type { View } from "./store.ts";
2
+
3
+ /**
4
+ * #423: the task a curated note belongs to, for grouping. A note's own `task` wins; otherwise the first `task:` node in
5
+ * `about` (sorted, so every reader picks the same one). The `@<created>` suffix is dropped so a note written with a task
6
+ * and a note that only mentions "task #N" in the same project fold together. Notes without a task never group, and a
7
+ * `shared` note never folds with a project note.
8
+ */
9
+ export function taskGroupKey(view: Pick<View, "task" | "about" | "project"> & { scope?: View["scope"] }): string | undefined {
10
+ const raw = view.task ?? view.about.find(node => node.startsWith("task:"))?.slice(5);
11
+ if (!raw) return undefined;
12
+ const task = raw.includes("#") ? raw.replace(/@\d+$/, "") : `${view.project}#${raw.replace(/@\d+$/, "")}`;
13
+ // A shared note and a project note of one task are different audiences: never fold one into the other.
14
+ return view.scope === "shared" ? `shared:${task}` : task;
15
+ }
16
+
17
+ /**
18
+ * #423: keep the first item of each task group, in input order (callers pass items best first), and count the items
19
+ * it folded in. Items with no curated view or no task are kept as they are with `folded: 0`. Read-time only: rows and
20
+ * the derived index are untouched.
21
+ */
22
+ export function groupByTask<T>(items: readonly T[], view: (item: T) => (Pick<View, "task" | "about" | "project"> & { scope?: View["scope"] }) | undefined): { item: T; folded: number }[] {
23
+ const out: { item: T; folded: number }[] = [], leader = new Map<string, { item: T; folded: number }>();
24
+ for (const item of items) {
25
+ const v = view(item), key = v ? taskGroupKey(v) : undefined;
26
+ const head = key === undefined ? undefined : leader.get(key);
27
+ if (head) { head.folded++; continue; }
28
+ const entry = { item, folded: 0 };
29
+ if (key !== undefined) leader.set(key, entry);
30
+ out.push(entry);
31
+ }
32
+ return out;
33
+ }
@@ -17,10 +17,12 @@ import { pendingLine, pendingSummary } from "./memory/candidate-pending.ts";
17
17
  import { memoryProjectKey } from "./memory/project.ts";
18
18
  import { registerReaderLease } from "./memory/reader-lease.ts";
19
19
  import { type ReadRef, type ReadWindow } from "./memory/search-fts.ts";
20
+ import { briefFailureReason } from "./memory/metrics.ts";
20
21
  import { aliasedKeys, captureShardDir, readShardedSelection, resolveAlias, shardDir } from "./memory/shard.ts";
21
22
  import { projectState } from "./memory/lifecycle.ts";
22
23
  import { boundRepoRoot, nearestRepoRootWithLog, readRepoScope, repoLogNearby, repoLogPresent, repoReadPolicy, type RepoView } from "./memory/repo-scope.ts";
23
- import type { MemoryStore } from "./memory/store.ts";
24
+ import type { MemoryStore, View } from "./memory/store.ts";
25
+ import { taskGroupKey } from "./memory/task-group.ts";
24
26
  import { WorkListStore, type WorkListFields, type WorkListView } from "./memory/work-lists.ts";
25
27
 
26
28
  export interface BriefOptions { cwd: string; base?: string; project?: string; maxTokens?: number; policy?: StandalonePolicyOptions;
@@ -129,8 +131,9 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
129
131
  if (repoLogPresent(repoRoot)) coverage.repo = "complete";
130
132
  const lines: string[] = [];
131
133
  const reasons: Partial<Record<Section, string>> = {};
132
- // Reserve the longest possible fixed header before selecting data; later coverage changes cannot overrun it.
133
- let remaining = maximum - Buffer.byteLength(header({ work: "unavailable", curated: "unavailable", capture: "unavailable", ...(coverage.repo ? { repo: "unavailable" as const } : {}) }, options.nativeSession ? { work: "deadline exhausted", curated: "generation refresh deferred", capture: "capture cache missing" } : {}));
134
+ // Native reasons are accounted for after selection; ordinary briefs keep their existing conservative reservation.
135
+ const reservedHeader = options.nativeSession ? header(coverage) : header({ work: "unavailable", curated: "unavailable", capture: "unavailable", ...(coverage.repo ? { repo: "unavailable" as const } : {}) });
136
+ let remaining = maximum - Buffer.byteLength(reservedHeader);
134
137
  // F7: one line, "N candidates pending, oldest expires in D days", only when some wait, so a brief with none is byte-identical to before. It is numbers only (no candidate text),
135
138
  // read-only (no database is created, pruned or altered here, and neither the brief nor the hook ever stamps a candidate as shown: only `amem review walk` does) and reserved out of the
136
139
  // same byte budget as everything else; when it does not fit it is left out.
@@ -155,7 +158,7 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
155
158
  const deferredReason = sharded || readSelector(base).selector?.kind === "generation" ? "generation refresh deferred" : "curated refresh deferred";
156
159
  const prepared = readCuratedBriefCache({ base, project, profile: curatedProfileBinding(base, project),
157
160
  supportingRelease: CURATED_CACHE_MIN_READER, deferredReason, now: (options.now ?? Date.now)() });
158
- if (!prepared.cache) { coverage.curated = "unavailable"; reasons.curated = prepared.reason!; }
161
+ if (!prepared.cache) { coverage.curated = "unavailable"; reasons.curated = `${prepared.reason!}; use amem_brief`; }
159
162
  else {
160
163
  coverage.curated = prepared.cache.partial ? "partial" : "complete";
161
164
  for (const row of prepared.cache.rows) {
@@ -189,8 +192,8 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
189
192
  if (!floorReason) try { machine = JSON.parse(readFileSync(join(base, "machine.json"), "utf8")).id; } catch { /* no machine, no cache */ }
190
193
  const cache = !floorReason && typeof machine === "string" && /^[a-f0-9]{16}$/.test(machine)
191
194
  ? readBriefCache({ directory: captureShardDir(base, project, machine), project, section: "capture" }) : undefined;
192
- if (floorReason) { coverage.capture = "unavailable"; reasons.capture = floorReason; }
193
- else if (!cache) { coverage.capture = "unavailable"; reasons.capture = "capture cache missing"; }
195
+ if (floorReason) { coverage.capture = "unavailable"; reasons.capture = `${floorReason}; use amem_search`; }
196
+ else if (!cache) { coverage.capture = "unavailable"; reasons.capture = "capture cache missing; use amem_search"; }
194
197
  else {
195
198
  coverage.capture = cache.partial ? "partial" : "complete";
196
199
  for (const row of cache.rows) {
@@ -227,6 +230,10 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
227
230
  const reservedSummary = newest && newest.size - 1 <= RECORD_BYTES && newest.size <= remaining ? newest : undefined;
228
231
  if (reservedSummary) remaining -= reservedSummary.size;
229
232
  else if (newest) coverage.capture = "partial";
233
+ const firstRecord = coverage.repo ? preparedRecords[0] : undefined;
234
+ const reservedRecord = firstRecord && firstRecord.size - 1 <= RECORD_BYTES && firstRecord.size <= remaining ? firstRecord : undefined;
235
+ if (reservedRecord) remaining -= reservedRecord.size;
236
+ else if (firstRecord) coverage.capture = "partial";
230
237
  const emitPrepared = (row: PreparedCapture): boolean => {
231
238
  if (row.size - 1 > RECORD_BYTES || row.size > remaining) { coverage.capture = "partial"; return false; }
232
239
  lines.push(row.line); remaining -= row.size;
@@ -250,13 +257,16 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
250
257
  guard();
251
258
  // ponytail: reserve cold-store variance plus cleanup/serialization before optional work.
252
259
  // A future paged deadline port can refine this section-level cutoff; the parent remains the hard stop.
253
- if (options.timeRemaining && options.timeRemaining() < (section === "work" ? 10 : 80)) { coverage[section] = "unavailable"; if (options.nativeSession) reasons[section] = "deadline exhausted"; return; }
260
+ if (options.timeRemaining && options.timeRemaining() < (section === "work" ? 10 : 80)) { coverage[section] = "unavailable"; if (options.nativeSession) reasons[section] = `deadline exhausted; ${section === "repo" ? "inspect repo log" : `use ${section === "work" ? "amem_work_state_read" : section === "curated" ? "amem_brief" : "amem_search"}`}`; return; }
254
261
  await work(); guard();
255
262
  }
256
263
  catch (error) {
257
264
  if (error instanceof BindingChanged || drifted) throw new BindingChanged();
258
265
  lines.splice(firstLine); remaining = priorRemaining; coverage[section] = "unavailable";
259
- if (options.nativeSession) reasons[section] = section === "capture" ? "capture history deferred" : "deadline exhausted";
266
+ if (options.nativeSession) {
267
+ const cause = briefFailureReason(error, options.timeRemaining);
268
+ reasons[section] = `${cause}; ${section === "repo" ? "inspect repo log" : `use ${section === "work" ? "amem_work_state_read" : section === "curated" ? "amem_brief" : "amem_search"}`}`;
269
+ }
260
270
  }
261
271
  };
262
272
  if (remaining < 0) {
@@ -279,6 +289,7 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
279
289
  const recent = async <T>(section: "curated" | "capture", read: (window: ReadWindow) => { rows: T[]; next?: ReadRef },
280
290
  display: (row: T) => { data: unknown; partial: boolean }, selectedBefore = 0, skipCaptureIds: ReadonlySet<number> = new Set()) => {
281
291
  let after: ReadWindow["after"], selected = selectedBefore, complete = false;
292
+ const tasks = new Set<string>(); // #423: one curated row per task, the newest; later same-task rows take no slot
282
293
  for (let pageNumber = 0; pageNumber < MAX_PAGES; pageNumber++) {
283
294
  guard();
284
295
  if (options.nativeSession && options.timeRemaining && options.timeRemaining() <= 0) throw new Error("brief deadline");
@@ -291,6 +302,9 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
291
302
  // Records have their own five-row, whole-line selection before raw captures.
292
303
  if (section === "capture" && (row as { event?: unknown }).event === "Record") continue;
293
304
  if (!await screen(row)) continue;
305
+ const group = section === "curated" ? taskGroupKey(row as unknown as View) : undefined;
306
+ if (group !== undefined && tasks.has(group)) continue;
307
+ if (group !== undefined) tasks.add(group);
294
308
  if (selected++ >= SECTION_RECORDS) { coverage[section] = "partial"; return; }
295
309
  await add(section, display(row), section === "curated");
296
310
  }
@@ -324,10 +338,10 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
324
338
  });
325
339
  if (coverage.repo) await run("repo", async () => {
326
340
  const scoped = repoReadPolicy(repoRoot!, configuredPolicyOptions(base, cwd, options.policy));
327
- if ("reason" in scoped) { coverage.repo = "unavailable"; reasons.repo = "repo policy unreadable"; return; }
341
+ if ("reason" in scoped) { coverage.repo = "unavailable"; reasons.repo = "repo policy unreadable; inspect repo policy"; return; }
328
342
  // The newest few rows only, and never past the caller's deadline: the read stops (partial) when less than the reserve is left, so a 1 MiB log cannot spend the hook's budget.
329
343
  const repo = await readRepoScope(repoRoot, scoped.policy, { limit: SECTION_RECORDS + 1, ...(options.timeRemaining ? { remainingMs: options.timeRemaining, reserveMs: 20 } : {}) }); guard();
330
- if (repo.state === "unsafe") { coverage.repo = "unavailable"; reasons.repo = "repo log is not a plain file"; return; }
344
+ if (repo.state === "unsafe") { coverage.repo = "unavailable"; reasons.repo = "repo log is not a plain file; inspect repo log"; return; }
331
345
  if (repo.partial || repo.skipped.withheld) coverage.repo = "partial";
332
346
  let shownRepo = 0; // not `selected`: scripts/measure-hook-stages.ts anchors on that exact line once
333
347
  for (const view of repo.views) {
@@ -336,7 +350,8 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
336
350
  }
337
351
  });
338
352
  if (nativeCache) {
339
- for (const row of preparedRecords) emitPrepared(row);
353
+ if (reservedRecord) { lines.push(reservedRecord.line); if (reservedRecord.partial) coverage.capture = "partial"; }
354
+ for (const row of preparedRecords.slice(reservedRecord ? 1 : 0)) emitPrepared(row);
340
355
  emitReserved();
341
356
  for (const row of preparedSummaries.slice(1)) emitPrepared(row);
342
357
  } else {
@@ -365,8 +380,19 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
365
380
  }
366
381
  }
367
382
  guard();
368
- const context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
369
- result = { context, tokens: Buffer.byteLength(context), partial: Object.values(coverage).some(value => value !== "complete"), coverage };
383
+ let context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
384
+ while (Buffer.byteLength(context) > maximum && lines.length) {
385
+ const repoIndex = lines.findLastIndex(line => line.startsWith('{"section":"repo",'));
386
+ const removed = JSON.parse(lines.splice(repoIndex >= 0 ? repoIndex : lines.length - 1, 1)[0]!) as { section?: Section };
387
+ if (removed.section && coverage[removed.section] === "complete") coverage[removed.section] = "partial";
388
+ context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
389
+ }
390
+ if (Buffer.byteLength(context) > maximum && candidateLine) {
391
+ candidateLine = undefined;
392
+ context = [header(coverage, reasons), ...lines].join("\n");
393
+ }
394
+ if (Buffer.byteLength(context) > maximum) result = unavailable();
395
+ else result = { context, tokens: Buffer.byteLength(context), partial: Object.values(coverage).some(value => value !== "complete"), coverage };
370
396
  }
371
397
  } catch { result = unavailable(); }
372
398
  finally {