Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

fix(brain): refresh the active preference digest (#296)

joo00der85260f2ca00d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index be7462d6..96125ac6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- **Windows: `o2b search reindex` no longer fails with `EBUSY` on its own staging file.** A `bun:sqlite` connection with unfinalized statements survives `close()` until garbage collection and keeps `brain.sqlite.new` open, so the rename swap failed on every attempt on Windows (POSIX `rename(2)` ignores open handles). The rebuild now forces a collection cycle right before the swap renames.
+- **The active preference digest no longer lists a retired preference.** `brain reject`, a tombstone and setting or clearing a preference's expiration now refresh `Brain/active.md`, an explicitly expired preference leaves the digest at its deadline, and `o2b brain refresh --stale` detects and rebuilds a digest that differs from the current preference set.
## [1.98.0] - 2026-11-02
diff --git a/openclaw/index.js b/openclaw/index.js
index 93a48ab2..b0817c6c 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -6311,7 +6311,7 @@ function isSwitched(context, options) {
} catch {
switched = false;
}
- if (switched) {
+ if (switched && options.persistSwitch !== false) {
seenSwitched.add(key);
writeMarker(root, device);
}
diff --git a/src/cli/brain/verbs/refresh.ts b/src/cli/brain/verbs/refresh.ts
index 350f6b06..a6173bdb 100644
--- a/src/cli/brain/verbs/refresh.ts
+++ b/src/cli/brain/verbs/refresh.ts
@@ -29,11 +29,12 @@ export async function cmdBrainRefresh(argv: string[]): Promise<number> {
let plan;
let result;
try {
- plan = planRecompile(vault);
+ const now = new Date();
+ plan = planRecompile(vault, { now, includeActiveDigest: true });
result = await executeRecompile(vault, plan, {
dryRun: Boolean(flags["dry-run"]),
agent: resolveBrainAgent(flags, config),
- now: new Date(),
+ now,
});
} catch (exc) {
return fail(`refresh failed: ${(exc as Error).message ?? exc}`);
diff --git a/src/cli/brain/verbs/reject.ts b/src/cli/brain/verbs/reject.ts
index 903a91a6..9b41a20a 100644
--- a/src/cli/brain/verbs/reject.ts
+++ b/src/cli/brain/verbs/reject.ts
@@ -3,6 +3,7 @@ import {
resolveNearDuplicateRetireSiblingsEnabled,
} from "../../../core/config.ts";
import { scanBrain } from "../../../core/brain/dream-scan.ts";
+import { regenerateActiveQuiet } from "../../../core/brain/active.ts";
import { READ_ALL_REFS } from "../../../core/brain/near-duplicate.ts";
import {
loadPreference,
@@ -101,6 +102,8 @@ export async function cmdBrainReject(argv: string[]): Promise<number> {
process.stderr.write(`warning: append reject log failed: ${(err as Error).message}\n`);
}
+ regenerateActiveQuiet(vault, { now, legacyOnly: true });
+
// Near-duplicate defense: list (never retire) the active preferences that
// resemble the one just rejected. The operator's own shell reads the whole
// vault, hence READ_ALL_REFS. Off, the output is unchanged. The retire
diff --git a/src/core/brain/active.ts b/src/core/brain/active.ts
index d6dad89c..c21872fa 100644
--- a/src/core/brain/active.ts
+++ b/src/core/brain/active.ts
@@ -45,7 +45,11 @@ import {
loadGuardrailsConfigSafe,
} from "./policy.ts";
import { isPreferenceVisible } from "./owner-scoped-facts.ts";
-import { compiledDigestPath, digestsRenderedOnDemand } from "./compiled-digest-path.ts";
+import {
+ compiledDigestPath,
+ digestCachePath,
+ digestsRenderedOnDemand,
+} from "./compiled-digest-path.ts";
import { legacyMemoryPage, type MemoryPage, storeMemoryPages } from "./memory-pages.ts";
import { withLogReadPass } from "./log-days.ts";
import { parseRetiredMeta } from "./preference.ts";
@@ -55,11 +59,13 @@ import {
buildChainLookup,
resolveChainTip,
type ChainLookup,
-} from "./lifecycle/tombstone.ts";
+} from "./lifecycle/tombstone-read.ts";
+import { filterExpired } from "./expiration.ts";
import { chainVerdict } from "../search/correction-coupling.ts";
import { BRAIN_TOMBSTONE_STATUS } from "./types.ts";
import { BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL } from "./path-constants.ts";
-import { brainActivePath, brainDirsForWrite, brainDirsOf } from "./paths.ts";
+import { brainActivePath, brainDirs, brainDirsOf } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { isoSecond } from "./time.ts";
import { sortByProvenanceTrust } from "./provenance/trust-order.ts";
import { BRAIN_PREFERENCE_STATUS, type BrainPreference, type BrainRetired } from "./types.ts";
@@ -176,10 +182,20 @@ export interface RegenerateActiveResult {
* `brain_doctor`; this render's job is to surface what is knowable.
*/
export function renderActive(vault: string | null, opts: RenderActiveOptions = {}): ActiveRender {
+ return renderActiveAt(vault, opts);
+}
+
+function renderActiveAt(
+ vault: string | null,
+ opts: RenderActiveOptions,
+ expirationNow?: Date,
+): ActiveRender {
const now = opts.now ?? new Date();
const readable = opts.readable ?? READ_EVERYTHING;
- const preferences = readActivePreferences(vault, opts.agentScope, readable);
+ const preferences = filterExpired(readActivePreferences(vault, opts.agentScope, readable), {
+ now: expirationNow ?? now,
+ });
const retiredRecent = readRecentlyRetired(
vault,
RECENTLY_RETIRED_COUNT,
@@ -312,15 +328,18 @@ export function activeDigestPathForRead(
// gives its body: what changed since is time alone, as for a vault file
// the next dream pass has not rewritten yet. A changed input renders now.
const path = compiledDigestPath(vault, "active");
+ const now = opts.now ?? new Date();
const stamp = readGeneratedAt(path);
const stampMs = stamp === null ? Number.NaN : Date.parse(stamp);
// One read pass: the check render and a regeneration share one log read.
return withLogReadPass(() => {
if (stamp !== null && !Number.isNaN(stampMs)) {
- const atStamp = renderActive(vault, { now: new Date(stampMs) });
+ // Keep the log window at the cached generation, but do not keep serving
+ // a preference whose explicit expiration has passed since then.
+ const atStamp = renderActiveAt(vault, { now: new Date(stampMs) }, now);
if (readExistingBody(path) === atStamp.body.trim()) return path;
}
- return regenerateActive(vault, opts).path;
+ return regenerateActive(vault, { now }).path;
});
}
@@ -337,7 +356,10 @@ export function regenerateActive(
opts: RegenerateActiveOptions = {},
): RegenerateActiveResult {
const now = opts.now ?? new Date();
- const path = compiledDigestPath(vault, "active");
+ const onDemand = digestsRenderedOnDemand(vault);
+ if (!onDemand && vault !== null) assertVaultIdentityForWrite(vault);
+ const path =
+ onDemand || vault === null ? digestCachePath(vault, "active") : brainActivePath(vault);
const rendered = renderActive(vault, { now });
// `readExistingBody` returns the trimmed body (parseFrontmatter
@@ -348,7 +370,7 @@ export function regenerateActive(
if (changed) {
// The device-local cache directory of a store-only machine may not
// exist yet; the vault's `Brain/` always does when this is reached.
- if (digestsRenderedOnDemand(vault)) mkdirSync(dirname(path), { recursive: true });
+ if (onDemand) mkdirSync(dirname(path), { recursive: true });
atomicWriteFileSync(path, rendered.document);
}
@@ -368,9 +390,10 @@ export function regenerateActive(
*/
export function regenerateActiveQuiet(
vault: string | null,
- opts: RegenerateActiveOptions = {},
+ opts: RegenerateActiveOptions & { legacyOnly?: boolean } = {},
): void {
try {
+ if (opts.legacyOnly && digestsRenderedOnDemand(vault)) return;
regenerateActive(vault, opts);
} catch (err) {
process.stderr.write(`warning: regenerate active.md failed: ${(err as Error).message}\n`);
@@ -403,7 +426,7 @@ function readActivePreferences(
readable: (rel: string) => boolean,
): BrainPreference[] {
// With no vault the folders are the store's (design D14).
- const dirs = vault === null ? brainDirsOf(null) : brainDirsForWrite(vault);
+ const dirs = brainDirsOf(vault);
// The shared delivery-path walk (context-integrity-gates, Unit A) owns
// the listing and the parse; a corrupted or status/folder-mismatched
// file is omitted there, and `brain_doctor` is the surface that flags
@@ -424,7 +447,7 @@ function readActivePreferences(
function legacyRetiredPages(vault: string | null): MemoryPage[] {
const root = legacyVaultOf(vault, "readRecentlyRetired");
- const dir = brainDirsForWrite(root).retired;
+ const dir = brainDirs(root).retired;
if (!existsSync(dir)) return [];
return readdirSync(dir).map((name) => legacyMemoryPage(root, "retired", name));
}
@@ -482,11 +505,17 @@ function readRecentlyRetired(
// Same rationale as readActivePreferences.
}
}
+ // Newest first; an unparseable date sorts last, and the id breaks ties so
+ // the order never depends on how the folder or the store lists its pages.
+ const time = (r: BrainRetired): number => {
+ const t = Date.parse(r.retired_at);
+ return Number.isNaN(t) ? Number.NEGATIVE_INFINITY : t;
+ };
out.sort((a, b) => {
- const ta = Date.parse(a.retired_at);
- const tb = Date.parse(b.retired_at);
- if (Number.isNaN(ta) || Number.isNaN(tb)) return 0;
- return tb - ta; // newest first
+ const ta = time(a);
+ const tb = time(b);
+ if (ta !== tb) return tb > ta ? 1 : -1;
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
});
return out.slice(0, limit);
}
@@ -615,6 +644,14 @@ function renderDocument(body: string, generatedAt: string): string {
return lines.join("\n");
}
+/** Find an existing stale vault digest using the same body comparison as regeneration. */
+export function legacyActiveIsStale(vault: string, path: string, now: Date): boolean {
+ if (!existsSync(path) || digestsRenderedOnDemand(vault, undefined, { persistSwitch: false })) {
+ return false;
+ }
+ return readExistingBody(path) !== renderActive(vault, { now }).body.trim();
+}
+
function readExistingBody(path: string): string | null {
if (!existsSync(path)) return null;
try {
diff --git a/src/core/brain/claim-graph.ts b/src/core/brain/claim-graph.ts
index b8cb9ec9..a1ef10cc 100644
--- a/src/core/brain/claim-graph.ts
+++ b/src/core/brain/claim-graph.ts
@@ -31,7 +31,7 @@ import type { FrontmatterMap } from "../types.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { parseFrontmatter } from "../vault.ts";
import { brainDirs, claimGraphPath } from "./paths.ts";
-import { isTombstoned, normalizeChainLink, resolveChainTip } from "./lifecycle/tombstone.ts";
+import { isTombstoned, normalizeChainLink, resolveChainTip } from "./lifecycle/tombstone-read.ts";
import { isValidAt } from "./lifecycle/temporal-replace.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
diff --git a/src/core/brain/compiled-digest-path.ts b/src/core/brain/compiled-digest-path.ts
index 9b8ac00e..c15821ee 100644
--- a/src/core/brain/compiled-digest-path.ts
+++ b/src/core/brain/compiled-digest-path.ts
@@ -49,14 +49,21 @@ const VAULT_KEY_CHARS = 16;
const NO_VAULT_DIGEST_KEY = "no-vault";
/** Whether the digests of `vault` are rendered on demand into the device-local cache. */
-export function digestsRenderedOnDemand(vault: string | null, configPath?: string): boolean {
+export function digestsRenderedOnDemand(
+ vault: string | null,
+ configPath?: string,
+ options: { persistSwitch?: boolean } = {},
+): boolean {
// No vault (or its stand-in path): store-only, and the digests have no
// vault file (D14 item 7).
if (vault === null || isNoVaultPath(vault)) return true;
// A machine that holds its own switch record renders on demand whatever
// state the vault folder is in (unmounted, briefly unreadable), as the
// rest of its machine state does (`machineStateLocation`).
- const mode = storeOnlyMode({ vault, ...(configPath !== undefined ? { configPath } : {}) });
+ const mode = storeOnlyMode(
+ { vault, ...(configPath !== undefined ? { configPath } : {}) },
+ options,
+ );
if (mode.reason === "device-switched") return true;
// Otherwise a vault path that names no directory, or one this process
// cannot list, is a configuration fault, not a store-only machine:
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index 25f5f649..f3760377 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -32,7 +32,7 @@ import {
resolveOwnerScopeDelivery,
type OwnerScopeDelivery,
} from "./preferences-collect.ts";
-import { buildChainLookup, isTombstoned, resolveChainTip } from "./lifecycle/tombstone.ts";
+import { buildChainLookup, isTombstoned, resolveChainTip } from "./lifecycle/tombstone-read.ts";
import { chainVerdict } from "../search/correction-coupling.ts";
import { preferChainTips } from "./inject-governor.ts";
import { tensionWarningsForContextItems } from "./tensions.ts";
diff --git a/src/core/brain/counterparty-brief.ts b/src/core/brain/counterparty-brief.ts
index 39e30e1d..2c900de4 100644
--- a/src/core/brain/counterparty-brief.ts
+++ b/src/core/brain/counterparty-brief.ts
@@ -65,7 +65,7 @@ import { buildEntityIndex } from "./entities/index-builder.ts";
import { resolveEntityLexicon } from "./entities/lexicon.ts";
import { ENTITY_STATUS_SCOPE, entityStatusInScope } from "./entities/status-scope.ts";
import type { BrainEntity } from "./entities/types.ts";
-import { readLifecycleState } from "./lifecycle/tombstone.ts";
+import { readLifecycleState } from "./lifecycle/tombstone-read.ts";
import { BRAIN_PREFERENCES_REL } from "./path-constants.ts";
import { validateIsoDate } from "./paths.ts";
import {
diff --git a/src/core/brain/dream-scan.ts b/src/core/brain/dream-scan.ts
index 7f1f6198..f889ea34 100644
--- a/src/core/brain/dream-scan.ts
+++ b/src/core/brain/dream-scan.ts
@@ -28,7 +28,7 @@ import {
SUPERSEDED_BY_KEY,
buildChainLookup,
resolveChainTip,
-} from "./lifecycle/tombstone.ts";
+} from "./lifecycle/tombstone-read.ts";
import { chainVerdict } from "../search/correction-coupling.ts";
import { brainDirs, brainDirsOf } from "./paths.ts";
import {
diff --git a/src/core/brain/expiration-set.ts b/src/core/brain/expiration-set.ts
index ea62468d..c451d9a3 100644
--- a/src/core/brain/expiration-set.ts
+++ b/src/core/brain/expiration-set.ts
@@ -41,6 +41,7 @@ import { join } from "node:path";
import type { FrontmatterMap } from "../types.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
+import { regenerateActiveQuiet } from "./active.ts";
import { EXPIRATION_DATE_FIELD, normalizeExpirationDate } from "./expiration.ts";
import { appendLogEvent } from "./log.ts";
import { brainDirsForWrite, ensureInsideVault } from "./paths.ts";
@@ -387,9 +388,10 @@ export function setExpiration(
kind === EXPIRATION_TARGET_KIND.signal ? SIGNAL_OPAQUE_FIELDS : PREFERENCE_OPAQUE_FIELDS;
return isPrivateFrontmatter(frontmatter) || rowNamesPrivatePage(vault, frontmatter, opaque);
};
+ const now = opts.now ?? new Date();
const logChange = (): void => {
appendLogEvent(vault, {
- timestamp: isoSecond(opts.now ?? new Date()),
+ timestamp: isoSecond(now),
eventType: BRAIN_LOG_EVENT_KIND.expirationSet,
body: {
target: `[[${trimmed}]]`,
@@ -403,26 +405,35 @@ export function setExpiration(
},
});
};
- withOperationPrivacy(targetPrivate, () => {
- if (kind === EXPIRATION_TARGET_KIND.signal) {
- routeSignalState({
- vault,
- id: trimmed,
- fields,
- ...(opts.agent?.trim() ? { agent: opts.agent.trim() } : {}),
- ...(frontmatter !== null ? { legacyFrontmatter: frontmatter } : {}),
- legacy,
- });
- } else {
- routePreferencePage({
- vault,
- slug,
- frontmatter: { [EXPIRATION_DATE_FIELD]: normalized ?? null } as FrontmatterMap,
- legacy,
- });
+ let preferenceWritten = false;
+ try {
+ withOperationPrivacy(targetPrivate, () => {
+ if (kind === EXPIRATION_TARGET_KIND.signal) {
+ routeSignalState({
+ vault,
+ id: trimmed,
+ fields,
+ ...(opts.agent?.trim() ? { agent: opts.agent.trim() } : {}),
+ ...(frontmatter !== null ? { legacyFrontmatter: frontmatter } : {}),
+ legacy,
+ });
+ } else {
+ routePreferencePage({
+ vault,
+ slug,
+ frontmatter: { [EXPIRATION_DATE_FIELD]: normalized ?? null } as FrontmatterMap,
+ legacy,
+ });
+ preferenceWritten = true;
+ }
+ logChange();
+ });
+ } finally {
+ // The preference write is authoritative even if its audit append throws.
+ if (preferenceWritten && trimmed.startsWith("pref-")) {
+ regenerateActiveQuiet(vault, { now, legacyOnly: true });
}
- logChange();
- });
+ }
return Object.freeze({
id: trimmed,
diff --git a/src/core/brain/lifecycle/temporal-replace.ts b/src/core/brain/lifecycle/temporal-replace.ts
index fa1df1d0..8ced7a4d 100644
--- a/src/core/brain/lifecycle/temporal-replace.ts
+++ b/src/core/brain/lifecycle/temporal-replace.ts
@@ -36,7 +36,7 @@ import { appendLogEvent } from "../log.ts";
import { resolveNotePath } from "../note-path.ts";
import { isoSecond } from "../time.ts";
import { BRAIN_LOG_EVENT_KIND } from "../types.ts";
-import { normalizeChainLink, SUPERSEDED_BY_KEY } from "./tombstone.ts";
+import { normalizeChainLink, SUPERSEDED_BY_KEY } from "./tombstone-read.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
// ----- Constants ------------------------------------------------------------
diff --git a/src/core/brain/lifecycle/tombstone-read.ts b/src/core/brain/lifecycle/tombstone-read.ts
new file mode 100644
index 00000000..d4dd29ae
--- /dev/null
+++ b/src/core/brain/lifecycle/tombstone-read.ts
@@ -0,0 +1,262 @@
+/** Read-only lifecycle state and supersession traversal. */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import type { FrontmatterMap } from "../../types.ts";
+import { parseFrontmatter } from "../../vault.ts";
+import { BRAIN_ROOT_REL, vaultRelative } from "../paths.ts";
+import {
+ MEMORY_FOLDERS,
+ memoryFolderRel,
+ memoryFromStore,
+ storeMemoryPages,
+} from "../memory-pages.ts";
+import { BRAIN_TOMBSTONE_STATUS } from "../types.ts";
+
+// ----- Constants ------------------------------------------------------------
+
+/** On-disk frontmatter key holding a memory's operational status. */
+export const LIFECYCLE_STATUS_KEY = "_status";
+/** Normalized (un-prefixed) status key produced by `normalizeDerivedKeys`. */
+export const LIFECYCLE_STATUS_KEY_NORMALIZED = "status";
+/** Frontmatter key: ISO-8601 UTC second the tombstone was applied. */
+export const TOMBSTONED_AT_KEY = "tombstoned_at";
+/** Frontmatter key: operator-supplied tombstone reason. */
+export const TOMBSTONE_REASON_KEY = "tombstone_reason";
+/** Frontmatter key: wikilink to the successor that replaced this entry. */
+export const SUPERSEDED_BY_KEY = "superseded_by";
+/**
+ * Hard cap on chain-walk depth. Guards against a pathological or
+ * cyclic `superseded_by` graph turning {@link resolveChainTip} into an
+ * unbounded loop; far beyond any realistic supersession depth.
+ */
+export const MAX_CHAIN_DEPTH = 64;
+
+// ----- Lifecycle state ------------------------------------------------------
+
+export interface LifecycleState {
+ readonly tombstoned: boolean;
+ /** ISO-8601 UTC second, or `null` when not tombstoned. */
+ readonly tombstonedAt: string | null;
+ readonly tombstoneReason: string | null;
+ /** Normalized successor wikilink (`[[...]]`), or `null`. */
+ readonly supersededBy: string | null;
+}
+
+export function readScalar(meta: Readonly<Record<string, unknown>>, key: string): string | null {
+ const value = meta[key];
+ return typeof value === "string" && value !== "" ? value : null;
+}
+
+/**
+ * Read the lifecycle state carried by a raw frontmatter map (the output
+ * of {@link parseFrontmatter}). Tolerant of both the `_status` on-disk
+ * shape and the normalized `status` shape so it works whether the caller
+ * passed raw or `normalizeDerivedKeys`-processed frontmatter.
+ */
+export function readLifecycleState(meta: Readonly<Record<string, unknown>>): LifecycleState {
+ const status =
+ readScalar(meta, LIFECYCLE_STATUS_KEY) ?? readScalar(meta, LIFECYCLE_STATUS_KEY_NORMALIZED);
+ const tombstoned = status === BRAIN_TOMBSTONE_STATUS;
+ return {
+ tombstoned,
+ tombstonedAt: readScalar(meta, TOMBSTONED_AT_KEY),
+ tombstoneReason: readScalar(meta, TOMBSTONE_REASON_KEY),
+ supersededBy: readScalar(meta, SUPERSEDED_BY_KEY),
+ };
+}
+
+/**
+ * True when a raw frontmatter map marks a tombstoned memory. This is the
+ * shared exclusion predicate wired into recall / inject / active.md /
+ * dream so a tombstoned (or superseded-non-tip, which is tombstoned with
+ * a `superseded_by` pointer) entry stops appearing.
+ */
+export function isTombstoned(meta: Readonly<Record<string, unknown>>): boolean {
+ return readLifecycleState(meta).tombstoned;
+}
+
+// ----- Link normalization ---------------------------------------------------
+
+/**
+ * Reduce a wikilink / bare id / basename to its bare identifier: strip
+ * the `[[ ]]` fence and any `|alias` display suffix, then the `.md`
+ * extension and directory components. Returns the trimmed identifier.
+ */
+export function normalizeChainLink(raw: string): string {
+ let value = raw.trim();
+ const fence = /^\[\[([^\]]+)\]\]$/.exec(value);
+ if (fence) value = fence[1]!.trim();
+ const pipe = value.indexOf("|");
+ if (pipe >= 0) value = value.slice(0, pipe).trim();
+ // Drop directory components and the markdown extension so a stored
+ // vault-relative path and a bare basename resolve to the same node.
+ const slash = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
+ if (slash >= 0) value = value.slice(slash + 1);
+ if (value.toLowerCase().endsWith(".md")) value = value.slice(0, -3);
+ return value;
+}
+
+// ----- Chain resolution -----------------------------------------------------
+
+export interface ChainLookupEntry {
+ /** Successor wikilink / id, or `null` when this node is a tip. */
+ readonly supersededBy: string | null;
+}
+
+/** Resolve a normalized node id to its chain entry, or `null` if unknown. */
+export type ChainLookup = (link: string) => ChainLookupEntry | null;
+
+export interface ResolveChainTipResult {
+ /** Normalized identifier of the resolved tip. */
+ readonly tip: string;
+ /** Number of successor hops walked from the start. */
+ readonly steps: number;
+ /** True when a cycle short-circuited the walk. */
+ readonly cycle: boolean;
+ /**
+ * True when every hop resolved to a known node. `false` when the walk
+ * stopped at an id the lookup could not resolve (dangling successor).
+ */
+ readonly resolvedAll: boolean;
+}
+
+/**
+ * Walk a chain of `superseded_by` links from `start` to its live tip.
+ * Pure: the caller supplies the {@link ChainLookup}, so this is unit- and
+ * property-testable without disk. Cycle- and depth-guarded.
+ */
+export function resolveChainTip(
+ start: string,
+ lookup: ChainLookup,
+ opts: { readonly maxDepth?: number } = {},
+): ResolveChainTipResult {
+ const maxDepth = opts.maxDepth ?? MAX_CHAIN_DEPTH;
+ const visited = new Set<string>();
+ let current = normalizeChainLink(start);
+ let steps = 0;
+ visited.add(current);
+
+ while (steps < maxDepth) {
+ const entry = lookup(current);
+ if (entry === null) {
+ // Reached an id the lookup cannot resolve (unknown start or a
+ // dangling successor): the walk stops at the last known node.
+ return { tip: current, steps, cycle: false, resolvedAll: false };
+ }
+ if (entry.supersededBy === null || entry.supersededBy === "") {
+ return { tip: current, steps, cycle: false, resolvedAll: true };
+ }
+ const next = normalizeChainLink(entry.supersededBy);
+ if (visited.has(next)) {
+ return { tip: current, steps, cycle: true, resolvedAll: true };
+ }
+ visited.add(next);
+ current = next;
+ steps++;
+ }
+ // Depth cap reached without terminating: treat as a pathological chain.
+ return { tip: current, steps, cycle: true, resolvedAll: true };
+}
+
+/**
+ * Build a {@link ChainLookup} over every markdown file under `Brain/`,
+ * keyed by bare basename. Reads each file's frontmatter once. A node
+ * that exists but carries no `superseded_by` resolves to a tip entry;
+ * an unknown basename resolves to `null`. A page whose vault-relative
+ * path `readable` refuses is not indexed at all, so it reads exactly as
+ * an unknown basename; absent, every page is indexed.
+ */
+export function buildChainLookup(
+ vault: string | null,
+ readable?: (rel: string) => boolean,
+): ChainLookup {
+ const index = new Map<string, ChainLookupEntry>();
+ // No vault: no pages on disk, only the store's.
+ if (vault !== null) {
+ const root = join(vault, BRAIN_ROOT_REL);
+ // Once switched the memory pages are the store's: the frozen legacy
+ // copies of those folders are not walked, so a page the store no
+ // longer holds cannot keep resolving from a stale file.
+ const skip = memoryFromStore(vault)
+ ? new Set(MEMORY_FOLDERS.map((f) => join(vault, ...memoryFolderRel(f).split("/"))))
+ : new Set<string>();
+ if (existsSync(root)) walk(vault, root, index, readable, skip);
+ }
+ addStoredMemoryPages(vault, index, readable);
+ return (link: string): ChainLookupEntry | null => index.get(normalizeChainLink(link)) ?? null;
+}
+
+/**
+ * On a store-only machine the memory pages are records, not files (task
+ * 2.10): index the pages the store's folds rebuild, under the same rules
+ * as a file of the walk.
+ */
+function addStoredMemoryPages(
+ vault: string | null,
+ index: Map<string, ChainLookupEntry>,
+ readable: ((rel: string) => boolean) | undefined,
+): void {
+ for (const folder of MEMORY_FOLDERS) {
+ for (const page of storeMemoryPages(vault, folder) ?? []) {
+ if (readable !== undefined && !readable(page.rel)) continue;
+ const supersededBy = readScalar(page.read()[0], SUPERSEDED_BY_KEY);
+ index.set(normalizeChainLink(page.name), { supersededBy });
+ }
+ }
+}
+
+function walk(
+ vault: string,
+ dir: string,
+ index: Map<string, ChainLookupEntry>,
+ readable: ((rel: string) => boolean) | undefined,
+ skip: ReadonlySet<string>,
+): void {
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name.startsWith(".") || skip.has(full)) continue;
+ walk(vault, full, index, readable, skip);
+ continue;
+ }
+ if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;
+ // Asked before the page is parsed, so a page the caller may not read
+ // contributes nothing - not even its basename.
+ if (readable !== undefined && !readable(vaultRelative(full, vault))) continue;
+ let meta: FrontmatterMap;
+ try {
+ [meta] = parseFrontmatter(full);
+ } catch {
+ continue;
+ }
+ const id = normalizeChainLink(entry.name);
+ const supersededBy = readScalar(meta, SUPERSEDED_BY_KEY);
+ index.set(id, { supersededBy });
+ }
+}
+
+/**
+ * Convenience: resolve a chain tip against the live vault. Builds the
+ * lookup from disk on each call - callers that resolve many tips in one
+ * pass should reuse a {@link buildChainLookup} result via
+ * {@link resolveChainTip} directly.
+ */
+export function resolveChainTipInVault(
+ vault: string,
+ start: string,
+ opts: {
+ readonly maxDepth?: number;
+ /** The vault-relative paths the caller may read; see {@link buildChainLookup}. */
+ readonly readable?: (rel: string) => boolean;
+ } = {},
+): ResolveChainTipResult {
+ return resolveChainTip(start, buildChainLookup(vault, opts.readable), opts);
+}
diff --git a/src/core/brain/lifecycle/tombstone.ts b/src/core/brain/lifecycle/tombstone.ts
index 085eca2f..fabbcfb6 100644
--- a/src/core/brain/lifecycle/tombstone.ts
+++ b/src/core/brain/lifecycle/tombstone.ts
@@ -17,13 +17,11 @@
* byte-identical no-op that returns the existing state and emits no
* event.
*
- * Import direction (design invariant): this module imports from
- * `preference.ts` / `types.ts` and the shared vault/log helpers, never
- * the reverse.
+ * The digest renderer depends only on the read side, so this writer can
+ * refresh the digest after changing a preference without a module cycle.
*/
-import { existsSync, readdirSync } from "node:fs";
-import { join, relative } from "node:path";
+import { relative } from "node:path";
import { normalizeAgentArgument } from "../../agent-identity.ts";
import { resolveAgentName } from "../../config.ts";
@@ -32,40 +30,47 @@ import type { FrontmatterMap } from "../../types.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../../vault.ts";
import { appendLogEvent } from "../log.ts";
import { appendDecisionChangeReceipt } from "../decisions/receipts.ts";
-import { BRAIN_ROOT_REL, vaultRelative } from "../paths.ts";
+import { regenerateActiveQuiet } from "../active.ts";
import {
- MEMORY_FOLDERS,
- memoryFolderRel,
- memoryFromStore,
- storeMemoryPages,
-} from "../memory-pages.ts";
+ LIFECYCLE_STATUS_KEY,
+ LIFECYCLE_STATUS_KEY_NORMALIZED,
+ TOMBSTONED_AT_KEY,
+ TOMBSTONE_REASON_KEY,
+ SUPERSEDED_BY_KEY,
+ normalizeChainLink,
+ readLifecycleState,
+ readScalar,
+ type LifecycleState,
+} from "./tombstone-read.ts";
import { resolveNotePath } from "../note-path.ts";
import { isoSecond } from "../time.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_TOMBSTONE_STATUS } from "../types.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
-// ----- Constants ------------------------------------------------------------
+// Keep the read API available through this module for existing callers.
+export {
+ LIFECYCLE_STATUS_KEY,
+ LIFECYCLE_STATUS_KEY_NORMALIZED,
+ TOMBSTONED_AT_KEY,
+ TOMBSTONE_REASON_KEY,
+ SUPERSEDED_BY_KEY,
+ MAX_CHAIN_DEPTH,
+ isTombstoned,
+ normalizeChainLink,
+ readLifecycleState,
+ buildChainLookup,
+ resolveChainTip,
+ resolveChainTipInVault,
+ type ChainLookup,
+ type ChainLookupEntry,
+ type LifecycleState,
+ type ResolveChainTipResult,
+} from "./tombstone-read.ts";
-/** On-disk frontmatter key holding a memory's operational status. */
-export const LIFECYCLE_STATUS_KEY = "_status";
-/** Normalized (un-prefixed) status key produced by `normalizeDerivedKeys`. */
-export const LIFECYCLE_STATUS_KEY_NORMALIZED = "status";
-/** Frontmatter key: ISO-8601 UTC second the tombstone was applied. */
-export const TOMBSTONED_AT_KEY = "tombstoned_at";
-/** Frontmatter key: operator-supplied tombstone reason. */
-export const TOMBSTONE_REASON_KEY = "tombstone_reason";
-/** Frontmatter key: wikilink to the successor that replaced this entry. */
-export const SUPERSEDED_BY_KEY = "superseded_by";
/** Default reason stamped when a supersede does not pass an explicit one. */
export const SUPERSEDE_DEFAULT_REASON = "superseded";
/** Cap on tombstone-reason length (mirrors the note-text field cap). */
const REASON_MAX_LEN = 512;
-/**
- * Hard cap on chain-walk depth. Guards against a pathological or
- * cyclic `superseded_by` graph turning {@link resolveChainTip} into an
- * unbounded loop; far beyond any realistic supersession depth.
- */
-export const MAX_CHAIN_DEPTH = 64;
// ----- Errors ---------------------------------------------------------------
@@ -77,71 +82,6 @@ export class TombstoneError extends Error {
}
}
-// ----- Lifecycle state ------------------------------------------------------
-
-export interface LifecycleState {
- readonly tombstoned: boolean;
- /** ISO-8601 UTC second, or `null` when not tombstoned. */
- readonly tombstonedAt: string | null;
- readonly tombstoneReason: string | null;
- /** Normalized successor wikilink (`[[...]]`), or `null`. */
- readonly supersededBy: string | null;
-}
-
-function scalar(meta: Readonly<Record<string, unknown>>, key: string): string | null {
- const value = meta[key];
- return typeof value === "string" && value !== "" ? value : null;
-}
-
-/**
- * Read the lifecycle state carried by a raw frontmatter map (the output
- * of {@link parseFrontmatter}). Tolerant of both the `_status` on-disk
- * shape and the normalized `status` shape so it works whether the caller
- * passed raw or `normalizeDerivedKeys`-processed frontmatter.
- */
-export function readLifecycleState(meta: Readonly<Record<string, unknown>>): LifecycleState {
- const status =
- scalar(meta, LIFECYCLE_STATUS_KEY) ?? scalar(meta, LIFECYCLE_STATUS_KEY_NORMALIZED);
- const tombstoned = status === BRAIN_TOMBSTONE_STATUS;
- return {
- tombstoned,
- tombstonedAt: scalar(meta, TOMBSTONED_AT_KEY),
- tombstoneReason: scalar(meta, TOMBSTONE_REASON_KEY),
- supersededBy: scalar(meta, SUPERSEDED_BY_KEY),
- };
-}
-
-/**
- * True when a raw frontmatter map marks a tombstoned memory. This is the
- * shared exclusion predicate wired into recall / inject / active.md /
- * dream so a tombstoned (or superseded-non-tip, which is tombstoned with
- * a `superseded_by` pointer) entry stops appearing.
- */
-export function isTombstoned(meta: Readonly<Record<string, unknown>>): boolean {
- return readLifecycleState(meta).tombstoned;
-}
-
-// ----- Link normalization ---------------------------------------------------
-
-/**
- * Reduce a wikilink / bare id / basename to its bare identifier: strip
- * the `[[ ]]` fence and any `|alias` display suffix, then the `.md`
- * extension and directory components. Returns the trimmed identifier.
- */
-export function normalizeChainLink(raw: string): string {
- let value = raw.trim();
- const fence = /^\[\[([^\]]+)\]\]$/.exec(value);
- if (fence) value = fence[1]!.trim();
- const pipe = value.indexOf("|");
- if (pipe >= 0) value = value.slice(0, pipe).trim();
- // Drop directory components and the markdown extension so a stored
- // vault-relative path and a bare basename resolve to the same node.
- const slash = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
- if (slash >= 0) value = value.slice(slash + 1);
- if (value.toLowerCase().endsWith(".md")) value = value.slice(0, -3);
- return value;
-}
-
/** Render a bare identifier as a canonical wikilink for on-disk storage. */
function toWikilink(raw: string): string {
return `[[${normalizeChainLink(raw)}]]`;
@@ -228,10 +168,11 @@ export function tombstone(input: TombstoneInput): TombstoneResult {
}
const priorStatus =
- scalar(rawMeta, LIFECYCLE_STATUS_KEY) ??
- scalar(rawMeta, LIFECYCLE_STATUS_KEY_NORMALIZED) ??
+ readScalar(rawMeta, LIFECYCLE_STATUS_KEY) ??
+ readScalar(rawMeta, LIFECYCLE_STATUS_KEY_NORMALIZED) ??
"unknown";
- const tombstonedAt = isoSecond(input.now ?? new Date());
+ const now = input.now ?? new Date();
+ const tombstonedAt = isoSecond(now);
const supersededBy = input.supersededBy ? toWikilink(input.supersededBy) : null;
const nextMeta: FrontmatterMap = { ...(rawMeta as FrontmatterMap) };
@@ -248,56 +189,62 @@ export function tombstone(input: TombstoneInput): TombstoneResult {
});
}
- const explicitAgent = normalizeAgentArgument(input.agent ?? null);
- const agent = explicitAgent ?? resolveAgentName(input.configPath);
- appendLogEvent(input.vault, {
- timestamp: tombstonedAt,
- eventType: BRAIN_LOG_EVENT_KIND.tombstone,
- body: {
- path: relPath,
- reason,
- prior_status: priorStatus,
- ...(supersededBy !== null ? { superseded_by: supersededBy } : {}),
- agent,
- },
- });
-
- // Belief lifecycle suite (B4): a supersede/tombstone is a belief change,
- // so it emits a decision-change receipt. The receipt's own idempotency
- // key (subject + before + after) makes a replay a no-op, mirroring the
- // tombstone no-op above. Fail-soft: an accountability-log hiccup must
- // never fail the tombstone write itself.
try {
- appendDecisionChangeReceipt(input.vault, {
- subject: relPath,
- before: `status:${priorStatus}`,
- after:
- supersededBy !== null
- ? `status:tombstoned superseded_by:${supersededBy}`
- : "status:tombstoned",
- actor: agent,
- rationale: reason,
- reasonCode: supersededBy !== null ? "supersede" : "tombstone",
- ...(supersededBy !== null ? { alternatives: [priorStatus] } : {}),
- ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ const explicitAgent = normalizeAgentArgument(input.agent ?? null);
+ const agent = explicitAgent ?? resolveAgentName(input.configPath);
+ appendLogEvent(input.vault, {
+ timestamp: tombstonedAt,
+ eventType: BRAIN_LOG_EVENT_KIND.tombstone,
+ body: {
+ path: relPath,
+ reason,
+ prior_status: priorStatus,
+ ...(supersededBy !== null ? { superseded_by: supersededBy } : {}),
+ agent,
+ },
});
- } catch {
- // Receipt is best-effort accountability; the tombstone frontmatter and
- // its `tombstone` log event remain authoritative.
- }
- return {
- changed: true,
- path: relPath,
- state: {
- tombstoned: true,
- tombstonedAt,
- tombstoneReason: reason,
- supersededBy,
- },
- agent,
- loggedAt: tombstonedAt,
- };
+ // Belief lifecycle suite (B4): a supersede/tombstone is a belief change,
+ // so it emits a decision-change receipt. The receipt's own idempotency
+ // key (subject + before + after) makes a replay a no-op, mirroring the
+ // tombstone no-op above. Fail-soft: an accountability-log hiccup must
+ // never fail the tombstone write itself.
+ try {
+ appendDecisionChangeReceipt(input.vault, {
+ subject: relPath,
+ before: `status:${priorStatus}`,
+ after:
+ supersededBy !== null
+ ? `status:tombstoned superseded_by:${supersededBy}`
+ : "status:tombstoned",
+ actor: agent,
+ rationale: reason,
+ reasonCode: supersededBy !== null ? "supersede" : "tombstone",
+ ...(supersededBy !== null ? { alternatives: [priorStatus] } : {}),
+ ...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ });
+ } catch {
+ // Receipt is best-effort accountability; the tombstone frontmatter and
+ // its `tombstone` log event remain authoritative.
+ }
+ return {
+ changed: true,
+ path: relPath,
+ state: {
+ tombstoned: true,
+ tombstonedAt,
+ tombstoneReason: reason,
+ supersededBy,
+ },
+ agent,
+ loggedAt: tombstonedAt,
+ };
+ } finally {
+ // The frontmatter is already committed, even if the audit append throws.
+ if (rawMeta["kind"] === "brain-preference") {
+ regenerateActiveQuiet(input.vault, { now, legacyOnly: true });
+ }
+ }
}
export interface SupersedeInput {
@@ -335,166 +282,3 @@ export function supersede(input: SupersedeInput): TombstoneResult {
...(input.readable !== undefined ? { readable: input.readable } : {}),
});
}
-
-// ----- Chain resolution -----------------------------------------------------
-
-export interface ChainLookupEntry {
- /** Successor wikilink / id, or `null` when this node is a tip. */
- readonly supersededBy: string | null;
-}
-
-/** Resolve a normalized node id to its chain entry, or `null` if unknown. */
-export type ChainLookup = (link: string) => ChainLookupEntry | null;
-
-export interface ResolveChainTipResult {
- /** Normalized identifier of the resolved tip. */
- readonly tip: string;
- /** Number of successor hops walked from the start. */
- readonly steps: number;
- /** True when a cycle short-circuited the walk. */
- readonly cycle: boolean;
- /**
- * True when every hop resolved to a known node. `false` when the walk
- * stopped at an id the lookup could not resolve (dangling successor).
- */
- readonly resolvedAll: boolean;
-}
-
-/**
- * Walk a chain of `superseded_by` links from `start` to its live tip.
- * Pure: the caller supplies the {@link ChainLookup}, so this is unit- and
- * property-testable without disk. Cycle- and depth-guarded.
- */
-export function resolveChainTip(
- start: string,
- lookup: ChainLookup,
- opts: { readonly maxDepth?: number } = {},
-): ResolveChainTipResult {
- const maxDepth = opts.maxDepth ?? MAX_CHAIN_DEPTH;
- const visited = new Set<string>();
- let current = normalizeChainLink(start);
- let steps = 0;
- visited.add(current);
-
- while (steps < maxDepth) {
- const entry = lookup(current);
- if (entry === null) {
- // Reached an id the lookup cannot resolve (unknown start or a
- // dangling successor): the walk stops at the last known node.
- return { tip: current, steps, cycle: false, resolvedAll: false };
- }
- if (entry.supersededBy === null || entry.supersededBy === "") {
- return { tip: current, steps, cycle: false, resolvedAll: true };
- }
- const next = normalizeChainLink(entry.supersededBy);
- if (visited.has(next)) {
- return { tip: current, steps, cycle: true, resolvedAll: true };
- }
- visited.add(next);
- current = next;
- steps++;
- }
- // Depth cap reached without terminating: treat as a pathological chain.
- return { tip: current, steps, cycle: true, resolvedAll: true };
-}
-
-/**
- * Build a {@link ChainLookup} over every markdown file under `Brain/`,
- * keyed by bare basename. Reads each file's frontmatter once. A node
- * that exists but carries no `superseded_by` resolves to a tip entry;
- * an unknown basename resolves to `null`. A page whose vault-relative
- * path `readable` refuses is not indexed at all, so it reads exactly as
- * an unknown basename; absent, every page is indexed.
- */
-export function buildChainLookup(
- vault: string | null,
- readable?: (rel: string) => boolean,
-): ChainLookup {
- const index = new Map<string, ChainLookupEntry>();
- // No vault: no pages on disk, only the store's.
- if (vault !== null) {
- const root = join(vault, BRAIN_ROOT_REL);
- // Once switched the memory pages are the store's: the frozen legacy
- // copies of those folders are not walked, so a page the store no
- // longer holds cannot keep resolving from a stale file.
- const skip = memoryFromStore(vault)
- ? new Set(MEMORY_FOLDERS.map((f) => join(vault, ...memoryFolderRel(f).split("/"))))
- : new Set<string>();
- if (existsSync(root)) walk(vault, root, index, readable, skip);
- }
- addStoredMemoryPages(vault, index, readable);
- return (link: string): ChainLookupEntry | null => index.get(normalizeChainLink(link)) ?? null;
-}
-
-/**
- * On a store-only machine the memory pages are records, not files (task
- * 2.10): index the pages the store's folds rebuild, under the same rules
- * as a file of the walk.
- */
-function addStoredMemoryPages(
- vault: string | null,
- index: Map<string, ChainLookupEntry>,
- readable: ((rel: string) => boolean) | undefined,
-): void {
- for (const folder of MEMORY_FOLDERS) {
- for (const page of storeMemoryPages(vault, folder) ?? []) {
- if (readable !== undefined && !readable(page.rel)) continue;
- const supersededBy = scalar(page.read()[0], SUPERSEDED_BY_KEY);
- index.set(normalizeChainLink(page.name), { supersededBy });
- }
- }
-}
-
-function walk(
- vault: string,
- dir: string,
- index: Map<string, ChainLookupEntry>,
- readable: ((rel: string) => boolean) | undefined,
- skip: ReadonlySet<string>,
-): void {
- let entries;
- try {
- entries = readdirSync(dir, { withFileTypes: true });
- } catch {
- return;
- }
- for (const entry of entries) {
- const full = join(dir, entry.name);
- if (entry.isDirectory()) {
- if (entry.name.startsWith(".") || skip.has(full)) continue;
- walk(vault, full, index, readable, skip);
- continue;
- }
- if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;
- // Asked before the page is parsed, so a page the caller may not read
- // contributes nothing - not even its basename.
- if (readable !== undefined && !readable(vaultRelative(full, vault))) continue;
- let meta: FrontmatterMap;
- try {
- [meta] = parseFrontmatter(full);
- } catch {
- continue;
- }
- const id = normalizeChainLink(entry.name);
- const supersededBy = scalar(meta, SUPERSEDED_BY_KEY);
- index.set(id, { supersededBy });
- }
-}
-
-/**
- * Convenience: resolve a chain tip against the live vault. Builds the
- * lookup from disk on each call - callers that resolve many tips in one
- * pass should reuse a {@link buildChainLookup} result via
- * {@link resolveChainTip} directly.
- */
-export function resolveChainTipInVault(
- vault: string,
- start: string,
- opts: {
- readonly maxDepth?: number;
- /** The vault-relative paths the caller may read; see {@link buildChainLookup}. */
- readonly readable?: (rel: string) => boolean;
- } = {},
-): ResolveChainTipResult {
- return resolveChainTip(start, buildChainLookup(vault, opts.readable), opts);
-}
diff --git a/src/core/brain/query.ts b/src/core/brain/query.ts
index fbfbbfdd..225aebfd 100644
--- a/src/core/brain/query.ts
+++ b/src/core/brain/query.ts
@@ -42,7 +42,7 @@ import {
isTombstoned,
resolveChainTip,
type ChainLookup,
-} from "./lifecycle/tombstone.ts";
+} from "./lifecycle/tombstone-read.ts";
import { chainVerdict } from "../search/correction-coupling.ts";
import { vaultRelative } from "../path-safety.ts";
import { normaliseWikilinkTarget } from "./wikilink.ts";
diff --git a/src/core/brain/recompile.ts b/src/core/brain/recompile.ts
index edb23d28..a122f466 100644
--- a/src/core/brain/recompile.ts
+++ b/src/core/brain/recompile.ts
@@ -18,8 +18,9 @@ import { basename, isAbsolute, join, relative, sep } from "node:path";
import { appendAuditRecord } from "../reliability/audit.ts";
import { HYGIENE_AUDIT_DIR } from "./audit-dirs.ts";
import { scanFreshness } from "./freshness.ts";
+import { legacyActiveIsStale, regenerateActive } from "./active.ts";
import { writeHandoffNote } from "./handoff.ts";
-import { brainDirsForWrite, snapshotsDir } from "./paths.ts";
+import { brainActivePath, brainDirsForWrite, snapshotsDir } from "./paths.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { detectAdapter } from "./sessions/registry.ts";
import type { SessionTurn } from "./sessions/types.ts";
@@ -30,7 +31,7 @@ import { lanePagesInStore, readLaneText, removeLanePage } from "../store/lane-pa
import { lanePlaceOf } from "../store/lane-paths.ts";
import { BRAIN_ROOT_REL } from "./path-constants.ts";
-export type RecompileEntryKind = "rederive-handoff" | "cleanup" | "manual";
+export type RecompileEntryKind = "rederive-handoff" | "rederive-active" | "cleanup" | "manual";
export interface RecompileEntry {
readonly kind: RecompileEntryKind;
@@ -68,11 +69,27 @@ function resolveSource(vault: string, source: string): string {
* Build the recompile plan from the current freshness state. Read-only
* and side-effect free - this IS the dry-run preview.
*/
-export function planRecompile(vault: string): RecompilePlan {
+export function planRecompile(
+ vault: string,
+ options: { now?: Date; includeActiveDigest?: boolean } = {},
+): RecompilePlan {
const freshness = scanFreshness(vault);
const entries: RecompileEntry[] = [];
+ // Comparing the shared digest reads preferences from the whole vault.
+ // Only the operator's CLI refresh opts in; scoped planners keep their existing scope.
+ const activePath = options.includeActiveDigest ? brainActivePath(vault) : null;
+ if (activePath !== null && legacyActiveIsStale(vault, activePath, options.now ?? new Date())) {
+ entries.push(
+ Object.freeze({
+ kind: "rederive-active" as const,
+ page: activePath,
+ reason: "the active preference digest differs from current memory state",
+ }),
+ );
+ }
for (const stale of freshness.stale) {
+ if (stale.page === activePath) continue;
const [meta] = parseFrontmatter(stale.page);
const sessionId = typeof meta["session_id"] === "string" ? meta["session_id"] : null;
const sources = Array.isArray(meta["source_paths"]) ? (meta["source_paths"] as string[]) : [];
@@ -99,6 +116,7 @@ export function planRecompile(vault: string): RecompilePlan {
}
for (const orphan of freshness.orphaned) {
+ if (orphan === activePath) continue;
entries.push(
Object.freeze({
kind: "cleanup" as const,
@@ -251,6 +269,9 @@ export async function executeRecompile(
targetPath: entry.page,
});
rederived.push(entry.page);
+ } else if (entry.kind === "rederive-active") {
+ const digest = regenerateActive(vault, { now: opts.now });
+ if (digest.changed) rederived.push(digest.path);
} else {
archived.push(archivePage(vault, entry.page, opts.now));
}
diff --git a/src/core/brain/stale-dependency.ts b/src/core/brain/stale-dependency.ts
index c74acbae..9d266cf1 100644
--- a/src/core/brain/stale-dependency.ts
+++ b/src/core/brain/stale-dependency.ts
@@ -74,7 +74,7 @@ import {
type StaleDependencyRow,
type StaleDependencyState,
} from "./doctor/stale-dependency-check.ts";
-import { readLifecycleState } from "./lifecycle/tombstone.ts";
+import { readLifecycleState } from "./lifecycle/tombstone-read.ts";
import { boundaryToMs, VALID_UNTIL_KEY } from "./lifecycle/temporal-replace.ts";
import { brainDirs } from "./paths.ts";
import { MS_PER_DAY } from "./time.ts";
diff --git a/src/core/search/pipeline/post-rank.ts b/src/core/search/pipeline/post-rank.ts
index ca153869..2505aa5f 100644
--- a/src/core/search/pipeline/post-rank.ts
+++ b/src/core/search/pipeline/post-rank.ts
@@ -19,7 +19,7 @@ import {
MAX_CHAIN_DEPTH,
SUPERSEDED_BY_KEY,
isTombstoned,
-} from "../../brain/lifecycle/tombstone.ts";
+} from "../../brain/lifecycle/tombstone-read.ts";
import {
buildMemoryTrustAssessment,
buildRetrievalDecisionTrace,
diff --git a/src/core/search/pipeline/relational-arm.ts b/src/core/search/pipeline/relational-arm.ts
index 2a3f7a2e..2b5dc4d9 100644
--- a/src/core/search/pipeline/relational-arm.ts
+++ b/src/core/search/pipeline/relational-arm.ts
@@ -22,7 +22,7 @@ import { loadSchemaPack } from "../../brain/schema-pack.ts";
import { rrfKey } from "../../scope-key.ts";
import { resolvedTransportReach, type TransportReach } from "../../graph/transport-reach.ts";
import { EXACT_WIKILINK_RE } from "../../brain/wikilink.ts";
-import { SUPERSEDED_BY_KEY } from "../../brain/lifecycle/tombstone.ts";
+import { SUPERSEDED_BY_KEY } from "../../brain/lifecycle/tombstone-read.ts";
import { discoverConfig } from "../../config.ts";
import { envOrConfig, parseBool } from "../../validate.ts";
import {
diff --git a/src/core/search/result-filters.ts b/src/core/search/result-filters.ts
index 879fa128..0cab9d7c 100644
--- a/src/core/search/result-filters.ts
+++ b/src/core/search/result-filters.ts
@@ -29,7 +29,7 @@ import type { Store } from "./store.ts";
import { deriveTrust, hasSupersededRelation } from "./enrich.ts";
import { KNOWLEDGE_PACK_FIELD, parseKnowledgePackStamp } from "../brain/portability/pack-stamp.ts";
import { isTerminalStatus } from "./evidence-pack.ts";
-import { isTombstoned } from "../brain/lifecycle/tombstone.ts";
+import { isTombstoned } from "../brain/lifecycle/tombstone-read.ts";
import { storeRecordPages, type StoreMemoryPage } from "../brain/memory-pages.ts";
import { memoryFromStore } from "../store/read/memory-ids.ts";
import { SUPERSEDE_FADE_MULTIPLIER } from "./ranker.ts";
diff --git a/src/core/store/store-only.ts b/src/core/store/store-only.ts
index 118e2ff4..971ed73a 100644
--- a/src/core/store/store-only.ts
+++ b/src/core/store/store-only.ts
@@ -65,6 +65,8 @@ export interface StoreOnlyContext {
}
export interface StoreOnlyOptions {
+ /** A read-only preview must not persist a newly observed switch. */
+ readonly persistSwitch?: boolean;
/**
* The switch-record reader (default: {@link readSwitchRecords}); no
* production caller sets it. It stays for the read-facade parity tests,
@@ -255,7 +257,7 @@ function isSwitched(context: StoreOnlyContext, options: StoreOnlyOptions): boole
} catch {
switched = false;
}
- if (switched) {
+ if (switched && options.persistSwitch !== false) {
seenSwitched.add(key);
writeMarker(root, device);
}
diff --git a/tests/cli/brain-merge.test.ts b/tests/cli/brain-merge.test.ts
index c24340a6..4a655039 100644
--- a/tests/cli/brain-merge.test.ts
+++ b/tests/cli/brain-merge.test.ts
@@ -9,11 +9,12 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { writePreference } from "../../src/core/brain/preference.ts";
+import { regenerateActive } from "../../src/core/brain/active.ts";
import { runCli } from "../helpers/run-cli.ts";
let tmp: string;
@@ -145,6 +146,8 @@ describe("o2b brain merge — happy paths", () => {
await bootstrap();
makePref("keep");
makePref("drop");
+ const digestPath = regenerateActive(vault).path;
+ expect(readFileSync(digestPath, "utf8")).toContain("## Confirmed (2)");
const r = await runCli(
["brain", "merge", "pref-keep", "pref-drop", "--vault", vault, "--force"],
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
@@ -153,6 +156,10 @@ describe("o2b brain merge — happy paths", () => {
expect(r.stdout).toContain("merged:");
expect(existsSync(join(vault, "Brain", "preferences", "pref-drop.md"))).toBe(false);
expect(existsSync(join(vault, "Brain", "retired", "ret-drop.md"))).toBe(true);
+ const digest = readFileSync(digestPath, "utf8");
+ expect(digest).toContain("## Confirmed (1)");
+ expect(digest).toContain("pref-keep");
+ expect(digest).not.toContain("pref-drop");
});
test("non-TTY without --force exits 1 with the TTY guard message", async () => {
diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.ts
index b12a3762..c88c8b45 100644
--- a/tests/cli/brain.test.ts
+++ b/tests/cli/brain.test.ts
@@ -33,6 +33,7 @@ import { join } from "node:path";
import { runCli } from "../helpers/run-cli.ts";
import { listLogDates, readLogDay } from "../../src/core/brain/log-jsonl.ts";
+import { regenerateActive } from "../../src/core/brain/active.ts";
import { hookAuditDir } from "../../src/core/brain/paths.ts";
let tmp: string;
@@ -641,6 +642,25 @@ describe("brain query", () => {
});
});
+describe("brain refresh", () => {
+ test("previews and rebuilds a stale active preference digest", async () => {
+ await bootstrap();
+ const path = regenerateActive(vault).path;
+ const stale = readFileSync(path, "utf8").replace("## Confirmed (0)", "## Confirmed (1)");
+ writeFileSync(path, stale, "utf8");
+ const opts = { env: { OPEN_SECOND_BRAIN_CONFIG: config } };
+ const args = ["brain", "refresh", "--stale", "--vault", vault, "--json"];
+ const preview = await runCli([...args, "--dry-run"], opts);
+ expect(preview.returncode).toBe(0);
+ expect(JSON.parse(preview.stdout).plan.entries).toMatchObject([{ kind: "rederive-active" }]);
+ expect(readFileSync(path, "utf8")).toBe(stale);
+ const applied = await runCli(args, opts);
+ expect(applied.returncode).toBe(0);
+ expect(JSON.parse(applied.stdout).result.rederived).toEqual([path]);
+ expect(readFileSync(path, "utf8")).toContain("## Confirmed (0)");
+ });
+});
+
describe("brain reject", () => {
test("moves a pref to retired/", async () => {
await bootstrap();
@@ -663,6 +683,8 @@ describe("brain reject", () => {
{ env: { OPEN_SECOND_BRAIN_CONFIG: config } },
);
expect(seed.returncode).toBe(0);
+ const digestPath = regenerateActive(vault).path;
+ expect(readFileSync(digestPath, "utf8")).toContain("## Confirmed (1)");
const r = await runCli(
[
"brain",
@@ -680,6 +702,10 @@ describe("brain reject", () => {
expect(r.stdout).toContain("retired: ret-obsolete");
expect(existsSync(join(vault, "Brain", "preferences", "pref-obsolete.md"))).toBe(false);
expect(existsSync(join(vault, "Brain", "retired", "ret-obsolete.md"))).toBe(true);
+ const digest = readFileSync(digestPath, "utf8");
+ expect(digest).toContain("## Confirmed (0)");
+ expect(digest).toContain("## Recently retired");
+ expect(digest).toContain("ret-obsolete");
});
test("missing --id exits 1", async () => {
diff --git a/tests/core/brain/expiration-set.test.ts b/tests/core/brain/expiration-set.test.ts
index a05f3fce..c36a063e 100644
--- a/tests/core/brain/expiration-set.test.ts
+++ b/tests/core/brain/expiration-set.test.ts
@@ -29,11 +29,12 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { regenerateActive } from "../../../src/core/brain/active.ts";
import {
EXPIRATION_CLEAR,
ExpirationTargetNotFoundError,
@@ -41,6 +42,8 @@ import {
setExpiration,
} from "../../../src/core/brain/expiration-set.ts";
import { queryByTopic } from "../../../src/core/brain/query.ts";
+import { resolveAppendShardId } from "../../../src/core/brain/ledger-shards.ts";
+import { logShardJsonlPath } from "../../../src/core/brain/paths.ts";
import { writePreference } from "../../../src/core/brain/preference.ts";
import { writeSignal } from "../../../src/core/brain/signal.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
@@ -114,6 +117,33 @@ function seedPreference(): string {
}
describe("setting an expiration", () => {
+ test("updates the digest if the expiration saves but the audit append fails", () => {
+ const id = seedPreference();
+ const now = new Date("2026-07-16T12:00:00Z");
+ const digest = regenerateActive(vault, { now }).path;
+ expect(readFileSync(digest, "utf8")).toContain(id);
+ const logPath = logShardJsonlPath(vault, "2026-07-16", resolveAppendShardId());
+ mkdirSync(logPath, { recursive: true });
+ expect(() => setExpiration(vault, id, "2026-07-15", { now })).toThrow("EISDIR");
+ const page = join(vault, "Brain", "preferences", `${id}.md`);
+ expect(readFileSync(page, "utf8")).toContain("expiration_date: 2026-07-15");
+ expect(readFileSync(digest, "utf8")).not.toContain(id);
+ });
+
+ test("the digest drops expired preferences and restores them when expiration is cleared", () => {
+ const id = seedPreference();
+ const now = new Date("2026-07-16T12:00:00Z");
+ const digest = regenerateActive(vault, { now }).path;
+ expect(readFileSync(digest, "utf8")).toContain(id);
+ setExpiration(vault, id, "2026-07-15", { now });
+ expect(readFileSync(digest, "utf8")).toContain("## Confirmed (0)");
+ expect(readFileSync(digest, "utf8")).not.toContain(id);
+ expect(existsSync(join(vault, "Brain", "preferences", `${id}.md`))).toBe(true);
+ setExpiration(vault, id, EXPIRATION_CLEAR, { now });
+ expect(readFileSync(digest, "utf8")).toContain("## Confirmed (1)");
+ expect(readFileSync(digest, "utf8")).toContain(id);
+ });
+
test("stamps a signal and leaves its other frontmatter alone", () => {
const id = seedSignal();
const before = readFileSync(join(vault, "Brain/inbox", `${id}.md`), "utf8");
diff --git a/tests/core/brain/lifecycle/tombstone.test.ts b/tests/core/brain/lifecycle/tombstone.test.ts
index 88ba5302..bde049e1 100644
--- a/tests/core/brain/lifecycle/tombstone.test.ts
+++ b/tests/core/brain/lifecycle/tombstone.test.ts
@@ -4,7 +4,10 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { parseFrontmatter, writeFrontmatter } from "../../../../src/core/vault.ts";
+import { regenerateActive } from "../../../../src/core/brain/active.ts";
import { readLogDay } from "../../../../src/core/brain/log-jsonl.ts";
+import { resolveAppendShardId } from "../../../../src/core/brain/ledger-shards.ts";
+import { logShardJsonlPath } from "../../../../src/core/brain/paths.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
import {
TombstoneError,
@@ -51,6 +54,8 @@ const NOW = new Date("2026-07-18T12:00:00Z");
test("tombstone sets lifecycle frontmatter without deleting the file and preserves the body", () => {
const rel = writePref("alpha", {}, "This is the human prose body.");
+ const digest = regenerateActive(vault, { now: NOW }).path;
+ expect(readFileSync(digest, "utf8")).toContain("## Confirmed (1)");
const res = tombstone({ vault, path: rel, reason: "wrong belief", agent: "tester", now: NOW });
expect(res.changed).toBe(true);
@@ -63,6 +68,21 @@ test("tombstone sets lifecycle frontmatter without deleting the file and preserv
expect(meta["tombstoned_at"]).toBe("2026-07-18T12:00:00Z");
expect(meta["tombstone_reason"]).toBe("wrong belief");
expect(body).toBe("This is the human prose body.");
+ expect(readFileSync(digest, "utf8")).toContain("## Confirmed (0)");
+ expect(readFileSync(digest, "utf8")).not.toContain("pref-alpha");
+});
+
+test("updates the digest if the tombstone saves but the audit append fails", () => {
+ const rel = writePref("log-failure");
+ const digest = regenerateActive(vault, { now: NOW }).path;
+ expect(readFileSync(digest, "utf8")).toContain("pref-log-failure");
+ const logPath = logShardJsonlPath(vault, "2026-07-18", resolveAppendShardId());
+ mkdirSync(logPath, { recursive: true });
+ expect(() => tombstone({ vault, path: rel, reason: "wrong", agent: "tester", now: NOW })).toThrow(
+ "EISDIR",
+ );
+ expect(parseFrontmatter(join(vault, rel))[0]["_status"]).toBe("tombstoned");
+ expect(readFileSync(digest, "utf8")).not.toContain("pref-log-failure");
});
test("re-issuing a tombstone is a byte-identical no-op returning the existing state", () => {
diff --git a/tests/core/brain/recompile.test.ts b/tests/core/brain/recompile.test.ts
index 69facd66..96788c1c 100644
--- a/tests/core/brain/recompile.test.ts
+++ b/tests/core/brain/recompile.test.ts
@@ -16,6 +16,7 @@ import { join } from "node:path";
import { tmpdir } from "node:os";
import { checkPageFreshness } from "../../../src/core/brain/freshness.ts";
+import { freezeVault } from "../../../src/core/brain/freeze.ts";
import { writeHandoffNote } from "../../../src/core/brain/handoff.ts";
import { executeRecompile, planRecompile } from "../../../src/core/brain/recompile.ts";
@@ -111,6 +112,45 @@ describe("executeRecompile", () => {
expect(readFileSync(page, "utf8")).toBe(before);
});
+ test("previews and refreshes stale active preferences without rewriting a fresh digest", async () => {
+ const digest = join(vault, "Brain", "active.md");
+ const stale =
+ "---\ngenerated_at: 2026-06-09T12:00:00Z\n---\n## Confirmed (1)\n- retired marker\n";
+ writeFileSync(digest, stale, "utf8");
+ expect(planRecompile(vault).entries).toEqual([]);
+ const plan = planRecompile(vault, { now: NOW, includeActiveDigest: true });
+ expect(plan.entries).toContainEqual({
+ kind: "rederive-active",
+ page: digest,
+ reason: "the active preference digest differs from current memory state",
+ });
+ await executeRecompile(vault, plan, { dryRun: true, agent: "tester", now: NOW });
+ expect(readFileSync(digest, "utf8")).toBe(stale);
+
+ const result = await executeRecompile(vault, plan, { agent: "tester", now: NOW });
+ expect(result.rederived).toEqual([digest]);
+ expect(result.errors).toEqual([]);
+ const fresh = readFileSync(digest, "utf8");
+ expect(fresh).toContain("## Confirmed (0)");
+ expect(fresh).not.toContain("retired marker");
+ expect(planRecompile(vault, { now: NOW, includeActiveDigest: true }).entries).toEqual([]);
+ expect(readFileSync(digest, "utf8")).toBe(fresh);
+ });
+
+ test("a frozen vault can preview a stale active digest but refuses a refresh write", async () => {
+ const digest = join(vault, "Brain", "active.md");
+ const stale = "---\nkind: brain-active\n---\n\n## Confirmed (1)\n";
+ writeFileSync(digest, stale, "utf8");
+ freezeVault(vault, { now: NOW, agent: "tester", reason: "migration" });
+ const plan = planRecompile(vault, { now: NOW, includeActiveDigest: true });
+ expect(plan.entries.map((entry) => entry.kind)).toEqual(["rederive-active"]);
+ await executeRecompile(vault, plan, { dryRun: true, now: NOW, agent: "tester" });
+ await expect(executeRecompile(vault, plan, { now: NOW, agent: "tester" })).rejects.toThrow(
+ "frozen",
+ );
+ expect(readFileSync(digest, "utf8")).toBe(stale);
+ });
+
test("re-derives a stale handoff note in place and makes it fresh again", async () => {
const { page } = seedStaleHandoff();
const plan = planRecompile(vault);
diff --git a/tests/core/brain/store-readers/reader-parity.test.ts b/tests/core/brain/store-readers/reader-parity.test.ts
index 49232bab..df1dafcf 100644
--- a/tests/core/brain/store-readers/reader-parity.test.ts
+++ b/tests/core/brain/store-readers/reader-parity.test.ts
@@ -20,6 +20,7 @@ import {
import { activeDigestPathForRead, renderActive } from "../../../../src/core/brain/active.ts";
import { collectExplorerData } from "../../../../src/core/brain/explorer.ts";
import { scanApplyEvidence } from "../../../../src/core/brain/dream-refresh.ts";
+import { setExpiration } from "../../../../src/core/brain/expiration-set.ts";
import { renderDigest } from "../../../../src/core/brain/digest.ts";
import { computeAgentSummary } from "../../../../src/core/brain/digest-agent-summary.ts";
import { collectEvidenceForSlug } from "../../../../src/core/brain/evidence.ts";
@@ -304,6 +305,27 @@ describe("compiled digests on a switched machine", () => {
expect(answers[1]).toEqual(answers[0]!);
expect(answers[1]!.body).toContain(FIXTURE.confirmed);
});
+
+ test("a store-only reader stops serving a preference when its expiration passes", () => {
+ const env = own.switched;
+ useEnv(env);
+ const path = activeDigestPathForRead(env.vault, { now: FIXTURE_NOW });
+ const before = readFileSync(path, "utf8");
+ expect(before).toContain(`\`${FIXTURE.confirmed}\``);
+ setExpiration(env.vault, FIXTURE.confirmed, "2026-11-07", {
+ now: FIXTURE_NOW,
+ });
+ expect(readFileSync(path, "utf8")).toBe(before);
+ expect(activeDigestPathForRead(env.vault, { now: new Date("2026-11-07T23:59:59Z") })).toBe(
+ path,
+ );
+ expect(readFileSync(path, "utf8")).toBe(before);
+ expect(activeDigestPathForRead(env.vault, { now: new Date("2026-11-08T00:00:00Z") })).toBe(
+ path,
+ );
+ expect(readFileSync(path, "utf8")).not.toContain(`\`${FIXTURE.confirmed}\``);
+ expect(existsSync(join(env.vault, "Brain", "active.md"))).toBe(false);
+ });
});
describe("guard: no reader reads an empty directory on a switched machine", () => {
diff --git a/tests/core/layering.test.ts b/tests/core/layering.test.ts
index d6dc56b3..8d6163ca 100644
--- a/tests/core/layering.test.ts
+++ b/tests/core/layering.test.ts
@@ -129,9 +129,10 @@ describe("core layering", () => {
const rawMentions: string[] = [];
for (const file of walk(CORE_ROOT)) {
const text = readFileSync(file, "utf8");
+ const code = lexCode(text);
for (const { pattern } of BANNED) {
if (text.includes(pattern)) rawMentions.push(`${file} mentions ${pattern}`);
- if (lexCode(text).includes(pattern)) {
+ if (code.includes(pattern)) {
throw new Error(`${file}: ${pattern} survives the code view`);
}
}