@staix/agent-mem 0.27.1 → 0.28.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.27.1",
3
+ "version": "0.28.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.27.1. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.28.0. Requires Bun 1.4.2 or later; no runtime dependencies.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
@@ -173,7 +173,7 @@ The manifest holds the absolute path and sha256 of `src/ui/plugin.ts` (of the `-
173
173
 
174
174
  - Reads are screened. Search, Timeline and Work lists call the in-process `amem_search`, `amem_timeline` and `amem_work_state_read` handlers for the chosen project and forward every option the tool declares, so console search returns exactly the `amem_search` set for the same query. Goals and the review queue pass the configured policy; a candidate that fails it, or whose target fails it, is not shown (the panel counts it and points to `amem review walk`). The console never shows unscreened content, also not to the person. It runs in no repository, so a repository's `.amem/config` narrowing does not apply; the machine's `amem.config.json` does.
175
175
  - Recap computes the current SessionStart brief only on its own panel snapshots, using machine policy. Curated and work inputs use bounded private scratch copies; capture is read-only, and no live reader lease is taken. It shows the full context, coverage, partial status, token upper bound and generation time; it is not a stored copy of a prior session's injected brief. The console has no repository binding, so the repository section is absent. No recap or new capture field is stored in the memory home.
176
- - Review shows the candidate kind, proposal, correction diff, stored evidence references, target-note quotes with dates and similar memories. Source sessions, proposing agents and times seen are not recorded by the candidate schema; the panel labels them unavailable rather than inferring them from capture data. An explicitly unavailable project is refused instead of falling back to another project.
176
+ - Review shows the candidate kind, proposal, correction diff, stored evidence references, target-note quotes with dates and similar memories. Since 0.28.0 a candidate records the origin its proposer supplied (#323): the capture session key, the proposing peer, the time and an optional turn id, as ids only. Review, `review list`, `review decide`, `review walk` and the panel show it, or `unavailable` when the proposer supplied none and `unknown` for a candidate proposed before 0.28.0; nothing is inferred from capture data. An accepted note keeps the origin as `session:`, `peer:`, `origin-at:` and `turn:` graph edges; a goal promotion keeps its origin on the candidate instead. Re-checking a note against its origin works only while that capture session is retained (capture is machine-local and expires); only a confirmed absence from a readable capture store reads as `origin expired` (shown by `review decide`); a missing, cold or policy-withheld capture reads as `unavailable`, never as a failed check. `amem show capture:<id>` prints a capture row with its session and time. An MCP server records origin when its host sets `AMEM_ORIGIN_SESSION` (hashed like capture) and `AGENTHUB_PEER_ID`. An explicitly unavailable project is refused instead of falling back to another project.
177
177
  - Review actions are the CLI's. Accept runs the same acceptance as `amem review accept` and writes the same note, edit-then-accept is `review walk`'s edit (the person's own note, then the candidate closed), reject is `review reject`. The console stamps the person as the actor (peer `person`). A privacy-screen hit refuses with a named reason and writes nothing. agent-mem keeps no reject reason, so a reason typed in the console is not recorded, and the reply says so.
178
178
  - Acon displays the Undo offer for 10 seconds; the plugin accepts a matching undo record for 60 seconds within its current provider instance. Undo stays bound to the candidate action: undoing an accept forgets the accepted note (an append-only forget op; a note a correction replaced shows again), undoing a reject makes the candidate pending again. A promotion has no undo. `merge_into` is not offered: the library has no merge operation.
179
179
  - Destructive forms (`gc`, `capacity_apply`, `project_forget`, `decay_apply`, `prune`) answer `needsConfirm` with the preview and `changes[]` and never write on the first call. The console's single-use confirm token carries the fingerprint back; the plugin recomputes the preview and writes only when it still matches. `prune` needs a generation home, as `amem prune` does.
@@ -297,7 +297,7 @@ amem capacity apply --split [--confirm] # each shard's share of the global cap
297
297
  - `capacity` also prints a per-shard split of the global disk-share budget. Each shard's weight halves every 14 days since its last capture, so recently used projects keep more capture and cold ones shrink first; the split never exceeds the budget, gives every shard at least 1 MB, keeps every shard at what it holds whenever the total fits, never proposes a retention shorter than a shard's idle time plus 30 days, and says when the budget forces a shard below what it holds. When the budget holds fewer whole MB than there are shards, no split is proposed and `capacity` says why (`splitRefused`). It proposes capture bounds only, and never evicts curated notes, goals or work lists. `capacity apply --split` previews, then `--confirm` writes exactly the previewed values to each shard's `config.json`, and only if the preview is under an hour old and the set of shards and every shard's config are unchanged since then (a `--disk-share` given only to `--confirm` changes nothing that is written).
298
298
  - amem lists vault candidates and never writes the vault.
299
299
 
300
- Resource budgets are acceptance criteria, measured by `bun scripts/measure-budget.ts` in CI on Ubuntu and macOS: a hook-like append (including the spool-and-exit path under contention) must stay under 150 ms p95 wall time and 100 MB RSS (R2), the search path under 100 MB idle and 200 MB peak RSS (R3), and no amem process may remain after exit (R1). For the actual-hook scripts (`measure-hooks-budget.ts`, `measure-transcript-budget.ts`, `measure-full-spool-budget.ts`) R2 is three gates: a 150 MB ceiling on every invocation, a regression gate of +10% over a committed per-runner p95 baseline (`docs/bench/r2-baseline.json`), and a 300 ms per-invocation maximum on the handler's own wall, with the outer CLI wall reported only (the transcript harness enforces it too since #226); see [docs/contracts.md](https://github.com/STAIxBWLB/agent-mem/blob/main/docs/contracts.md) (#228). The script prints a machine-readable verdict per budget and its CI log is also the FTS5 availability evidence for Linux (R5). The AC4 retrieval re-check of the frozen P0 query set is in [docs/p1-ac4-recheck.md](https://github.com/STAIxBWLB/agent-mem/blob/main/docs/p1-ac4-recheck.md).
300
+ Resource budgets are acceptance criteria, measured by `bun scripts/measure-budget.ts` in CI on Ubuntu and macOS: a hook-like append (including the spool-and-exit path under contention) must stay under 150 ms p95 wall time and 100 MB RSS (R2), the search path under 100 MB idle and 200 MB peak RSS (R3), and no amem process may remain after exit (R1). For the actual-hook scripts (`measure-hooks-budget.ts`, `measure-transcript-budget.ts`, `measure-full-spool-budget.ts`) R2 is three gates: a 150 MB ceiling on every invocation, a regression gate of +10% over a committed per-runner p95 baseline (`docs/bench/r2-baseline.json`), and a 300 ms per-invocation maximum on the handler's own wall, with the outer CLI wall reported only (the transcript harness enforces it too since #226); see [docs/contracts.md](https://github.com/STAIxBWLB/agent-mem/blob/main/docs/contracts.md) (#228). The script prints a machine-readable verdict per budget and its CI log is also the FTS5 availability evidence for Linux (R5). The hosted budget measurement steps still run and retain their own assertions, but their failures are advisory. Validation steps in those jobs still gate the required check, and a cancelled or missing measurement job remains an error. A green required check alone does not mean the measured budgets passed. The AC4 retrieval re-check of the frozen P0 query set is in [docs/p1-ac4-recheck.md](https://github.com/STAIxBWLB/agent-mem/blob/main/docs/p1-ac4-recheck.md).
301
301
 
302
302
  ## Claude Code hooks and SessionStart context
303
303
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.27.1",
3
+ "version": "0.28.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",
package/src/cli.ts CHANGED
@@ -24,6 +24,8 @@ import { importClaudeMemCapture, importClaudeMemWorkState } from "./memory/impor
24
24
  import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, rmSync, writeFileSync } from "node:fs";
25
25
  import { isAbsolute, join } from "node:path";
26
26
  import { fileURLToPath } from "node:url";
27
+ import { captureSessionKey } from "./memory/capture-input.ts";
28
+ import { originLine, originRecheck } from "./memory/candidate-origin.ts";
27
29
  import { MemoryStore, looksSecret, machineId, openShardStore, type StoreOptions } from "./memory/store.ts";
28
30
  import { rawMemoryCommand, rawGoalCommand, claudeMemImportText } from "./memory/commands.ts";
29
31
  import { memoryProjectKey } from "./memory/project.ts";
@@ -32,7 +34,7 @@ import { candidateOverlaps, candidateOverlapsBatch } from "./memory/candidate-ov
32
34
  import { openCuratedForRead } from "./memory/curated-read.ts";
33
35
  import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
34
36
  import { capacityReport, capacityText, capacityApplyText, capacitySplitText } from "./memory/capacity.ts";
35
- import { readCaptureConfigFile, writeCaptureConfigFile, type CaptureConfig } from "./memory/capture.ts";
37
+ import { CaptureStore, readCaptureConfigFile, writeCaptureConfigFile, type CaptureConfig } from "./memory/capture.ts";
36
38
 
37
39
  import { COMMANDS, commandHelp, parseCommand } from "./commands-table.ts";
38
40
  import { completionScript } from "./completion.ts";
@@ -346,7 +348,11 @@ const preloadMcp = () => Promise.all([import("./memory/store.ts"), import("./mem
346
348
  async function runCliCommand(argv: readonly string[], context: CliContext): Promise<string> {
347
349
  if (argv.length === 1 && argv[0] === "mcp") {
348
350
  await preloadMcp();
349
- const memory = createMemoryMcp({ cwd: context.cwd ?? process.cwd(), base: memoryHome(context.env ?? process.env) });
351
+ // #323: a host that knows the proposing session passes it; the CLI keys it like capture does, so a candidate points at the same session rows.
352
+ const env = context.env ?? process.env;
353
+ const originSession = captureSessionKey(env.AMEM_ORIGIN_SESSION), originPeer = env.AGENTHUB_PEER_ID?.trim() || undefined;
354
+ const memory = createMemoryMcp({ cwd: context.cwd ?? process.cwd(), base: memoryHome(env),
355
+ ...(originSession || originPeer ? { origin: () => ({ ...(originSession ? { session: originSession } : {}), ...(originPeer ? { peer: originPeer } : {}) }) } : {}) });
350
356
  await serveMcp({ tools: memory.tools, close: memory.close, onEmitted: memory.onEmitted, version: VERSION });
351
357
  return "";
352
358
  }
@@ -463,7 +469,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
463
469
  const assertCurrent = () => { binding(); assertProjectActive(base, project); if (resolveAlias(base, requested) !== project || aliasedKeys(base, project).join("\n") !== aliases.join("\n")) throw Error("consolidation project binding changed"); };
464
470
  candidates = new CandidateStore({ memoryDir: base, reconcile: { canonical: project, aliases } });
465
471
  const readRecords = recordWindow(base, project, policyCwd);
466
- const report = await proposeConsolidation(store, candidates, { project, actor, policy: policyOf, policyVersion: policyKey, assertCurrent, ...(readRecords ? { records: readRecords } : {}) });
472
+ const origin = { peer: identity.peer, at: new Date().toISOString(), ...(captureSessionKey((context.env ?? process.env).AMEM_ORIGIN_SESSION) ? { session: captureSessionKey((context.env ?? process.env).AMEM_ORIGIN_SESSION)! } : {}) };
473
+ const report = await proposeConsolidation(store, candidates, { project, actor, origin, policy: policyOf, policyVersion: policyKey, assertCurrent, ...(readRecords ? { records: readRecords } : {}) });
467
474
  return options["--json"] ? JSON.stringify(report, null, 2) : `${report.candidates.length} consolidation candidates queued for amem review; no curated notes changed${report.records ? `; ${report.records.queued} of ${report.records.found} Record(s)${report.records.truncated ? " in the newest 32" : ""}` : ""}${report.alreadyReviewed ? `; ${report.alreadyReviewed} already reviewed` : ""}${report.truncated ? "; scan truncated" : ""}${report.oversized ? `; ${report.oversized} proposals too large` : ""}${report.localExcluded ? `; ${report.localExcluded} local sources excluded` : ""}`;
468
475
  } finally { candidates?.close(); store.close(); }
469
476
  }
@@ -709,6 +716,18 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
709
716
  if (input.kind === "consolidation") return `${input.action}. Sources: ${input.targets.map(target => `mem:${target.id}`).join(", ")}. ${input.text}`;
710
717
  return input.kind === "memory" ? `${input.title ? `${input.title}: ` : ""}${input.text}` : input.kind === "fail" ? `fail. Approach: ${input.approach} Symptom: ${input.symptom} Cause: ${input.cause} Retry when: ${input.retryWhen}`
711
718
  : input.kind === "correction" ? `correction. ${input.proposedText} Reason: ${input.reason}` : `decay. ${input.reason}`; };
719
+ // #323 item 4: can the origin still be re-checked against capture? An expired session is reported as such, never as a failed check.
720
+ const recheckOf = (candidate: import("./memory/candidates.ts").Candidate) => {
721
+ // Read-only: a preview never creates or migrates capture storage; a missing or cold shard is unavailable, not expired.
722
+ let capture: import("./memory/capture.ts").CaptureStore | undefined;
723
+ try {
724
+ const policy = policyOf();
725
+ return originRecheck(candidate.origin, candidate.originKnown, session => {
726
+ const opened = capture ??= new CaptureStore({ memoryDir: memoryHome(), project, cwd: policyCwd, readOnly: true, recentReadRows: true, maxReadRows: 128 });
727
+ return opened.sessionState(session, row => policy.screenStandalone(row));
728
+ });
729
+ } catch { return "unavailable" as const; } finally { capture?.close(); }
730
+ };
712
731
  if (sub === "decide") {
713
732
  // #431 AC5: what `review walk` gives a person, one candidate at a time and without a terminal. The preview prints the
714
733
  // candidate and its overlaps and stamps it shown (the caller read it); --confirm then applies exactly the named decision.
@@ -722,11 +741,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
722
741
  if (options["--confirm"] !== true) {
723
742
  const shown = terminalSafe(body(candidate)), overlaps = await overlapsFor(candidate);
724
743
  const preview = { candidateId: candidate.id, kind: candidate.input.kind, createdAt: candidate.createdAt, decision, body: shown,
744
+ origin: candidate.originKnown ? candidate.origin ?? null : "unknown", originRecheck: recheckOf(candidate),
725
745
  overlaps: overlaps.map(overlap => ({ id: overlap.id, score: overlap.score, title: overlap.title ?? null })), next: `amem review decide ${candidate.id} ${decision} --confirm` };
726
746
  administrative(preview);
727
747
  markShown(realPath(candidates.dir), [project, ...aliases], Date.now(), [candidate.id]);
728
748
  return options["--json"] ? JSON.stringify(preview, null, 2)
729
- : [`${candidate.id} ${candidate.input.kind} ${candidate.createdAt.slice(0, 10)}`, ` ${shown}`, ...preview.overlaps.map(overlap => ` overlap mem:${overlap.id} (${overlap.score.toFixed(3)}): ${terminalSafe(overlap.title ?? "untitled")}`),
749
+ : [`${candidate.id} ${candidate.input.kind} ${candidate.createdAt.slice(0, 10)}`, ` ${shown}`, ` ${originLine(candidate.origin, candidate.originKnown)} (recheck: ${preview.originRecheck})`, ...preview.overlaps.map(overlap => ` overlap mem:${overlap.id} (${overlap.score.toFixed(3)}): ${terminalSafe(overlap.title ?? "untitled")}`),
730
750
  `preview only: run ${preview.next} to ${decision} it`].join("\n");
731
751
  }
732
752
  if (decision === "defer") return options["--json"] ? JSON.stringify({ candidateId: candidate.id, status: "pending", decision }, null, 2) : `deferred candidate ${candidate.id}; it stays pending`;
@@ -755,7 +775,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
755
775
  for (const [index, candidate] of rows.entries()) {
756
776
  assertWalkCurrent();
757
777
  if (!candidatePermitted(candidate)) throw Error("Memory operation unavailable or refused; no partial result is shown.");
758
- lines.push(`${index + 1}/${rows.length} ${candidate.id.slice(0, 12)} ${candidate.input.kind} ${candidate.createdAt.slice(0, 10)}`, ` ${terminalSafe(body(candidate))}`);
778
+ lines.push(`${index + 1}/${rows.length} ${candidate.id.slice(0, 12)} ${candidate.input.kind} ${candidate.createdAt.slice(0, 10)}`, ` ${originLine(candidate.origin, candidate.originKnown)}`, ` ${terminalSafe(body(candidate))}`);
759
779
  for (const overlap of await overlapsFor(candidate)) lines.push(` overlap mem:${overlap.id} (${overlap.score.toFixed(3)}): ${terminalSafe(overlap.title ?? "untitled")}`);
760
780
  assertWalkCurrent();
761
781
  markShown(base, scope, Date.now(), [candidate.id]); // after the write: shown means the person could read it
@@ -802,7 +822,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
802
822
  if (JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)) !== revision) throw Error("overlap policy changed");
803
823
  return JSON.stringify(hinted, null, 2);
804
824
  }
805
- return rows.length ? rows.map(candidate => `${candidate.id} ${candidate.input.kind} ${candidate.status} ${candidate.createdAt}`).join("\n") : "no candidates waiting for review";
825
+ return rows.length ? rows.map(candidate => `${candidate.id} ${candidate.input.kind} ${candidate.status} ${candidate.createdAt} ${originLine(candidate.origin, candidate.originKnown)}`).join("\n") : "no candidates waiting for review";
806
826
  }
807
827
  if (sub === "reject") {
808
828
  candidates.reject(id!, { project, actor, verdict: "public" });
@@ -1078,6 +1098,17 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1078
1098
  return [...preview, `appended to ${written.path}. amem does not commit or push: review and commit it yourself.`,
1079
1099
  ...(repoLogIgnored(root) ? ["WARNING: git ignores .amem/log.jsonl here, so `git status` will not show it and it cannot be committed until you un-ignore it (a .gitignore or .git/info/exclude rule)."] : [])].join("\n");
1080
1100
  }
1101
+ if (sub === "show" && /^capture:[1-9][0-9]*$/.test(parsed.positionals[0] ?? "") && options["--history"] !== true && options["--as-of"] === undefined) {
1102
+ // #323 item 3: a capture row (a Record included) by id, through the screened MCP read, with its session and row time.
1103
+ const memory = createMemoryMcp({ cwd: context.cwd ?? process.cwd(), base: memoryHome() });
1104
+ try {
1105
+ const shown = await memory.tools.amem_show({ id: parsed.positionals[0]! }) as { capture?: import("./memory/capture.ts").CaptureRow } | null;
1106
+ const row = shown?.capture; if (!row) throw new Error(`no capture row ${parsed.positionals[0]} in this project (capture is machine-local and expires; inspect the current project timeline and retention)`);
1107
+ return options["--json"] === true ? JSON.stringify(row, null, 2)
1108
+ : [`capture:${row.id} ${row.event}${row.tool ? ` ${row.tool}` : ""}, ${row.at}, agent ${row.agent}, session ${row.session ?? "unavailable"}${row.subagent ? ", subagent" : ""}`,
1109
+ ...(row.paths.length ? [`paths: ${row.paths.join(", ")}`] : []), "", terminalSafe(row.excerpt)].join("\n");
1110
+ } finally { memory.close(); }
1111
+ }
1081
1112
  if (sub === "show" && /^repo:/.test(parsed.positionals[0] ?? "")) {
1082
1113
  const project = boundProject(), root = boundRepoRoot(repoCwd, memoryHome(), project), scoped = root ? repoReadPolicy(root) : undefined;
1083
1114
  const rows = root && scoped && !("reason" in scoped) ? (await readRepoScope(root, scoped.policy)).views : [];
package/src/mcp-memory.ts CHANGED
@@ -25,6 +25,7 @@ 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 { validOrigin, type CandidateOrigin } from "./memory/candidate-origin.ts";
28
29
  import { groupByTask } from "./memory/task-group.ts";
29
30
  /** #423: how many ranked hits per requested slot a grouped search reads, so folded same-task hits do not empty the page. */
30
31
  const TASK_GROUP_WINDOW = 4;
@@ -36,7 +37,10 @@ export const MCP_SCAN_LIMIT = 5000;
36
37
  const SEARCH_CANDIDATES = 5000;
37
38
  const READ_PAGE = 256;
38
39
  type SearchValue = { source: "curated"; evidence: true; view: View } | { source: "repo"; evidence: false; view: RepoView } | { source: "capture"; evidence: false; capture: CaptureRow };
39
- export interface MemoryMcpOptions { cwd: string; base?: string; project?: string; policy?: StandalonePolicyOptions; allowed?: () => boolean; policyVersion?: () => string; assertCurrent?: () => void }
40
+ export interface MemoryMcpOptions {
41
+ /** #323: ids the host knows about the proposing session, read on each proposal; nothing is inferred when absent. */
42
+ origin?: () => { session?: string; peer?: string; turn?: string } | undefined;
43
+ cwd: string; base?: string; project?: string; policy?: StandalonePolicyOptions; allowed?: () => boolean; policyVersion?: () => string; assertCurrent?: () => void }
40
44
  export interface MemoryMcp { tools: McpHandlers; close(): void; onEmitted: NonNullable<McpOptions["onEmitted"]> }
41
45
  const unavailable = (): never => { throw new Error("memory operation unavailable"); };
42
46
  const bound = (args: Record<string, unknown>, keys: string[]) => { if (Object.keys(args).some(key => !keys.includes(key))) unavailable(); };
@@ -154,16 +158,25 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
154
158
  const revision = target && candidateTargetRevision(target);
155
159
  const currentPolicy = () => createStandalonePolicy(configuredPolicyOptions(base, cwd, options.policy));
156
160
  const check = () => { guard(); if (target && candidateTargetRevision(correctionTarget(target.id)) !== revision) unavailable(); };
157
- const complete = target ? { ...input, targetView: target } : input;
161
+ let supplied: ReturnType<NonNullable<MemoryMcpOptions["origin"]>>;
162
+ try { supplied = options.origin?.(); } catch { supplied = undefined; }
163
+ // Ids only and bounded (validOrigin, secret screen included); an invalid host value records no origin rather than refusing.
164
+ let origin: CandidateOrigin | undefined;
165
+ try { origin = validOrigin(supplied ? { ...supplied, at: new Date(store.readNow()).toISOString() } : undefined); } catch { origin = undefined; }
166
+ // AC3: the origin is screened with the proposal by the full host policy, then by the final synchronous snapshot that fences the append.
167
+ // A declined origin is dropped and the proposal alone is screened again on both paths, so the proposal still stands.
168
+ const completeOf = (withOrigin: boolean) => ({ ...(target ? { ...input, targetView: target } : input), ...(withOrigin && origin ? { origin } : {}) });
158
169
  check();
159
- if (!await currentPolicy().screen(complete)) unavailable();
170
+ if (origin && !await currentPolicy().screen(completeOf(true))) origin = undefined;
171
+ if (!await currentPolicy().screen(completeOf(false))) unavailable();
160
172
  check();
161
173
  const overlaps = includeOverlaps ? (await candidateOverlaps(candidates.get(candidateInputId(input), project) ?? { status: "pending", input }, store,
162
174
  { project, policy: currentPolicy, policyVersion: policyRevisionForCall, assertCurrent: check })).map(row => row.id) : undefined;
163
- // Config can tighten while the host screen awaits. Its synchronous check fences the final append.
164
- if (!currentPolicy().screenStandalone(complete)) unavailable();
175
+ // Config can tighten while the host screen awaits. Its synchronous check fences the final append, origin included.
176
+ if (!currentPolicy().screenStandalone(completeOf(false))) unavailable();
177
+ if (origin && !currentPolicy().screenStandalone(completeOf(true))) origin = undefined;
165
178
  check();
166
- return { id: candidates.put(input, "public"), ...(overlaps === undefined ? {} : { overlaps }) };
179
+ return { id: candidates.put(input, "public", origin), ...(overlaps === undefined ? {} : { overlaps }) };
167
180
  };
168
181
  const tools: McpHandlers = {
169
182
  async amem_evidence(args) {
@@ -0,0 +1,63 @@
1
+ /**
2
+ * #323: where a candidate came from, as ids only. The proposing host supplies them; nothing is inferred from capture.
3
+ * Stored in its own nullable `candidates.origin` column, outside the hashed payload, so a candidate id and every older reader
4
+ * (which selects named columns or ignores unknown ones) are unchanged. A row written before 0.28 has no origin: `unknown`.
5
+ */
6
+ export interface CandidateOrigin {
7
+ /** The capture session key: 16 lowercase hex, the same `session` a capture row carries. */
8
+ session?: string;
9
+ /** The proposing agent's peer id. */
10
+ peer?: string;
11
+ /** When the proposal was made, canonical UTC. */
12
+ at?: string;
13
+ /** An opaque host turn id. */
14
+ turn?: string;
15
+ }
16
+ import { looksSecret } from "./screen.ts";
17
+ const SESSION = /^[a-f0-9]{16}$/, ID = /^[A-Za-z0-9._:@-]{1,120}$/;
18
+
19
+ /** Ids only: a field that is not a bounded id is refused, so no text, path or secret can enter `origin`. */
20
+ export function validOrigin(value: unknown): CandidateOrigin | undefined {
21
+ if (value === undefined || value === null) return undefined;
22
+ if (typeof value !== "object" || Array.isArray(value)) throw new Error("candidate origin must be an object; supply session, peer, at or turn ids");
23
+ const keys = Object.keys(value), raw = value as Record<string, unknown>;
24
+ if (keys.some(key => !["session", "peer", "at", "turn"].includes(key))) throw new Error("candidate origin has an unknown field; use only session, peer, at and turn");
25
+ const out: CandidateOrigin = {};
26
+ if (raw.session !== undefined) { if (typeof raw.session !== "string" || !SESSION.test(raw.session)) throw new Error("candidate origin session must be a 16-character lowercase hex capture session key; pass the capture session key"); out.session = raw.session; }
27
+ if (raw.peer !== undefined) { if (typeof raw.peer !== "string" || !ID.test(raw.peer)) throw new Error("candidate origin peer must be 1 to 120 characters from A-Z, a-z, 0-9, dot, underscore, colon, at sign or hyphen; pass a peer id"); out.peer = raw.peer; }
28
+ if (raw.turn !== undefined) { if (typeof raw.turn !== "string" || !ID.test(raw.turn)) throw new Error("candidate origin turn must be 1 to 120 characters from A-Z, a-z, 0-9, dot, underscore, colon, at sign or hyphen; pass a turn id"); out.turn = raw.turn; }
29
+ if (raw.at !== undefined) {
30
+ if (typeof raw.at !== "string" || !Number.isFinite(Date.parse(raw.at)) || new Date(raw.at).toISOString() !== raw.at) throw new Error("candidate origin time must be canonical UTC; pass an ISO timestamp with milliseconds and Z");
31
+ out.at = raw.at;
32
+ }
33
+ // AC3: the unchanged secret screen applies to the ids too; an id shaped like a token is refused, never stored.
34
+ if (Object.values(out).some(value => looksSecret(value))) throw new Error("candidate origin refused by the secret screen; remove the secret-like id and pass a safe session or peer id");
35
+ return Object.keys(out).length ? out : undefined;
36
+ }
37
+
38
+ /** #323 AC1: every supplied origin field as an ids-only graph node, so an accepted note keeps the whole origin. */
39
+ export function originNodes(origin: CandidateOrigin | undefined): string[] {
40
+ if (!origin) return [];
41
+ return [...(origin.session ? [`session:${origin.session}`] : []), ...(origin.peer ? [`peer:${origin.peer}`] : []),
42
+ ...(origin.at ? [`origin-at:${origin.at}`] : []), ...(origin.turn ? [`turn:${origin.turn}`] : [])];
43
+ }
44
+
45
+ export type OriginRecheck = "available" | "origin expired" | "unavailable" | "unknown";
46
+ /**
47
+ * #323 item 4: whether a note's origin session can still be re-checked against capture. Only a confirmed absence from a readable,
48
+ * session-capable store is `origin expired` (never a failed check). An unreadable, missing, unsupported or policy-withheld capture is
49
+ * `unavailable`, so expiry is never claimed and withheld rows are never disclosed; no recorded session is `unavailable` too.
50
+ */
51
+ export function originRecheck(origin: CandidateOrigin | undefined, known: boolean, lookup: (session: string) => "present" | "absent" | "unavailable" | "unsupported"): OriginRecheck {
52
+ if (!known) return "unknown";
53
+ if (!origin?.session) return "unavailable";
54
+ let state: ReturnType<typeof lookup>; try { state = lookup(origin.session); } catch { return "unavailable"; }
55
+ return state === "present" ? "available" : state === "absent" ? "origin expired" : "unavailable";
56
+ }
57
+
58
+ /** One line for previews and the note provenance; absent fields read `unavailable`, never a guess. */
59
+ export function originLine(origin: CandidateOrigin | undefined, known = true): string {
60
+ if (!known) return "origin: unknown (proposed before origin was recorded)";
61
+ if (!origin) return "origin: unavailable";
62
+ return `origin: session ${origin.session ?? "unavailable"}, peer ${origin.peer ?? "unavailable"}, at ${origin.at ?? "unavailable"}${origin.turn ? `, turn ${origin.turn}` : ""}`;
63
+ }
@@ -9,6 +9,8 @@ import { cliAttribution } from "./cli-attribution.ts";
9
9
  import { memoryHome } from "./home.ts";
10
10
  import { realPath } from "./platform.ts";
11
11
  import { stripPrivateDeep } from "./private-spans.ts";
12
+ import { originNodes, validOrigin, type CandidateOrigin } from "./candidate-origin.ts";
13
+ const hasColumn = (db: Database, name: string): boolean => (db.query("PRAGMA table_info(candidates)").all() as { name: string }[]).some(column => column.name === name);
12
14
  import { MemoryStore, type GoalView, type NoteInput, type View } from "./store.ts";
13
15
 
14
16
  export const CANDIDATE_DB_BUSY_TIMEOUT_MS = 3000;
@@ -46,7 +48,11 @@ export type CandidateInput = { project: string } & (
46
48
  | { kind: "model-answer"; marker: "model-answer"; targets: CandidateTarget[]; text: string }
47
49
  );
48
50
  export type CandidateStatus = "pending" | "accepting" | "accepted" | "rejected";
49
- export interface Candidate { id: string; createdAt: string; status: CandidateStatus; input: CandidateInput; acceptedNoteId: string | null }
51
+ export interface Candidate { id: string; createdAt: string; status: CandidateStatus; input: CandidateInput; acceptedNoteId: string | null;
52
+ /** #323: ids the proposing host supplied; absent when it supplied none. */
53
+ origin?: CandidateOrigin;
54
+ /** #323: false for a row written before origin was recorded (pre-0.28 writer): its origin is unknown, not absent. */
55
+ originKnown: boolean }
50
56
  export interface ConsolidationReview { status: Exclude<CandidateStatus, "pending">; acceptedNoteId: string | null }
51
57
  const KINDS: readonly string[] = ["correction", "fail", "decay", "memory", "promotion", "consolidation", "model-answer"] satisfies CandidateInput["kind"][];
52
58
  export interface CandidateFilter { project: string; status?: CandidateStatus | "all"; kind?: CandidateInput["kind"]; limit?: number }
@@ -167,14 +173,21 @@ function retryLocked(work: () => void): void {
167
173
  }
168
174
  }
169
175
 
170
- type CandidateRow = { id: string; payload: string; at: number; status: CandidateStatus; note_id: string | null };
176
+ type CandidateRow = { id: string; payload: string; at: number; status: CandidateStatus; note_id: string | null; origin?: string | null };
177
+ /** #323: NULL (a pre-0.28 row, or a column an older writer never filled) is unknown; `{}` is a recorded empty origin. */
178
+ function decodeOrigin(raw: string | null | undefined): { origin?: CandidateOrigin; originKnown: boolean } {
179
+ if (raw === null || raw === undefined) return { originKnown: false };
180
+ let parsed: unknown; try { parsed = JSON.parse(raw); } catch { throw new Error("candidate origin unreadable; inspect or restore the candidate database before retrying"); }
181
+ const origin = validOrigin(parsed);
182
+ return origin ? { origin, originKnown: true } : { originKnown: true };
183
+ }
171
184
  /** Canonical persisted decoding shared by the writer and its read-only inbox port. */
172
185
  function decodeCandidate(row: CandidateRow, unknownKind: () => void): Candidate | undefined {
173
186
  const input = JSON.parse(row.payload) as CandidateInput;
174
187
  if (input && typeof input === "object" && !KINDS.includes(input.kind)) { unknownKind(); return undefined; }
175
188
  validate(input);
176
189
  if (hash({ schema: "agent-mem.candidate/v1", input }) !== row.id) throw new Error("candidate content hash mismatch");
177
- return { id: row.id, createdAt: new Date(row.at).toISOString(), status: row.status, input, acceptedNoteId: row.note_id };
190
+ return { id: row.id, createdAt: new Date(row.at).toISOString(), status: row.status, input, acceptedNoteId: row.note_id, ...decodeOrigin(row.origin) };
178
191
  }
179
192
  const CANDIDATE_EXPIRED_SQL = "at <= ? AND (status IN ('accepted', 'rejected') OR (shown_at IS NOT NULL AND shown_at <= ?))";
180
193
  const CANDIDATE_PRIORITY_SQL = "CASE WHEN status IN ('pending', 'accepting') AND shown_at IS NULL THEN 2 WHEN status IN ('pending', 'accepting') THEN 1 ELSE 0 END DESC, at DESC";
@@ -194,8 +207,8 @@ export function withPendingCandidates<T>(memoryDir: string, run: (reader: Pendin
194
207
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("pending candidates unavailable");
195
208
  const db = new Database(file, { readonly: true }); let closed = false;
196
209
  try {
197
- const shown = hasShownColumn(db), now = Date.now();
198
- const live = (scope: boolean) => `WITH raw AS (SELECT rowid AS candidate_rowid, id, project, kind, payload, at, status, note_id, ${shown ? "shown_at" : "NULL AS shown_at"} FROM candidates${scope ? " WHERE project IN (SELECT value FROM json_each(?))" : ""}),
210
+ const shown = hasShownColumn(db), origins = hasColumn(db, "origin"), now = Date.now();
211
+ const live = (scope: boolean) => `WITH raw AS (SELECT rowid AS candidate_rowid, id, project, kind, payload, at, status, note_id, ${shown ? "shown_at" : "NULL AS shown_at"}, ${origins ? "origin" : "NULL AS origin"} FROM candidates${scope ? " WHERE project IN (SELECT value FROM json_each(?))" : ""}),
199
212
  live AS (SELECT * FROM raw WHERE NOT (${CANDIDATE_EXPIRED_SQL})),
200
213
  retained AS (SELECT *, row_number() OVER (PARTITION BY project ORDER BY ${CANDIDATE_PRIORITY_SQL}, candidate_rowid DESC) AS retention_rank FROM live)`;
201
214
  const assertOpen = () => { if (closed) throw new Error("pending candidate reader is closed"); };
@@ -265,6 +278,8 @@ export class CandidateStore {
265
278
  // F7 / AC4: when a candidate was first shown to the person. In place and nullable: an older database gains it here, and a reader without it treats every row as unshown.
266
279
  // Several processes open this store at once (every `amem mcp` builds it at startup), so the check and the ALTER are one immediate transaction: the loser waits, then sees the column.
267
280
  if (!hasShownColumn(this.db)) this.db.transaction(() => { if (!hasShownColumn(this.db)) this.db.run("ALTER TABLE candidates ADD COLUMN shown_at INTEGER"); }).immediate();
281
+ // #323: the origin ids, in place and nullable like shown_at. Outside the hashed payload, so ids are unchanged and an older reader never sees it.
282
+ if (!hasColumn(this.db, "origin")) this.db.transaction(() => { if (!hasColumn(this.db, "origin")) this.db.run("ALTER TABLE candidates ADD COLUMN origin TEXT"); }).immediate();
268
283
  this.db.run("CREATE TABLE IF NOT EXISTS consolidation_reviews (id TEXT PRIMARY KEY, project TEXT NOT NULL, status TEXT NOT NULL, note_id TEXT)");
269
284
  this.db.run("CREATE TABLE IF NOT EXISTS counters (id TEXT PRIMARY KEY, project TEXT NOT NULL, payload TEXT NOT NULL, at INTEGER NOT NULL, rendered INTEGER, delivered INTEGER, cited INTEGER)");
270
285
  this.prune();
@@ -300,11 +315,13 @@ export class CandidateStore {
300
315
  private decode(row: CandidateRow): Candidate | undefined {
301
316
  return decodeCandidate(row, () => { this.skippedUnknownKinds++; });
302
317
  }
303
- put(rawInput: CandidateInput, verdict: CandidateVerdict): string {
318
+ put(rawInput: CandidateInput, verdict: CandidateVerdict, rawOrigin?: CandidateOrigin, screen?: (origin: CandidateOrigin) => boolean): string {
304
319
  // `<private>` spans are never stored: dropped before the input is validated, hashed (so the id) or written.
305
320
  const input = stripPrivateDeep(rawInput);
306
321
  publicOnly(verdict); validate(input);
307
- const payload = canonical(input), id = candidateInputId(input);
322
+ const origin = validOrigin(rawOrigin), payload = canonical(input), id = candidateInputId(input);
323
+ // AC3: the caller's configured privacy screen sees the origin ids before they are stored; a refused origin refuses the proposal.
324
+ if (origin && screen && screen(origin) !== true) throw new Error("candidate origin refused by the configured privacy policy; remove the declined id or review the current policy");
308
325
  // Prune, count, insert and prune again are ONE immediate transaction: concurrent proposers (several agents) cannot all pass the count and then let the cap evict an unseen candidate.
309
326
  return this.db.transaction((): string => {
310
327
  this.prune();
@@ -321,7 +338,8 @@ export class CandidateStore {
321
338
  // Upgrade with an explicit person-audited receipt archive before increasing this bounded sidecar capacity.
322
339
  if (allocated.n >= CONSOLIDATION_REVIEW_LIMIT) throw new ConsolidationReviewLimit(input.project, allocated.n);
323
340
  }
324
- this.db.query("INSERT OR IGNORE INTO candidates (id, project, kind, payload, at, status) VALUES (?, ?, ?, ?, ?, 'pending')").run(id, input.project, input.kind, payload, this.now());
341
+ // A re-proposal of the same content keeps its first origin: the id is content-addressed, and the first proposer is the one to re-check.
342
+ this.db.query("INSERT OR IGNORE INTO candidates (id, project, kind, payload, at, status, origin) VALUES (?, ?, ?, ?, ?, 'pending', ?)").run(id, input.project, input.kind, payload, this.now(), JSON.stringify(origin ?? {}));
325
343
  this.prune();
326
344
  return id;
327
345
  }).immediate();
@@ -449,7 +467,7 @@ export class CandidateStore {
449
467
  tier: data.kind === "correction" && target!.local ? "short" : "long",
450
468
  kind: data.kind === "fail" ? "fail" : data.noteKind ?? (target?.kind === "contract" || target?.kind === "fail" || target?.kind === "preference" ? target.kind : "decision"), peer: attributionPeer(context.actor), source: "person",
451
469
  // A Record candidate carries the edges its anchors name, so the accepted note stays findable by path and symbol.
452
- about: [...new Set([...(target?.about ?? []), ...(data.kind === "memory" || data.kind === "fail" ? data.about ?? [] : [])])],
470
+ about: [...new Set([...(target?.about ?? []), ...(data.kind === "memory" || data.kind === "fail" ? data.about ?? [] : []), ...originNodes(candidate.origin)])],
453
471
  text: data.kind === "correction" ? acceptedCorrectionText(data, id) : `Accepted candidate: ${id}\nTarget revision: ${(data.kind === "memory" ? undefined : data.target)?.revision ?? "none"}\nTarget entry: ${(data.kind === "memory" ? undefined : data.target)?.id ?? "none"}\n\n${body}` };
454
472
  if (note.text.length > 4000) throw new Error("accepted candidate text exceeds the v1 note limit");
455
473
  if (context.policy(structuredClone(candidate), target && structuredClone(target), structuredClone(note)) !== true) throw new Error("candidate refused by current host policy");
@@ -499,7 +517,7 @@ export class CandidateStore {
499
517
  return current;
500
518
  };
501
519
  const sources = check(), first = sources[0]!;
502
- const note: NoteInput = { op: "note", project: context.project, scope: first.scope, tier: "long", kind: data.noteKind, peer: attributionPeer(context.actor), source: "person", about: [...data.about],
520
+ const note: NoteInput = { op: "note", project: context.project, scope: first.scope, tier: "long", kind: data.noteKind, peer: attributionPeer(context.actor), source: "person", about: [...new Set([...data.about, ...originNodes(candidate.origin)])],
503
521
  text: `${ACCEPTED_CONSOLIDATION_PREFIX}${candidate.id}\nAction: ${data.action}\nSources: ${data.targets.map(target => `mem:${target.id}`).join(", ")}\n\n${data.text}` };
504
522
  if (note.text.length > 4000) throw Error("accepted consolidation exceeds the v1 note limit");
505
523
  for (const source of sources) if (context.policy(structuredClone(candidate), structuredClone(source), structuredClone(note)) !== true) throw Error("consolidation refused by current host policy");
@@ -543,6 +561,8 @@ export class CandidateStore {
543
561
  resolve();
544
562
  const replay = this.beginAcceptance(candidate.id, context.project); if (replay) return { candidateId: candidate.id, noteId: replay, alreadyAccepted: true };
545
563
  // A thrown append remains accepting: its authored-row outcome needs person-audited recovery.
564
+ // #323: a promotion keeps its canonical identity (the id is the source note's own fields), so its origin stays on the candidate row
565
+ // (`amem review list --status all`), not on the promoted note: an extra edge would fork that id across machines.
546
566
  const noteId = context.store.promote(target.id, context.actor, context.project);
547
567
  if (noteId === undefined) {
548
568
  this.db.query("UPDATE candidates SET status = 'pending' WHERE id = ? AND project IN (SELECT value FROM json_each(?)) AND status = 'accepting'").run(candidate.id, this.scope(context.project));
@@ -737,6 +737,31 @@ export class CaptureStore {
737
737
  * window holds only the newest 32, so proving a candidate with that window would read every older row as pruned. These are
738
738
  * point lookups on the `at` index with an explicit per-turn cap: no scan, no window, and no index or spool work.
739
739
  */
740
+ /**
741
+ * #323 item 4: check at most 128 newest rows plus a sentinel, with no unbounded session scan. Any withheld row makes an absent
742
+ * session inconclusive, so the result cannot distinguish a hidden session from an absent one. Only a complete screened window
743
+ * can establish absence. This port requires a read-only store and never creates or migrates capture storage.
744
+ */
745
+ sessionState(session: string, visible: (row: CaptureRow) => boolean): "present" | "absent" | "unavailable" | "unsupported" {
746
+ this.checkReadBinding();
747
+ if (!this.readOnly) throw new Error("session recheck requires a read-only capture store; open CaptureStore with readOnly: true");
748
+ if (typeof session !== "string" || !SESSION_KEY.test(session)) throw new Error("invalid session key; use a 16-character lowercase hex capture session key");
749
+ const columns = new Set((this.db.query("PRAGMA table_info(rows)").all() as { name: string }[]).map(column => column.name));
750
+ if (!columns.has("session")) return "unsupported";
751
+ // INTEGER PRIMARY KEY order stops after the fixed sentinel; never filter by session before the bound.
752
+ const rows = this.db.query("SELECT * FROM rows ORDER BY id DESC LIMIT 129").all() as RawRow[];
753
+ let withheld = false, present = false;
754
+ try {
755
+ for (const raw of rows.slice(0, 128)) {
756
+ const row = toRow(raw), permitted = visible(row) === true;
757
+ if (!permitted) withheld = true;
758
+ else if (row.project === this.key && row.session === session) present = true;
759
+ }
760
+ } catch { return "unavailable"; }
761
+ if (present) return "present";
762
+ return withheld || rows.length > 128 || this.recentReadTruncated ? "unavailable" : "absent";
763
+ }
764
+
740
765
  readRecordTurns(turns: readonly { session: string; at: string }[]): CaptureRow[] {
741
766
  this.checkReadBinding();
742
767
  if (!Array.isArray(turns) || turns.length < 1 || turns.length > 8 || turns.some(turn => !turn
@@ -4,11 +4,14 @@ import { memoryPolicySnapshot, type StandalonePolicy } from "./policy.ts";
4
4
  import { recallViewIsLive } from "./recall.ts";
5
5
  import type { MemoryStore, View } from "./store.ts";
6
6
  import { realPath } from "./platform.ts";
7
+ import { validOrigin, type CandidateOrigin } from "./candidate-origin.ts";
7
8
  import { proposeModelConsolidations, type ModelConsolidationOptions, type ModelConsolidationReport } from "./consolidation-model.ts";
8
9
  import { recordCandidates, type RecordCandidateCounts, type RecordCandidateWindow } from "./record-candidates.ts";
9
10
 
10
11
  export interface ConsolidationOptions {
11
12
  project: string; actor: "person" | "agent"; policy: () => StandalonePolicy; policyVersion: () => string;
13
+ /** #323: ids of the run that proposes (its peer, its session if the host knows one); recorded on each candidate, never inferred. */
14
+ origin?: CandidateOrigin;
12
15
  allowed?: () => boolean; assertCurrent?: () => void;
13
16
  /** Person-enabled host callback only. Absent means no model work or budget reservation. */
14
17
  model?: ModelConsolidationOptions;
@@ -51,6 +54,14 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
51
54
  check();
52
55
  if (!await policy.screen({ project })) throw Error("consolidation refused by current policy");
53
56
  check();
57
+ // #323 AC3: the full host policy screens the run origin, then the synchronous snapshot again after the check fence; a declined
58
+ // origin is recorded as none and the run goes on. The policy version is fenced by check() before every put below.
59
+ let originSnapshot: CandidateOrigin | undefined;
60
+ try { originSnapshot = validOrigin(memoryPolicySnapshot(options.origin)); } catch { originSnapshot = undefined; }
61
+ if (originSnapshot) Object.freeze(originSnapshot);
62
+ let runOrigin = originSnapshot && await policy.screen({ project, origin: originSnapshot }) ? originSnapshot : undefined;
63
+ check();
64
+ if (runOrigin && !policy.screenStandalone({ project, origin: runOrigin })) runOrigin = undefined;
54
65
  const raw = store.withDeferredPromotions(() => store.list({ project, limit: 257 })), rows: View[] = [];
55
66
  for (const value of raw) {
56
67
  check(); const row = memoryPolicySnapshot(value);
@@ -86,7 +97,7 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
86
97
  check();
87
98
  const id = candidateInputId(input), known = candidates.get(id, project);
88
99
  if (known && known.status !== "pending" || candidates.reviewedConsolidation(id, project)) { report.alreadyReviewed++; continue; }
89
- candidates.put(input, "public");
100
+ candidates.put(input, "public", runOrigin && policy.screenStandalone({ project, origin: runOrigin }) ? runOrigin : undefined);
90
101
  report.candidates.push({ id, action: input.action, sources: input.targets.map(target => `mem:${target.id}`) });
91
102
  }
92
103
  // #368: the same one-at-a-time discipline for Record rows. A group key already in the queue is not proposed again, so a
@@ -103,14 +114,15 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
103
114
  check(); if (!await policy.screen(proposal.source)) { counts.refused++; continue; }
104
115
  check(); if (!await policy.screen(proposal.input)) { counts.refused++; continue; }
105
116
  check();
106
- candidates.put(proposal.input, "public");
117
+ // #323: the proposer's origin only. The Record's own capture sessions stay in its bound sources; none is promoted to origin.
118
+ candidates.put(proposal.input, "public", runOrigin && policy.screenStandalone({ project, origin: runOrigin }) ? runOrigin : undefined);
107
119
  counts.queued++;
108
120
  report.candidates.push({ id: candidateInputId(proposal.input), action: `record:${proposal.input.kind === "fail" ? "fail" : proposal.input.noteKind}`,
109
121
  sources: (proposal.input.record?.sources ?? []).map(source => `capture:${source.session}@${source.at}`) });
110
122
  }
111
123
  report.records = counts;
112
124
  }
113
- if (options.model !== undefined) report.model = await proposeModelConsolidations(store, candidates, synced, options.model, { project, actor: options.actor, check, policy });
125
+ if (options.model !== undefined) report.model = await proposeModelConsolidations(store, candidates, synced, options.model, { project, actor: options.actor, check, policy, ...(runOrigin ? { origin: runOrigin } : {}) });
114
126
  } catch (error) { throw new ConsolidationProposalError(report.candidates.map(row => row.id), error instanceof ConsolidationReviewLimit ? error : undefined); }
115
127
  return report;
116
128
  }
@@ -1,6 +1,7 @@
1
1
  import { types } from "node:util";
2
2
  import { candidateTargetRevision, type CandidateInput, type CandidateStore } from "./candidates.ts";
3
3
  import { memoryPolicySnapshot, type StandalonePolicy } from "./policy.ts";
4
+ import { validOrigin, type CandidateOrigin } from "./candidate-origin.ts";
4
5
  import { realPath } from "./platform.ts";
5
6
  import { recallViewIsLive } from "./recall.ts";
6
7
  import type { MemoryStore, View } from "./store.ts";
@@ -11,7 +12,7 @@ export interface ModelConsolidationOptions {
11
12
  enabled: true;
12
13
  run: (input: ModelConsolidationInput, signal: AbortSignal) => Promise<{ text: string } | null>;
13
14
  }
14
- export interface ModelConsolidationGuard { project: string; actor: "person" | "agent"; check(): void; policy: StandalonePolicy }
15
+ export interface ModelConsolidationGuard { project: string; actor: "person" | "agent"; check(): void; policy: StandalonePolicy; /** #323: the run origin, kept on each model candidate. */ origin?: import("./candidate-origin.ts").CandidateOrigin }
15
16
  export interface ModelConsolidationReport {
16
17
  state: "disabled" | "known" | "unknown"; ids: string[]; calls: number; nonAnswers: number; rejected: number; oversized: number;
17
18
  limited: boolean; timedOut: boolean; truncated: boolean;
@@ -35,6 +36,9 @@ export async function proposeModelConsolidations(store: MemoryStore, candidates:
35
36
  if (model === undefined) return report;
36
37
  if (guard.actor !== "person" && guard.actor !== "agent") throw Error("model consolidation requires a person or an agent-marked session");
37
38
  try {
39
+ let originSnapshot: CandidateOrigin | undefined;
40
+ try { originSnapshot = validOrigin(memoryPolicySnapshot(guard.origin)); } catch { originSnapshot = undefined; }
41
+ if (originSnapshot) Object.freeze(originSnapshot);
38
42
  if (!model || model.enabled !== true || typeof model.run !== "function" || !guard.project.trim() || guard.project.length > 400) throw Error("model consolidation unavailable");
39
43
  guard.check();
40
44
  if (realPath(candidates.dir) !== realPath(store.profile.home)) throw Error("model consolidation home mismatch");
@@ -88,9 +92,11 @@ export async function proposeModelConsolidations(store: MemoryStore, candidates:
88
92
  if (text.length > 3000) { report.oversized++; continue; }
89
93
  const candidate: Extract<CandidateInput, { kind: "model-answer" }> = { project, kind: "model-answer", marker: "model-answer", targets: batch.map(row => ({ id: row.id, revision: row.revision })), text };
90
94
  guard.check();
95
+ // #323 AC3: the run origin goes through the same full host screen as the candidate, with it; a declined origin is dropped.
96
+ const origin = originSnapshot && await guard.policy.screen({ project, candidate, origin: originSnapshot }) && guard.policy.screenStandalone({ project, candidate, origin: originSnapshot }) ? originSnapshot : undefined;
91
97
  const permitted = await guard.policy.screen({ project, output: value, candidate }); check(batch);
92
98
  if (!permitted) { report.rejected++; continue; }
93
- report.ids.push(candidates.put(candidate, "public"));
99
+ report.ids.push(candidates.put(candidate, "public", origin && guard.policy.screenStandalone({ project, candidate, origin }) ? origin : undefined));
94
100
  }
95
101
  return report;
96
102
  } catch { report.state = "unknown"; report.rejected++; return report; }
@@ -0,0 +1,100 @@
1
+ /** Closed v2 publication append intent. The I/O layer owns fencing and durable prefix completion. */
2
+ import { createHash } from "node:crypto";
3
+ import { types } from "node:util";
4
+ import { canonicalJSON, hashJSON } from "./generation.ts";
5
+ import { PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_MAX_OBJECTS, PLACEMENT_JOURNAL_MAX_RECORDS,
6
+ SyncPlacementJournalError, validatePlacementRecord, type PlacementRecord } from "./sync-placement-journal-format.ts";
7
+
8
+ // ponytail: 20 MiB holds the records under the existing 256-object/64 KiB journal ceiling plus metadata;
9
+ // replace this in-memory envelope with a bounded streaming manifest before increasing the journal ceiling.
10
+ export const PLACEMENT_BATCH_INTENT_MAX_BYTES = 20 * 1024 * 1024;
11
+ export interface PlacementBatchChunk { name: string; prefixBytes: number; prefixHash: string; first: number; count: number; suffixHash: string }
12
+ export interface PlacementBatchIntent {
13
+ schema: "agent-mem.sync-placement-append-intent/v2"; epochHash: string; attemptHash: string;
14
+ previousHash: string; records: PlacementRecord[]; chunks: PlacementBatchChunk[]; seal: string;
15
+ }
16
+ const digest = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
17
+ const bytesOf = (record: PlacementRecord) => Buffer.from(canonicalJSON(record) + "\n");
18
+ const hex = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
19
+ const object = (value: unknown, keys: string[]): Record<string, unknown> => {
20
+ if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value)) throw new SyncPlacementJournalError("corrupt");
21
+ const descriptors = Object.getOwnPropertyDescriptors(value);
22
+ if (Object.keys(descriptors).sort().join(",") !== [...keys].sort().join(",") || Object.values(descriptors).some(descriptor => !("value" in descriptor))) throw new SyncPlacementJournalError("corrupt");
23
+ return Object.fromEntries(Object.entries(descriptors).map(([key, descriptor]) => [key, descriptor.value]));
24
+ };
25
+ const fail = (): never => { throw new SyncPlacementJournalError("corrupt"); };
26
+ const array = (value: unknown, limit: number): unknown[] => {
27
+ if (!Array.isArray(value) || types.isProxy(value) || value.length < 1 || value.length > limit) return fail();
28
+ const descriptors = Object.getOwnPropertyDescriptors(value);
29
+ if (Object.keys(descriptors).length !== value.length + 1) return fail();
30
+ return Array.from({ length: value.length }, (_, index) => {
31
+ const descriptor = descriptors[String(index)];
32
+ if (!descriptor || !("value" in descriptor)) return fail();
33
+ return descriptor.value;
34
+ });
35
+ };
36
+
37
+ /** Validate an entire batch and its canonical record chain before any storage effect. */
38
+ export function validatePlacementBatchIntent(value: unknown, epochHash: string): PlacementBatchIntent {
39
+ const row = object(value, ["schema", "epochHash", "attemptHash", "previousHash", "records", "chunks", "seal"]);
40
+ if (row.schema !== "agent-mem.sync-placement-append-intent/v2" || row.epochHash !== epochHash || !hex(epochHash)
41
+ || !hex(row.attemptHash) || !hex(row.previousHash) || !hex(row.seal)) return fail();
42
+ let recordBytes = 0;
43
+ const records = array(row.records, PLACEMENT_JOURNAL_MAX_RECORDS).map(value => {
44
+ const record = validatePlacementRecord(value);
45
+ recordBytes += bytesOf(record).length;
46
+ if (recordBytes > PLACEMENT_BATCH_INTENT_MAX_BYTES) return fail();
47
+ return record;
48
+ });
49
+ let head = row.previousHash, sequence = records[0]!.sequence - 1;
50
+ for (const record of records) {
51
+ if (record.epochHash !== epochHash || record.previousHash !== head || record.sequence !== ++sequence) return fail();
52
+ head = record.seal;
53
+ }
54
+ let first = 0, previousIndex = -1;
55
+ const chunks = array(row.chunks, PLACEMENT_JOURNAL_MAX_OBJECTS).map(value => {
56
+ const chunk = object(value, ["name", "prefixBytes", "prefixHash", "first", "count", "suffixHash"]);
57
+ if (typeof chunk.name !== "string" || !/^records-\d{5}\.jsonl$/.test(chunk.name)
58
+ || !Number.isSafeInteger(chunk.prefixBytes) || (chunk.prefixBytes as number) < 0 || !hex(chunk.prefixHash)
59
+ || !Number.isSafeInteger(chunk.first) || chunk.first !== first || !Number.isSafeInteger(chunk.count)
60
+ || (chunk.count as number) < 1 || !hex(chunk.suffixHash)) return fail();
61
+ const index = Number(chunk.name.slice(8, 13)), count = chunk.count as number;
62
+ if ((previousIndex >= 0 && index !== previousIndex + 1) || first + count > records.length
63
+ || (first > 0 && (chunk.prefixBytes !== 0 || chunk.prefixHash !== digest(Buffer.alloc(0))))) return fail();
64
+ const suffix = Buffer.concat(records.slice(first, first + count).map(bytesOf));
65
+ if ((chunk.prefixBytes as number) + suffix.length > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES || digest(suffix) !== chunk.suffixHash) return fail();
66
+ const result: PlacementBatchChunk = { name: chunk.name, prefixBytes: chunk.prefixBytes as number, prefixHash: chunk.prefixHash, first, count, suffixHash: chunk.suffixHash };
67
+ first += count; previousIndex = index; return result;
68
+ });
69
+ if (first !== records.length) return fail();
70
+ const body = { schema: "agent-mem.sync-placement-append-intent/v2" as const, epochHash, attemptHash: row.attemptHash, previousHash: row.previousHash, records, chunks };
71
+ if (hashJSON(body) !== row.seal || Buffer.byteLength(canonicalJSON({ ...body, seal: row.seal }) + "\n") > PLACEMENT_BATCH_INTENT_MAX_BYTES) return fail();
72
+ return { ...body, seal: row.seal };
73
+ }
74
+
75
+ /** Lay out the frozen record sequence across existing or new journal chunks without reading or writing files. */
76
+ export function planPlacementBatchIntent(epochHash: string, attemptHash: string, records: readonly PlacementRecord[],
77
+ existing: readonly { name: string; size: number; hash: string }[]): PlacementBatchIntent {
78
+ if (!records.length || !hex(epochHash) || !hex(attemptHash)) return fail();
79
+ const chunks: PlacementBatchChunk[] = [], empty = digest(Buffer.alloc(0));
80
+ let used = existing.at(-1)?.size ?? 0, index = existing.length ? existing.length - 1 : 0;
81
+ let prefixBytes = existing.at(-1)?.size ?? 0, prefixHash = existing.at(-1)?.hash ?? empty;
82
+ let first = 0, count = 0, suffix: Buffer[] = [];
83
+ const flush = () => {
84
+ if (!count) return;
85
+ chunks.push({ name: `records-${String(index).padStart(5, "0")}.jsonl`, prefixBytes, prefixHash, first, count, suffixHash: digest(Buffer.concat(suffix)) });
86
+ first += count; count = 0; suffix = []; index++; used = 0; prefixBytes = 0; prefixHash = empty;
87
+ };
88
+ for (const record of records) {
89
+ const data = bytesOf(validatePlacementRecord(record));
90
+ if (data.length > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) return fail();
91
+ if (used + data.length > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) {
92
+ if (count) flush(); else { index++; used = 0; prefixBytes = 0; prefixHash = empty; }
93
+ }
94
+ used += data.length; count++; suffix.push(data);
95
+ }
96
+ flush();
97
+ const body = { schema: "agent-mem.sync-placement-append-intent/v2" as const, epochHash, attemptHash,
98
+ previousHash: records[0]!.previousHash, records: [...records], chunks };
99
+ return validatePlacementBatchIntent({ ...body, seal: hashJSON(body) }, epochHash);
100
+ }
@@ -16,6 +16,8 @@ import { validatePlacementPublicationRoot, validatePlacementPublicationBundle, v
16
16
  import { PlacementProjection } from "./sync-placement-projection.ts";
17
17
  import { WRITER_RENEWAL_INTENT_FILE, WRITER_RENEWAL_INTENT_MAX_BYTES, WRITER_COMMIT_LOG, writerHistoryFileLimit, writerRevisionFile } from "./sync-placement-writer-revision-format.ts";
18
18
  import { isWriterRenewalIntentTempName } from "./sync-placement-writer-history.ts";
19
+ import { PLACEMENT_BATCH_INTENT_MAX_BYTES, planPlacementBatchIntent, validatePlacementBatchIntent, type PlacementBatchIntent } from "./sync-placement-batch-intent.ts";
20
+ import { formatFloorAtLeast } from "./formats.ts";
19
21
 
20
22
  export type PlacementStoragePhase = "epoch-written" | "epoch-fsync" | "activation-written" | "activation-fsync" | "fence-written" | "fence-fsync"
21
23
  | "intent-written" | "intent-fsync" | "chunk-written" | "chunk-fsync" | "intent-cleared"
@@ -23,12 +25,12 @@ export type PlacementStoragePhase = "epoch-written" | "epoch-fsync" | "activatio
23
25
  | "publication-root-written" | "publication-root-fsync" | "publication-fact-written" | "publication-fact-fsync" | "publication-durability-file-fsync" | "publication-durability-dir-fsync";
24
26
  export interface PlacementStorageOptions { mutation: MutationHandle; assertCurrent(): void; phase?(phase: PlacementStoragePhase): void; publicationAttemptHash?: string }
25
27
  export interface PlacementJournalRead {
26
- epoch: PlacementEpoch; activation: SyncPlacementActivationPlan; records: PlacementRecord[]; headHash: string; sequence: number; objects: number; pending: boolean; pendingRecordSequence?: number; pendingRecord?: PlacementRecord; publicationReservation?: { attemptHash: string; reservedRecords: number; consumedRecords: number };
28
+ epoch: PlacementEpoch; activation: SyncPlacementActivationPlan; records: PlacementRecord[]; headHash: string; sequence: number; objects: number; pending: boolean; pendingRecordSequence?: number; pendingRecord?: PlacementRecord; pendingBatch?: { attemptHash: string; count: number }; publicationReservation?: { attemptHash: string; reservedRecords: number; consumedRecords: number };
27
29
  }
28
30
  interface Paths { home: string; root: string; epochs: string; dir: string; hash: string }
29
31
  interface Chunk { name: string; size: number; hash: string }
30
32
  interface Intent { schema: "agent-mem.sync-placement-append-intent/v1"; epochHash: string; record: PlacementRecord; chunk: string; prefixBytes: number; prefixHash: string; lineHash: string }
31
- interface Snapshot extends PlacementJournalRead { chunks: Chunk[]; projection: PlacementProjection; intent?: Intent; intentPending: boolean; fencePending: boolean }
33
+ interface Snapshot extends PlacementJournalRead { chunks: Chunk[]; projection: PlacementProjection; intent?: Intent; batchIntent?: PlacementBatchIntent; intentPending: boolean; fencePending: boolean }
32
34
  const inflight = new WeakSet<MutationHandle>(), hex = (value: unknown, width = 64): value is string => typeof value === "string" && value.length === width && new RegExp(`^[a-f0-9]{${width}}$`).test(value);
33
35
  function fail(code: SyncPlacementJournalErrorCode = "corrupt"): never { throw new SyncPlacementJournalError(code); }
34
36
  const digest = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
@@ -79,7 +81,7 @@ function inventory(p: Paths): { files: Map<string, BigIntStats>; token: string;
79
81
  const writerLimit=writerHistoryFileLimit(name);
80
82
  if (!chunk && !publicationName(name) && writerLimit===undefined && !["epoch.json", "activation.json", "append-intent.json"].includes(name)) fail();
81
83
  const stat = state(join(p.dir, name))!;
82
- if (stat.size > BigInt(writerLimit??(chunk || /-chunk-\d{5}\.json$/.test(name) ? PLACEMENT_JOURNAL_CHUNK_MAX_BYTES : PLACEMENT_JOURNAL_ROOT_MAX_BYTES))) fail("bound");
84
+ if (stat.size > BigInt(writerLimit??(name === "append-intent.json" ? PLACEMENT_BATCH_INTENT_MAX_BYTES : chunk || /-chunk-\d{5}\.json$/.test(name) ? PLACEMENT_JOURNAL_CHUNK_MAX_BYTES : PLACEMENT_JOURNAL_ROOT_MAX_BYTES))) fail("bound");
83
85
  files.set(name, stat);
84
86
  }
85
87
  // One global active.json slot is always reserved, whether that fence exists yet or not.
@@ -138,16 +140,21 @@ export function releasePlacementStorageCaches(): void { journalPrefix = undefine
138
140
  // Records are frozen and shared (the bulk); every small mutable field is a fresh copy, so a caller's mutation never reaches the memo.
139
141
  const detachSnapshot = (value: Snapshot): Snapshot => ({ ...value, records: value.records.map(freeze), chunks: value.chunks.map(chunk => ({ ...chunk })), projection: value.projection.clone(),
140
142
  epoch: structuredClone(value.epoch), activation: structuredClone(value.activation),
141
- ...(value.intent ? { intent: structuredClone(value.intent) } : {}), ...(value.pendingRecord ? { pendingRecord: structuredClone(value.pendingRecord) } : {}) });
143
+ ...(value.intent ? { intent: structuredClone(value.intent) } : {}), ...(value.batchIntent ? { batchIntent: structuredClone(value.batchIntent) } : {}), ...(value.pendingBatch ? { pendingBatch: { ...value.pendingBatch } } : {}), ...(value.pendingRecord ? { pendingRecord: structuredClone(value.pendingRecord) } : {}) });
142
144
  function snapshot(p: Paths): Snapshot {
143
145
  const before = inventory(p);
144
146
  if (journalSnapshot?.token === canonicalJSON([p.dir, before.token])) return detachSnapshot(journalSnapshot.value);
145
147
  const epoch = decode(readOwned(join(p.dir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
146
148
  if (placementEpochHash(epoch) !== p.hash) return fail("conflict");
147
149
  const plan = decode(readOwned(join(p.dir, "activation.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), value => activation(epoch, p.hash, value));
148
- const pendingBytes = readOwned(join(p.dir, "append-intent.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
150
+ const pendingBytes = readOwned(join(p.dir, "append-intent.json"), PLACEMENT_BATCH_INTENT_MAX_BYTES);
149
151
  const intentPending = pendingBytes !== undefined && (!pendingBytes.length || pendingBytes.at(-1) !== 10);
150
- const pending = pendingBytes && !intentPending ? decode(pendingBytes, value => intent(value, p.hash)) : undefined;
152
+ let pending: Intent | undefined, batch: PlacementBatchIntent | undefined;
153
+ if (pendingBytes && !intentPending) {
154
+ const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(pendingBytes)) as { schema?: unknown };
155
+ if (parsed?.schema === "agent-mem.sync-placement-append-intent/v2") batch = decode(pendingBytes, value => validatePlacementBatchIntent(value, p.hash));
156
+ else { if (pendingBytes.length > PLACEMENT_JOURNAL_ROOT_MAX_BYTES) fail("bound"); pending = decode(pendingBytes, value => intent(value, p.hash)); }
157
+ }
151
158
  let projection = new PlacementProjection(epoch); const records: PlacementRecord[] = [], chunks: Chunk[] = [];
152
159
  const apply = (bytes: Buffer) => {
153
160
  let start = 0;
@@ -159,16 +166,30 @@ function snapshot(p: Paths): Snapshot {
159
166
  };
160
167
  const chunkNames = [...before.files.keys()].filter(name => /^records-\d{5}\.jsonl$/.test(name));
161
168
  const prefixKey = (count: number) => canonicalJSON([p.dir, stamp(before.files.get("epoch.json")!), chunkNames.slice(0, count).map(name => [name, stamp(before.files.get(name)!)])]);
162
- const cached = journalPrefix && journalPrefix.count < chunkNames.length && journalPrefix.key === prefixKey(journalPrefix.count) ? journalPrefix : undefined;
169
+ const cached = !batch && journalPrefix && journalPrefix.count < chunkNames.length && journalPrefix.key === prefixKey(journalPrefix.count) ? journalPrefix : undefined;
170
+ let batchPartial = false;
163
171
  let prefix: typeof journalPrefix, tail: typeof journalTail;
164
172
  if (cached) { projection = cached.projection.clone(); records.push(...cached.records); chunks.push(...cached.chunks); }
165
173
  for (const [index, name] of chunkNames.entries()) {
166
174
  if (index < (cached?.count ?? 0)) continue;
167
- if (index > 0 && index === chunkNames.length - 1) prefix = { key: prefixKey(index), count: index, records: records.map(freeze), chunks: [...chunks], projection: projection.clone() };
175
+ if (!batch && index > 0 && index === chunkNames.length - 1) prefix = { key: prefixKey(index), count: index, records: records.map(freeze), chunks: [...chunks], projection: projection.clone() };
168
176
  if (name !== `records-${String(index).padStart(5, "0")}.jsonl`) fail();
169
177
  const bytes = readOwned(join(p.dir, name), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES)!;
170
- chunks.push({ name, size: bytes.length, hash: digest(bytes) });
171
- if (pending?.chunk === name) {
178
+ const batchChunk = batch?.chunks.find(chunk => chunk.name === name);
179
+ if (batchChunk) {
180
+ if (batchPartial || bytes.length < batchChunk.prefixBytes || digest(bytes.subarray(0, batchChunk.prefixBytes)) !== batchChunk.prefixHash) fail();
181
+ if (batchChunk.prefixBytes) {
182
+ if (batchChunk.first !== 0) fail();
183
+ chunks.push({ name, size: batchChunk.prefixBytes, hash: batchChunk.prefixHash });
184
+ apply(bytes.subarray(0, batchChunk.prefixBytes));
185
+ }
186
+ const suffix = bytes.subarray(batchChunk.prefixBytes);
187
+ const expected = Buffer.concat(batch!.records.slice(batchChunk.first, batchChunk.first + batchChunk.count).map(line));
188
+ if (suffix.length > expected.length || !expected.subarray(0, suffix.length).equals(suffix)) fail();
189
+ if (suffix.length !== expected.length) batchPartial = true;
190
+ } else if (batch && Number(name.slice(8, 13)) >= Number(batch.chunks[0]!.name.slice(8, 13))) fail();
191
+ else if (pending?.chunk === name) {
192
+ chunks.push({ name, size: bytes.length, hash: digest(bytes) });
172
193
  if (index !== chunkNames.length - 1 || bytes.length < pending.prefixBytes || digest(bytes.subarray(0, pending.prefixBytes)) !== pending.prefixHash) fail();
173
194
  apply(bytes.subarray(0, pending.prefixBytes));
174
195
  if (projection.headHash !== pending.record.previousHash || projection.sequence + 1 !== pending.record.sequence) fail();
@@ -176,6 +197,7 @@ function snapshot(p: Paths): Snapshot {
176
197
  if (suffix.length > expected.length || !expected.subarray(0, suffix.length).equals(suffix)) fail();
177
198
  if (suffix.length === expected.length) apply(suffix);
178
199
  } else {
200
+ chunks.push({ name, size: bytes.length, hash: digest(bytes) });
179
201
  if (!bytes.length) fail();
180
202
  const last = index === chunkNames.length - 1, known = last ? journalTail : undefined;
181
203
  if (known && known.key === prefixKey(index) && known.name === name && bytes.length >= known.bytes.length && bytes.subarray(0, known.bytes.length).equals(known.bytes)) {
@@ -190,6 +212,18 @@ function snapshot(p: Paths): Snapshot {
190
212
  if (!found && (projection.headHash !== pending.record.previousHash || projection.sequence + 1 !== pending.record.sequence)) fail();
191
213
  if (pending.record.sequence > PLACEMENT_JOURNAL_MAX_RECORDS) fail("bound");
192
214
  }
215
+ if (batch) {
216
+ const first = batch.chunks[0]!, firstIndex = Number(first.name.slice(8, 13));
217
+ const existingIndex = first.prefixBytes ? firstIndex : firstIndex - 1;
218
+ if (chunks.length !== existingIndex + 1 || projection.headHash !== batch.previousHash
219
+ || projection.sequence + 1 !== batch.records[0]!.sequence || (first.prefixBytes && !chunkNames.includes(first.name))
220
+ || (!first.prefixBytes && first.prefixHash !== digest(Buffer.alloc(0)))) fail();
221
+ let absent = false;
222
+ for (const descriptor of batch.chunks) {
223
+ if (!chunkNames.includes(descriptor.name)) absent = true;
224
+ else if (absent) fail();
225
+ }
226
+ }
193
227
  let fencePending = false, activeFence: PlacementActiveFence | undefined;
194
228
  const fenceBytes = readOwned(join(p.root, "active.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
195
229
  if (fenceBytes !== undefined) {
@@ -203,14 +237,14 @@ function snapshot(p: Paths): Snapshot {
203
237
  if (inventory(p).token !== before.token) fail("changed");
204
238
  if (prefix) journalPrefix = prefix;
205
239
  if (tail) journalTail = tail;
206
- const result: Snapshot = { epoch, activation: plan, records, projection, headHash: projection.headHash, sequence: projection.sequence, objects: before.files.size + 1 + before.renewalObjects, pending: !!pending || intentPending || fencePending, chunks, intentPending, fencePending, ...(pending ? { pendingRecordSequence: pending.record.sequence, pendingRecord: validatePlacementRecord(pending.record) } : {}), ...(pending ? { intent: pending } : {}) };
240
+ const result: Snapshot = { epoch, activation: plan, records, projection, headHash: projection.headHash, sequence: projection.sequence, objects: before.files.size + 1 + before.renewalObjects, pending: !!pending || !!batch || intentPending || fencePending, chunks, intentPending, fencePending, ...(pending ? { pendingRecordSequence: pending.record.sequence, pendingRecord: validatePlacementRecord(pending.record) } : {}), ...(pending ? { intent: pending } : {}), ...(batch ? { batchIntent: batch, pendingBatch: { attemptHash: batch.attemptHash, count: batch.records.length }, pendingRecordSequence: batch.records[0]!.sequence, pendingRecord: validatePlacementRecord(batch.records[0]!) } : {}) };
207
241
  journalSnapshot = { token: canonicalJSON([p.dir, before.token]), value: detachSnapshot(result) };
208
242
  return result;
209
243
  }
210
244
  export function readPlacementJournal(home: string, epochHash: string): PlacementJournalRead {
211
245
  return protectedIO(() => {
212
246
  const p = paths(home, epochHash), before = inventory(p).token;
213
- const { chunks: _chunks, projection: _projection, intent: _intent, intentPending: _intentPending, fencePending: _fencePending, ...result } = snapshot(p);
247
+ const { chunks: _chunks, projection: _projection, intent: _intent, batchIntent: _batchIntent, intentPending: _intentPending, fencePending: _fencePending, ...result } = snapshot(p);
214
248
  const reservation = pendingPublication(p);
215
249
  if (reservation) {
216
250
  const root = reservation.bundle.root, consumedRecords = result.sequence - root.journal.sequence;
@@ -328,6 +362,43 @@ function sameEvent(record: PlacementRecord, value: PlacementEvent): boolean {
328
362
  const { schema: _schema, epochHash: _epoch, sequence: _seq, previousHash: _previous, seal: _seal, ...event } = record;
329
363
  return canonicalJSON(validatePlacementEvent(event)) === canonicalJSON(value);
330
364
  }
365
+
366
+ /** A publication step is one durable intent; chunk writes remain bounded and prefix-only. */
367
+ export function appendPlacementEvents(home: string, epochHash: string, values: readonly PlacementEvent[], expectedHead: string,
368
+ opts: PlacementStorageOptions): { records: PlacementRecord[]; already: boolean } {
369
+ if (!values.length || !hex(expectedHead) || !opts.publicationAttemptHash) fail("invalid");
370
+ if (!formatFloorAtLeast(home, "sync", "0.28.0")) throw new Error("Placement batch append requires the sync or home format floor 0.28.0; upgrade all readers and run amem formats raise sync 0.28.0 before retrying.");
371
+ const events = values.map(validatePlacementEvent);
372
+ return writer(home, epochHash, opts, p => {
373
+ const read = snapshot(p);
374
+ if (read.intent || read.fencePending || read.headHash !== expectedHead) fail("conflict");
375
+ checkPublicationAppend(p, read, events[0]!, opts);
376
+ let head = expectedHead;
377
+ const records = events.map((event, index) => {
378
+ const record = createPlacementRecord(epochHash, read.sequence + index + 1, head, event);
379
+ head = record.seal; checkPublicationRecord(p, record, opts); read.projection.apply(record); return record;
380
+ });
381
+ const transaction = planPlacementBatchIntent(epochHash, opts.publicationAttemptHash!, records, read.chunks);
382
+ if (read.batchIntent && canonicalJSON(read.batchIntent) !== canonicalJSON(transaction)) fail("pending");
383
+ const required = ["append-intent.json", ...transaction.chunks.map(chunk => chunk.name)];
384
+ const encoded = line(transaction), saved = readOwned(join(p.dir, "append-intent.json"), PLACEMENT_BATCH_INTENT_MAX_BYTES);
385
+ if (saved && (saved.length > encoded.length || !encoded.subarray(0, saved.length).equals(saved))) fail("conflict");
386
+ current(p, opts, required); ensureFence(p, read.epoch, opts, required);
387
+ complete(p, opts, join(p.dir, "append-intent.json"), encoded, PLACEMENT_BATCH_INTENT_MAX_BYTES, required, "intent-written", "intent-fsync");
388
+ for (const chunk of transaction.chunks) {
389
+ const prior = readOwned(join(p.dir, chunk.name), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) ?? Buffer.alloc(0);
390
+ if (prior.length < chunk.prefixBytes || digest(prior.subarray(0, chunk.prefixBytes)) !== chunk.prefixHash) fail("changed");
391
+ const suffix = Buffer.concat(records.slice(chunk.first, chunk.first + chunk.count).map(line));
392
+ const expected = Buffer.concat([prior.subarray(0, chunk.prefixBytes), suffix]);
393
+ complete(p, opts, join(p.dir, chunk.name), expected, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, required, "chunk-written", "chunk-fsync");
394
+ }
395
+ current(p, opts, required);
396
+ if (!readOwned(join(p.dir, "append-intent.json"), PLACEMENT_BATCH_INTENT_MAX_BYTES)?.equals(encoded)) fail("changed");
397
+ unlinkSync(join(p.dir, "append-intent.json")); syncDirectory(p, opts, p.dir, []); opts.phase?.("intent-cleared");
398
+ current(p, opts); const done = snapshot(p); if (done.pending || done.headHash !== head) fail("changed");
399
+ return { records, already: false };
400
+ });
401
+ }
331
402
  export function appendPlacementEvent(home: string, epochHash: string, value: PlacementEvent, expectedHead: string, opts: PlacementStorageOptions): { record: PlacementRecord; already: boolean } {
332
403
  const event = validatePlacementEvent(value); if (!hex(expectedHead)) return fail("invalid");
333
404
  return writer(home, epochHash, opts, p => {
@@ -19,7 +19,8 @@ import type { PlannedGitObject } from "./sync-placement-git.ts";
19
19
  import { PLACEMENT_FORMAT } from "./sync-placement-format.ts";
20
20
  import { PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type PlacementHoldReason, type PlacementRecord } from "./sync-placement-journal-format.ts";
21
21
  import { rebuildPlacementProjection, type PlacementProjection } from "./sync-placement-projection.ts";
22
- import { readPlacementJournal, appendPlacementEvent, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
22
+ import { readPlacementJournal, appendPlacementEvent, appendPlacementEvents, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
23
+ import { formatFloorAtLeast } from "./formats.ts";
23
24
  import { preparePlacementPublication, readPlacementPublication, recordPlacementPublicationPhase, type PlacementPublicationRead } from "./sync-placement-publication-storage.ts";
24
25
  import { planPlacementPublication, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
25
26
  import { ShardHistoryAuditor, type ShardHistory } from "./shard-sync-history.ts";
@@ -355,6 +356,15 @@ class PlacementTransport {
355
356
  if(consumed<0||consumed>root.reservedRecords)refuse();
356
357
  for(let index=0;index<Math.min(consumed,records.length);index++)
357
358
  if(canonicalJSON(read.records[root.journal.sequence+index])!==canonicalJSON(records[index]))refuse();
359
+ if(read.pendingBatch){
360
+ const index=read.sequence-root.journal.sequence, end=index+read.pendingBatch.count;
361
+ if(read.pendingBatch.attemptHash!==root.seal || end>count || end>events.length)refuse();
362
+ appendPlacementEvents(this.home,this.epochHash,events.slice(index,end),read.headHash,this.storage(factual));read=readPlacementJournal(this.home,this.epochHash);
363
+ }else if(read.pending&&!read.pendingRecord&&formatFloorAtLeast(this.home,"sync","0.28.0")){
364
+ const index=read.sequence-root.journal.sequence;
365
+ try { appendPlacementEvents(this.home,this.epochHash,events.slice(index,count),read.headHash,this.storage(factual));read=readPlacementJournal(this.home,this.epochHash); }
366
+ catch(error){ if(!(error instanceof SyncPlacementJournalError)||error.code!=="conflict")throw error; }
367
+ }
358
368
  if(read.pending){
359
369
  const sequence=read.pendingRecordSequence??read.sequence+1, index=sequence-root.journal.sequence-1;
360
370
  const record=records[index];
@@ -362,7 +372,11 @@ class PlacementTransport {
362
372
  appendPlacementEvent(this.home,this.epochHash,events[index]!,record.previousHash,this.storage(factual));read=readPlacementJournal(this.home,this.epochHash);
363
373
  }
364
374
  this.progress?.advance(Math.max(0,Math.min(count,read.sequence-root.journal.sequence)));
365
- for(let index=read.sequence-root.journal.sequence;index<count;index++){
375
+ const next=read.sequence-root.journal.sequence;
376
+ if(next<count&&formatFloorAtLeast(this.home,"sync","0.28.0")){
377
+ appendPlacementEvents(this.home,this.epochHash,events.slice(next,count),read.headHash,this.storage(factual));this.progress?.advance(count-next);return;
378
+ }
379
+ for(let index=next;index<count;index++){
366
380
  const record=records[index];if(!record)refuse();appendPlacementEvent(this.home,this.epochHash,events[index]!,record.previousHash,this.storage(factual));this.progress?.advance();
367
381
  }
368
382
  }
@@ -403,7 +417,7 @@ class PlacementTransport {
403
417
  const before=readPlacementJournal(this.home,this.epochHash);
404
418
  if(before.pending){
405
419
  const old=await this.frozenOld(read.bundle),schedule=this.events(read.bundle,projection,old);
406
- const sequence=before.pendingRecordSequence??before.sequence+1;
420
+ const sequence=before.pendingBatch ? before.sequence+before.pendingBatch.count : before.pendingRecordSequence??before.sequence+1;
407
421
  if(!before.pendingRecord&&schedule.events[sequence-root.journal.sequence-1]?.kind!=="hold")refuse();
408
422
  this.appendThrough(read.bundle,schedule.events,Math.max(holds.length,sequence-root.journal.sequence),true);
409
423
  }else this.appendThrough(read.bundle,holds,holds.length,true);
package/src/ui/panel.js CHANGED
@@ -37,7 +37,7 @@ export default (host) => {
37
37
  sections.push({ title: `Evidence (${evidence.length})`, open: evidence.length > 0, body: h("div", {},
38
38
  ui.rows(evidence, (e) => ui.row(e)) ?? ui.empty("No evidence attached", "This kind of candidate carries no references."),
39
39
  ...(r.targets ?? []).filter((t) => typeof t.text === "string").map((t) => h("blockquote", {}, h("pre", { class: "amem-pre", text: t.text }))),
40
- h("p", { class: "amem-sub", text: "Source session, proposing agent and times seen are not recorded in the candidate store." })) });
40
+ h("p", { class: "amem-sub", text: origin(r.origin) })) });
41
41
  sections.push({ title: `Similar memories (${r.overlaps.length})`, open: r.overlaps.length > 0,
42
42
  body: ui.rows(r.overlaps, (o) => ui.row({ title: o.title ?? "Untitled note", sub: `mem:${o.id.slice(0, 8)} · overlap ${o.score.toFixed(2)}` })) ?? ui.empty("No similar memories") });
43
43
  if (r.edit !== null) {
@@ -46,11 +46,16 @@ export default (host) => {
46
46
  sections.push({ title: "Edit, then accept", body: h("form", { class: "amem-form", onsubmit: (e) => { e.preventDefault(); act({ action: "edit_accept", id: r.id, text: text.value }); } },
47
47
  text, h("button", { type: "submit", class: "btn", text: "Save edit and accept" })) });
48
48
  }
49
+ const originRows = r.origin && typeof r.origin === "object" ? [{ label: "Origin session", value: r.origin.session ?? "unavailable" }, { label: "Proposed by", value: r.origin.peer ?? "unavailable" }] : [{ label: "Origin", value: r.origin === "unknown" ? "unknown" : "unavailable" }];
49
50
  return ui.detail({ kind: `${r.kind} candidate`, title: line(r.text, 90), state: { text: "pending", tone: "warn" }, whoseMove: "you", actions, summary: r.text,
50
- provenance: [{ label: "Proposed", value: day(r.createdAt), at: r.createdAt }, { label: "Project", value: project ?? "" }, ...(r.noteKind ? [{ label: "Note kind", value: r.noteKind }] : [])],
51
+ provenance: [{ label: "Proposed", value: day(r.createdAt), at: r.createdAt }, { label: "Project", value: project ?? "" }, ...originRows, ...(r.noteKind ? [{ label: "Note kind", value: r.noteKind }] : [])],
51
52
  sections, footer: [r.id] });
52
53
  };
53
54
 
55
+ // #323: the proposing session and agent as recorded ids, or why they are missing; never inferred from capture.
56
+ const origin = (o) => o === "unknown" ? "Origin unknown: this candidate was proposed before origin was recorded."
57
+ : o && typeof o === "object" ? `Origin: session ${o.session ?? "unavailable"}, proposed by ${o.peer ?? "unavailable"}${o.at ? ` at ${o.at}` : ""}.`
58
+ : "Origin unavailable: the proposer supplied no session or agent.";
54
59
  const views = {
55
60
  review(s) {
56
61
  const rows = s.rows ?? [], picked = rows.find((r) => r.id === s.selected);
package/src/ui/plugin.ts CHANGED
@@ -205,6 +205,8 @@ export const plugin = {
205
205
  const targets = targetsOf(input).map(t => { const v = store?.get(t.id, project); return v ? { id: v.id, at: v.at, kind: v.kind, title: v.title, text: v.text } : { id: t.id }; });
206
206
  return {
207
207
  id: c.id, kind: input.kind, createdAt: c.createdAt, text: candidateText(input),
208
+ // #323: ids only; "unknown" for a row written before origin was recorded, null when the proposer supplied none.
209
+ origin: c.originKnown ? c.origin ?? null : "unknown",
208
210
  noteKind: "noteKind" in input ? input.noteKind ?? null : null,
209
211
  diff: input.kind === "correction" ? { now: (targets[0] as { text?: string } | undefined)?.text ?? null, proposed: input.proposedText, reason: input.reason } : null,
210
212
  evidence: input.kind === "fail" ? input.evidenceRefs : [],