Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(takes): takes rebuild, takes remove, and accepted proposals with provenance (#5167, #5214)

time-attack46f208de2cee
diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.md
index 3ad6a66882..c09725c19b 100644
--- a/docs/architecture/key-files/hindsight.md
+++ b/docs/architecture/key-files/hindsight.md
@@ -33,9 +33,9 @@ unresolvable+true|false, pre-v80 NULL/NULL rows survive).
- `src/core/think/prompt.ts` — anti-bias prompt shaping. `withCalibration` option on `buildThinkSystemPrompt` adds anti-bias rules. `buildCalibrationBlock()` emits the `<calibration>` XML. `buildThinkUserMessage` has TWO shapes: default (question first), and with-calibration (retrieval → calibration → question) when opt-in. Wired into `runThink` via `opts.withCalibration` + `opts.calibrationHolder`.
- `src/commands/calibration.ts` — CLI: `gbrain calibration` (read + print), `--regenerate`, `--undo-wave <ver>`, `ab-report`. MCP op `get_calibration_profile` (scope: read) backs the same data path. Source-scoped via `sourceScopeOpts(ctx)`.
- `src/core/owner-holder.ts` — single source of truth for "the brain owner" holder string. `DEFAULT_OWNER_HOLDER = 'self'` (matches the consolidate facts→takes writer + `docs/takes-vs-facts.md`); `resolveOwnerHolder({override, configValue})` returns override > `emotional_weight.user_holder` config > `'self'`. Consumed by the calibration_profile cycle phase, `gbrain calibration` CLI, the `get_calibration_profile` op, `think`'s calibration block, `emotional-weight`'s `DEFAULT_USER_HOLDER`, and doctor's `calibration_freshness`. Pure; unit-tested in `test/owner-holder.test.ts`. Does NOT unify owner-identity fragmentation (`self`/`brain`/`people-<owner>`) — tracked separately.
-- `src/commands/takes.ts` — the full `gbrain takes` subcommand dispatcher (list/search/embed/add/update/supersede/resolve/propose/scorecard/calibration/extract/revisit). `takes list --limit N --offset N` validates integers at the CLI; the engine clamps limit (default 100, cap 500) and floors offset at 0. `takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker.
+- `src/commands/takes.ts` — the full `gbrain takes` subcommand dispatcher (list/search/embed/add/update/supersede/resolve/propose/scorecard/calibration/extract/revisit). `takes list --limit N --offset N` validates integers at the CLI; the engine clamps limit (default 100, cap 500) and floors offset at 0. `takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker. #5167: `takes remove <slug> --row N` goes through `takes-mutation.ts` to the local-only `takes_remove` op (persistence `takes-prepare.ts`): the row leaves the fence and the takes table in one coordinated publication, other row numbers stay, and a resolved row, a row another row cites as "superseded by" it, or a row whose DB claim disagrees with the fence is refused (the last names `takes rebuild`); thin clients are refused. `takes rebuild <slug> [--source-id]` runs `extractTakes({source:"db", slugs:[slug], sourceId, rebuild:true})`, whose rebuild now deletes only indexed rows whose (row_num, claim) left the fence, so matching rows keep resolutions and vectors. The v0_28_0 hint names `gbrain reindex --markdown` instead of the nonexistent `extract takes --rebuild`.
- `src/core/extract-takes-from-pages.ts` — bootstrap extraction keeps page selection and zero-claim behavior unchanged. Managed pages capture their revision before classification and publish the complete appended takes fence through coordinated `put_page`, whose canonical projection commits the takes rows with the page; conflicts skip that page. Unmanaged pages retain the md-first writer. Pinned by `test/persistence-managed-takes-extract.test.ts` and `test/extract-takes-md-first.test.ts`.
-- `src/core/take-proposals.ts` — owns the `take_proposals` queue's row contract. `normalizeTakeProposalRow` coerces Postgres driver BigInt/string values (`id`, `weight`, `promoted_row_num`) to numbers at the query boundary so both engines return the same numeric row shape. `acceptProposal` promotes through a coordinated `takes_add` mutation (`submitPageMutation`, the same path `gbrain takes add` uses), so accept works on a managed brain where a direct fence write is refused with `writer_coordinator_required` (`test/takes-propose-accept-managed.test.ts`).
+- `src/core/take-proposals.ts` — owns the `take_proposals` queue's row contract. `normalizeTakeProposalRow` coerces Postgres driver BigInt/string values (`id`, `weight`, `promoted_row_num`) to numbers at the query boundary so both engines return the same numeric row shape. `acceptProposal` promotes through a coordinated `takes_add` mutation (`submitPageMutation`, the same path `gbrain takes add` uses), so accept works on a managed brain where a direct fence write is refused with `writer_coordinator_required` (`test/takes-propose-accept-managed.test.ts`). #5214: an accepted proposal's take records `take_proposals#<id>` as its source; `acceptProposal(target, id, edits)` (`takes propose --accept <id> --claim/--weight/--who/--kind`) applies the edits as a plain takes_add with source `take_proposals#<id> (edited)` while the queue row keeps the original claim text.
- `admin/src/pages/Calibration.tsx` — Calibration tab. Single-column layout. `<TrustedSVG>` wrapper handles `dangerouslySetInnerHTML` for the server-rendered SVG.
- `admin/src/index.css` — `--text-muted: #777` (WCAG AA contrast bump to ~5.5 on the #0a0a0f bg).
- `test/fixtures/calibration/extract-takes-corpus/` — synthetic prompt-tuning corpus. Ships 5 representative pages; full 50-page + 10-page holdout generated by `gbrain calibration build-corpus`. All anonymized per CLAUDE.md placeholder list.
diff --git a/docs/wave9/sg.md b/docs/wave9/sg.md
index 6ce0f93432..3f2543f868 100644
--- a/docs/wave9/sg.md
+++ b/docs/wave9/sg.md
@@ -13,6 +13,8 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md
- **`gbrain reindex --markdown` works on managed brains (#5377, C-NEW-5).** It used to fail every page with "cannot mutate a managed brain through the legacy writer", while doctor, upgrade and post-upgrade kept prescribing it. On a managed brain it now runs the projection repairs (`gbrain repair safe-chunks`, then `contextual-mode` unless `--no-embed`): no page revision, journal request or canonical file changes. `--type` is refused on managed brains with the repair commands.
- **`gbrain sources writer status` no longer reports a CLI's own consumer as the brain's ingress (C-NEW-4).** The `ingress` field (always `not_running` from a one-shot CLI) is replaced by `local_process_ingress`, which says it describes only the process that answered; ownership stays under `worktrees` and `bindings`.
- **Doctor sees unpushed source checkouts (#5063).** New `git_convergence` check: a source checkout or `sync.repo_path` with commits not on its upstream warns after 6 hours and fails after 24; uncommitted changes older than 6 hours warn. It compares with the last fetched upstream and never fetches. `bootstrap_push_health` no longer says `ok` on a recent push while the workspace is still ahead of origin, and `scripts/smoke-test.sh` accepts a configured database URL and a keyless embedding provider that doctor accepts.
+- **`gbrain takes rebuild <slug>` and `gbrain takes remove <slug> --row N` (#5167).** Rebuild re-derives one page's takes index from its fence; rows whose number and claim still match keep their resolution and vector, rows the index disagrees on are re-inserted from the fence. Remove takes one row out of the fence and the index together; other row numbers do not change, and it refuses resolved rows, rows another row cites as their replacement, and rows whose index copy disagrees with the fence (it names `takes rebuild`). Local-only (`takes_remove` is not an MCP tool). The v0.28.0 migration hint now names `gbrain reindex --markdown` instead of the nonexistent `gbrain extract takes --rebuild`.
+- **Accepted take proposals keep their provenance (#5214).** `gbrain takes propose --accept <id>` records `take_proposals#<id>` as the take's source; `--claim/--weight/--who/--kind` edit the take before it is written, recorded as `take_proposals#<id> (edited)`, while the proposal keeps its original text.
## Upgrade-note rows
@@ -27,3 +29,5 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md
| Managed `reindex --markdown` delegates to projection repairs (#5377) | Managed brains with chunker or contextual-mode drift | doctor calibration hint (`gbrain reindex --markdown`) now works | Run `gbrain repair safe-chunks` / `contextual-mode` directly for per-kind control |
| `writer status`: `ingress` → `local_process_ingress` with a `scope` note (C-NEW-4) | Scripts reading `ingress` from `gbrain sources writer status --json` | none | Read `local_process_ingress.state`; for ownership read `worktrees`/`bindings` |
| New doctor `git_convergence`; `bootstrap_push_health` warns when ahead (#5063) | Brains syncing from Git checkouts with an upstream | `gbrain doctor --only git_convergence` | Push the checkout; checkouts without an upstream are skipped |
+| New `takes rebuild` / `takes remove` (local-only op `takes_remove`) (#5167) | Operators repairing takes | `gbrain takes <slug> --json` | None |
+| Accepted proposals carry `source: take_proposals#<id>` (#5214) | Anyone reading take sources | `gbrain takes <slug>` | None |
diff --git a/src/commands/migrations/v0_28_0.ts b/src/commands/migrations/v0_28_0.ts
index 1efbc2ed9b..6e93174091 100644
--- a/src/commands/migrations/v0_28_0.ts
+++ b/src/commands/migrations/v0_28_0.ts
@@ -97,7 +97,7 @@ async function phaseBBackfill(
try {
// Inline run on both engines for v0.28.0 simplicity. Larger brains can run
- // `gbrain extract takes --rebuild` later; the migration's job is to get
+ // `gbrain takes rebuild <slug>` later; the migration's job is to get
// the table populated for upgrade-time doctor checks.
const { extractTakes } = await import('../../core/cycle/extract-takes.ts');
const result = await extractTakes(engine, { source: 'db' });
@@ -162,7 +162,7 @@ function phaseCRechunkTodo(opts: OrchestratorOpts): OrchestratorPhaseResult {
ts: new Date().toISOString(),
skill: 'skills/migrations/v0.28.0.md',
reason: 'Pages with pre-v0.28 chunks still contain fenced takes content. Re-chunk so the new chunker strip rule is applied (Codex P0 #3 fix).',
- command: "gbrain extract takes --rebuild # forces re-chunk via reimport pipeline; see migration doc for the precise sweep command in your env",
+ command: 'gbrain reindex --markdown # re-chunks pages below the current chunker version',
_key: key,
};
appendFileSync(pendingHostWorkPath(), JSON.stringify(entry) + '\n');
diff --git a/src/commands/takes-mutation.ts b/src/commands/takes-mutation.ts
index 63bfc570b3..d8a103b47b 100644
--- a/src/commands/takes-mutation.ts
+++ b/src/commands/takes-mutation.ts
@@ -16,18 +16,19 @@ import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';
import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
-const names = ['add', 'update', 'supersede', 'resolve'] as const;
+const names = ['add', 'update', 'supersede', 'resolve', 'remove'] as const;
export type TakesMutation = typeof names[number];
export function isTakesMutation(value: string): value is TakesMutation { return (names as readonly string[]).includes(value); }
const USAGE_FIX = readFix('Prints every gbrain takes form with its flags.', { argv: ['gbrain', 'takes', '--help'] });
const invalid = (message: string, suggestion: string, fix: Action = USAGE_FIX) => opError('invalid_params', message, suggestion, { fix });
const REQUIRED_USAGE: Record<TakesMutation, string> = {
add: '--claim "..." --kind fact|take|bet|hunch --who HOLDER', update: '--row N', supersede: '--row N --claim "..."', resolve: '--row N --quality correct|incorrect|partial',
+ remove: '--row N',
};
export function parseTakesMutation(args: string[]): { operation: `takes_${TakesMutation}`; params: Record<string, unknown>; sourceId?: string; json: boolean } {
const [sub, slug, ...rest] = args;
- if (!isTakesMutation(sub) || !slug || slug.startsWith('-')) throw invalid('Usage: gbrain takes add|update|supersede|resolve <slug> [options].',
+ if (!isTakesMutation(sub) || !slug || slug.startsWith('-')) throw invalid('Usage: gbrain takes add|update|supersede|resolve|remove <slug> [options].',
isTakesMutation(sub) ? `Name the page slug right after takes ${sub}: gbrain takes ${sub} people/alice-example ${REQUIRED_USAGE[sub]}.`
: 'Start with the mutation and the page slug, e.g. gbrain takes add people/alice-example --claim "..." --kind take --who alice-example.');
const params: Record<string, unknown> = { slug };
@@ -65,6 +66,7 @@ export function parseTakesMutation(args: string[]): { operation: `takes_${TakesM
const allowed = sub === 'add' ? ['claim', 'kind', 'holder', 'weight', 'source', 'since']
: sub === 'update' ? ['row_num', 'weight', 'source', 'since']
: sub === 'supersede' ? ['row_num', 'claim', 'kind', 'holder', 'weight', 'source', 'since']
+ : sub === 'remove' ? ['row_num']
: ['row_num', 'quality', 'outcome', 'evidence', 'source', 'value', 'unit', 'resolved_by'];
const flagOf = (key: string) => Object.keys(fields).find(flag => fields[flag] === key) ?? `--${key}`;
for (const key of Object.keys(params)) if (![...common, ...allowed].includes(key)) throw invalid(`${key} is not supported by takes ${sub}.`,
@@ -106,6 +108,8 @@ export async function runTakesMutation(engine: BrainEngine | (() => Promise<Brai
const config = configOverride ?? loadConfig(), cli = getCliOptions();
let result: Record<string, unknown>;
if (isThinClient(config)) {
+ if (operation === 'takes_remove') throw invalid('takes remove runs only on the brain host.',
+ 'Run gbrain takes remove on the brain host; a remote connection cannot remove takes.');
if (args.some(arg => arg === '--outcome' || arg.startsWith('--outcome='))) console.error('[deprecated] --outcome is the v0.28 alias for --quality. Prefer --quality correct|incorrect|partial in new scripts.');
if (cli.brain || parsed.sourceId || params.local_dir !== undefined) throw invalid('--brain, --source-id, and --dir require a local brain host; the remote credential selects its source.',
'Drop --brain, --source-id and --dir on this thin client: the remote connection\'s credential selects the brain and source.',
@@ -139,6 +143,7 @@ export async function runTakesMutation(engine: BrainEngine | (() => Promise<Brai
if (operation === 'takes_add') console.log(`Added take #${row} to ${params.slug}.`);
else if (operation === 'takes_update') console.log(`Updated take #${row} on ${params.slug}.`);
else if (operation === 'takes_supersede') console.log(`Superseded #${result.old_row} → new #${result.new_row} on ${params.slug}.`);
+ else if (operation === 'takes_remove') console.log(`Removed take #${row} from ${params.slug}.`);
else console.log(`Resolved take #${row} on ${params.slug}: quality=${params.quality}.`);
}
} catch (error) {
diff --git a/src/commands/takes.ts b/src/commands/takes.ts
index b9e7970b8f..a820606acc 100644
--- a/src/commands/takes.ts
+++ b/src/commands/takes.ts
@@ -9,6 +9,8 @@
* takes update <slug> --row N ...flags — update mutable fields
* takes supersede <slug> --row N ... — strikethrough old + append new
* takes resolve <slug> --row N --outcome true|false [--value N --unit u]
+ * takes remove <slug> --row N — remove one row (fence + DB)
+ * takes rebuild <slug> [--source-id id] — rebuild one page's takes index from its fence
*
* Markdown is canonical. The four direct mutation commands use the same
* durable takes_* operations as MCP, via takes-mutation.ts. This dispatcher
@@ -381,13 +383,29 @@ async function cmdPropose(engine: BrainEngine, args: string[], sourceId: string)
configValue: await engine.getConfig('emotional_weight.user_holder'),
});
+ const editFlags = ['--claim', '--weight', '--who', '--kind'].filter(flag => flagPresent(args, flag));
+ if (editFlags.length && acceptRaw === undefined) {
+ console.error(`Error: ${editFlags.join(', ')} edit a proposal only together with --accept <id>.`);
+ process.exit(1);
+ }
if (acceptRaw !== undefined) {
const id = parseId(acceptRaw, '--accept');
const dirArg = flagValue(args, '--dir');
+ const weightRaw = flagValue(args, '--weight');
+ const weight = weightRaw === undefined ? undefined : Number(weightRaw);
+ if (weight !== undefined && (!Number.isFinite(weight) || weight < 0 || weight > 1)) {
+ console.error(`Invalid --weight "${weightRaw}". Expected a number from 0 to 1.`);
+ process.exit(1);
+ }
+ const kind = flagValue(args, '--kind');
+ if (kind !== undefined && !['fact', 'take', 'bet', 'hunch'].includes(kind)) {
+ console.error(`Invalid --kind "${kind}". Expected fact, take, bet or hunch.`);
+ process.exit(1);
+ }
const brainDir = await resolveBrainDir(engine, dirArg ?? null);
try {
const { proposal, rowNum } = await acceptProposal({ engine, brainDir, sourceId, actedBy, config: loadConfig() ?? { engine: 'pglite' },
- ...(dirArg ? { localDir: resolvePath(dirArg) } : {}) }, id);
+ ...(dirArg ? { localDir: resolvePath(dirArg) } : {}) }, id, { claim: flagValue(args, '--claim'), weight, holder: flagValue(args, '--who'), kind });
console.log(`Accepted proposal #${id} → take #${rowNum} on ${proposal.page_slug}.`);
} catch (err) {
if (err instanceof TakeProposalError) {
@@ -465,9 +483,13 @@ Subcommands:
[--evidence "..."] [--value N --unit usd|pct|count] [--by <slug>]
Record bet resolution (immutable, v0.30.0)
Back-compat: --outcome true|false (deprecated alias)
+ takes remove <slug> --row N Remove one take row from the fence and the DB (other row numbers stay)
+ takes rebuild <slug> [--source-id <id>] [--json]
+ Rebuild one page's takes index from its canonical fence
takes propose [--limit N] [--json] List pending LLM-proposed takes (propose_takes queue)
- takes propose --accept <id> [--dir <path>]
- Promote a proposal into the page's takes fence
+ takes propose --accept <id> [--dir <path>] [--claim "..."] [--weight 0.6] [--who <holder>] [--kind <k>]
+ Promote a proposal into the page's takes fence (source take_proposals#<id>;
+ edits mark it "(edited)" and the queue keeps the original text)
takes propose --reject <id> Dismiss a proposal
takes scorecard [<holder>] [--domain <prefix>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--json]
Aggregate calibration scorecard (v0.30.0)
@@ -496,7 +518,9 @@ Common flags:
case 'add':
case 'update':
case 'supersede':
- case 'resolve': { const { runTakesMutation } = await import('./takes-mutation.ts'); return runTakesMutation(engine, args); }
+ case 'resolve':
+ case 'remove': { const { runTakesMutation } = await import('./takes-mutation.ts'); return runTakesMutation(engine, args); }
+ case 'rebuild': return cmdRebuild(engine, rest);
// #2411: `takes propose` used to fall through to the slug path and print
// "No takes on propose." — the LLM proposal queue had no drain surface.
case 'propose': return cmdPropose(engine, rest, await resolveTakesSourceId(engine));
@@ -510,6 +534,32 @@ Common flags:
}
}
+/**
+ * #5167: `gbrain takes rebuild <slug> [--source-id <id>]` rebuilds one page's
+ * takes index from the canonical fence its page holds (trusted local CLI).
+ * Rows whose number and claim still match keep their resolution and vector;
+ * rows the index and the fence disagree on are re-inserted from the fence.
+ */
+async function cmdRebuild(engine: BrainEngine, rest: string[]): Promise<void> {
+ const slug = rest[0];
+ if (!slug || slug.startsWith('-')) {
+ process.stderr.write('Usage: gbrain takes rebuild <slug> [--source-id <id>] [--json]\n');
+ process.exit(1);
+ }
+ const sourceId = await resolveSourceId(engine, flagValue(rest, '--source-id') ?? null);
+ const { extractTakes } = await import('../core/cycle/extract-takes.ts');
+ const result = await extractTakes(engine, { source: 'db', slugs: [slug], sourceId, rebuild: true });
+ if (flagPresent(rest, '--json')) {
+ process.stdout.write(`${JSON.stringify({ slug, source_id: sourceId, ...result }, null, 2)}\n`);
+ } else if (result.pagesScanned === 0) {
+ process.stderr.write(`No page ${slug} in source ${sourceId}.\n`);
+ } else {
+ for (const warning of result.warnings) process.stderr.write(`[takes rebuild] ${warning}\n`);
+ console.log(`Rebuilt ${result.takesUpserted} take row(s) on ${slug} from its takes fence.`);
+ }
+ if (result.pagesScanned === 0 || result.warnings.length) process.exit(1);
+}
+
/**
* v0.41.18.0 (A12, A24, T9) — `gbrain takes extract --from-pages` runs
* Haiku over concept/atom/lore/briefing/writing/originals pages and
diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.ts
index 9fd7bcbb4c..c304c7c010 100644
--- a/src/core/cycle/extract-takes.ts
+++ b/src/core/cycle/extract-takes.ts
@@ -8,9 +8,12 @@
* timeline; parse fence; batch upsert
*
* Source-of-truth contract: markdown is canonical. The takes table is a
- * derived index. `gbrain extract takes --rebuild` deletes all takes for
- * the affected pages first, then re-inserts. Without --rebuild, ON CONFLICT
- * (page_id, row_num) DO UPDATE keeps the table in sync incrementally.
+ * derived index. `gbrain takes rebuild <slug>` (rebuild) first deletes every
+ * indexed row whose (row_num, claim) is not in the page's fence, so a row the
+ * index and the fence disagree on is re-inserted fresh, while a row whose
+ * claim is unchanged keeps its resolution and vector (#5167). Without
+ * rebuild, ON CONFLICT (page_id, row_num) DO UPDATE keeps the table in sync
+ * incrementally.
* On a managed brain the db path publishes each page's rows through the
* persistence coordinator (the `takes` guard refuses any other writer).
*
@@ -43,8 +46,10 @@ export interface ExtractTakesOpts {
slugs?: string[];
/** Dry-run: parse + count, don't write. */
dryRun?: boolean;
- /** When true, deletes existing takes for affected pages first. */
+ /** When true, first deletes each affected page's indexed rows whose (row_num, claim) left its fence. */
rebuild?: boolean;
+ /** db path: only pages of this source (default: every source holding the slug). */
+ sourceId?: string;
}
export interface ExtractTakesResult {
@@ -103,6 +108,13 @@ async function pruneRemovedTakes(
);
}
+/** Rebuild: drop indexed rows the fence no longer carries with the same claim; rows that still match keep resolution and vector. */
+async function deleteDivergedTakes(engine: BrainEngine, pageId: number, takes: ParsedTake[]): Promise<void> {
+ await engine.executeRaw(`DELETE FROM takes WHERE page_id = $1 AND NOT EXISTS (
+ SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) AS f(row_num int, claim text) WHERE f.row_num = takes.row_num AND f.claim = takes.claim)`,
+ [pageId, JSON.stringify(takes.map(t => ({ row_num: t.rowNum, claim: t.claim })))]);
+}
+
function parsedTakeToBatchInput(pageId: number, t: ParsedTake): TakeBatchInput {
return {
page_id: pageId,
@@ -187,9 +199,7 @@ export async function extractTakesFromFs(
await pruneRemovedTakes(engine, pageId, body, takes, warnings, dryRun);
if (takes.length === 0) continue;
- if (opts.rebuild && !dryRun) {
- await engine.executeRaw(`DELETE FROM takes WHERE page_id = $1`, [pageId]);
- }
+ if (opts.rebuild && !dryRun) await deleteDivergedTakes(engine, pageId, takes);
result.pagesWithTakes++;
for (const t of takes) {
@@ -214,7 +224,7 @@ export async function extractTakesFromFs(
*/
export async function extractTakesFromDb(
engine: BrainEngine,
- opts: { slugs?: string[]; dryRun?: boolean; rebuild?: boolean } = {},
+ opts: { slugs?: string[]; dryRun?: boolean; rebuild?: boolean; sourceId?: string } = {},
): Promise<ExtractTakesResult> {
const result: ExtractTakesResult = {
pagesScanned: 0, pagesWithTakes: 0, takesUpserted: 0, warnings: [], failedFiles: [],
@@ -224,7 +234,7 @@ export async function extractTakesFromDb(
// Every (slug, source_id) pair across all sources; bare slugs re-extract
// the page in every source that holds that slug.
const slugFilter = opts.slugs && opts.slugs.length > 0 ? new Set(opts.slugs) : null;
- const refs = (await engine.listAllPageRefs()).filter(ref => !slugFilter || slugFilter.has(ref.slug));
+ const refs = (await engine.listAllPageRefs()).filter(ref => (!slugFilter || slugFilter.has(ref.slug)) && (!opts.sourceId || ref.source_id === opts.sourceId));
const buffer: TakeBatchInput[] = [];
const coordinated = !dryRun && await managedPersistenceEnabled(engine);
@@ -276,9 +286,7 @@ async function reconcilePageTakes(
}
await pruneRemovedTakes(db, page.id, body, takes, warnings, dryRun);
if (takes.length === 0) return [];
- if (rebuild && !dryRun) {
- await db.executeRaw(`DELETE FROM takes WHERE page_id = $1`, [page.id]);
- }
+ if (rebuild && !dryRun) await deleteDivergedTakes(db, page.id, takes);
result.pagesWithTakes++;
return takes;
}
@@ -330,6 +338,7 @@ export async function extractTakes(
slugs: opts.slugs,
dryRun: opts.dryRun,
rebuild: opts.rebuild,
+ sourceId: opts.sourceId,
});
}
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index e46351748f..320213984b 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -442,7 +442,7 @@ export const CLIENT_FENCED_WRITE_OPS: ReadonlySet<string> = new Set([
// Own-principal receipt controls recheck original/current source + slug
// authority. They are not meta-op exemptions: degraded fences still deny.
'get_write_request', 'list_write_requests', 'cancel_write_request',
- 'takes_add', 'takes_update', 'takes_resolve', 'takes_supersede',
+ 'takes_add', 'takes_update', 'takes_resolve', 'takes_supersede', 'takes_remove',
'put_skill', 'delete_skill',
]);
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 3850266207..5284f87a6e 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -482,11 +482,38 @@ const takes_resolve: Operation = {
},
};
+const takes_remove: Operation = {
+ name: 'takes_remove',
+ idempotent: true,
+ outputRedaction: 'no_stored_text',
+ description:
+ 'Remove one take row from a page\'s takes fence and the takes table together (#5167). Local-only. ' +
+ 'Other rows keep their numbers. Refuses a resolved row, a row another row cites as "superseded by" it, ' +
+ 'and a row whose database copy disagrees with the fence (run `gbrain takes rebuild <slug>` first). ' +
+ 'CLI: `gbrain takes remove <slug> --row N`.',
+ params: {
+ request_id: WRITE_REQUEST_PARAM,
+ local_dir: { type: 'string', description: 'Trusted CLI directory hint; must equal the registered source root.' },
+ slug: { type: 'string', required: true, description: 'Page slug.' },
+ row_num: { type: 'number', required: true, description: 'Take row number to remove (from takes_list).' },
+ },
+ scope: 'write',
+ mutating: true,
+ localOnly: true,
+ area: 'takes',
+ handler: async (ctx, p) => {
+ const slug = p.slug as string;
+ validatePageSlug(slug);
+ if (ctx.dryRun) return { dry_run: true, action: 'takes_remove', slug, row_num: p.row_num };
+ return submitPageMutation(ctx, { operation: 'takes_remove', params: p });
+ },
+};
+
// Ops in EXACTLY the canonical `operations` array order: the v0.28 trio
// (takes_list, takes_search, think), the v0.30 calibration aggregates, then
// the gap-closure write verbs.
export const takesOperations: Operation[] = [
takes_list, takes_search, think,
takes_scorecard, takes_calibration,
- takes_add, takes_update, takes_resolve, takes_supersede,
+ takes_add, takes_update, takes_resolve, takes_supersede, takes_remove,
];
diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.ts
index 8d897dc3fb..3ddf613dfe 100644
--- a/src/core/persistence/ipc.ts
+++ b/src/core/persistence/ipc.ts
@@ -23,14 +23,14 @@ export const PERSISTENCE_IPC_OPERATIONS = [
'put_skill', 'delete_skill', 'join_brain', 'sync_brain_skills', 'leave_brain',
'get_skill_policy', 'set_skill_policy', 'get_skill_retention', 'prune_skill_revisions',
'retain_skill_revision', 'import_skill_proposal',
- 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve',
+ 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove',
] as const;
export type PersistenceIpcOperation = typeof PERSISTENCE_IPC_OPERATIONS[number];
const OPERATIONS = new Set<string>(PERSISTENCE_IPC_OPERATIONS);
const MUTATIONS = new Set<string>([
'put_page', 'put_pages', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page', 'remember', 'forget', 'extract_facts',
'put_skill', 'delete_skill', 'import_skill_proposal',
- 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve',
+ 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove',
]);
export interface PersistenceIpcRegistration {
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 140958c213..2c0884154f 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -195,7 +195,7 @@ export async function preparePageAdmission(ctx: OperationContext,
`Source ${sourceId} is archived or not registered, so nothing was written. Write to an active source (sources_list shows them).`);
}
let slug = typeof p.slug === 'string' ? p.slug.toLowerCase() : '';
- const intent = ['takes_add','takes_update','takes_supersede','takes_resolve'].includes(input.operation)
+ const intent = ['takes_add','takes_update','takes_supersede','takes_resolve','takes_remove'].includes(input.operation)
? await (await import('./takes-prepare.ts')).normalizeTakesIntent(ctx,p) : { ...p };
delete intent.request_id;
if (input.operation === 'put_page') await normalizeSubagentPageInput(ctx, intent);
diff --git a/src/core/persistence/semantic.ts b/src/core/persistence/semantic.ts
index db22482740..18002ad6da 100644
--- a/src/core/persistence/semantic.ts
+++ b/src/core/persistence/semantic.ts
@@ -1,6 +1,6 @@
import type { WriteRequest } from './model.ts';
export const SEMANTIC_PAGE_OPERATIONS: ReadonlySet<string> = new Set([
- 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'remember',
+ 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove', 'remember',
]);
/** Recompute only supported merges; caller-supplied stale replacements remain conflicts. */
export function mayReprepare(row: WriteRequest, error: { code?: string }): boolean {
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 7ae6891c6e..4c60a5587f 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -71,7 +71,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest
if (row.operation === 'loops_close' && row.intent?.kind === 'retire_loop_fact') return (await import('./loop-fact-retirement.ts')).prepareLoopFactRetirement(e, row, cfg);
if (row.operation === 'decide_proposal') return (await import('../facts/proposal-supersede.ts')).prepareProposalMutation(e, row, cfg);
if (row.operation === 'relink_facts') return (await import('../facts/relink-publish.ts')).prepareRelinkMutation(e, row, cfg);
- if (['takes_add','takes_update','takes_supersede','takes_resolve'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);
+ if (['takes_add','takes_update','takes_supersede','takes_resolve','takes_remove'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);
if (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);
if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal);
throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);
diff --git a/src/core/persistence/takes-prepare.ts b/src/core/persistence/takes-prepare.ts
index 0d263f5f2d..a6bbeb7ab4 100644
--- a/src/core/persistence/takes-prepare.ts
+++ b/src/core/persistence/takes-prepare.ts
@@ -70,6 +70,7 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
let changed: ParsedTake[] = [];
let result: Record<string, unknown>;
let oldRow: number | undefined;
+ let removedRow: number | undefined;
if (row.operation === 'takes_add') {
if (typeof p.claim !== 'string' || !p.claim.trim() || typeof p.kind !== 'string' || typeof p.holder !== 'string') throw takesRefusal('invalid_params','claim, kind and holder are required.',row,
'takes_add needs claim, kind and holder as non-empty text.');
@@ -85,8 +86,18 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
const target=edit.findFenceRow(parsed.takes,number,holders,row.slug);
requiredHolders.add(target.holder);
if (target.resolvedAt) throw new TakesWriteError('already_resolved','Resolved takes are immutable.');
- if (!target.active) throw new TakesWriteError('row_inactive','The take was superseded.');
- if (row.operation==='takes_supersede') {
+ if (row.operation==='takes_remove') {
+ const citing=parsed.takes.find(t=>t.rowNum!==number && Number(t.source?.match(/superseded by #(\d+)/)?.[1])===number);
+ if (citing) throw takesRefusal('invalid_params',`Row #${number} replaces row #${citing.rowNum}.`,row,
+ `Row #${citing.rowNum} on ${row.slug} cites row #${number} as "superseded by #${number}"; remove row #${citing.rowNum} first, or keep both.`);
+ const [stored]=await engine.executeRaw<{claim:string}>('SELECT claim FROM takes WHERE page_id=$1 AND row_num=$2',[snapshot.page.id,number]);
+ if (stored && stored.claim!==target.claim) throw takesRefusal('invalid_params',`Row #${number}'s database copy disagrees with the page's takes fence; run gbrain takes rebuild ${row.slug} --source-id ${row.source_id} first.`,row,
+ `Rebuild the page's takes index from its fence first with gbrain takes rebuild ${row.slug} --source-id ${row.source_id}, check the row, then remove it again.`);
+ removedRow=number;
+ next=edit.replaceFence(body,parsed.takes.filter(t=>t.rowNum!==number));
+ result={slug:row.slug,row_num:number,removed:true};
+ } else if (!target.active) throw new TakesWriteError('row_inactive','The take was superseded.');
+ else if (row.operation==='takes_supersede') {
if (typeof p.claim!=='string' || !p.claim.trim()) throw takesRefusal('invalid_params','claim is required.',row,
'takes_supersede needs the replacement claim as non-empty text.');
const holder=typeof p.holder==='string'?p.holder:target.holder;
@@ -112,7 +123,7 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
resolvedEvidence:p.evidence as string | undefined,resolvedValue:p.value as number | undefined,
resolvedUnit:p.unit as string | undefined,resolvedBy:String(p.resolved_by)};
} else throw takesRefusal('invalid_params','Unsupported takes mutation.',row,
- `${row.operation} is not a takes mutation this release can publish (takes_add, takes_update, takes_supersede or takes_resolve).`);
+ `${row.operation} is not a takes mutation this release can publish (takes_add, takes_update, takes_supersede, takes_resolve or takes_remove).`);
changed=[updated]; next=edit.replaceFence(body,parsed.takes.map(t=>t.rowNum===number?updated:t));
result={slug:row.slug,row_num:number,...(row.operation==='takes_resolve'?{quality:p.quality,resolved_by:p.resolved_by}:{})};
}
@@ -130,7 +141,8 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
if (!prepared.noop) {
const batch:TakeBatchInput[]=changed.map(t=>edit.toBatchInput(snapshot.page.id,t,
t.rowNum===oldRow?Number(result.new_row):null));
- await tx.addTakesBatch(batch);
+ if (batch.length) await tx.addTakesBatch(batch);
+ if (removedRow!==undefined) await tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=$2',[snapshot.page.id,removedRow]);
if (row.operation==='takes_resolve') {
const t=changed[0];
await tx.resolveTake(snapshot.page.id,t.rowNum,{quality:t.resolvedQuality!,outcome:t.resolvedOutcome,
diff --git a/src/core/take-proposals.ts b/src/core/take-proposals.ts
index d65eea1be4..a610b7462d 100644
--- a/src/core/take-proposals.ts
+++ b/src/core/take-proposals.ts
@@ -171,6 +171,9 @@ export interface ProposalActionTarget {
localDir?: string;
}
+/** #5214: reviewer edits applied over the proposal at accept; the queue row keeps the original text. */
+export interface ProposalEdits { claim?: string; weight?: number; holder?: string; kind?: string }
+
/**
* One write request per claim: derived from the proposal id and the claim's
* acted_at, so resuming a claimed-but-unrecorded accept replays the same
@@ -208,6 +211,7 @@ async function promoteProposalViaTakesAdd(
target: ProposalActionTarget,
proposal: TakeProposalRow,
requestId: string,
+ edits: ProposalEdits,
): Promise<number> {
const ctx: OperationContext = {
engine: target.engine,
@@ -217,12 +221,14 @@ async function promoteProposalViaTakesAdd(
dryRun: false,
logger: { info: message => console.error(message), warn: message => console.error(message), error: message => console.error(message) },
};
+ const edited = Object.values(edits).some(value => value !== undefined);
const params: Record<string, unknown> = {
slug: proposal.page_slug,
- claim: proposal.claim_text,
- kind: coerceProposalKind(proposal.kind),
- holder: proposal.holder,
- weight: typeof proposal.weight === 'number' ? proposal.weight : Number(proposal.weight),
+ claim: edits.claim ?? proposal.claim_text,
+ kind: edits.kind ?? coerceProposalKind(proposal.kind),
+ holder: edits.holder ?? proposal.holder,
+ weight: edits.weight ?? (typeof proposal.weight === 'number' ? proposal.weight : Number(proposal.weight)),
+ source: `take_proposals#${proposal.id}${edited ? ' (edited)' : ''}`,
source_id: proposal.source_id,
request_id: requestId,
...(target.localDir !== undefined ? { local_dir: target.localDir } : {}),
@@ -246,6 +252,7 @@ async function promoteProposalViaTakesAdd(
export async function acceptProposal(
target: ProposalActionTarget,
id: number,
+ edits: ProposalEdits = {},
): Promise<{ proposal: TakeProposalRow; rowNum: number }> {
const { engine } = target;
const proposal = await loadProposal(engine, id, target.sourceId, { allowStranded: true });
@@ -303,7 +310,7 @@ export async function acceptProposal(
// The row's OWN source, never the caller's, is what promoteProposalViaTakesAdd
// scopes the mutation to — the scoped load above already proved they agree
// when a caller scope was provided.
- rowNum = await promoteProposalViaTakesAdd(target, proposal, requestId);
+ rowNum = await promoteProposalViaTakesAdd(target, proposal, requestId, edits);
} catch (e) {
// Release the claim only when its write provably cannot commit: no
// durable request was admitted, or every one settled without committing.
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index e4859bb227..6930c0575e 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 203079,
- "stdoutSha256": "3f2a347db6f4a41890023a83565e4a811e9fb1127b881fad419a24f3365f3d21",
+ "stdoutBytes": 204379,
+ "stdoutSha256": "0a92173c7d03c33fa0d630a5aefacdfc0209b52802129b7b75a761c424aa0bfc",
"toolNames": [
"remember",
"entity",
@@ -102,6 +102,7 @@
"takes_update",
"takes_resolve",
"takes_supersede",
+ "takes_remove",
"whoami",
"sources_add",
"sources_list",
@@ -4202,6 +4203,46 @@
},
"scope": "write"
},
+ {
+ "description": "Remove one take row from a page's takes fence and the takes table together (#5167). Local-only. Other rows keep their numbers. Refuses a resolved row, a row another row cites as \"superseded by\" it, and a row whose database copy disagrees with the fence (run `gbrain takes rebuild <slug>` first). CLI: `gbrain takes remove <slug> --row N`.",
+ "idempotent": true,
+ "local_only": true,
+ "mutating": true,
+ "name": "takes_remove",
+ "parameters": {
+ "local_dir": "string?",
+ "request_id": "string?",
+ "row_num": "number",
+ "slug": "string"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "local_dir": {
+ "description": "Trusted CLI directory hint; must equal the registered source root.",
+ "type": "string"
+ },
+ "request_id": {
+ "description": "UUID; retry with it on timeout.",
+ "type": "string"
+ },
+ "row_num": {
+ "description": "Take row number to remove (from takes_list).",
+ "type": "number"
+ },
+ "slug": {
+ "description": "Page slug.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "slug",
+ "row_num"
+ ],
+ "type": "object"
+ },
+ "scope": "write"
+ },
{
"description": "Your identity: transport, scopes and, over OAuth, client, source_id and federated_read.",
"idempotent": true,
diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.ts
index efdb219dbc..2c470faf3f 100644
--- a/test/operations-coverage-ledger.test.ts
+++ b/test/operations-coverage-ledger.test.ts
@@ -120,6 +120,7 @@ const LEDGER: Record<string, string> = {
takes_update: 'test/takes-write-ops.test.ts',
takes_resolve: 'test/takes-write-ops.test.ts',
takes_supersede: 'test/takes-write-ops.test.ts',
+ takes_remove: 'test/takes-verbs-5167-5214.test.ts',
whoami: 'test/whoami.test.ts',
sources_add: 'test/sources-mcp.test.ts',
sources_list: 'test/sources-mcp.test.ts',
diff --git a/test/takes-verbs-5167-5214.test.ts b/test/takes-verbs-5167-5214.test.ts
new file mode 100644
index 0000000000..f9b0b2a9a9
--- /dev/null
+++ b/test/takes-verbs-5167-5214.test.ts
@@ -0,0 +1,150 @@
+/**
+ * #5167: `gbrain takes rebuild <slug>` rebuilds one page's takes index from its
+ * canonical fence; `gbrain takes remove <slug> --row N` removes one row from the
+ * fence and the index together (other row numbers unchanged) and refuses when
+ * they disagree. #5214: an accepted proposal records `take_proposals#<id>` as
+ * its source, and an edited accept records the overrides with
+ * `take_proposals#<id> (edited)` while the queue keeps the original text.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall as dispatch } from '../src/mcp/dispatch.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { parseTakesFence } from '../src/core/takes-fence.ts';
+import { extractTakes } from '../src/core/cycle/extract-takes.ts';
+import { acceptProposal } from '../src/core/take-proposals.ts';
+import { operations } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+let repo: string;
+let cli: LocalRegistration;
+const config = { engine: 'pglite' as const, embedding_disabled: true };
+
+async function call(operation: string, params: Record<string, unknown>) {
+ const result = await withVerifiedLocalRegistration(engine, cli,
+ () => dispatch(engine, operation, { request_id: randomUUID(), ...params }, { config, remote: false, sourceId: 'default' }));
+ return { error: result.isError ?? false, body: JSON.parse(result.content[0].text) };
+}
+/** The trusted local path `gbrain takes remove` takes (takes_remove is local-only, never an MCP tool). */
+async function local(operation: string, params: Record<string, unknown>) {
+ const op = operations.find(candidate => candidate.name === operation)!;
+ try {
+ const body = await withVerifiedLocalRegistration(engine, cli, () => op.handler({ engine, config, remote: false, sourceId: 'default', dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } }, { request_id: randomUUID(), ...params }));
+ return { error: false, body: body as Record<string, unknown> };
+ } catch (error) {
+ return { error: true, body: { code: (error as { code?: string }).code, message: (error as Error).message, suggestion: (error as { suggestion?: string }).suggestion } };
+ }
+}
+async function seed(slug: string) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `about ${slug}` }, { sourceId: 'default' });
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const path = join(repo, `${slug}.md`);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, serializePageToMarkdown(snapshot.page, snapshot.tags), 'utf8');
+}
+const fence = (slug: string) => parseTakesFence(readFileSync(join(repo, `${slug}.md`), 'utf8')).takes;
+async function rows(slug: string) {
+ return engine.executeRaw<{ row_num: number; claim: string; source: string | null }>(
+ "SELECT t.row_num, t.claim, t.source FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.slug=$1 ORDER BY t.row_num", [slug]);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ cli = await registerLocalWriter(engine, 'cli');
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-takes-verbs-'));
+ await engine.setConfig('sync.repo_path', repo);
+ for (const slug of ['notes/rebuild', 'notes/remove', 'notes/accept']) await seed(slug);
+});
+afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ rmSync(repo, { recursive: true, force: true });
+});
+
+describe('takes rebuild (#5167)', () => {
+ test('restores the page index from its fence and keeps rows whose claim is unchanged', async () => {
+ for (const claim of ['First claim', 'Second claim']) {
+ expect((await call('takes_add', { slug: 'notes/rebuild', claim, kind: 'take', holder: 'world' })).error).toBe(false);
+ }
+ await engine.executeRaw("UPDATE takes SET claim='Drifted claim', resolved_quality=NULL WHERE row_num=2 AND page_id=(SELECT id FROM pages WHERE slug='notes/rebuild')");
+ await engine.executeRaw("UPDATE takes SET embedded_text_hash='kept' WHERE row_num=1 AND page_id=(SELECT id FROM pages WHERE slug='notes/rebuild')");
+ const result = await extractTakes(engine, { source: 'db', slugs: ['notes/rebuild'], sourceId: 'default', rebuild: true });
+ expect(result.warnings).toEqual([]);
+ expect((await rows('notes/rebuild')).map(row => [row.row_num, row.claim])).toEqual([[1, 'First claim'], [2, 'Second claim']]);
+ const [kept] = await engine.executeRaw<{ embedded_text_hash: string | null }>(
+ "SELECT embedded_text_hash FROM takes WHERE row_num=1 AND page_id=(SELECT id FROM pages WHERE slug='notes/rebuild')");
+ expect(kept.embedded_text_hash).toBe('kept');
+ });
+});
+
+describe('takes remove (#5167)', () => {
+ test('removes one row from the fence and the index; other row numbers stay', async () => {
+ for (const claim of ['Keep one', 'Drop me', 'Keep three']) {
+ expect((await call('takes_add', { slug: 'notes/remove', claim, kind: 'take', holder: 'world' })).error).toBe(false);
+ }
+ const removed = await local('takes_remove', { slug: 'notes/remove', row_num: 2 });
+ expect(removed.error).toBe(false);
+ expect(removed.body).toMatchObject({ row_num: 2, removed: true });
+ expect(fence('notes/remove').map(t => [t.rowNum, t.claim])).toEqual([[1, 'Keep one'], [3, 'Keep three']]);
+ expect((await rows('notes/remove')).map(row => [row.row_num, row.claim])).toEqual([[1, 'Keep one'], [3, 'Keep three']]);
+ });
+
+ test('refuses when the index disagrees with the fence and names takes rebuild', async () => {
+ await engine.executeRaw("UPDATE takes SET claim='Not what the fence says' WHERE row_num=3 AND page_id=(SELECT id FROM pages WHERE slug='notes/remove')");
+ const refused = await local('takes_remove', { slug: 'notes/remove', row_num: 3 });
+ expect(refused.error).toBe(true);
+ expect(JSON.stringify(refused.body)).toContain('gbrain takes rebuild notes/remove');
+ expect(fence('notes/remove').map(t => t.rowNum)).toEqual([1, 3]);
+ });
+
+ test('refuses a row another row cites as its replacement', async () => {
+ expect((await call('takes_supersede', { slug: 'notes/remove', row_num: 1, claim: 'Keep one, revised' })).error).toBe(false);
+ const replacement = fence('notes/remove').find(t => t.claim === 'Keep one, revised')!;
+ const refused = await local('takes_remove', { slug: 'notes/remove', row_num: replacement.rowNum });
+ expect(refused.error).toBe(true);
+ expect(refused.body.message).toContain(`replaces row #1`);
+ expect(fence('notes/remove').some(t => t.rowNum === replacement.rowNum)).toBe(true);
+ });
+
+ test('is local-only: no MCP caller can remove takes', async () => {
+ expect(operations.find(candidate => candidate.name === 'takes_remove')?.localOnly).toBe(true);
+ const result = await withVerifiedLocalRegistration(engine, cli, () => dispatch(engine, 'takes_remove',
+ { request_id: randomUUID(), slug: 'notes/remove', row_num: 1 }, { config, remote: true, transport: 'stdio', sourceId: 'default', takesHoldersAllowList: ['world'] }));
+ expect(result.isError).toBe(true);
+ });
+});
+
+describe('takes propose --accept provenance (#5214)', () => {
+ async function propose(claim: string): Promise<number> {
+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO take_proposals
+ (source_id, page_slug, content_hash, prompt_version, proposal_run_id, claim_text, kind, holder, weight, domain, model_id, status)
+ VALUES ('default', 'notes/accept', md5($1), 'test-v1', 'run-test', $1, 'bet', 'world', 0.7, NULL, 'test-model', 'pending') RETURNING id`, [claim]);
+ return row.id;
+ }
+ const target = () => ({ engine, brainDir: repo, sourceId: 'default', actedBy: 'people/tester', config });
+
+ test('a plain accept records take_proposals#<id> as the take source', async () => {
+ const id = await propose('Plain proposal claim');
+ const { rowNum } = await acceptProposal(target(), id);
+ expect(fence('notes/accept').find(t => t.rowNum === rowNum)?.source).toBe(`take_proposals#${id}`);
+ expect((await rows('notes/accept')).find(row => row.row_num === rowNum)?.source).toBe(`take_proposals#${id}`);
+ });
+
+ test('an edited accept applies the overrides, marks the source edited, and keeps the original proposal text', async () => {
+ const id = await propose('Original proposal claim');
+ const { rowNum } = await acceptProposal(target(), id, { claim: 'Edited claim text', weight: 0.4, kind: 'take', holder: 'world' });
+ const take = fence('notes/accept').find(t => t.rowNum === rowNum)!;
+ expect([take.claim, take.weight, take.kind, take.source]).toEqual(['Edited claim text', 0.4, 'take', `take_proposals#${id} (edited)`]);
+ const [queued] = await engine.executeRaw<{ claim_text: string; status: string }>('SELECT claim_text, status FROM take_proposals WHERE id=$1', [id]);
+ expect(queued).toEqual({ claim_text: 'Original proposal claim', status: 'accepted' });
+ });
+});