@staix/agent-mem 0.27.0 → 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.
@@ -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 : [],