@theronap/agnoclast-mcp 0.9.308 → 0.9.310
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/page_nudge.mjs +64 -11
- package/lib/record_render.mjs +4 -0
- package/lib/release_gate.mjs +1 -1
- package/lib/server.mjs +111 -9
- package/lib/split_render.mjs +88 -0
- package/package.json +1 -1
package/lib/page_nudge.mjs
CHANGED
|
@@ -8,20 +8,35 @@
|
|
|
8
8
|
//
|
|
9
9
|
// Self-contained (Node built-ins only): setup copies it to ~/.cortex/hooks/page-nudge.mjs and the hook runs it with
|
|
10
10
|
// plain `node`, since it fires on every Bash and edit call.
|
|
11
|
-
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
|
|
11
|
+
import { readFileSync, writeFileSync, mkdirSync, openSync, readSync, fstatSync, closeSync } from 'node:fs'
|
|
12
12
|
import { homedir } from 'node:os'
|
|
13
13
|
import { join, dirname, basename } from 'node:path'
|
|
14
14
|
import { createHash } from 'node:crypto'
|
|
15
15
|
|
|
16
16
|
export const STRETCH = 40
|
|
17
|
+
const TAIL_BYTES = 2_000_000
|
|
18
|
+
const NAMED = 3
|
|
17
19
|
|
|
20
|
+
// Each must start a command (line start, or after ; & | ( { or $( ), so a name inside an echo or a test does not count.
|
|
21
|
+
const AT = String.raw`(?:^|[;&|({\n]|\$\()\s*(?:cd\s+\S+\s*&&\s*)?`
|
|
18
22
|
const SHIP = [
|
|
19
|
-
[
|
|
20
|
-
[
|
|
21
|
-
[
|
|
22
|
-
[
|
|
23
|
-
[
|
|
23
|
+
[new RegExp(`${AT}gh\\s+pr\\s+merge\\b`), 'a pull request merged'],
|
|
24
|
+
[new RegExp(`${AT}npm\\s+publish\\b`), 'a package was published'],
|
|
25
|
+
[new RegExp(`${AT}vercel\\b[^\\n;&|]*\\s--prod\\b`), 'a production deploy ran'],
|
|
26
|
+
[new RegExp(`${AT}(?:npx\\s+)?wrangler\\s+(?:deploy|publish)\\b`), 'a deploy ran'],
|
|
27
|
+
[new RegExp(`${AT}fly(?:ctl)?\\s+deploy\\b`), 'a deploy ran'],
|
|
24
28
|
]
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* PURE. A shell command with heredoc bodies and quoted strings blanked, so only what it runs is left. On 2026-11-04
|
|
32
|
+
* a heredoc writing a test that mentioned `gh pr merge` was taken for a merge.
|
|
33
|
+
*/
|
|
34
|
+
export function commandText(cmd) {
|
|
35
|
+
return String(cmd)
|
|
36
|
+
.replace(/<<-?\s*(['"]?)(\w+)\1[^\n]*\n[\s\S]*?\n\s*\2(?=\s|$)/g, ' ')
|
|
37
|
+
.replace(/'[^']*'/g, "''")
|
|
38
|
+
.replace(/"(?:[^"\\]|\\.)*"/g, '""')
|
|
39
|
+
}
|
|
25
40
|
const SPEC_DIR = /\/(?:docs|specs?|plans?|designs?|rfcs?)\/(?:[^/]+\/)*[^/]+\.md$/i
|
|
26
41
|
const NOT_SPEC = /^(?:readme|changelog|claude|agents|license|contributing|security|code_of_conduct)\.md$/i
|
|
27
42
|
const PAGE_WRITE = /__(?:edit_page|author)$/
|
|
@@ -33,7 +48,8 @@ export function nudgeDecision({ tool, input = {}, state = {} }) {
|
|
|
33
48
|
if (!WORK.has(tool)) return null
|
|
34
49
|
if (tool === 'Bash') {
|
|
35
50
|
const cmd = String(input.command ?? '')
|
|
36
|
-
|
|
51
|
+
const run = commandText(cmd)
|
|
52
|
+
if (!/--dry-run\b/.test(run)) for (const [re, what] of SHIP) if (re.test(run)) return { kind: 'ship', key: `ship:${cmd.slice(0, 200)}`, what, cmd }
|
|
37
53
|
} else {
|
|
38
54
|
const path = String(input.file_path ?? '')
|
|
39
55
|
if (SPEC_DIR.test(path) && !NOT_SPEC.test(basename(path)) && !/\/node_modules\//.test(path)) return { kind: 'spec', key: `spec:${path}`, path }
|
|
@@ -42,11 +58,47 @@ export function nudgeDecision({ tool, input = {}, state = {} }) {
|
|
|
42
58
|
return { count: true }
|
|
43
59
|
}
|
|
44
60
|
|
|
61
|
+
/**
|
|
62
|
+
* PURE. The pages a session read or wrote, most recent first, from the tail of its transcript. A nudge that names
|
|
63
|
+
* no page was ignored the first time it fired (2026-11-04); naming the pages makes acting on it one call.
|
|
64
|
+
*/
|
|
65
|
+
export function recentPages(text, limit = NAMED) {
|
|
66
|
+
const seen = []
|
|
67
|
+
for (const line of text.split('\n').reverse()) {
|
|
68
|
+
if (!/__(?:read_page|edit_page|author)"/.test(line)) continue
|
|
69
|
+
let d
|
|
70
|
+
try { d = JSON.parse(line) } catch { continue }
|
|
71
|
+
const blocks = Array.isArray(d.message?.content) ? d.message.content : []
|
|
72
|
+
for (const b of [...blocks].reverse()) {
|
|
73
|
+
const name = b.type === 'tool_use' && /__(?:read_page|edit_page|author)$/.test(b.name) ? b.input?.name : null
|
|
74
|
+
if (typeof name === 'string' && name && !seen.includes(name)) seen.push(name)
|
|
75
|
+
if (seen.length >= limit) return seen
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return seen
|
|
79
|
+
}
|
|
80
|
+
|
|
45
81
|
/** PURE. The line the session reads: facts and options, never orders. */
|
|
46
|
-
export function nudgeLine(d) {
|
|
47
|
-
|
|
82
|
+
export function nudgeLine(d, pages = []) {
|
|
83
|
+
const named = pages.length
|
|
84
|
+
? `Pages this session read or edited: ${pages.map((p) => `"${p}"`).join(', ')}. If the work made one of them stale, edit_page it now, while the details are in front of you.`
|
|
85
|
+
: 'This session has not opened an Agnoclast page; if the work belongs on one, grep for it and bring it current with edit_page.'
|
|
86
|
+
if (d.kind === 'ship') return `Agnoclast note: ${d.what} (\`${d.cmd.trim().slice(0, 80)}\`). ${named}`
|
|
48
87
|
if (d.kind === 'spec') return `Agnoclast note: ${basename(d.path)} looks like a plan or spec, and on disk only this repo can see it. If it is one, it can live on a page (author), or the page it belongs to can link it, so teammates and later sessions find it.`
|
|
49
|
-
return `Agnoclast note: ${d.count} edits and commands since this session last wrote a page.
|
|
88
|
+
return `Agnoclast note: ${d.count} edits and commands since this session last wrote a page. ${named}`
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The last TAIL_BYTES of a file, or '' if it cannot be read. */
|
|
92
|
+
function tail(path) {
|
|
93
|
+
let fd
|
|
94
|
+
try {
|
|
95
|
+
fd = openSync(path, 'r')
|
|
96
|
+
const size = fstatSync(fd).size
|
|
97
|
+
const len = Math.min(size, TAIL_BYTES)
|
|
98
|
+
const buf = Buffer.alloc(len)
|
|
99
|
+
readSync(fd, buf, 0, len, size - len)
|
|
100
|
+
return buf.toString('utf8')
|
|
101
|
+
} catch { return '' } finally { if (fd !== undefined) try { closeSync(fd) } catch {} }
|
|
50
102
|
}
|
|
51
103
|
|
|
52
104
|
const statePath = (home, sessionId) =>
|
|
@@ -69,7 +121,8 @@ export function runPageNudge({ input, home = homedir(), env = process.env }) {
|
|
|
69
121
|
const next = { ...state, sinceWrite: d.kind === 'stretch' ? 0 : sinceWrite, nudged: { ...state.nudged, [d.key]: true } }
|
|
70
122
|
if (d.kind === 'stretch') next.stretches = (state.stretches ?? 0) + 1
|
|
71
123
|
save(file, next)
|
|
72
|
-
|
|
124
|
+
const pages = d.kind === 'spec' || !p.transcript_path ? [] : recentPages(tail(p.transcript_path))
|
|
125
|
+
return { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: nudgeLine(d, pages) } }
|
|
73
126
|
}
|
|
74
127
|
|
|
75
128
|
function save(file, state) {
|
package/lib/record_render.mjs
CHANGED
|
@@ -69,6 +69,10 @@ export function renderRecord(rec, maxChars = READ_RECORD_DEFAULT_CHARS, part = '
|
|
|
69
69
|
out.push(pages.length
|
|
70
70
|
? `Filed on: ${pages.map((p) => `“${p.title}” (ref ${p.ref})`).join(' · ')}`
|
|
71
71
|
: 'Filed on: no page you can see.')
|
|
72
|
+
// ADR-0027: the one attached page whose tier the record takes. Absent from a server before 2026-11-04, and
|
|
73
|
+
// null when the record has none or the viewer cannot open it — then nothing is printed, never a guess.
|
|
74
|
+
const gov = rec.governingPage
|
|
75
|
+
if (gov && typeof gov === 'object' && gov.ref) out.push(`Governed by: “${gov.title || '(untitled)'}” (ref ${gov.ref})`)
|
|
72
76
|
const inside = Array.isArray(rec.containedIn) ? rec.containedIn : []
|
|
73
77
|
if (inside.length) out.push(`Inside:\n${inside.map(line).join('\n')}`)
|
|
74
78
|
if (Array.isArray(rec.contains)) {
|
package/lib/release_gate.mjs
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// That is safe because hiding a tool is a courtesy, and every gated route checks its own flag on the server.
|
|
12
12
|
|
|
13
13
|
/** Tools any release flag gates — hidden when the server cannot be asked. Mirror of allGatedTools(). */
|
|
14
|
-
export const GATED_FALLBACK = ['arrivals', 'attach_document', 'document_diff', 'export_page', 'file_arrival', 'file_document', 'find_documents', 'finish_task', 'get_document', 'hand_task', 'handed_tasks', 'hold_task', 'import_document_as_page', 'intake_shadow', 'list_documents', 'my_messages', 'my_tasks', 'pin_document', 'read_conversation', 'read_document', 'send_message', 'set_manager', 'store_file', 'tasks_waiting', 'upload_document_version']
|
|
14
|
+
export const GATED_FALLBACK = ['arrivals', 'attach_document', 'document_diff', 'export_page', 'file_arrival', 'file_document', 'find_documents', 'finish_task', 'get_document', 'hand_task', 'handed_tasks', 'hold_task', 'import_document_as_page', 'intake_shadow', 'list_documents', 'my_messages', 'my_tasks', 'pin_document', 'place_split_records', 'read_conversation', 'read_document', 'send_message', 'set_manager', 'split_page', 'split_records', 'store_file', 'tasks_waiting', 'undo_split', 'upload_document_version']
|
|
15
15
|
|
|
16
16
|
export const RELEASE_FETCH_TIMEOUT_MS = 2500
|
|
17
17
|
/** A remembered answer older than this is not trusted: a week covers a quiet weekend without hiding tools for long. */
|
package/lib/server.mjs
CHANGED
|
@@ -36,6 +36,7 @@ import { formatSeriesRefusal, formatSeriesUpdated } from './series_render.mjs'
|
|
|
36
36
|
import { formatSends } from './sends_render.mjs'
|
|
37
37
|
import { applyLock, fetchLockState, lockedAnswerFor, lockStateWithin } from './locked_tools.mjs'
|
|
38
38
|
import { applyRelease, fetchReleaseState, releaseStateWithin, rememberReleaseState, rememberedReleaseState } from './release_gate.mjs'
|
|
39
|
+
import { renderPlacement, renderSplitRefusal, renderUndo, renderWorklist } from './split_render.mjs'
|
|
39
40
|
import { filterUnshownSettling, renderSettlingV2 } from './settling_shown.mjs'
|
|
40
41
|
import { renderContactBriefing, renderContactCandidates, renderContactList } from './contacts_render.mjs'
|
|
41
42
|
import { renderConversation, renderMessageInbox } from './messages_render.mjs'
|
|
@@ -221,10 +222,9 @@ export function renderIntakePreviewLine(body) {
|
|
|
221
222
|
// it from offset 0, so the footer of a huge page is the part nobody reaches — and these notes exist for
|
|
222
223
|
// exactly those pages. Shared by read_page and project_status so the two cannot drift, which is how every
|
|
223
224
|
// earlier fix to this file's page rendering landed on one surface and not the other.
|
|
224
|
-
//
|
|
225
|
-
//
|
|
226
|
-
//
|
|
227
|
-
export const SPLIT_PAGE_TOOL_AVAILABLE = false
|
|
225
|
+
// PAGE SPLITTING v2 (Theron, 2026-11-04; ADR-0036 amendment): split_page, split_records, place_split_records and
|
|
226
|
+
// undo_split are registered for everyone and HIDDEN by the server's `page_splitting` release flag (release_gate.mjs),
|
|
227
|
+
// so only internal brains see them. v1 kept split_page unregistered behind a constant here; the flag replaces it.
|
|
228
228
|
|
|
229
229
|
export const renderHeaderNotes = (notes) => {
|
|
230
230
|
const lines = (Array.isArray(notes) ? notes : [])
|
|
@@ -2900,22 +2900,24 @@ function renderNudge(payload) {
|
|
|
2900
2900
|
},
|
|
2901
2901
|
)
|
|
2902
2902
|
|
|
2903
|
-
|
|
2903
|
+
server.registerTool(
|
|
2904
2904
|
'split_page',
|
|
2905
2905
|
{
|
|
2906
2906
|
title: 'Move sections onto a new child page',
|
|
2907
|
-
description: 'SPLIT a page: move whole sections onto a NEW page
|
|
2907
|
+
description: 'SPLIT a page: move whole sections onto a NEW child page; the original stays. For a page that has outgrown one read — an agent that cannot read the whole authority answers from part of it. TWO STEPS: mode "preview" writes nothing and returns a `plan`; mode "apply" with that plan commits the whole split in ONE transaction (a retry returns the first result). The source then links to the child where the sections were. It NEVER retires the original, moves governance, or rewrites inbound [[links]]. Every refusal comes before any write: you need EDIT access (edit_forbidden); pages with several tier versions are paused (multi_version_page); `headings` must match the STORED heading exactly, INCLUDING any `· as of <date>` suffix, and a heading two sections share is refused (ambiguous_heading); moving every section is a rename; `new_title` must not name any existing page or an archived project (title_taken); a STRICTER child is refused and a LOOSER one needs the source page\'s owner (widening_requires_owner); too_large, identity_claim. The child keeps the source page\'s OWNER, tier and grants. AFTER APPLY, SORT THE RECORDS: split_records lists every candidate; read EACH ONE IN FULL (read_record part "all"; a recording over ~20k chars by its OWN sub-agent reading every word — never keyword search, never skim); unclear → both; then place_split_records, whose description has the whole procedure (rules shadow, inbound links, governance). If a split stops after the child exists (source_trim_failed), finish with merge_sections (`from` only) for each heading in `remaining` — never re-run split_page. undo_split reverses the whole split.',
|
|
2908
2908
|
inputSchema: {
|
|
2909
2909
|
name: z.string().describe('the exact page name to split, as read_page shows it'),
|
|
2910
2910
|
headings: z.array(z.string()).min(1).describe('the headings of the sections to MOVE, matched EXACTLY against the stored heading — include any `· as of <date>` suffix. A heading two sections share is refused: rename one with rename_section first. Everything not listed stays on the original.'),
|
|
2911
2911
|
new_title: z.string().describe('the title of the new child page. It must not name ANY existing page in this brain, or an archived project: a split never adopts or revives one.'),
|
|
2912
2912
|
base_version: z.string().describe('the `version` read_page prints for the SOURCE page (64-hex). REQUIRED — it is the concurrency check AND how the right brain is resolved.'),
|
|
2913
2913
|
reason: z.string().describe('WHY you are splitting, in one short phrase — recorded in page_history. Say what outgrew the page.'),
|
|
2914
|
+
mode: z.enum(['preview', 'apply']).optional().describe('"preview" (do this first) checks everything, writes nothing and returns a `plan`; "apply" with that `plan` performs it. Omitted: plan and apply in one call.'),
|
|
2915
|
+
plan: z.string().optional().describe('with mode "apply": the `plan` token the preview returned, unchanged.'),
|
|
2914
2916
|
owner: z.string().optional().describe('omit to keep the SOURCE page\'s owner, so the child has exactly the same audience — almost always right. Naming a different user is an ownership change: it needs the page owner, or someone above them who can read the page, and must be an active member of this brain.'),
|
|
2915
2917
|
tier: z.enum(PAGE_TIERS).optional().describe('omit to COPY the source page tier, which is almost always right. A LOOSER or merely DIFFERENT tier (peers from a reports page) changes who can read the moved text, so only the source page\'s owner may choose it; a STRICTER one is refused, since a split cannot tighten access.'),
|
|
2916
2918
|
},
|
|
2917
2919
|
},
|
|
2918
|
-
async ({ name, headings, new_title, base_version, reason, owner, tier }) => {
|
|
2920
|
+
async ({ name, headings, new_title, base_version, reason, mode, plan, owner, tier }) => {
|
|
2919
2921
|
let res
|
|
2920
2922
|
try {
|
|
2921
2923
|
res = await fetchCortex(`${BASE}/api/brain/split-page`, {
|
|
@@ -2923,6 +2925,7 @@ function renderNudge(payload) {
|
|
|
2923
2925
|
headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
|
|
2924
2926
|
body: JSON.stringify({
|
|
2925
2927
|
name, headings, new_title, base_version, reason,
|
|
2928
|
+
...(mode ? { mode } : {}), ...(plan ? { plan } : {}),
|
|
2926
2929
|
...(owner ? { owner } : {}), ...(tier ? { tier } : {}),
|
|
2927
2930
|
}),
|
|
2928
2931
|
})
|
|
@@ -2951,8 +2954,106 @@ function renderNudge(payload) {
|
|
|
2951
2954
|
: out.owner_defaulted
|
|
2952
2955
|
? '\n⚠ The child is owned by you because no `owner` was given. Set one deliberately if it should belong to someone else — transfer is unreachable once an owner is deactivated.'
|
|
2953
2956
|
: ''
|
|
2957
|
+
const a = out.proposals?.attached
|
|
2958
|
+
const records = a
|
|
2959
|
+
? `\nRecords on the source: ${a.candidates} to sort${a.hidden ? ` (${a.hidden} you cannot read)` : ''}` +
|
|
2960
|
+
`${a.viaKeptClaims ? `; ${a.viaKeptClaims} held by a routing claim the source keeps stay with it` : ''}.`
|
|
2961
|
+
: ''
|
|
2962
|
+
const recordsNext = out.records_next ? `\nRECORDS: ${out.records_next}` : ''
|
|
2963
|
+
if (out.preview) {
|
|
2964
|
+
return { content: [{ type: 'text', text: `PREVIEW — nothing was written. Splitting "${name}" (${out.brain} · ${out.tier} tier) would move ${out.moved.join(' · ')} to a new page "${out.child}".${records}\nThe source would read: ${out.source_link}\nNEXT: ${out.next}${recordsNext}${ownerNote}` }] }
|
|
2965
|
+
}
|
|
2954
2966
|
const grants = out.grants_copied ? ` ${out.grants_copied} access grant(s) copied.` : ''
|
|
2955
|
-
return { content: [{ type: 'text', text: `Split "${name}" (${out.brain} · ${out.tier} tier) → new page "${out.child}". Moved: ${out.moved.join(' · ')}.${grants} Child version: ${out.version}\n${out.note}\nNEXT: ${out.next}${ownerNote}\nReversible:
|
|
2967
|
+
return { content: [{ type: 'text', text: `Split "${name}" (${out.brain} · ${out.tier} tier) → new page "${out.child}"${out.child_ref ? ` (ref ${out.child_ref})` : ''}. Moved: ${out.moved.join(' · ')}.${grants} Child version: ${out.version}. Plan: ${out.plan}${out.replayed ? ' (already applied — this is its first result)' : ''}\n${out.note}${records}\nNEXT: ${out.next}${recordsNext}${ownerNote}\nReversible: undo_split with this plan puts the source back, retires the child and reverses any record placement.` }] }
|
|
2968
|
+
},
|
|
2969
|
+
)
|
|
2970
|
+
|
|
2971
|
+
server.registerTool(
|
|
2972
|
+
'split_records',
|
|
2973
|
+
{
|
|
2974
|
+
title: 'List every record a split must sort',
|
|
2975
|
+
description: 'List EVERY record a split you applied left on its source — the full worklist for place_split_records, not the 20 that split_page names. Page through with `offset` until you have covered `total`. Each line: id, title, source/type, date, approximate length, RECORDING when it is a meeting, transcript or handoff (each long one gets its own reader), and how it is attached (moved_claim = through a routing claim the moved text names; direct). Records you cannot read are counted, never named; records held by a routing claim the source keeps stay with it and are not candidates. Also says whether the records were already placed or the split was undone, and the rules pipeline\'s graduation streak. Read-only.',
|
|
2976
|
+
inputSchema: {
|
|
2977
|
+
plan: z.string().describe('the `plan` token split_page returned when you applied the split'),
|
|
2978
|
+
offset: z.number().int().min(0).optional().describe('where to start (default 0); the reply names the next offset'),
|
|
2979
|
+
limit: z.number().int().min(1).max(200).optional().describe('records per page (default 50, at most 200)'),
|
|
2980
|
+
},
|
|
2981
|
+
},
|
|
2982
|
+
async ({ plan, offset, limit }) => {
|
|
2983
|
+
let res
|
|
2984
|
+
try {
|
|
2985
|
+
const q = new URLSearchParams({ plan, ...(offset ? { offset: String(offset) } : {}), ...(limit ? { limit: String(limit) } : {}) })
|
|
2986
|
+
res = await fetchCortex(`${BASE}/api/brain/split-records?${q}`, { headers: { Authorization: `Bearer ${TOKEN}` } })
|
|
2987
|
+
} catch (e) {
|
|
2988
|
+
return toolError(`Could not list the split's records: ${e.message}`)
|
|
2989
|
+
}
|
|
2990
|
+
const out = await res.json().catch(() => null)
|
|
2991
|
+
if (!res.ok || !out?.ok) return toolError(renderSplitRefusal("list the split's records", out, res.status))
|
|
2992
|
+
return { content: [{ type: 'text', text: renderWorklist(out) }] }
|
|
2993
|
+
},
|
|
2994
|
+
)
|
|
2995
|
+
|
|
2996
|
+
server.registerTool(
|
|
2997
|
+
'place_split_records',
|
|
2998
|
+
{
|
|
2999
|
+
title: 'Place a split\'s records, sorted by a full read',
|
|
3000
|
+
description: 'Place the records of a split you APPLIED, in ONE transaction: child = attach to the child and detach from the source; both = attach to the child too; parent = leave. PROCEDURE, every split: (a) FULL READ — list the whole worklist with split_records. Read EVERY candidate in full with read_record part "all" and max_chars at least its length. Each recording over ~20k chars gets its OWN sub-agent that reads every word: no keyword search, no skimming (a trial agent once keyword-searched two 150k transcripts). Decide child (only about the moved text), parent (only about what stayed) or both; anything unclear → both. (b) SHADOW — also run the FROZEN rules that split_records prints on its first page, without looking at the full read (Haiku segments each recording; Opus decides with rules 1–5, incl. the 0.7 confidence floor), and send them as `shadow` for the same records. Only the full read is applied. (c) INBOUND LINKS — grep "[[<source title>]]" in substring mode; judge each link from its snippet; edit_page the ones you may edit to point at the child when they meant the moved text; list the rest for their owners. (d) GOVERNANCE NEVER MOVES — a record governed by the source stays on it even when you say child (it goes on both). Every readable candidate needs a decision (parent leaves it). Idempotent: a second call returns the first result. Replies with the shadow diff (harmful = the rules put a record on fewer pages or the opposite one; clutter = the rules said both) and the rules\' streak (they graduate after 10 clean splits in a row).',
|
|
3001
|
+
inputSchema: {
|
|
3002
|
+
plan: z.string().describe('the `plan` token of the applied split'),
|
|
3003
|
+
decisions: z.array(z.object({
|
|
3004
|
+
record_id: z.string(),
|
|
3005
|
+
placement: z.enum(['child', 'parent', 'both']),
|
|
3006
|
+
confidence: z.number().min(0).max(1).optional(),
|
|
3007
|
+
reason: z.string().optional().describe('one line: what in the record decided it'),
|
|
3008
|
+
})).describe('the FULL READ: one decision for EVERY candidate split_records lists'),
|
|
3009
|
+
shadow: z.array(z.object({
|
|
3010
|
+
record_id: z.string(),
|
|
3011
|
+
placement: z.enum(['child', 'parent', 'both']),
|
|
3012
|
+
confidence: z.number().min(0).max(1).optional(),
|
|
3013
|
+
})).optional().describe('the frozen rules pipeline\'s decisions for the same records — stored and compared, never applied'),
|
|
3014
|
+
},
|
|
3015
|
+
},
|
|
3016
|
+
async ({ plan, decisions, shadow }) => {
|
|
3017
|
+
let res
|
|
3018
|
+
try {
|
|
3019
|
+
res = await fetchCortex(`${BASE}/api/brain/split-records`, {
|
|
3020
|
+
method: 'POST',
|
|
3021
|
+
headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
|
|
3022
|
+
body: JSON.stringify({ plan, decisions, ...(shadow ? { shadow } : {}) }),
|
|
3023
|
+
})
|
|
3024
|
+
} catch (e) {
|
|
3025
|
+
return toolError(`Could not place the split's records: ${e.message}`)
|
|
3026
|
+
}
|
|
3027
|
+
const out = await res.json().catch(() => null)
|
|
3028
|
+
if (!res.ok || !out?.ok) return toolError(renderSplitRefusal("place the split's records", out, res.status))
|
|
3029
|
+
return { content: [{ type: 'text', text: renderPlacement(out) }] }
|
|
3030
|
+
},
|
|
3031
|
+
)
|
|
3032
|
+
|
|
3033
|
+
server.registerTool(
|
|
3034
|
+
'undo_split',
|
|
3035
|
+
{
|
|
3036
|
+
title: 'Undo a split',
|
|
3037
|
+
description: 'Undo a split you applied, in ONE transaction: the moved sections go back on the source exactly as they were (from page history, with their dates), the child page is retired (superseded by the source, never deleted), and every record placement is reversed. Refused when either page changed after the split — the reply lists the revisions that would be lost, so you can deal with them first. Only the member who applied the split, and only once.',
|
|
3038
|
+
inputSchema: {
|
|
3039
|
+
plan: z.string().describe('the `plan` token of the applied split'),
|
|
3040
|
+
reason: z.string().optional().describe('why, in one phrase — recorded in page_history'),
|
|
3041
|
+
},
|
|
3042
|
+
},
|
|
3043
|
+
async ({ plan, reason }) => {
|
|
3044
|
+
let res
|
|
3045
|
+
try {
|
|
3046
|
+
res = await fetchCortex(`${BASE}/api/brain/split-undo`, {
|
|
3047
|
+
method: 'POST',
|
|
3048
|
+
headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
|
|
3049
|
+
body: JSON.stringify({ plan, ...(reason ? { reason } : {}) }),
|
|
3050
|
+
})
|
|
3051
|
+
} catch (e) {
|
|
3052
|
+
return toolError(`Could not undo the split: ${e.message}`)
|
|
3053
|
+
}
|
|
3054
|
+
const out = await res.json().catch(() => null)
|
|
3055
|
+
if (!res.ok || !out?.ok) return toolError(renderSplitRefusal('undo the split', out, res.status))
|
|
3056
|
+
return { content: [{ type: 'text', text: renderUndo(out) }] }
|
|
2956
3057
|
},
|
|
2957
3058
|
)
|
|
2958
3059
|
|
|
@@ -8172,6 +8273,7 @@ function renderNudge(payload) {
|
|
|
8172
8273
|
const red = out?.links?.red ?? 0
|
|
8173
8274
|
const redList = Array.isArray(out?.redLinks) && out.redLinks.length ? `\nRed-links (wanted nodes): ${out.redLinks.map((r) => `[[${r}]]`).join(', ')}` : ''
|
|
8174
8275
|
const retiredList = Array.isArray(out?.retiredLinks) && out.retiredLinks.length ? `\nRetired links (not current or wanted): ${out.retiredLinks.map((r) => `[[${r}]]`).join(', ')}` : ''
|
|
8276
|
+
const unlinkedNote = typeof out?.unlinkedNote === 'string' ? `\n⚠ ${out.unlinkedNote}` : ''
|
|
8175
8277
|
const stamps = Array.isArray(out?.identifiers) && out.identifiers.length ? `\nIdentifier stamps (join keys): ${out.identifiers.map((i) => `[[${i}]]`).join(', ')}` : ''
|
|
8176
8278
|
// TIER RETARGET — say it out loud. The server has always computed these (AuthorResult.tierCorrections)
|
|
8177
8279
|
// and its own comment says corrections are "surfaced (not hidden)", but nothing ever printed them, so
|
|
@@ -8217,7 +8319,7 @@ function renderNudge(payload) {
|
|
|
8217
8319
|
const unroutedLines = renderUnroutedPathStamps(out)
|
|
8218
8320
|
const unrouted = unroutedLines.length ? `\n${unroutedLines.join('\n')}` : ''
|
|
8219
8321
|
const verb = out?.created ? 'Created + authored' : 'Authored'
|
|
8220
|
-
const note = out?.built ? `${verb} "${name}" (${out.built} tier${out.built === 1 ? '' : 's'}). Links: ${blue} resolved, ${retired} retired, ${red} red.${corrections}${retiredList}${redList}${stamps}${undated}${identityRefused}${unrouted}`
|
|
8322
|
+
const note = out?.built ? `${verb} "${name}" (${out.built} tier${out.built === 1 ? '' : 's'}). Links: ${blue} resolved, ${retired} retired, ${red} red.${corrections}${unlinkedNote}${retiredList}${redList}${stamps}${undated}${identityRefused}${unrouted}`
|
|
8221
8323
|
: `No change to "${name}"${out?.skipped?.length ? ` (${out.skipped.join(', ')})` : ''}.${corrections}`
|
|
8222
8324
|
return { content: [{ type: 'text', text: note }] }
|
|
8223
8325
|
},
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Page splitting v2 (ADR-0036 amendment, 2026-11-04) — the replies of split_page, split_records,
|
|
2
|
+
// place_split_records and undo_split. PURE, so the wording is tested here rather than through a live server.
|
|
3
|
+
//
|
|
4
|
+
// The procedure itself lives in the tool DESCRIPTIONS (server.mjs), because that is what an agent reads
|
|
5
|
+
// before it calls; these replies only report what happened and name the next call.
|
|
6
|
+
|
|
7
|
+
const kchars = (n) => (n >= 1000 ? `~${Math.round(n / 1000)}k` : `~${n}`) + ' chars'
|
|
8
|
+
|
|
9
|
+
/** One line of the worklist. */
|
|
10
|
+
export function worklistLine(r) {
|
|
11
|
+
const date = r.occurred_at ? String(r.occurred_at).slice(0, 10) : 'undated'
|
|
12
|
+
const kind = [r.source, r.record_type].filter(Boolean).join('/')
|
|
13
|
+
return `· ${r.id} — ${r.title || '(untitled)'} — ${kind} · ${date} · ${kchars(Number(r.approx_chars) || 0)}` +
|
|
14
|
+
`${r.is_recording ? ' · RECORDING' : ''} · ${r.via}`
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function graduationLine(g) {
|
|
18
|
+
if (!g) return ''
|
|
19
|
+
return `Rules shadow: ${g.streak} of ${g.needed} clean splits in a row` +
|
|
20
|
+
(g.graduated ? ' — GRADUATED (Theron decides whether the rules replace the full read).' : '.') +
|
|
21
|
+
` ${g.splits} split(s) with a shadow so far.`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** split_records' reply: one page of the worklist. */
|
|
25
|
+
export function renderWorklist(out) {
|
|
26
|
+
const lines = []
|
|
27
|
+
const shownTo = out.offset + out.records.length
|
|
28
|
+
lines.push(`Split ${out.plan} (${out.brain}): ${out.total} record(s) to sort` +
|
|
29
|
+
(out.records.length ? ` — showing ${out.offset + 1}–${shownTo}` : '') +
|
|
30
|
+
`, ${out.recordings} of them recordings.`)
|
|
31
|
+
if (out.child?.title) lines.push(`Child: "${out.child.title}"${out.child.ref ? ` (ref ${out.child.ref})` : ''}.`)
|
|
32
|
+
if (out.hidden) lines.push(`${out.hidden} more you cannot read: counted, never named — their owners decide.`)
|
|
33
|
+
if (out.via_kept_claims) lines.push(`${out.via_kept_claims} record(s) are held by a routing claim the source keeps; they stay with it.`)
|
|
34
|
+
if (out.records.length) lines.push('', ...out.records.map(worklistLine), '')
|
|
35
|
+
if (shownTo < out.total) lines.push(`More: split_records with plan "${out.plan}" and offset ${shownTo}.`)
|
|
36
|
+
if (out.undone_at) lines.push(`⚠ This split was UNDONE at ${out.undone_at}.`)
|
|
37
|
+
else if (out.placement) lines.push(`Already placed at ${out.placement.applied_at} — place_split_records returns that result.`)
|
|
38
|
+
else if (out.total) lines.push('Read every one IN FULL (recordings over ~20k chars by their own sub-agent), run the rules shadow, then place_split_records.')
|
|
39
|
+
const g = graduationLine(out.graduation)
|
|
40
|
+
if (g) lines.push(g)
|
|
41
|
+
if (out.procedure && !out.placement && !out.undone_at) lines.push('', out.procedure)
|
|
42
|
+
return lines.join('\n')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** place_split_records' reply: what moved, the shadow diff, and the streak. */
|
|
46
|
+
export function renderPlacement(out) {
|
|
47
|
+
const p = out.placement ?? {}
|
|
48
|
+
const decisions = Array.isArray(p.decisions) ? p.decisions : []
|
|
49
|
+
const actions = Array.isArray(p.actions) ? p.actions : []
|
|
50
|
+
const count = (k) => decisions.filter((d) => d.placement === k).length
|
|
51
|
+
const lines = []
|
|
52
|
+
lines.push(`${out.replayed ? 'Already placed' : 'Placed'} ${decisions.length} record(s) for split ${out.plan} (${out.brain}): ` +
|
|
53
|
+
`${count('child')} child, ${count('both')} both, ${count('parent')} parent.`)
|
|
54
|
+
const attached = actions.filter((a) => a.attached_child).length
|
|
55
|
+
const detached = actions.filter((a) => a.detached_source).length
|
|
56
|
+
const kept = actions.filter((a) => a.kept_governing).length
|
|
57
|
+
lines.push(`Attached to the child: ${attached}. Detached from the source: ${detached}.` +
|
|
58
|
+
(kept ? ` ${kept} record(s) GOVERNED by the source stay on it as well — governance never moves in a split.` : ''))
|
|
59
|
+
const shadow = Array.isArray(p.shadow) ? p.shadow : []
|
|
60
|
+
if (!shadow.length) {
|
|
61
|
+
lines.push('No rules shadow was sent, so this split does not count toward the rules\' graduation.')
|
|
62
|
+
} else {
|
|
63
|
+
const d = p.diff ?? { agree: 0, harmful: [], clutter: [] }
|
|
64
|
+
lines.push(`Rules shadow: ${d.agree} agree, ${d.clutter.length} clutter (rules said both), ${d.harmful.length} HARMFUL.`)
|
|
65
|
+
if (d.harmful.length) lines.push(`Harmful (rules would have left evidence off a page): ${d.harmful.join(', ')}`)
|
|
66
|
+
}
|
|
67
|
+
const g = graduationLine(out.graduation)
|
|
68
|
+
if (g) lines.push(g)
|
|
69
|
+
lines.push('Next: inbound [[links]] to the source that meant the moved text (see split_page). undo_split reverses the whole split.')
|
|
70
|
+
return lines.join('\n')
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** undo_split's reply. */
|
|
74
|
+
export function renderUndo(out) {
|
|
75
|
+
return [
|
|
76
|
+
`Undid split ${out.plan} (${out.brain}) at ${out.undoneAt}.`,
|
|
77
|
+
`The source has its sections back (${(out.restoredHeadings ?? []).join(' · ')}); its version is now ${out.sourceVersion}.`,
|
|
78
|
+
out.childRetired ? 'The child page is retired (superseded by the source), not deleted.' : 'The child page was already retired.',
|
|
79
|
+
`Records put back on the source: ${out.reattachedToSource}; taken off the child: ${out.detachedFromChild}.`,
|
|
80
|
+
out.otherChildRecords ? `⚠ ${out.otherChildRecords} record(s) are still attached to the retired child — the split did not put them there; route them yourself.` : '',
|
|
81
|
+
].filter(Boolean).join('\n')
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Any of the four tools' refusals: the code, the message, and the quoted detail lines. */
|
|
85
|
+
export function renderSplitRefusal(what, out, status) {
|
|
86
|
+
const detail = Array.isArray(out?.detail) && out.detail.length ? `\n${out.detail.map((d) => `· ${d}`).join('\n')}` : ''
|
|
87
|
+
return `Could not ${what}: ${out?.error ?? status}${out?.message ? ` — ${out.message}` : ''}${detail}${out?.hint ? `\n${out.hint}` : ''}`
|
|
88
|
+
}
|
package/package.json
CHANGED