@staix/agent-mem 0.26.2 → 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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +8 -3
- package/package.json +1 -1
- package/src/brief-curated-native.ts +1 -1
- package/src/brief-curated.ts +5 -0
- package/src/cli.ts +31 -1
- package/src/commands-table.ts +5 -3
- package/src/hooks.ts +9 -4
- package/src/index.ts +1 -0
- package/src/mcp-memory.ts +10 -2
- package/src/mcp.ts +1 -1
- package/src/memory/commands.ts +13 -5
- package/src/memory/config.ts +11 -1
- package/src/memory/metrics.ts +40 -1
- package/src/memory/recall-staleness.ts +7 -4
- package/src/memory/shard-sync-history.ts +5 -1
- package/src/memory/store.ts +22 -9
- package/src/memory/sync-placement-active.ts +21 -0
- package/src/memory/sync-placement-bound.ts +39 -0
- package/src/memory/sync-placement-capture.ts +2 -1
- package/src/memory/sync-placement-dependencies.ts +6 -4
- package/src/memory/sync-placement-journal-storage.ts +70 -15
- package/src/memory/sync-placement-materialize.ts +20 -9
- package/src/memory/sync-placement-projection.ts +10 -1
- package/src/memory/sync-placement-publication-plan.ts +4 -2
- package/src/memory/sync-placement-refusal-category.ts +3 -0
- package/src/memory/sync-placement-refusal.ts +49 -0
- package/src/memory/sync-placement-transport.ts +138 -59
- package/src/memory/sync-progress.ts +197 -0
- package/src/memory/sync.ts +17 -3
- package/src/memory/task-group.ts +33 -0
- package/src/session-brief.ts +39 -13
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #418: advisory progress for a long-running placement sync. Telemetry only: never mutation authority, a publication
|
|
3
|
+
* receipt or proof of success. A snapshot carries phase names, unit counts and timestamps, never a memory body, path,
|
|
4
|
+
* project name, row id, policy pattern, credential or remote URL.
|
|
5
|
+
*
|
|
6
|
+
* There is no timer. Every update is a cooperative checkpoint reached by real work, so a blocked call or a starved
|
|
7
|
+
* event loop leaves an honest stale `lastAliveUnixMs` instead of a manufactured heartbeat.
|
|
8
|
+
*/
|
|
9
|
+
import { randomBytes } from "node:crypto";
|
|
10
|
+
import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { PLACEMENT_REFUSAL_CATEGORIES, type PlacementRefusalCategory } from "./sync-placement-refusal-category.ts";
|
|
13
|
+
import { processLiveness, processSignature, type Liveness } from "./platform.ts";
|
|
14
|
+
|
|
15
|
+
export const SYNC_PROGRESS_SCHEMA = "agent-mem.sync-progress/v1", SYNC_PROGRESS_INTERVAL_MS = 1000, SYNC_PROGRESS_DIR = "sync-status";
|
|
16
|
+
const MAX_OPERATIONS = 8, MAX_BYTES = 4096, MAX_NAMES = 64;
|
|
17
|
+
const PHASES = ["writer-verification", "remote-verification", "source-capture", "policy-evaluation", "dependency-decisions", "artifact-construction",
|
|
18
|
+
"publication-plan", "journal", "publication", "acknowledgment", "import", "receipt"] as const;
|
|
19
|
+
const UNITS = ["rows", "records", "objects"] as const, STATES = ["running", "succeeded", "failed", "cancelled", "interrupted"] as const;
|
|
20
|
+
const CAUSES = ["bound", "unknown-outcome", "unavailable", "cancelled"] as const;
|
|
21
|
+
export type SyncProgressPhase = typeof PHASES[number];
|
|
22
|
+
export type SyncProgressUnit = typeof UNITS[number];
|
|
23
|
+
export type SyncProgressState = typeof STATES[number];
|
|
24
|
+
export type SyncProgressCause = typeof CAUSES[number];
|
|
25
|
+
export interface SyncProgressCounts { permitted: number; local: number; declined: number; held: number }
|
|
26
|
+
export interface SyncProgressSnapshot {
|
|
27
|
+
schema: typeof SYNC_PROGRESS_SCHEMA; operationId: string; state: SyncProgressState; phase: SyncProgressPhase;
|
|
28
|
+
/** How many times this operation entered this phase; completed counts are monotonic within one phase attempt. */
|
|
29
|
+
attempt: number;
|
|
30
|
+
startedUnixMs: number; elapsedMs: number; phaseElapsedMs: number;
|
|
31
|
+
/** Absent when the phase has no countable unit or its total is not genuinely known. No percentage or ETA is derived. */
|
|
32
|
+
unit?: SyncProgressUnit; completed?: number; total?: number;
|
|
33
|
+
counts?: SyncProgressCounts;
|
|
34
|
+
/** Complete writer/source proofs and cheap fence checks so far (#417 measurement counters). */
|
|
35
|
+
proofs: { complete: number; fence: number };
|
|
36
|
+
/** Advances only when a unit of work or a phase completes; `lastAliveUnixMs` is any checkpoint the process reached. */
|
|
37
|
+
lastWorkProgressUnixMs: number; lastAliveUnixMs: number;
|
|
38
|
+
cause?: SyncProgressCause;
|
|
39
|
+
/** #426: for a failed placement sync, the fixed category of the check that refused (allowlisted, no text). */
|
|
40
|
+
category?: PlacementRefusalCategory;
|
|
41
|
+
}
|
|
42
|
+
export type SyncProgressSink = (snapshot: SyncProgressSnapshot) => void;
|
|
43
|
+
export interface SyncProgressOptions { sink: SyncProgressSink; intervalMs?: number; now?: () => number; mono?: () => number; operationId?: string }
|
|
44
|
+
|
|
45
|
+
/** Reporter shared by the CLI and the transport. A sink that throws is dropped; it can never fail or alter the sync. */
|
|
46
|
+
export class SyncProgress {
|
|
47
|
+
readonly operationId: string;
|
|
48
|
+
private sink?: SyncProgressSink; private readonly intervalMs: number; private readonly now: () => number; private readonly mono: () => number;
|
|
49
|
+
private readonly started: number; private readonly startedMono: number; private phaseMono: number; private emitted = -Infinity;
|
|
50
|
+
private current: SyncProgressPhase = "writer-verification"; private readonly entered = new Map<SyncProgressPhase, number>();
|
|
51
|
+
private unit?: SyncProgressUnit; private completed?: number; private total?: number; private outcome?: SyncProgressCounts;
|
|
52
|
+
private state: SyncProgressState = "running"; private cause?: SyncProgressCause; private category?: PlacementRefusalCategory; private work: number; private aliveAt: number;
|
|
53
|
+
private readonly proofs = { complete: 0, fence: 0 };
|
|
54
|
+
constructor(options: SyncProgressOptions) {
|
|
55
|
+
this.sink = options.sink; this.intervalMs = Math.max(0, options.intervalMs ?? SYNC_PROGRESS_INTERVAL_MS);
|
|
56
|
+
this.now = options.now ?? Date.now; this.mono = options.mono ?? (() => performance.now());
|
|
57
|
+
this.operationId = options.operationId ?? randomBytes(8).toString("hex");
|
|
58
|
+
this.started = this.work = this.aliveAt = this.now(); this.startedMono = this.phaseMono = this.mono(); this.emit(true);
|
|
59
|
+
}
|
|
60
|
+
snapshot(): SyncProgressSnapshot {
|
|
61
|
+
const mono = this.mono();
|
|
62
|
+
return { schema: SYNC_PROGRESS_SCHEMA, operationId: this.operationId, state: this.state, phase: this.current, attempt: this.entered.get(this.current) ?? 1,
|
|
63
|
+
startedUnixMs: this.started, elapsedMs: Math.round(mono - this.startedMono), phaseElapsedMs: Math.round(mono - this.phaseMono),
|
|
64
|
+
...(this.unit ? { unit: this.unit, completed: this.completed ?? 0, ...(this.total !== undefined ? { total: this.total } : {}) } : {}),
|
|
65
|
+
...(this.outcome ? { counts: { ...this.outcome } } : {}), proofs: { ...this.proofs },
|
|
66
|
+
lastWorkProgressUnixMs: this.work, lastAliveUnixMs: this.aliveAt, ...(this.cause ? { cause: this.cause } : {}), ...(this.category ? { category: this.category } : {}) };
|
|
67
|
+
}
|
|
68
|
+
private emit(force: boolean): void {
|
|
69
|
+
if (!this.sink) return; const mono = this.mono();
|
|
70
|
+
if (!force && mono - this.emitted < this.intervalMs) return; this.emitted = mono;
|
|
71
|
+
try { this.sink(this.snapshot()); } catch { this.sink = undefined; }
|
|
72
|
+
}
|
|
73
|
+
/** A phase change is always reported at once, before its long work begins. */
|
|
74
|
+
phase(phase: SyncProgressPhase, unit?: SyncProgressUnit, total?: number): void {
|
|
75
|
+
if (this.state !== "running") return;
|
|
76
|
+
this.current = phase; this.entered.set(phase, (this.entered.get(phase) ?? 0) + 1);
|
|
77
|
+
this.unit = unit; this.completed = unit ? 0 : undefined; this.total = unit && total !== undefined && Number.isSafeInteger(total) && total >= 0 ? total : undefined;
|
|
78
|
+
this.phaseMono = this.mono(); this.work = this.aliveAt = this.now(); this.emit(true);
|
|
79
|
+
}
|
|
80
|
+
advance(count = 1): void { if (this.state !== "running" || !this.unit) return; this.completed = (this.completed ?? 0) + count; this.work = this.aliveAt = this.now(); this.emit(false); }
|
|
81
|
+
/** A reached checkpoint that completed no unit: it never moves completed counts or the last-work timestamp. */
|
|
82
|
+
alive(): void { if (this.state !== "running") return; this.aliveAt = this.now(); this.emit(false); }
|
|
83
|
+
proof(complete: boolean): void { this.proofs[complete ? "complete" : "fence"]++; this.alive(); }
|
|
84
|
+
counts(counts: SyncProgressCounts): void { this.outcome = { ...counts }; }
|
|
85
|
+
/** Terminal state. Success is reported only by the caller that holds the real sync receipt. */
|
|
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();
|
|
89
|
+
if (state === "succeeded") this.work = this.aliveAt; this.emit(true);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const seconds = (ms: number) => `${Math.max(0, Math.round(ms / 1000))}s`;
|
|
94
|
+
/** One human line; unknown totals stay unknown and no percentage or ETA is printed. */
|
|
95
|
+
export function renderSyncProgress(snapshot: SyncProgressSnapshot, now = Date.now()): string {
|
|
96
|
+
const phase = snapshot.phase.replaceAll("-", " "), units = snapshot.unit ? `: ${snapshot.completed ?? 0}${snapshot.total !== undefined ? `/${snapshot.total}` : ""} ${snapshot.unit}` : "";
|
|
97
|
+
const counts = snapshot.counts ? `; permitted ${snapshot.counts.permitted}, local ${snapshot.counts.local}, declined ${snapshot.counts.declined}, held ${snapshot.counts.held}` : "";
|
|
98
|
+
const attempt = snapshot.attempt > 1 ? `; attempt ${snapshot.attempt}` : "";
|
|
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)}`;
|
|
100
|
+
return `amem sync: ${phase}${units}${attempt}${counts}; elapsed ${seconds(snapshot.elapsedMs)}; last work progress ${seconds(now - snapshot.lastWorkProgressUnixMs)} ago`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
interface Owner { pid: number; signature?: string }
|
|
104
|
+
function privateDirectory(dir: string): boolean {
|
|
105
|
+
const stat = lstatSync(dir, { throwIfNoEntry: false });
|
|
106
|
+
return !!stat && stat.isDirectory() && !stat.isSymbolicLink() && stat.uid === process.getuid?.() && (stat.mode & 0o077) === 0;
|
|
107
|
+
}
|
|
108
|
+
function names(dir: string): string[] {
|
|
109
|
+
const reader = opendirSync(dir), found: string[] = [];
|
|
110
|
+
try { for (;;) { const entry = reader.readSync(); if (!entry || found.length >= MAX_NAMES) break; if (/^[a-f0-9]{16}\.json$/.test(entry.name)) found.push(entry.name); } } finally { reader.closeSync(); }
|
|
111
|
+
return found;
|
|
112
|
+
}
|
|
113
|
+
function readBounded(file: string): Buffer | undefined {
|
|
114
|
+
const before = lstatSync(file, { throwIfNoEntry: false });
|
|
115
|
+
if (!before || !before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.size > MAX_BYTES) return undefined;
|
|
116
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
117
|
+
try {
|
|
118
|
+
const stat = fstatSync(fd); if (!stat.isFile() || stat.size > MAX_BYTES) return undefined;
|
|
119
|
+
const bytes = Buffer.alloc(stat.size); let at = 0;
|
|
120
|
+
while (at < bytes.length) { const count = readSync(fd, bytes, at, bytes.length - at, at); if (count <= 0) return undefined; at += count; }
|
|
121
|
+
return bytes;
|
|
122
|
+
} finally { closeSync(fd); }
|
|
123
|
+
}
|
|
124
|
+
const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
125
|
+
/** Allowlisted enumerations and non-negative integers only: a tampered sidecar cannot inject text into a terminal. */
|
|
126
|
+
function validate(value: unknown, operationId: string): { snapshot: SyncProgressSnapshot; owner: Owner } | undefined {
|
|
127
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
128
|
+
const v = value as Record<string, unknown>, owner = v.owner as Record<string, unknown> | undefined, proofs = v.proofs as Record<string, unknown> | undefined, counts = v.counts as Record<string, unknown> | undefined;
|
|
129
|
+
if (v.schema !== SYNC_PROGRESS_SCHEMA || v.operationId !== operationId || !(STATES as readonly unknown[]).includes(v.state) || !(PHASES as readonly unknown[]).includes(v.phase)
|
|
130
|
+
|| ![v.attempt, v.startedUnixMs, v.elapsedMs, v.phaseElapsedMs, v.lastWorkProgressUnixMs, v.lastAliveUnixMs].every(count)
|
|
131
|
+
|| !proofs || !count(proofs.complete) || !count(proofs.fence) || !owner || !count(owner.pid) || owner.signature !== undefined && (typeof owner.signature !== "string" || owner.signature.length > 256)
|
|
132
|
+
|| v.unit !== undefined && (!(UNITS as readonly unknown[]).includes(v.unit) || !count(v.completed)) || v.total !== undefined && !count(v.total)
|
|
133
|
+
|| v.cause !== undefined && !(CAUSES as readonly unknown[]).includes(v.cause)
|
|
134
|
+
|| v.category !== undefined && !(PLACEMENT_REFUSAL_CATEGORIES as readonly unknown[]).includes(v.category)
|
|
135
|
+
|| counts !== undefined && ![counts.permitted, counts.local, counts.declined, counts.held].every(count)) return undefined;
|
|
136
|
+
const snapshot: SyncProgressSnapshot = { schema: SYNC_PROGRESS_SCHEMA, operationId, state: v.state as SyncProgressState, phase: v.phase as SyncProgressPhase, attempt: v.attempt as number,
|
|
137
|
+
startedUnixMs: v.startedUnixMs as number, elapsedMs: v.elapsedMs as number, phaseElapsedMs: v.phaseElapsedMs as number,
|
|
138
|
+
...(v.unit !== undefined ? { unit: v.unit as SyncProgressUnit, completed: v.completed as number, ...(v.total !== undefined ? { total: v.total as number } : {}) } : {}),
|
|
139
|
+
...(counts ? { counts: { permitted: counts.permitted as number, local: counts.local as number, declined: counts.declined as number, held: counts.held as number } } : {}),
|
|
140
|
+
proofs: { complete: proofs.complete as number, fence: proofs.fence as number }, lastWorkProgressUnixMs: v.lastWorkProgressUnixMs as number, lastAliveUnixMs: v.lastAliveUnixMs as number,
|
|
141
|
+
...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}), ...(v.category !== undefined ? { category: v.category as PlacementRefusalCategory } : {}) };
|
|
142
|
+
return { snapshot, owner: { pid: owner.pid as number, ...(typeof owner.signature === "string" ? { signature: owner.signature } : {}) } };
|
|
143
|
+
}
|
|
144
|
+
function load(dir: string, name: string): { snapshot: SyncProgressSnapshot; owner: Owner } | undefined {
|
|
145
|
+
try { const bytes = readBounded(join(dir, name)); return bytes ? validate(JSON.parse(bytes.toString("utf8")), name.slice(0, 16)) : undefined; } catch { return undefined; }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Telemetry sidecar under `<home>/sync-status/<operationId>.json`: outside every source, journal and proof namespace,
|
|
150
|
+
* one file per operation, replaced atomically at most once per reporting interval. It keeps the newest 8 operations;
|
|
151
|
+
* a running operation whose owner is alive is never pruned. Any failure throws into the reporter, which drops the sink.
|
|
152
|
+
*/
|
|
153
|
+
export function syncProgressSidecar(home: string, owner: Owner = { pid: process.pid, ...(processSignature(process.pid) ? { signature: processSignature(process.pid)! } : {}) }): SyncProgressSink {
|
|
154
|
+
const dir = join(home, SYNC_PROGRESS_DIR); let ready = false;
|
|
155
|
+
return snapshot => {
|
|
156
|
+
if (!ready) {
|
|
157
|
+
mkdirSync(dir, { mode: 0o700, recursive: true }); if (!privateDirectory(dir)) throw new Error("sync status directory unavailable");
|
|
158
|
+
const kept = names(dir).filter(name => name !== `${snapshot.operationId}.json`).map(name => ({ name, mtimeMs: lstatSync(join(dir, name), { throwIfNoEntry: false })?.mtimeMs ?? 0 })).sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
159
|
+
for (const { name } of kept.slice(MAX_OPERATIONS - 1)) {
|
|
160
|
+
const old = load(dir, name);
|
|
161
|
+
if (!old || old.snapshot.state !== "running" || processLiveness(old.owner.pid, old.owner.signature) === "gone") rmSync(join(dir, name), { force: true });
|
|
162
|
+
}
|
|
163
|
+
ready = true;
|
|
164
|
+
}
|
|
165
|
+
const file = join(dir, `${snapshot.operationId}.json`), temporary = join(dir, `.${snapshot.operationId}.tmp`);
|
|
166
|
+
rmSync(temporary, { force: true }); writeFileSync(temporary, JSON.stringify({ ...snapshot, owner }) + "\n", { mode: 0o600, flag: "wx" }); renameSync(temporary, file);
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export interface SyncOperationStatus extends SyncProgressSnapshot { ownerLiveness: Liveness; lastAliveAgoMs: number; lastWorkProgressAgoMs: number }
|
|
171
|
+
export interface SyncStatusReport { operations: SyncOperationStatus[]; malformed: number }
|
|
172
|
+
/**
|
|
173
|
+
* Read-only status for another terminal: opens no realm, takes no lock, renews no proof and writes nothing. A running
|
|
174
|
+
* operation whose owner is gone is reported as interrupted, never as a success; unreadable sidecars are only counted.
|
|
175
|
+
*/
|
|
176
|
+
export function readSyncStatus(home: string, now = Date.now(), liveness: (pid: number, signature?: string) => Liveness = processLiveness): SyncStatusReport {
|
|
177
|
+
const dir = join(home, SYNC_PROGRESS_DIR), report: SyncStatusReport = { operations: [], malformed: 0 };
|
|
178
|
+
if (!privateDirectory(dir)) return report;
|
|
179
|
+
for (const name of names(dir)) {
|
|
180
|
+
const read = load(dir, name); if (!read) { report.malformed++; continue; }
|
|
181
|
+
const ownerLiveness = read.snapshot.state === "running" ? liveness(read.owner.pid, read.owner.signature) : "gone";
|
|
182
|
+
report.operations.push({ ...read.snapshot, ...(read.snapshot.state === "running" && ownerLiveness === "gone" ? { state: "interrupted" as const } : {}), ownerLiveness,
|
|
183
|
+
lastAliveAgoMs: Math.max(0, now - read.snapshot.lastAliveUnixMs), lastWorkProgressAgoMs: Math.max(0, now - read.snapshot.lastWorkProgressUnixMs) });
|
|
184
|
+
}
|
|
185
|
+
report.operations.sort((a, b) => b.startedUnixMs - a.startedUnixMs || a.operationId.localeCompare(b.operationId));
|
|
186
|
+
report.operations.splice(MAX_OPERATIONS); return report;
|
|
187
|
+
}
|
|
188
|
+
export function renderSyncStatus(report: SyncStatusReport, now = Date.now()): string {
|
|
189
|
+
if (!report.operations.length) return `no placement sync operation recorded${report.malformed ? ` (${report.malformed} unreadable status file${report.malformed === 1 ? "" : "s"} ignored)` : ""}`;
|
|
190
|
+
const lines = report.operations.map(row => {
|
|
191
|
+
const line = renderSyncProgress(row, now).replace(/^amem sync: /, "");
|
|
192
|
+
const tail = row.state === "running" ? `; last observed alive ${seconds(row.lastAliveAgoMs)} ago${row.ownerLiveness === "unknown" ? "; owner liveness unknown" : ""}; percentage and ETA unknown`
|
|
193
|
+
: row.state === "interrupted" ? `; owner process is gone; last observed alive ${seconds(row.lastAliveAgoMs)} ago; not a successful sync` : "";
|
|
194
|
+
return `${row.operationId} ${row.state === "interrupted" ? line.replace(/; last work progress .*$/, "").replace(/^/, "interrupted in ") : line}${tail}`;
|
|
195
|
+
});
|
|
196
|
+
return [...lines, ...(report.malformed ? [`(${report.malformed} unreadable status file${report.malformed === 1 ? "" : "s"} ignored)`] : [])].join("\n");
|
|
197
|
+
}
|
package/src/memory/sync.ts
CHANGED
|
@@ -8,8 +8,13 @@ import { memoryGitArgv, memoryGitEnv, memoryGitSync, processLiveness, processSig
|
|
|
8
8
|
import { acquireMutation } from "./mutation.ts";
|
|
9
9
|
import type { MemoryStore } from "./store.ts";
|
|
10
10
|
import { syncGenerationMemory } from "./generation-sync.ts";
|
|
11
|
+
import { loadAmemConfig } from "./config.ts";
|
|
12
|
+
import { memoryHome } from "./home.ts";
|
|
11
13
|
import { outboundScreen, screenOutboundRows, screenOwnSegment, type RowScreen } from "./sync-screen.ts";
|
|
12
14
|
import { shardSyncBinding } from "./sync-binding.ts";
|
|
15
|
+
import type { PlacementSyncBound } from "./sync-placement-bound.ts";
|
|
16
|
+
import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
|
|
17
|
+
import type { PlacementRefusalCategory } from "./sync-placement-refusal.ts";
|
|
13
18
|
|
|
14
19
|
/**
|
|
15
20
|
* #258 phase 2: hub memory between a person's machines through a git remote they configure. The memory directory is a
|
|
@@ -19,7 +24,11 @@ import { shardSyncBinding } from "./sync-binding.ts";
|
|
|
19
24
|
export type Visibility = "public" | "private" | "unknown";
|
|
20
25
|
export interface SyncResult { ok: boolean; pushed: boolean; entries: number; warning?: string; error?: string;
|
|
21
26
|
placementPublication?: { attemptHash?: string; outcome: "committed" | "unknown" | "not-needed"; withheld: number; exported: number;
|
|
22
|
-
lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean
|
|
27
|
+
lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean;
|
|
28
|
+
/** #419: an expected size refusal before any publication attempt; numbers only. */
|
|
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 } };
|
|
23
32
|
pruneApplication?: {transport:"durable"|"unconfirmed";proofComplete:number;projectionActive:number|null;nativeApplied:number|null;held:number;phase:"preflight"|"prepared"|"active"|"complete"};
|
|
24
33
|
}
|
|
25
34
|
|
|
@@ -179,10 +188,13 @@ export function githubRepoOf(url: string): string | undefined {
|
|
|
179
188
|
return match && match[2] !== "." && match[2] !== ".." ? `${match[1]}/${match[2]}` : undefined;
|
|
180
189
|
}
|
|
181
190
|
|
|
182
|
-
/**
|
|
191
|
+
/**
|
|
192
|
+
* GitHub remotes are asked through `gh`, pinned to github.com. Any other URL is private only when it exactly matches the home's
|
|
193
|
+
* person-attested `privateRemotes` (#420); otherwise, or when `gh` cannot answer or the policy is unreadable, it is unknown.
|
|
194
|
+
*/
|
|
183
195
|
export async function remoteVisibility(url: string): Promise<Visibility> {
|
|
184
196
|
const repo = githubRepoOf(url);
|
|
185
|
-
if (!repo) return "unknown";
|
|
197
|
+
if (!repo) { try { return loadAmemConfig(memoryHome()).config.privateRemotes?.includes(url) ? "private" : "unknown"; } catch { return "unknown"; } }
|
|
186
198
|
try {
|
|
187
199
|
// GH_HOST (and the enterprise token variables) would send `gh repo view` to a different server: pin it, so the answer is about github.com's repository.
|
|
188
200
|
const env: Record<string, string | undefined> = { ...process.env, GH_HOST: "github.com" };
|
|
@@ -220,6 +232,8 @@ function lock(dir: string): (() => void) | undefined {
|
|
|
220
232
|
export interface SyncOptions {
|
|
221
233
|
/** Fresh compatibility facts for an already activated v3 profile; never activates a legacy profile or bypasses policy. */
|
|
222
234
|
placementAttestation?: PlacementCapturePort["attest"];
|
|
235
|
+
/** #418: advisory placement-sync progress reporter; never authority, and a failing sink cannot fail the sync. */
|
|
236
|
+
progress?: SyncProgress;
|
|
223
237
|
/** Set (or replace) the remote first: a person's choice. */
|
|
224
238
|
remote?: string;
|
|
225
239
|
visibility?: (url: string) => Promise<Visibility>;
|
|
@@ -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
|
+
}
|
package/src/session-brief.ts
CHANGED
|
@@ -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
|
-
//
|
|
133
|
-
|
|
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] =
|
|
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)
|
|
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
|
-
|
|
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
|
-
|
|
369
|
-
|
|
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 {
|