Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

37.2 KB
Raw Blame
import { readFileSync, readdirSync, mkdirSync, renameSync, writeFileSync, unlinkSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { ledgerFileHash, readLedger } from './request-groups.mjs';
import { activitySignature, buildAgentView, readAgentRecords } from './agent-view.mjs';
import { reduceWorkState } from './work-state-reduce.mjs';
import { buildSharedProjectionUpdates, applySharedProjection, decorateSharedView, isSharedProjectionValue } from './shared-projection.mjs';
import { createSharedRecordReader, publishSharedRecords } from './shared-record-store.mjs';
import { SHARED_WORK_MAX_UPDATES, sharedRecordKey, sharedValueHash, sharedWorkListSql } from './shared-records.mjs';
import { canonicalJson } from '../sync/CanonicalContent.js';
import { redactJsonStrings } from '../../utils/redaction.js';
import { isTransientSqliteBusy } from '../worker/db-init-retry.js';

const digest = value => createHash('sha256').update(canonicalJson(value ?? null)).digest('hex');
const MAX_FILE_BYTES = 8 * 1024 * 1024;
const fixedFiles = ['request-groups.json', 'story.json', 'refresh.json', 'agent-written-prompts.json'];
const fileKinds = name => name === 'request-groups.json' ? ['group', 'ignored']
  : name === 'story.json' ? ['story'] : name === 'refresh.json' ? ['refresh']
  : name === 'agent-written-prompts.json' ? ['exclusion']
  : /^progress\/g_[a-f0-9]{12}\.json$/.test(name) ? ['progress'] : [];

function load(path) {
  try {
    const raw = readFileSync(path);
    if (raw.byteLength > MAX_FILE_BYTES) throw new RangeError('Shared My Work file is over the local import limit');
    return JSON.parse(raw.toString('utf8'));
  } catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
}

/**
 * The observed hash of the file a staged write is about to replace. A file whose bytes are not JSON hashes its raw
 * bytes instead, a stable marker of that damaged file, so the write that replaces it can proceed (a damaged
 * refresh.json otherwise blocked every refresh check). Every other read error still throws.
 */
function observedFileHash(path) {
  try { return digest(load(path)); }
  catch (error) {
    if (!(error instanceof SyntaxError)) throw error;
    return `unparsed:${createHash('sha256').update(readFileSync(path)).digest('hex')}`;
  }
}

/** Write `value` to a new temp file beside `path` and return the temp file's path; the caller renames or removes it. */
function writeTemporary(path, value) {
  mkdirSync(join(path, '..'), { recursive: true });
  const temp = `${path}.${randomUUID()}.shared.tmp`;
  try { writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' }); }
  catch (error) { removeTemporary(temp); throw error; }
  return temp;
}

function removeTemporary(temp) { try { unlinkSync(temp); } catch { /* Renamed or never created. */ } }

function rawWrite(path, value) {
  const temp = writeTemporary(path, value);
  try { renameSync(temp, path); } finally { removeTemporary(temp); }
}

function removeFile(path) { try { unlinkSync(path); } catch (error) { if (error.code !== 'ENOENT') throw error; } }

/**
 * Split one save's changes into publish batches of at most `size` so that no prefix of whole batches claims a
 * conversation for two groups. A replica applies a batch once its commit row arrives, and a sync page (500 ops) can end
 * between two batches of one save, so it can hold the first batches until its next pull. A group change that takes a
 * conversation therefore goes after the change that gives it up (a deleted or shrunk group), and changes that take from
 * each other (a swap) form one unit that is not split across batches (strongly connected components, Tarjan). Only a
 * unit larger than `size` is split.
 */
function membershipSafeBatches(changes, shared, size) {
  if (changes.length <= size) return [changes];
  const membersOf = record => record && !record.deleted && Array.isArray(record.value?.members) ? record.value.members : [];
  const giver = new Map();
  const taken = changes.map(change => {
    if (change.kind !== 'group') return [];
    const before = new Set(membersOf(shared.records.get(sharedRecordKey('group', change.key))));
    const after = new Set(change.deleted ? [] : change.value?.members ?? []);
    return { before, after };
  }).map((claims, index) => {
    if (!claims.before) return [];
    for (const member of claims.before) if (!claims.after.has(member)) giver.set(member, index);
    return [...claims.after].filter(member => !claims.before.has(member));
  });
  // Each change's prerequisites: the changes that give up a conversation it takes.
  const edges = taken.map(members => [...new Set(members.filter(member => giver.has(member)).map(member => giver.get(member)))]);
  // Tarjan emits a component after every component it reaches, so prerequisites come first.
  const order = changes.map(() => -1), low = [], onStack = [], stack = [], units = [];
  let counter = 0;
  const visit = node => { order[node] = low[node] = counter++; stack.push(node); onStack[node] = true; };
  for (let root = 0; root < changes.length; root++) {
    if (order[root] !== -1) continue;
    visit(root);
    const work = [[root, 0]];
    while (work.length) {
      const frame = work.at(-1), node = frame[0];
      if (frame[1] < edges[node].length) {
        const target = edges[node][frame[1]++];
        if (order[target] === -1) { visit(target); work.push([target, 0]); }
        else if (onStack[target]) low[node] = Math.min(low[node], order[target]);
        continue;
      }
      work.pop();
      if (work.length) low[work.at(-1)[0]] = Math.min(low[work.at(-1)[0]], low[node]);
      if (low[node] !== order[node]) continue;
      const unit = [];
      let member;
      do { member = stack.pop(); onStack[member] = false; unit.push(member); } while (member !== node);
      units.push(unit.sort((a, b) => a - b));
    }
  }
  const batches = [[]];
  for (const unit of units) {
    if (batches.at(-1).length + unit.length > size) batches.push([]);
    for (const index of unit) {
      if (batches.at(-1).length === size) batches.push([]);
      batches.at(-1).push(changes[index]);
    }
  }
  return batches.filter(batch => batch.length);
}

/**
 * Local files are compatibility caches. Their observed/base hashes and pending
 * writes live in SQLite, so a crash between database commit and rename cannot
 * import the older file as a new decision on restart.
 */
export class SharedLedgerAdapter {
  constructor(db, { directory, deviceId, project = '__my_work__', notify = () => {} }) {
    Object.assign(this, { db, directory, deviceId, project, notify });
    this.errors = [];
    this.activity = null;
    this.copyHash = null;
    this.sharedRevision = null;
    this.storyHash = null;
    this.lastSignature = null;
    this.lastDiagnostic = null;
    db.exec(`CREATE TABLE IF NOT EXISTS my_work_file_state (
      name TEXT PRIMARY KEY, observed_hash TEXT, bases TEXT NOT NULL DEFAULT '{}',
      keys_json TEXT NOT NULL DEFAULT '[]', pending_json TEXT, pending_delete INTEGER NOT NULL DEFAULT 0
    )`);
    if (!db.prepare('PRAGMA table_info(my_work_file_state)').all().some(row => row.name === 'pending_delete')) db.exec('ALTER TABLE my_work_file_state ADD COLUMN pending_delete INTEGER NOT NULL DEFAULT 0');
  }

  state(name) {
    const row = this.db.prepare('SELECT * FROM my_work_file_state WHERE name = ?').get(name);
    return row ? { ...row, bases: JSON.parse(row.bases), keys: JSON.parse(row.keys_json) } : { observed_hash: null, bases: {}, keys: [], pending_json: null };
  }

  pendingMaterialization() {
    return this.db.prepare('SELECT COUNT(*) AS count FROM my_work_file_state WHERE pending_json IS NOT NULL').get().count;
  }

  sharedReader() {
    return this.readShared ??= createSharedRecordReader(this.db, { deviceId: this.deviceId, validateValue: isSharedProjectionValue, reviewStack: 'exclude' });
  }

  shared() { return this.sharedReader()(); }

  tombstoneKeys(name, shared) {
    const kinds = fileKinds(name);
    return [...shared.records].filter(([, record]) => record.deleted && kinds.includes(record.kind)
      && (record.kind !== 'progress' || record.key === name.slice(9, -5))
      && (record.kind !== 'refresh' || record.key === this.deviceId)).map(([key]) => key);
  }

  remember(name, value, updates, shared, pending, pendingDelete = false) {
    value = redactJsonStrings(value);
    const prior = this.state(name);
    const keys = updates.map(update => sharedRecordKey(update.kind, update.key));
    // Keep deleted objects' accepted hashes too: their tombstone is the base
    // for a later recreation of this same stable identity, including restart.
    const knownKeys = new Set([...Object.keys(prior.bases), ...prior.keys, ...keys, ...this.tombstoneKeys(name, shared)]);
    const bases = Object.fromEntries([...knownKeys].map(key => [key, shared.records.get(key)?.hash ?? prior.bases[key] ?? null]));
    this.db.prepare(`INSERT INTO my_work_file_state(name, observed_hash, bases, keys_json, pending_json, pending_delete) VALUES(?, ?, ?, ?, ?, ?)
      ON CONFLICT(name) DO UPDATE SET observed_hash=excluded.observed_hash, bases=excluded.bases,
      keys_json=excluded.keys_json, pending_json=excluded.pending_json, pending_delete=excluded.pending_delete`)
      .run(name, pending ? prior.observed_hash ?? observedFileHash(join(this.directory, name)) : digest(value), JSON.stringify(bases), JSON.stringify(keys), pending ? JSON.stringify(value) : null, Number(pending && pendingDelete));
  }

  localLedger() {
    try { return readLedger(this.directory); }
    catch {
      const safe = (name, fallback) => { try { return load(join(this.directory, name)) ?? fallback; } catch { return fallback; } };
      const groups = safe('request-groups.json', { groups: {}, conversations: {}, ignored: {} });
      const progress = {};
      try { for (const name of readdirSync(join(this.directory, 'progress'))) if (/^g_[a-f0-9]{12}\.json$/.test(name)) {
        const value = safe(`progress/${name}`, null); if (value) progress[name.slice(0, -5)] = value;
      } } catch { /* A missing progress directory is empty. */ }
      return { groups, progress, story: safe('story.json', null), refresh: safe('refresh.json', null),
        agentWrittenPromptIds: new Set(safe('agent-written-prompts.json', {}).promptIds ?? []) };
    }
  }

  signature(captureActivity, dataVersion = this.db.prepare('PRAGMA data_version').get()) {
    const names = [...fixedFiles, 'human-copy.json'];
    try { names.push(...readdirSync(join(this.directory, 'progress')).filter(name => /^g_[a-f0-9]{12}\.json$/.test(name)).map(name => `progress/${name}`)); } catch { /* Missing directory. */ }
    const files = names.sort().map(name => {
      try { const stat = statSync(join(this.directory, name)); return [name, stat.ino, stat.size, stat.mtimeMs]; }
      catch { return [name, 'missing']; }
    });
    return JSON.stringify([dataVersion, captureActivity, files]);
  }

  updatesForFile(name, value) {
    const kinds = fileKinds(name);
    if (!kinds.length) return [];
    const object = item => item !== null && typeof item === 'object' && !Array.isArray(item);
    if (value !== null && !object(value)) throw new TypeError('Shared My Work file must contain an object');
    if (name === 'request-groups.json' && value !== null && (!object(value.groups) || !object(value.conversations)
      || (value.ignored !== undefined && !object(value.ignored)) || (value.suggestions !== undefined && !object(value.suggestions)))) {
      throw new TypeError('Shared request groups have an invalid shape');
    }
    if (name.startsWith('progress/') && value !== null && value.groupId !== name.slice(9, -5)) throw new TypeError('Shared progress names a different group');
    if (name === 'agent-written-prompts.json' && value !== null && (!Array.isArray(value.promptIds)
      || value.promptIds.some(id => !Number.isSafeInteger(id) || id <= 0))) throw new TypeError('Shared prompt exclusions have an invalid shape');
    const ledger = this.localLedger();
    if (name === 'request-groups.json') ledger.groups = value ?? { groups: {}, conversations: {}, ignored: {} };
    else if (name === 'story.json') ledger.story = value ?? null;
    else if (name === 'refresh.json') ledger.refresh = value ?? null;
    else if (name === 'agent-written-prompts.json') ledger.agentWrittenPromptIds = new Set(value?.promptIds ?? []);
    else {
      const id = name.slice('progress/'.length, -5);
      ledger.progress = { ...ledger.progress };
      if (value == null) delete ledger.progress[id]; else ledger.progress[id] = value;
    }
    return buildSharedProjectionUpdates(this.db, { ledger, deviceId: this.deviceId })
      .filter(update => kinds.includes(update.kind) && (kinds[0] !== 'progress' || update.key === name.slice(9, -5)));
  }

  /** The shared record keys a write may not overwrite without an explicit resolution: the conflicts `shared` holds. */
  conflictedKeys(shared) {
    const { diagnostics } = applySharedProjection(this.db, shared, { ledger: this.localLedger(), deviceId: this.deviceId });
    return new Set(diagnostics.conflicts.flatMap(entry => entry.kind === 'group-membership'
      ? entry.groups.map(group => sharedRecordKey('group', group)) : [sharedRecordKey(entry.kind, entry.key)]));
  }

  /**
   * Stage canonical rows and their recovery intent without touching files or notifying observers.
   * The shared records and their conflicts are read before the write lock is taken: a cold read of them took 3.9 s on
   * the owner's Mac (2,015 records, 2026-11-27), and every other writer, the worker included, waits while this
   * transaction holds the lock. Under the lock the reader only checks that they did not change (about 0.2 s there) and
   * reads them again only when another writer changed them meanwhile. Inside a caller's transaction nothing is cached,
   * so the read stays inside. IMMEDIATE takes the lock before the first read, so a busy database makes this wait up to
   * the connection's busy_timeout: a deferred transaction that reads and then writes fails at once with
   * SQLITE_BUSY_SNAPSHOT when another connection committed in between, and SQLite never runs the busy handler for it
   * (the reason SyncApply.applyOps takes its lock the same way). A refusal names the file and that nothing was saved.
   * readHash: the hash of the file the caller built `value` from (request-groups.mjs readHashOf). Under the lock the write
   * is refused when the file no longer has it, or another write's intent is still pending: that writer's decision is
   * committed and `value` was built without it. The wait for the lock made this window seconds long; without the check the
   * older value replaced the newer one (an owner's Join saved while a CLI apply waited). Each base is the record's hash as
   * this file last held it, so the base check alone cannot see a write that also updated the bases.
   */
  stageFile(name, value, { resolveKeys = [], resolutionBaseline, readHash } = {}) {
    if (!fileKinds(name).length) return null;
    value = redactJsonStrings(value);
    const updates = this.updatesForFile(name, value);
    let read = this.db.inTransaction ? null : this.shared();
    let conflicted = read && this.conflictedKeys(read);
    let changed = null;
    try { this.db.transaction(() => {
      const prior = this.state(name);
      if (readHash !== undefined && (prior.pending_json !== null || ledgerFileHash(join(this.directory, name)) !== readHash)) {
        throw new Error(`Shared My Work: ${name} changed since this command read it (another writer saved a newer version${prior.pending_json !== null ? ', which is still being written to the file' : ''}), so this write was not saved: no shared record and no file were written. Run the command again.`);
      }
      const shared = this.shared();
      if (shared !== read) { read = shared; conflicted = this.conflictedKeys(shared); }
      const resolving = new Set(resolveKeys.map(key => sharedRecordKey('group', key)));
      if (resolving.size && name !== 'request-groups.json') throw new TypeError('Only explicit grouping decisions can resolve group conflicts');
      if (resolving.size) {
        if (!resolutionBaseline) throw new TypeError('Explicit grouping resolution requires its canonical baseline');
        const baseline = new Map(this.updatesForFile(name, resolutionBaseline).filter(update => update.kind === 'group')
          .map(update => [sharedRecordKey(update.kind, update.key), sharedValueHash(update.kind, update.key, update.value, update.deleted)]));
        const desired = new Map(updates.filter(update => update.kind === 'group')
          .map(update => [sharedRecordKey(update.kind, update.key), sharedValueHash(update.kind, update.key, update.value, update.deleted)]));
        for (const key of new Set([...baseline.keys(), ...desired.keys()])) {
          if (!resolving.has(key) && baseline.get(key) !== desired.get(key)) throw new Error('Shared My Work: resolution changed an unrelated group');
        }
      }
      const nextKeys = new Set(updates.map(update => sharedRecordKey(update.kind, update.key)));
      const changes = updates.flatMap(update => {
        const key = sharedRecordKey(update.kind, update.key);
        if (resolving.size && update.kind === 'group' && !resolving.has(key)) return [];
        const existing = shared.records.get(key);
        if (conflicted.has(key) && !resolving.has(key)) {
          throw new Error('Shared My Work has a conflicting decision; retained the local file');
        }
        return [{ ...update, expectedHash: resolving.has(key) ? existing?.hash ?? null : prior.bases[key] ?? null }];
      });
      for (const key of new Set([...prior.keys, ...resolving])) if (!nextKeys.has(key)) {
        const existing = shared.records.get(key);
        if (existing) {
          if (resolving.size && existing.kind === 'group' && !resolving.has(key)) continue;
          if (conflicted.has(key) && !resolving.has(key)) {
            if (existing.deleted) continue;
            throw new Error('Shared My Work has a conflicting decision; retained the local file');
          }
          changes.push({ kind: existing.kind, key: existing.key, deleted: true, expectedHash: resolving.has(key) ? existing.hash : prior.bases[key] ?? null });
        }
      }
      // A first encounter with a materialized equal value is safe; a different
      // pre-existing value needs an explicit conflict choice, not an overwrite.
      for (const change of changes) {
        const key = sharedRecordKey(change.kind, change.key);
        const existing = shared.records.get(key);
        if (!Object.hasOwn(prior.bases, key) && existing
          && sharedValueHash(change.kind, change.key, change.value, change.deleted) === (existing.valueHash ?? existing.hash)) change.expectedHash = existing.hash;
      }
      // One publish takes at most SHARED_WORK_MAX_UPDATES records, and request-groups.json alone can hold more
      // (every group and every ignored conversation is a record). Publish it in batches inside this transaction, so a
      // refusal in any batch still saves nothing. Only the first batch can pass readState: it must be read with nothing
      // written since, so each later batch reads again; its records' expectedHash still holds the bases read above.
      // A replica can apply the first batches before the rest, so they are ordered to never claim a conversation twice.
      const reader = this.sharedReader();
      let published = 0;
      for (const [index, batch] of membershipSafeBatches(changes, shared, SHARED_WORK_MAX_UPDATES).entries()) {
        published += publishSharedRecords(this.db, { deviceId: this.deviceId, project: this.project,
          updates: batch, validateValue: isSharedProjectionValue, reader, ...(index === 0 ? { readState: shared } : {}) }).changed;
      }
      this.remember(name, value, updates, this.shared(), true, value === null);
      if (published) changed = { rules: changes.some(change => change.kind === 'story') };
    }).immediate(); }
    catch (error) {
      if (!isTransientSqliteBusy(error)) throw error;
      throw Object.assign(new Error(`Shared My Work: another writer held the claude-mem database for longer than ${this.busyTimeoutMs()} ms (its busy_timeout), so ${name} was not saved: no shared record and no file were written. Run the command again.`, { cause: error }), { code: error.code });
    }
    return { name, value, updates, changed, notified: false };
  }

  /** How long this connection waits for another writer's lock (PRAGMA busy_timeout), for the refusal's wording. */
  busyTimeoutMs() {
    return this.db.prepare('PRAGMA busy_timeout').get()?.timeout ?? 0;
  }

  /**
   * After stageFile committed: put the file in place and record it as written, in one IMMEDIATE transaction, and only
   * while the recovery intent is still this write's. The rename is under the lock because two writers of one file rename
   * in either order otherwise: when the older write's rename landed last, the newer one had already recorded its hash, so
   * the reconciler read the older file as a new local edit and published it over the newer decision. The bytes go to a
   * temp file before the lock, so the lock covers one rename and one UPDATE. A later writer's intent is never cleared:
   * this write's temp file is removed, and that writer puts its own value in place. writeFile false (the reconciler's
   * import of a file that already holds the value) only records it. The bases and keys stay as stageFile recorded them
   * against the records its own publish left, which are what this file holds, so no shared record is read here.
   * The decision is already durable when this runs, so it never throws: when the database stays busy past busy_timeout,
   * or the temp file or the rename fails, nothing is renamed, the intent stays pending and the reconciler writes the file
   * (finishPendingFile), as after a crash between the commit and the rename. 'pending' and its reason are returned
   * instead, so a caller never repeats a decision that was saved.
   */
  finishWrite(stage, { writeFile = true } = {}) {
    let temporary = null;
    try {
      const value = redactJsonStrings(stage.value);
      const path = join(this.directory, stage.name);
      if (writeFile && value !== null) temporary = writeTemporary(path, value);
      this.db.transaction(() => {
        if (this.state(stage.name).pending_json !== JSON.stringify(value)) return;
        if (writeFile) { if (temporary) renameSync(temporary, path); else removeFile(path); }
        this.db.prepare('UPDATE my_work_file_state SET observed_hash = ?, pending_json = NULL, pending_delete = 0 WHERE name = ?').run(digest(value), stage.name);
      }).immediate();
      return { materialization: 'complete' };
    } catch (error) {
      return { materialization: 'pending', reason: isTransientSqliteBusy(error)
        ? `another writer held the claude-mem database for longer than ${this.busyTimeoutMs()} ms` : String(error?.message ?? error) };
    } finally { if (temporary) removeTemporary(temporary); }
  }

  notifyCommitted(stage) {
    if (this.db.inTransaction) throw new Error('Shared My Work: the outer transaction has not committed');
    this.lastSignature = null;
    if (!stage?.changed || stage.notified) return;
    stage.notified = true;
    // A notification failure cannot undo a durable decision. The normal poll
    // still sees the committed canonical rows and pending materialization.
    try { this.notify(stage.changed); }
    catch { this.lastDiagnostic = null; }
  }

  /** After the owning transaction commits, materialize its durable recovery intent. */
  materializeFile(stage) {
    this.notifyCommitted(stage);
    if (!stage) return { materialization: 'complete' };
    const { name, value, updates } = stage;
    try {
      return { materialization: this.completePending(name, value, updates) ? 'complete' : 'pending' };
    } catch {
      // The canonical action is already durable. Keep pending_json for the
      // normal reconciler and report a saved action, not a failed intention.
      return { materialization: 'pending' };
    }
  }

  /**
   * Replace the file and clear the receipt only if `value` is still the pending
   * intent. The write lock is held throughout, so a writer on another connection
   * commits fully before this check or after this commit, never in between.
   */
  completePending(name, value, updates, shared) {
    return this.db.transaction(() => {
      // A later writer replaced this intent. Never overwrite it with older bytes.
      if (this.state(name).pending_json !== JSON.stringify(redactJsonStrings(value))) return false;
      if (value === null) { try { unlinkSync(join(this.directory, name)); } catch (error) { if (error.code !== 'ENOENT') throw error; } }
      else rawWrite(join(this.directory, name), value);
      this.remember(name, value, updates, shared ?? this.shared(), false);
      return true;
    }).immediate();
  }

  /**
   * Record the intent to materialize a projection. Skips when a writer on another
   * connection owns the file or has changed its records since `shared` was read;
   * that writer's newer value wins and the next reconcile projects from it.
   */
  stageProjection(name, value, updates, shared, pendingDelete = false) {
    const recordHashes = source => {
      const kinds = fileKinds(name);
      return JSON.stringify([...source.records].filter(([, record]) => kinds.includes(record.kind)).map(([key, record]) => [key, record.hash]).sort());
    };
    return this.db.transaction(() => {
      if (this.state(name).pending_json !== null || recordHashes(this.shared()) !== recordHashes(shared)) return false;
      this.remember(name, value, updates, shared, true, pendingDelete);
      return true;
    }).immediate();
  }

  /** Finish an interrupted write. Runs under the write lock so it always finishes the newest intent. */
  finishPendingFile(name) {
    return this.db.transaction(() => {
      const prior = this.state(name);
      const current = load(join(this.directory, name));
      if (prior.pending_json === null) return current;
      const originallyPending = JSON.parse(prior.pending_json);
      const pending = redactJsonStrings(originallyPending);
      if (current !== undefined && digest(current) !== prior.observed_hash && digest(current) !== digest(originallyPending)
        && digest(current) !== digest(pending)) throw new Error('Local file changed during an unfinished shared write');
      if (prior.pending_delete) { try { unlinkSync(join(this.directory, name)); } catch (error) { if (error.code !== 'ENOENT') throw error; } }
      else rawWrite(join(this.directory, name), pending);
      this.remember(name, pending, this.updatesForFile(name, pending), this.shared(), false);
      return pending;
    }).immediate();
  }

  /** Called when a writer replaces its file: commits the shared records, and returns the finish that writes the file
   * (finishWrite). Its `value` is the redacted value the file will hold. */
  beforeWrite(name, value, options) {
    if (this.db.inTransaction) throw new Error('Shared My Work: stage file writes until the outer transaction commits');
    const stage = this.stageFile(name, value, options);
    if (!stage) return null;
    this.notifyCommitted(stage);
    return Object.assign((finishOptions) => this.finishWrite(stage, finishOptions), { value: stage.value });
  }

  saveFile(name, value, options) {
    if (!fileKinds(name).length) throw new TypeError('Unsupported shared My Work file');
    return this.beforeWrite(name, value, options)();
  }

  publish(updates) {
    let changed = 0;
    const shared = this.shared();
    const conflicted = new Set(shared.diagnostics.conflicts.map(entry => sharedRecordKey(entry.kind, entry.key)));
    if (updates.some(update => conflicted.has(sharedRecordKey(update.kind, update.key)))) {
      throw new Error('Shared My Work has a conflicting decision; retained the previous complete state');
    }
    const safe = updates;
    for (let offset = 0; offset < safe.length; offset += SHARED_WORK_MAX_UPDATES) {
      changed += publishSharedRecords(this.db, { deviceId: this.deviceId, project: this.project, updates: safe.slice(offset, offset + SHARED_WORK_MAX_UPDATES), validateValue: isSharedProjectionValue, reader: this.sharedReader() }).changed;
    }
    if (changed) this.notify({ rules: safe.some(update => update.kind === 'story') });
    if (changed) this.lastSignature = null;
    return changed;
  }

  /**
   * Whether this database holds a row the activity capture could publish for. With no ledger and no copy entries,
   * buildSharedProjectionUpdates publishes provenance only for a session with a tool call, a deliverable, or an
   * observation or prompt this device wrote (tool_uses and deliverables are never synced, so any row there is
   * local; a pulled observation or prompt carries another device's origin). A replica that only pulls has none of
   * them: on the cloud viewer's account, 0 of 163,082 observations and 0 of 5,598 prompts. Local rows are counted
   * as all rows minus rows with an origin, because both counts use indexes and an IS NULL filter scans the table.
   */
  ownsActivity() {
    const count = (sql, params = []) => {
      try { return this.db.prepare(sql).get(...params).count; }
      catch (error) { if (/no such table/i.test(String(error.message))) return 0; throw error; }
    };
    if (count('SELECT COUNT(*) AS count FROM (SELECT 1 FROM tool_uses LIMIT 1)') || count('SELECT COUNT(*) AS count FROM (SELECT 1 FROM deliverables LIMIT 1)')) return true;
    return ['observations', 'user_prompts'].some(table => {
      const total = count(`SELECT COUNT(*) AS count FROM ${table}`);
      if (!total) return false;
      try {
        return total > count(`SELECT COUNT(*) AS count FROM ${table} WHERE origin_device_id IS NOT NULL`)
          || count(`SELECT COUNT(*) AS count FROM (SELECT 1 FROM ${table} WHERE origin_device_id = ? LIMIT 1)`, [this.deviceId]) > 0;
      } catch (error) {
        // An older database without origin columns has only local rows.
        if (/no such column/i.test(String(error.message))) return true;
        throw error;
      }
    });
  }

  reconcile({ captureActivity = true } = {}) {
    const dataVersion = this.db.prepare('PRAGMA data_version').get();
    const signature = this.signature(captureActivity, dataVersion);
    if (signature === this.lastSignature && this.lastDiagnostic) return this.lastDiagnostic;
    this.errors = [];
    // A finish left pending (finishWrite) changes nothing this pass's signature sees once the busy writer rolls back.
    let finishPending = false;
    const names = [...new Set([...fixedFiles, ...this.db.prepare('SELECT name FROM my_work_file_state').all().map(row => row.name)])];
    try { names.push(...readdirSync(join(this.directory, 'progress')).filter(name => /^g_[a-f0-9]{12}\.json$/.test(name)).map(name => `progress/${name}`)); }
    catch (error) { if (error.code !== 'ENOENT') throw error; }
    for (const name of names) {
      try {
        const current = this.state(name).pending_json !== null ? this.finishPendingFile(name) : load(join(this.directory, name));
        if ((current !== undefined || this.state(name).observed_hash !== null) && digest(current) !== this.state(name).observed_hash) {
          const finish = this.beforeWrite(name, current ?? null);
          // The file is rewritten only when redaction changed the value it holds.
          const finished = finish?.({ writeFile: digest(current) !== digest(finish.value) });
          // Saved, with the file's record left pending for the next pass: reported like any file this pass did not finish.
          if (finished?.materialization === 'pending') {
            finishPending = true;
            this.errors.push({ file: name, message: `Saved; recording the local file is pending: ${finished.reason}` });
          }
        }
      } catch (error) { this.errors.push({ file: name, message: String(error.message) }); }
    }
    const shared = this.shared();
    let projectionSuperseded = false;
    let activityPublishFailed = false;
    let ledger = this.localLedger();
    const applied = applySharedProjection(this.db, shared, { ledger, deviceId: this.deviceId });
    ledger = applied.ledger;
    const materialized = { 'request-groups.json': ledger.groups, 'story.json': ledger.story,
      'agent-written-prompts.json': { promptIds: [...ledger.agentWrittenPromptIds].sort((a,b) => a-b) } };
    for (const [id, progress] of Object.entries(ledger.progress)) materialized[`progress/${id}.json`] = progress;
    for (const [name, value] of Object.entries(materialized)) {
      if (value == null || this.errors.some(error => error.file === name)) continue;
      const kinds = fileKinds(name);
      if (!shared.records.size || ![...shared.records.values()].some(record => kinds.includes(record.kind))) continue;
      if (digest(load(join(this.directory, name))) === digest(value)) {
        const prior = this.state(name);
        if (this.tombstoneKeys(name, shared).some(key => prior.bases[key] !== shared.records.get(key).hash)) {
          this.remember(name, value, this.updatesForFile(name, value), shared, false);
        }
        continue;
      }
      const updates = this.updatesForFile(name, value);
      if (this.stageProjection(name, value, updates, shared)) this.completePending(name, value, updates, shared);
      else projectionSuperseded = true;
    }
    for (const record of shared.records.values()) {
      if (!record.deleted) continue;
      const name = record.kind === 'story' && record.key === 'current' ? 'story.json'
        : record.kind === 'progress' && /^g_[a-f0-9]{12}$/.test(record.key) ? `progress/${record.key}.json` : null;
      if (!name || this.errors.some(error => error.file === name)) continue;
      if (load(join(this.directory, name)) === undefined) {
        if (this.state(name).bases[sharedRecordKey(record.kind, record.key)] !== record.hash) this.remember(name, null, [], shared, false);
        continue;
      }
      if (this.stageProjection(name, null, [], shared, true)) this.completePending(name, null, [], shared);
      else projectionSuperseded = true;
    }
    // Never materialize a remote refresh's PID/ownership into refresh.json.
    const activity = captureActivity ? activitySignature(this.db) : null;
    let copies = {}, copyHash = null;
    if (captureActivity) {
      try {
        copies = load(join(this.directory, 'human-copy.json'))?.entries ?? {};
        copyHash = digest(copies);
      } catch (error) { this.errors.push({ file: 'human-copy.json', message: String(error.message) }); }
    }
    // Legacy copy writers can finish without another memory/tool row. Their
    // semantic file hash is an independent import trigger, not activity.
    // A replica that only pulls owns no activity, and then the capture below publishes nothing (see ownsActivity),
    // yet every pulled commit moves the activity signature. Skip its full view build there.
    if (captureActivity && (activity !== this.activity || copyHash !== this.copyHash) && !Object.keys(copies).length && !this.ownsActivity()) {
      this.activity = activity;
      this.copyHash = copyHash;
    } else if (captureActivity && (activity !== this.activity || copyHash !== this.copyHash)) {
      // The reducer drops shared rows, which are most of this table on a busy replica: leave them in SQLite.
      const entries = this.db.prepare(`SELECT id, project, list_name, fields, created_at_epoch, origin_device_id, origin_local_id
        FROM work_state_entries WHERE NOT ${sharedWorkListSql('list_name')}`).all();
      const state = reduceWorkState(entries, { localDeviceId: this.deviceId });
      let records = readAgentRecords(this.db, { workState: state, ledger });
      records = applySharedProjection(this.db, shared, { ledger, records, deviceId: this.deviceId }).records;
      const view = decorateSharedView(buildAgentView(state, records, { ledger }), { records });
      try { this.publish(buildSharedProjectionUpdates(this.db, { ledger: null, records, view, deviceId: this.deviceId, copyEntries: copies })); }
      catch (error) {
        this.errors.push({ file: 'activity', message: String(error.message) });
        // A busy database wrote nothing, and nothing else would republish this
        // activity, so replicas would never receive the session provenance:
        // keep it uncaptured for the next pass. Any other error (a conflict, an
        // invalid value) repeats until the data changes, and each pass rebuilds
        // the whole view, so that one stays captured.
        activityPublishFailed = String(error?.code ?? '').startsWith('SQLITE_BUSY');
      }
      if (!activityPublishFailed) {
        this.activity = activity;
        this.copyHash = copyHash;
      }
    }
    const final = this.shared();
    if (final.revision !== this.sharedRevision) {
      const story = final.records.get(sharedRecordKey('story', 'current'));
      const storyHash = story?.hash ?? null;
      this.notify({ rules: storyHash !== this.storyHash });
      this.storyHash = storyHash;
      this.sharedRevision = final.revision;
    }
    // Keep the database version from before capture. A concurrent connection
    // may have committed after our snapshot and still needs the next pass.
    // A skipped projection also has newer records left to materialize, and a pending finish a receipt to finish.
    this.lastSignature = projectionSuperseded || activityPublishFailed || finishPending ? null : this.signature(captureActivity, dataVersion);
    const diagnostics = applySharedProjection(this.db, final, { ledger, deviceId: this.deviceId }).diagnostics;
    this.lastDiagnostic = { ...diagnostics, files: this.errors };
    return this.lastDiagnostic;
  }
}