Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

private-labels: dependents follow the remote privacy rules and bind the preview; a torn ledger tail keeps the next line readable (GST-2092, GST-2093 review)

garrytan54fdfcd78895
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9da6bd434c..adc9a96f52 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,7 +20,7 @@ The owner's `recall` with a `question` now returns its private facts, as `recall
`--class restore` treats ledger lines as untrusted input. It re-adds only `access` (a string) and `visibility: private`. A line with any other key, a non-string value or a page id that isn't an integer is counted as unreadable instead of failing the preview (GST-2092, GST-2128).
-The private-labels preview now counts the pages each window would expose along with its own: `derived_from` pages whose origin loses `visibility: private`, and life-chronicle events extracted from a listed page. It reports them by category (`details.dependents`, no slugs) and warns when the count isn't zero (GST-2093).
+The private-labels preview now counts the pages each window would expose along with its own: `derived_from` pages, atoms whose origin is a listed page, synthesized concepts built from such atoms, and life-chronicle events extracted from a listed page, each judged by the rules remote reads use. It reports them by category (`details.dependents`, no slugs) and warns when the count isn't zero. The preview hash covers the pages it counted, so an apply that would expose a page added since the preview refuses `preview_changed` (GST-2093). A ledger line a crash cut off no longer swallows the next one.
On a brain without managed persistence, a page whose file sits in its source's checkout is no longer cleared in the database only, because the next sync or re-import would put the label back from the file. The apply holds it with outcome `file_backed` and names the file to edit. Repo-less pages clear as before (GST-2128).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 02ede77317..bb56ce47c4 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2119,10 +2119,13 @@ What it clears and what it keeps:
The preview lists one window of pages under a hash, with every class's count
before and after the window. It also counts, by category and without slugs, the
pages that the window would expose along with its own (`details.dependents`).
-These are `derived_from` pages whose origin loses `visibility: private`, and
-life-chronicle events extracted from a listed page. A warning names the counts
-when they aren't zero. To keep one of those pages private, give it its own
-label before you apply.
+It judges each page by the same rules remote reads use, before and after the
+window: `derived_from` pages, atoms whose origin is a listed page, synthesized
+concepts built from such atoms, and life-chronicle events extracted from a
+listed page. A warning names the counts when they aren't zero. To keep one of
+those pages private, give it its own label before you apply. The preview hash
+covers the pages it counted, so if a new page would be exposed by the time you
+apply, the apply refuses with `preview_changed` and you preview again.
`--apply --expect <preview_hash>` applies exactly that window and checks each
page against its current revision and labels first. A page edited since the
diff --git a/src/commands/repair-private-labels.ts b/src/commands/repair-private-labels.ts
index 73226d59f0..8548ee6fb7 100644
--- a/src/commands/repair-private-labels.ts
+++ b/src/commands/repair-private-labels.ts
@@ -5,7 +5,7 @@
* 0700 directory, the file 0600. The core reads the lines for --class restore
* and appends through `record`.
*/
-import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { appendFileSync, chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
import { dirname } from 'node:path';
import { gbrainPath } from '../core/config.ts';
import type { PrivateLabelsLedger } from '../core/repair/private-labels.ts';
@@ -21,7 +21,19 @@ export function privateLabelsLedger(brainId: string): PrivateLabelsLedger {
return { path, lines, unreadable, record(line) {
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
chmodSync(dirname(path), 0o700);
- appendFileSync(path, `${JSON.stringify(line)}\n`, { mode: 0o600 });
+ appendFileSync(path, `${tornTail(path) ? '\n' : ''}${JSON.stringify(line)}\n`, { mode: 0o600 });
chmodSync(path, 0o600);
} };
}
+
+/** A ledger whose last line a crash cut off: the next line starts on a fresh one, so it stays readable. */
+function tornTail(path: string): boolean {
+ const size = existsSync(path) ? statSync(path).size : 0;
+ if (!size) return false;
+ const fd = openSync(path, 'r');
+ try {
+ const last = Buffer.alloc(1);
+ readSync(fd, last, 0, 1, size - 1);
+ return last[0] !== 0x0a;
+ } finally { closeSync(fd); }
+}
diff --git a/src/core/repair/private-labels.ts b/src/core/repair/private-labels.ts
index e86e0653af..6141bcf0fb 100644
--- a/src/core/repair/private-labels.ts
+++ b/src/core/repair/private-labels.ts
@@ -57,7 +57,7 @@ import { importFromContent } from '../import-file.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
-import { PRIVACY_ALIASES, privacyAliasSql, privateSnapshotFilterFragment, readHonorAliases } from '../search/private-visibility.ts';
+import { PRIVACY_ALIASES, privacyAliasSql, privacyPartSql, privateSnapshotFilterFragment, readHonorAliases } from '../search/private-visibility.ts';
import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';
export type ClearClass = 'alias' | 'alias-and-visibility' | 'git-publish';
@@ -76,7 +76,7 @@ const bounded = { timeoutMs: 120_000 };
type Labels = { access?: string; visibility?: string };
interface LabelRow { id: number; source_id: string; slug: string; type: string; frontmatter: Record<string, unknown> | null; revision: string | null; chars: number; git: boolean }
interface Selection { source_ids: string[]; class: LabelsClass | null }
-interface Approved { mode: 'clear' | 'restore'; class: LabelsClass; brain_id: string; source_id: string; slug: string; page_id: number; revision: string | null; labels: Labels; chars: number; selection: Selection }
+interface Approved { mode: 'clear' | 'restore'; class: LabelsClass; brain_id: string; source_id: string; slug: string; page_id: number; revision: string | null; labels: Labels; chars: number; selection: Selection; exposes?: number[] }
interface LabelsItem extends RepairItem { entry: Approved; ledger: PrivateLabelsLedger }
/**
* One ledger line. `phase`: `intent` is appended before the page write, `committed` after it landed, with the revision it
@@ -156,7 +156,7 @@ function selectedClass(opts?: RepairPlanOptions): LabelsClass | null {
}
const hashParts = (scope: RepairScope, selection: Selection, entries: Approved[]) => ({ kind: 'private-labels-v1', brain_id: scope.brain_id, selection,
- items: entries.map(e => [e.mode, e.class, e.source_id, e.page_id, e.slug, e.revision, Object.entries(e.labels).sort()]) });
+ items: entries.map(e => [e.mode, e.class, e.source_id, e.page_id, e.slug, e.revision, Object.entries(e.labels).sort(), e.exposes ?? []]) });
/** Every category's count over the scope and the clear entries of the selected classes, in (class, page id) order. */
async function planClear(engine: BrainEngine, scope: RepairScope, selection: Selection, classes: readonly ClearClass[]) {
@@ -215,34 +215,49 @@ async function planRestore(engine: BrainEngine, scope: RepairScope, selection: S
return { counts: counts as Record<string, number>, entries, unreadable };
}
+type Dependents = { derived_from: number; atom: number; concept: number; life_chronicle: number };
+
/**
- * GST-2093: the pages a window's clears expose besides themselves, by category: a derived_from page (not itself a derived
- * type) whose declared origins that are visibility: private all lose it in this window, and a life-chronicle event whose
- * origin (`event.depth`) is a listed page hidden now. Each must not be private by its own fields. Counts only.
+ * GST-2093: the pages a window's clears expose besides themselves, by category, judged by the remote privacy rules
+ * (privacyPartSql) on each page as it is now and as it would be once the window applies. A candidate is a live page of
+ * the same source tied to a cleared page the way those rules follow privacy: `derived_from`, an atom's `source_slug`, a
+ * life-chronicle event's `event.depth`, or a concept-provenance link to a cleared atom or to an atom of a cleared origin.
+ * The postimage is the pages table shadowed with the window's keys removed. Also returned, per cleared page id, the
+ * exposed page ids tied to it: the preview hash binds them, and apply refuses a window that would expose a page outside them.
*/
-async function windowDependents(engine: BrainEngine, window: Approved[]): Promise<{ derived_from: number; life_chronicle: number }> {
+async function windowDependents(engine: BrainEngine, window: Approved[]): Promise<{ counts: Dependents; exposes: Map<number, number[]> }> {
+ const counts: Dependents = { derived_from: 0, atom: 0, concept: 0, life_chronicle: 0 };
+ const exposes = new Map<number, number[]>();
const clears = window.filter(entry => entry.mode === 'clear');
- if (!clears.length) return { derived_from: 0, life_chronicle: 0 };
+ if (!clears.length) return { counts, exposes };
await readHonorAliases(engine);
- const declared = (p: string) => `ARRAY(SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text(
- CASE WHEN jsonb_typeof(${p}.frontmatter->'derived_from') = 'array' THEN ${p}.frontmatter->'derived_from' ELSE jsonb_build_array(${p}.frontmatter->'derived_from') END) AS declared(slug))`;
- const [row] = await engine.executeRaw<{ derived_from: number; life_chronicle: number }>(`WITH cleared AS (
- SELECT * FROM unnest($1::text[], $2::text[], $3::text[]) AS c(source_id, slug, visibility)),
- lineage AS (SELECT p.source_id, ${declared('p')} AS origins FROM pages p
- WHERE p.deleted_at IS NULL AND p.source_id = ANY($1::text[]) AND jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string')
- AND p.type NOT IN ('atom', 'question', 'concept', 'event') AND ${privateSnapshotFilterFragment('p')}
- AND NOT EXISTS (SELECT 1 FROM cleared c WHERE c.source_id = p.source_id AND c.slug = p.slug))
- SELECT (SELECT count(*)::int FROM lineage l
- WHERE EXISTS (SELECT 1 FROM cleared c WHERE c.visibility = 'private' AND c.source_id = l.source_id AND c.slug = ANY(l.origins))
- AND NOT EXISTS (SELECT 1 FROM pages o WHERE o.source_id = l.source_id AND o.slug = ANY(l.origins) AND o.frontmatter->>'visibility' = 'private'
- AND NOT EXISTS (SELECT 1 FROM cleared c WHERE c.visibility = 'private' AND c.source_id = o.source_id AND c.slug = o.slug))) AS derived_from,
- (SELECT count(*)::int FROM pages e
- JOIN cleared c ON c.source_id = e.source_id AND c.slug = e.frontmatter->'event'->>'depth'
- JOIN pages o ON o.source_id = c.source_id AND o.slug = c.slug AND o.deleted_at IS NULL
- WHERE e.deleted_at IS NULL AND e.type = 'event' AND e.frontmatter->>'captured_via' LIKE 'life-chronicle:%' AND NOT (e.frontmatter ? 'derived_from')
- AND ${privateSnapshotFilterFragment('e')} AND NOT ${privateSnapshotFilterFragment('o')}) AS life_chronicle`,
- [clears.map(entry => entry.source_id), clears.map(entry => entry.slug), clears.map(entry => entry.labels.visibility ?? '')], bounded);
- return { derived_from: Number(row?.derived_from ?? 0), life_chronicle: Number(row?.life_chronicle ?? 0) };
+ const rows = await engine.executeRaw<{ id: number; cleared_id: number; category: keyof Dependents }>(`WITH cleared AS (
+ SELECT * FROM unnest($1::integer[], $2::text[], $3::text[], $4::text[]) AS c(id, source_id, slug, keys)),
+ candidates AS (SELECT DISTINCT p.id, c.id AS cleared_id FROM pages p JOIN cleared c ON c.source_id = p.source_id
+ WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM cleared x WHERE x.id = p.id) AND (
+ p.frontmatter->>'source_slug' = c.slug OR p.frontmatter->'event'->>'depth' = c.slug
+ OR (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND c.slug = ANY(ARRAY(SELECT regexp_replace(declared.slug, '\\.md$', '')
+ FROM jsonb_array_elements_text(CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from'
+ ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))
+ OR EXISTS (SELECT 1 FROM links l JOIN pages a ON a.id = l.to_page_id WHERE l.from_page_id = p.id AND l.link_source = 'concept-provenance'
+ AND l.link_type = 'synthesized_from' AND (a.id = c.id OR (a.source_id = c.source_id AND a.frontmatter->>'source_slug' = c.slug)))))
+ SELECT cand.id, cand.cleared_id, CASE WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN 'life_chronicle'
+ WHEN p.type = 'atom' THEN 'atom' WHEN p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL THEN 'concept' ELSE 'derived_from' END AS category
+ FROM candidates cand JOIN pages p ON p.id = cand.id
+ WHERE NOT ${privacyPartSql('p')} AND cand.id IN (
+ WITH pages AS NOT MATERIALIZED (SELECT pg.id, pg.source_id, pg.slug, pg.type, pg.deleted_at,
+ CASE WHEN c.id IS NULL THEN pg.frontmatter ELSE pg.frontmatter - string_to_array(c.keys, ',') END AS frontmatter
+ FROM pages pg LEFT JOIN cleared c ON c.id = pg.id)
+ SELECT after_clear.id FROM pages after_clear WHERE after_clear.id IN (SELECT id FROM candidates) AND ${privacyPartSql('after_clear')})
+ ORDER BY cand.id`,
+ [clears.map(entry => entry.page_id), clears.map(entry => entry.source_id), clears.map(entry => entry.slug), clears.map(entry => Object.keys(entry.labels).sort().join(','))], bounded);
+ const counted = new Set<number>();
+ for (const row of rows) {
+ const id = Number(row.id);
+ if (!counted.has(id)) { counted.add(id); counts[row.category]++; }
+ exposes.set(Number(row.cleared_id), [...(exposes.get(Number(row.cleared_id)) ?? []), id]);
+ }
+ return { counts, exposes };
}
/**
@@ -296,6 +311,8 @@ export const privateLabelsRepair: RepairHandler = {
if (approved.items.some(entry => (entry.selection.class ?? null) !== selection.class || JSON.stringify(entry.selection.source_ids) !== JSON.stringify(selection.source_ids))) {
throw previewChangedError(opts.expect, command);
}
+ const approvedExposes = new Set(approved.items.flatMap(entry => entry.exposes ?? []));
+ if ([...(await windowDependents(engine, approved.items)).exposes.values()].flat().some(id => !approvedExposes.has(id))) throw previewChangedError(opts.expect, command);
return { items: toItems(approved.items).filter(item => afterCursor(item.cursor, after)), preview_hash: opts.expect, residuals: {} };
}
const size = Math.min(Math.max(1, opts?.limit ?? PRIVATE_LABELS_WINDOW), PRIVATE_LABELS_WINDOW_MAX);
@@ -311,11 +328,13 @@ export const privateLabelsRepair: RepairHandler = {
projected.restorable!--;
projected.already_restored!++;
}
+ const found = restore ? null : await windowDependents(engine, window);
+ for (const entry of window) if (found?.exposes.has(entry.page_id)) entry.exposes = found.exposes.get(entry.page_id);
const hash = previewHash(hashParts(scope, selection, window));
if (window.length) await saveApprovedSet<Approved>(engine, { command: 'private-labels', hash }, window);
const gitPublish = restore ? 0 : before['git-publish'] ?? 0;
- const dependents = restore ? null : await windowDependents(engine, window);
- const exposed = dependents ? dependents.derived_from + dependents.life_chronicle : 0;
+ const dependents = found?.counts ?? null;
+ const exposed = dependents ? Object.values(dependents).reduce((sum, n) => sum + n, 0) : 0;
const fileBacked = (await filesInCheckout(engine, window.map(entry => entry.page_id))).size;
const warnings = [
...(pastWindow ? [`This preview lists one window of ${window.length} item(s); ${pastWindow} more found past it. Apply this window (or decide not to), then preview again for the next one: ${command}`] : []),
@@ -327,8 +346,8 @@ export const privateLabelsRepair: RepairHandler = {
+ 'from the checkout, but every earlier commit, and any remote it was pushed to, keeps the page\'s content.'] : []),
...(gitPublish && selection.class !== 'git-publish' ? [`${gitPublish} page(s) of class git-publish (git-canonical sources) carry the same label and are not in this preview: `
+ 'private pages there are database-only, so clearing commits each into its source\'s Git history for the first time. Preview them by name: gbrain repair private-labels --class git-publish'] : []),
- ...(exposed ? [`Clearing this window also exposes ${exposed} page(s) whose only privacy is a listed page's label: ${dependents!.derived_from} derived_from page(s) whose `
- + `declared origin loses visibility: private, ${dependents!.life_chronicle} life-chronicle event(s) extracted from a listed page. Remote callers that are not the brain owner `
+ ...(exposed ? [`Clearing this window also exposes ${exposed} page(s) whose only privacy is a listed page's label: ${dependents!.derived_from} derived_from page(s), `
+ + `${dependents!.atom} atom(s), ${dependents!.concept} synthesized concept(s) and ${dependents!.life_chronicle} life-chronicle event(s) extracted from a listed page. Remote callers that are not the brain owner `
+ 'can read them once this window applies (readable_by and folder rules still apply). To keep one private, give it its own label first; --class restore re-hides them with their origins.'] : []),
...(fileBacked ? [`${fileBacked} listed page(s) have a file in their source's checkout on a brain without managed persistence. This repair writes only the database there, `
+ 'and the next sync or re-import would put the label back from the file, so the apply holds each (outcome file_backed) with the file to edit.'] : []),
diff --git a/test/repair-private-labels.test.ts b/test/repair-private-labels.test.ts
index fa76a79813..3e3084cbe2 100644
--- a/test/repair-private-labels.test.ts
+++ b/test/repair-private-labels.test.ts
@@ -514,6 +514,48 @@ describe('repair private-labels write-ahead ledger', () => {
});
});
+/**
+ * Review finding on GST-2092: a crash can leave the ledger's last line cut off. The next intent line must start on a
+ * line of its own, or it joins the torn tail, is unreadable, and restore cannot find the page it cleared.
+ */
+describe('repair private-labels ledger with a torn last line', () => {
+ test('the intent line after a torn tail stays readable, so a crash after the page write still restores', async () => {
+ const source = 'source-t';
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-private-labels-torn-'));
+ const runIn = async (argv: string[]) => {
+ const out = JSON.parse(await withEnv({ GBRAIN_HOME: home, GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() => runRepairCommand(engine, [...argv, '--json'])))).results[0];
+ _resetCliExitVerdictForTests();
+ return out;
+ };
+ try {
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);
+ await seed('notes/t', 'note', { access: 'private' }, source);
+ const preview = await runIn(['private-labels', '--source', source]);
+ const brain = preview.scope.brain_id;
+ const path = join(home, '.gbrain', 'repair', 'private-labels', brain + '.jsonl');
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, '{"');
+ const scope = await resolveRepairScope(engine, source);
+ const logger = { info() {}, warn() {}, error() {} };
+ const applied = await withEnv({ GBRAIN_HOME: home }, async () => {
+ const real = privateLabelsLedger(brain);
+ const crashing = { ...real, record(line: PrivateLabelsLedgerLine) {
+ if (line.phase !== 'intent') throw new Error('forced crash after the page write');
+ real.record(line);
+ } };
+ return (await repairRunner(engine, { apply: true, logger })).run('private-labels', scope, { explicit: true, expect: preview.preview_hash, privateLabelsLedger: crashing });
+ });
+ expect(applied.failed).toEqual([]);
+ expect('access' in (await row('notes/t', source)).frontmatter).toBe(false);
+ const restore = await runIn(['private-labels', '--source', source, '--class', 'restore']);
+ expect(restore.listing).toEqual([{ item: source + ':notes/t', class: 'restore', detail: 're-add access: private' }]);
+ expect(restore.warnings.some((w: string) => w.startsWith('1 ledger line(s) could not be read'))).toBe(true);
+ expect((await runIn(['private-labels', '--source', source, '--class', 'restore', '--apply', '--expect', restore.preview_hash])).applied).toBe(1);
+ expect((await row('notes/t', source)).frontmatter.access).toBe('private');
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ });
+});
+
/**
* GST-2128 item 4: restore reads ledger lines as untrusted input. Only access and visibility (visibility only as
* private) with string values are re-added; any other line, and one whose page id is not an integer, is counted
@@ -592,10 +634,10 @@ describe('repair private-labels preview counts the dependents a window exposes',
const first = await json(['private-labels', '--source', source, '--limit', '1']);
expect(first.listing).toEqual([{ item: source + ':meetings/m1', class: 'alias', detail: 'remove access: private' }]);
- expect(first.details.dependents).toEqual({ derived_from: 0, life_chronicle: 1 });
+ expect(first.details.dependents).toEqual({ derived_from: 0, atom: 0, concept: 0, life_chronicle: 1 });
const whole = await json(['private-labels', '--source', source]);
expect(whole.listing.map((l: { item: string }) => l.item)).toEqual([source + ':meetings/m1', source + ':notes/origin-d']);
- expect(whole.details.dependents).toEqual({ derived_from: 1, life_chronicle: 1 });
+ expect(whole.details.dependents).toEqual({ derived_from: 1, atom: 0, concept: 0, life_chronicle: 1 });
const warning = whole.warnings.find((w: string) => w.includes('page(s) whose only privacy'));
expect(warning).toContain('2 page(s)');
expect(warning).toContain('1 derived_from');
@@ -609,11 +651,63 @@ describe('repair private-labels preview counts the dependents a window exposes',
expect(await remoteGet('events/e1')).toContain('canaryeventone');
expect(await remoteGet('notes/summary-two')).not.toContain('canary');
const none = await json(['private-labels', '--source', source]);
- expect(none.details.dependents).toEqual({ derived_from: 0, life_chronicle: 0 });
+ expect(none.details.dependents).toEqual({ derived_from: 0, atom: 0, concept: 0, life_chronicle: 0 });
expect(none.warnings.some((w: string) => w.includes('page(s) whose only privacy'))).toBe(false);
});
});
+/**
+ * Review findings on GST-2093: the dependents count follows the remote privacy rules on every page type (an ordinary
+ * concept or note with derived_from, an atom whose origin is the cleared page, a synthesized concept built from such an
+ * atom), and the preview hash binds the pages it exposes, so a dependent added after the preview refuses the apply.
+ */
+describe('repair private-labels dependents follow the remote privacy rules and bind the preview', () => {
+ const remoteGetIn = async (source: string, slug: string) => (await dispatchToolCall(engine, 'get_page', { slug }, { remote: true, transport: 'stdio', sourceId: source, takesHoldersAllowList: ['world'] }))
+ .content.map(c => c.text).join(NL);
+
+ test('every page type whose only privacy is the cleared origin is counted, and each becomes readable remotely', async () => {
+ const source = 'source-x';
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);
+ await seed('notes/origin-x', 'note', { access: 'private', visibility: 'private' }, source);
+ await seed('concepts/plain-x', 'concept', { derived_from: 'notes/origin-x' }, source, 'canaryplainconcept lineage page.');
+ await seed('notes/note-x', 'note', { derived_from: 'notes/origin-x' }, source, 'canarynotex lineage page.');
+ await seed('atoms/a1-x', 'atom', { visibility: 'world', source_slug: 'notes/origin-x' }, source, 'canaryatomone extracted atom.');
+ await seed('atoms/a2-x', 'atom', { visibility: 'world', source_slug: 'notes/origin-x' }, source, 'canaryatomtwo extracted atom.');
+ await seed('concepts/synth-x', 'concept', { synthesized_by: 'test', visibility: 'world' }, source, 'canarysynthx synthesized concept.');
+ await engine.executeRaw("INSERT INTO links (from_page_id, to_page_id, link_type, link_source) SELECT c.id, a.id, 'synthesized_from', 'concept-provenance' FROM pages c, pages a "
+ + "WHERE c.source_id = $1 AND a.source_id = $1 AND c.slug = 'concepts/synth-x' AND a.slug = 'atoms/a2-x'", [source]);
+ const dependents = ['concepts/plain-x', 'notes/note-x', 'atoms/a1-x', 'atoms/a2-x', 'concepts/synth-x'];
+ for (const slug of dependents) expect(await remoteGetIn(source, slug)).not.toContain('canary');
+
+ const preview = await json(['private-labels', '--source', source]);
+ expect(preview.listing).toEqual([{ item: source + ':notes/origin-x', class: 'alias-and-visibility', detail: 'remove access: private, visibility: private' }]);
+ expect(preview.details.dependents).toEqual({ derived_from: 2, atom: 2, concept: 1, life_chronicle: 0 });
+ expect(preview.warnings.find((w: string) => w.includes('page(s) whose only privacy'))).toContain('5 page(s)');
+
+ expect((await json(['private-labels', '--source', source, '--apply', '--expect', preview.preview_hash])).applied).toBe(1);
+ __resetPrivateVisibilityCacheForTests();
+ for (const slug of dependents) expect(await remoteGetIn(source, slug)).toContain('canary');
+ });
+
+ test('a dependent added after the preview refuses the old --expect; a fresh preview counts it and applies', async () => {
+ const source = 'source-y';
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);
+ await seed('notes/origin-y', 'note', { access: 'private', visibility: 'private' }, source);
+ const preview = await json(['private-labels', '--source', source]);
+ expect(preview.details.dependents).toEqual({ derived_from: 0, atom: 0, concept: 0, life_chronicle: 0 });
+ await seed('notes/summary-y', 'note', { derived_from: 'notes/origin-y' }, source, 'canarysummaryy lineage page.');
+ const refused = await refusal(() => run(['private-labels', '--source', source, '--apply', '--expect', preview.preview_hash, '--json']));
+ _resetCliExitVerdictForTests();
+ expect(refused.code).toBe('preview_changed');
+ expect((await row('notes/origin-y', source)).frontmatter.access).toBe('private');
+ const fresh = await json(['private-labels', '--source', source]);
+ expect(fresh.details.dependents).toEqual({ derived_from: 1, atom: 0, concept: 0, life_chronicle: 0 });
+ expect(fresh.preview_hash).not.toBe(preview.preview_hash);
+ expect((await json(['private-labels', '--source', source, '--apply', '--expect', fresh.preview_hash])).applied).toBe(1);
+ });
+});
+
/**
* GST-2128 item 1: on a brain without managed persistence the repair writes only the database, so a page whose file sits
* in its source's checkout would get the label back from the file at the next sync or re-import while the ledger says