Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 681d4092c32ec266197bd3e56a186402b0a469f8
parent 775d6e29225f1792a83925e4cfb33934634f405f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 10 Oct 2026 12:33:37 -0400

umtool: release 23 F3 — notes get an agent write path: a WORKER_TOKEN bearer is stamped "agent"

umtool's POST /api/notes stamps a write "operator" with no Authorization
header (the page, as before), "agent" for `Authorization: Bearer
<WORKER_TOKEN>`, and answers 401 for any other Authorization header; `by` is
never read from the body (lib/annotations/agentAuth.mjs). umtool reads
WORKER_TOKEN from its environment, else the editor's editor/.env(.local) —
loadEditorEnv's order — per request.

The MCP's `notes` reply now writes through that route with its WORKER_TOKEN
(the target found from the open notes when omitted) instead of answering with
the `umtool notes reply` command. instructions.ts, mcp/README.md,
umtool/docs/notes.md and ENVIRONMENT.md say so. umtool's notes UI already
badges an agent's note and reply.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MENVIRONMENT.md | 4++--
Mcommon/lib/envVars.ts | 4++--
Mmcp/README.md | 8++++----
Mmcp/src/archivalTools.test.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mmcp/src/archivalTools.ts | 114++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mmcp/src/instructions.ts | 3++-
Mumtool/app/api/notes/route.ts | 20++++++++++++--------
Mumtool/docs/notes.md | 14+++++++++++++-
Mumtool/e2e/article-notes.spec.ts | 23+++++++++++++++++++++++
Aumtool/lib/annotations/agentAuth.mjs | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/annotations/agentAuth.test.mjs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 465 insertions(+), 45 deletions(-)

diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -53,7 +53,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | Variable | Default | What it does | Read by | |---|---|---|---| -| `WORKER_TOKEN` | unset (both surfaces off) | Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback). Set the same value on both ends. | common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts | +| `WORKER_TOKEN` | unset (both surfaces off) | Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped "agent"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end. | common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs | | `SYNC_HEARTBEAT_SECONDS` | `settings.syncScheduler.heartbeatSeconds` | Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead). | editor/app/scheduler/heartbeat.ts | | `SYNC_TICK_URL` | `http://127.0.0.1:3001/api/scheduler/tick` | Where `archilyzer sync tick` (cron's heartbeat) posts. | common/bin/sync-tick.ts | | `SYNC_TICK_TOKEN` | unset (no auth) | Bearer token for the tick endpoint; set on both the editor and the cron job. | common/bin/sync-tick.ts, editor/app/scheduler/auth.ts | @@ -82,7 +82,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `CLAUDE_DIGEST_MODEL` | the CLI's default | The model the metered digest lane asks `claude` for when settings name none. | common/lib/digestApps.ts | | `NITTER_INSTANCES` | a built-in list | Comma-separated Nitter instances for the X fallback fetcher, in order of preference. | common/social/xNitterFetcher.ts | | `ARCHILYZER_X_BROWSER` | the first of `chromium`, `google-chrome`, `google-chrome-stable`, `chrome` on PATH, else Playwright's bundled Chromium | The Chromium-family browser /settings' "Connect X account" opens (a path, or a name looked up on PATH), and a forum-thread channel's "Connect forum session" too. It is launched without the automation signals, in the X session profile (or the forum host's profile); a value that is not an executable refuses the connect rather than opening another browser. | common/social/xBrowser.ts | -| `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there (e.g. `http://localhost:3050`). | editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts | +| `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). | editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts | | `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. | mcp/src/sources.ts | | `TRANSCRIPT_HUB_URL` | — | MCP server: a hub, federating every archive it lists. | mcp/src/sources.ts | | `TRANSCRIPT_LOCAL_DIR` | — | MCP server: a composed public dir on disk. | mcp/src/sources.ts | diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -89,7 +89,7 @@ const DECLARED: EnvVarDecl[] = [ paths("STAGIT_BIN", "`stagit` on PATH, then `~/.local/bin/stagit`", "stagit, which renders the source's history pages (`/source/git/`: the log and a page per commit with its diff). Optional: without it the source is published without them. See [PUBLISH.md](PUBLISH.md)."), // ── runtime ──────────────────────────────────────────────────────────── - { name: "WORKER_TOKEN", audience: "runtime", default: "unset (both surfaces off)", readBy: "common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts", doc: "Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback). Set the same value on both ends." }, + { name: "WORKER_TOKEN", audience: "runtime", default: "unset (both surfaces off)", readBy: "common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs", doc: "Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped \"agent\"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end." }, { name: "SYNC_HEARTBEAT_SECONDS", audience: "runtime", default: "`settings.syncScheduler.heartbeatSeconds`", readBy: "editor/app/scheduler/heartbeat.ts", doc: "Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead)." }, { name: "SYNC_TICK_URL", audience: "runtime", default: "`http://127.0.0.1:3001/api/scheduler/tick`", readBy: "common/bin/sync-tick.ts", doc: "Where `archilyzer sync tick` (cron's heartbeat) posts." }, { name: "SYNC_TICK_TOKEN", audience: "runtime", default: "unset (no auth)", readBy: "common/bin/sync-tick.ts, editor/app/scheduler/auth.ts", doc: "Bearer token for the tick endpoint; set on both the editor and the cron job." }, @@ -118,7 +118,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "CLAUDE_DIGEST_MODEL", audience: "runtime", default: "the CLI's default", readBy: "common/lib/digestApps.ts", doc: "The model the metered digest lane asks `claude` for when settings name none." }, { name: "NITTER_INSTANCES", audience: "runtime", default: "a built-in list", readBy: "common/social/xNitterFetcher.ts", doc: "Comma-separated Nitter instances for the X fallback fetcher, in order of preference." }, { name: "ARCHILYZER_X_BROWSER", audience: "runtime", default: "the first of `chromium`, `google-chrome`, `google-chrome-stable`, `chrome` on PATH, else Playwright's bundled Chromium", readBy: "common/social/xBrowser.ts", doc: "The Chromium-family browser /settings' \"Connect X account\" opens (a path, or a name looked up on PATH), and a forum-thread channel's \"Connect forum session\" too. It is launched without the automation signals, in the X session profile (or the forum host's profile); a value that is not an executable refuses the connect rather than opening another browser." }, - { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there (e.g. `http://localhost:3050`)." }, + { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`)." }, { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP." }, { name: "TRANSCRIPT_HUB_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a hub, federating every archive it lists." }, { name: "TRANSCRIPT_LOCAL_DIR", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a composed public dir on disk." }, diff --git a/mcp/README.md b/mcp/README.md @@ -11,9 +11,9 @@ The exceptions all ask a local Archilyzer editor (`ARCHILYZER_EDITOR_URL` + `WORKER_TOKEN`, the editor's own) to do the work — `fetch_clip` fetches a clip window, `enqueue` queues archival work, `get_job` / `channel_coverage` read the editor's jobs and disk, and `get_transcript` falls back to the editor's disk for a -video not yet published; `notes` reads umtool (`UMTOOL_URL`). The MCP itself still -writes nothing. Settings, storage and deletes are not reachable from it (`pnpm ops` -only). +video not yet published; `notes` reads umtool (`UMTOOL_URL`) and writes a reply +there as the agent's. The MCP itself still writes nothing. Settings, storage and +deletes are not reachable from it (`pnpm ops` only). ## Tools @@ -32,7 +32,7 @@ only). | `get_job` | One editor job's state — kind, channel, status, times, exit code, where it waits in its queue — and the last `tail` (default 40) log lines (`GET /api/ops/job/<id>`). For the job id `enqueue` or `fetch_clip` returned. Needs the editor. | | `enqueue` | Queue archival work on a channel the editor archives, as its page's buttons do (`POST /api/ops/<kind>`): `sync` (`full`), `download-missing`, `retry-bucket` (`bucket`, `ids` — the way to download chosen videos), `transcribe-bucket` (`ids`), `fetch-posts` (`full` / `older`), `import-video` (`url`). Answers the job id; the editor runs it on its own queues at each platform's pace. Only when the operator asks. Needs the editor. | | `channel_coverage` | What a channel **holds** on the editor's disk by date (`GET /api/ops/coverage`): count, first and last day, per year, and every gap longer than `gap_days` (30); `date_from` / `date_to` narrow it, `list` lists the videos. Each video is dated by its **recorded date** when the channel has a title rule (a VOD mirror, release 20), else its upload date. Needs the editor. | -| `notes` | The operator's notes in umtool on articles and report-video projects: `list` (every open note, by target), `read` (`target` as `list` names it — the digest with anchors resolved and the source file to edit). `reply` answers with the `umtool notes reply` command, because umtool records a reply sent over HTTP as the operator's. Needs `UMTOOL_URL`. | +| `notes` | The operator's notes in umtool on articles and report-video projects: `list` (every open note, by target), `read` (`target` as `list` names it — the digest with anchors resolved and the source file to edit). `reply` (`note_id`, `text`, `resolve`) writes the reply in umtool (`POST /api/notes` with `Authorization: Bearer <WORKER_TOKEN>`), which stamps it "agent" — never the operator's; its `target` is found from the open notes when omitted. Edit the note's source file and regenerate first. Needs `UMTOOL_URL`; a reply needs `WORKER_TOKEN` (the editor's own, which umtool reads too — a 401 means umtool holds another). | | `open_link` | Paste an archilyzer viewer **share link** to re-run that exact search here (query tree + every filter, at full fidelity) — plan, results and corpus handle in **one** call. `dry_run:true` for the plan alone. | | `list_sources` | Show the **default** corpus and, with a hub, its member sites as ready-to-paste handles. A site with reports says how many; a cited-only site says it is one. | | `resolve_source` | Turn a URL or site name into the canonical `source` handle and check it can be read. Changes nothing. | diff --git a/mcp/src/archivalTools.test.ts b/mcp/src/archivalTools.test.ts @@ -144,7 +144,7 @@ test("channel_coverage: the query sent, and the gaps read back", async () => { assert.match(textOf(bad), /date_to is a date, YYYY-MM-DD/); }); -test("notes: list groups open notes by target; read fetches the digest; reply is the CLI command", async () => { +test("notes: list groups open notes by target; read fetches the digest", async () => { const umtool = { UMTOOL_URL: "http://umtool.test/" }; const { deps, sent } = fakeEditor((s) => { if (s.url.includes("/api/browse/decisions")) { @@ -191,14 +191,71 @@ test("notes: list groups open notes by target; read fetches the digest; reply is assert.equal(q.get("status"), "all"); assert.match(read.text, /^# Notes on demo-site\/a-report/); + const none = await notesTool({ action: "list" }, { env: {}, fetch: deps.fetch }); + assert.match(none.text, /no umtool configured\. Set UMTOOL_URL/); +}); + +// ─── notes reply: written through umtool as the agent's (release 23 F3) ─── + +test("notes reply: POSTs the reply to umtool's route with the bearer token, the target found from the open notes", async () => { + const env = { UMTOOL_URL: "http://umtool.test/", WORKER_TOKEN: "tok" }; + const { deps, sent } = fakeEditor((s) => { + if (s.url.includes("/api/browse/decisions")) { + return { + status: 200, + body: { + items: [ + { kind: "open-note", project: "sites/demo-site/a-report", href: "/sites/demo-site/a-report?note=n_abc" }, + { kind: "open-note", project: "demo/video-project", href: "/browse/demo/video-project?note=n_other" }, + ], + }, + }; + } + return { status: 200, body: { note: { id: "n_abc", status: "resolved", replies: [{ author: "agent" }] } } }; + }, env); + const client = await connectWith(deps); const reply = await client.callTool({ name: "notes", arguments: { action: "reply", note_id: "n_abc", text: "Changed it", resolve: true }, }); - assert.equal(isError(reply), true); - assert.match(textOf(reply), /umtool notes reply n_abc "Changed it" --resolve/); - assert.equal(sent.length, 1, "a reply sends nothing"); + assert.equal(isError(reply), false, textOf(reply)); + assert.match(textOf(reply), /^Replied to n_abc on sites\/demo-site\/a-report as the agent; the note is resolved \(1 reply\)\./); + const post = sent.at(-1)!; + assert.equal(post.method, "POST"); + assert.equal(post.url, "http://umtool.test/api/notes?article=demo-site%2Fa-report"); + assert.equal(post.headers?.authorization, "Bearer tok"); + // Who wrote it is the token's to say, never the body's. + assert.deepEqual(post.body, { op: { op: "reply", id: "n_abc", text: "Changed it", resolve: true } }); - const none = await notesTool({ action: "list" }, { env: {}, fetch: deps.fetch }); - assert.match(none.text, /no umtool configured\. Set UMTOOL_URL/); + // An explicit target skips the lookup; a project target is a project param. + const before = sent.length; + await notesTool({ action: "reply", note_id: "n_other", text: "Shortened", target: "demo/video-project" }, deps); + assert.equal(sent.length, before + 1); + assert.equal(sent.at(-1)!.url, "http://umtool.test/api/notes?project=demo%2Fvideo-project"); + assert.equal((sent.at(-1)!.body as { op: { resolve: boolean } }).op.resolve, false); +}); + +test("notes reply: refusals — no token, a bad id, no open note, umtool's 401", async () => { + const noToken = await notesTool( + { action: "reply", note_id: "n_abc", text: "x" }, + { env: { UMTOOL_URL: "http://umtool.test" }, fetch: async () => { throw new Error("must not fetch"); } }, + ); + assert.equal(noToken.isError, true); + assert.match(noToken.text, /a reply needs WORKER_TOKEN/); + + const env = { UMTOOL_URL: "http://umtool.test", WORKER_TOKEN: "wrong" }; + const { deps } = fakeEditor((s) => + s.url.includes("/api/browse/decisions") + ? { status: 200, body: { items: [] } } + : { status: 401, body: { error: "notes: that bearer token is not umtool's WORKER_TOKEN" } }, + env); + assert.match((await notesTool({ action: "reply", note_id: "../x", text: "x" }, deps)).text, /reply needs note_id/); + assert.match((await notesTool({ action: "reply", note_id: "n_abc", text: "" }, deps)).text, /reply needs text/); + assert.match( + (await notesTool({ action: "reply", note_id: "n_gone", text: "x" }, deps)).text, + /no open note n_gone; pass target/, + ); + const refused = await notesTool({ action: "reply", note_id: "n_abc", text: "x", target: "sites/demo-site/a-report" }, deps); + assert.equal(refused.isError, true); + assert.match(refused.text, /umtool refused the token \(HTTP 401\): notes: that bearer token is not umtool's WORKER_TOKEN/); }); diff --git a/mcp/src/archivalTools.ts b/mcp/src/archivalTools.ts @@ -13,14 +13,13 @@ import { describeFetchError, isVideoId, REQUEST_TIMEOUT_MS } from "./fetchClip"; // transcribe-bucket | fetch-posts | import-video} // channel_coverage GET /api/ops/coverage?slug=… // notes umtool (UMTOOL_URL): GET /api/browse/decisions (list), -// GET /api/notes/context (read) +// GET /api/notes/context (read), POST /api/notes (reply) // // Settings, storage and deletes are deliberately absent (operator ruling, -// release 19): `pnpm ops` / `archilyzer` only. A notes REPLY is not written -// from here: umtool stamps every write through its HTTP route as the -// OPERATOR's ("there is no way to claim to be one here", umtool's -// app/api/notes/route.ts), so an agent reply must go through `umtool notes -// reply`, which stamps "agent" — the tool answers with that command. +// release 19): `pnpm ops` / `archilyzer` only. A notes REPLY is written +// through umtool's route with `Authorization: Bearer <WORKER_TOKEN>`, which +// umtool stamps "agent" — never the operator's (release 23 F3, ruled +// 2026-10-10: agents get their own write path). // // Pure apart from the injected deps; server.ts adapts. @@ -306,22 +305,94 @@ export function notesTarget(raw: string): { param: "article" | "project"; value: type Decision = { kind: string; project: string; projectKind?: string; target?: string; why?: string; href?: string }; -export async function notesTool(args: Record<string, unknown>, deps: NotesDeps): Promise<ToolAnswer> { - const action = trimmed(args.action) || "list"; - if (action === "reply") { - const id = trimmed(args.note_id) || "<note id>"; - const text = trimmed(args.text) || "<what changed>"; +const NOTE_ID_RE = /^n_[a-z0-9]+$/; + +// The target an open note is on, from the decisions list (each open note's +// href ends `?note=<id>`, its project is the target as list names it). +async function openNoteTarget(deps: NotesDeps, id: string): Promise<{ target: string } | { error: string }> { + const r = await umtoolGet(deps, "/api/browse/decisions"); + if (!r.ok) return { error: r.error }; + if (r.status !== 200) return { error: `notes: umtool answered HTTP ${r.status}` }; + const items = ((r.json as { items?: Decision[] } | null)?.items ?? []).filter( + (d) => d.kind === "open-note" && (d.href ?? "").endsWith(`note=${encodeURIComponent(id)}`), + ); + const targets = [...new Set(items.map((d) => d.project))]; + if (targets.length === 1) return { target: targets[0] }; + if (targets.length === 0) { + return { error: `notes: no open note ${id}; pass target (as list names it) to reply to a resolved one` }; + } + return { error: `notes: ${id} is open on ${targets.length} targets (${targets.join(", ")}); pass target` }; +} + +// A reply, written through umtool's route as the agent's: Bearer WORKER_TOKEN +// (the editor's, which umtool reads too). No stale-write token: an agent +// writes between the operator's reads, which umtool's page handles (a 409 +// there, and a re-read). +async function notesReply(args: Record<string, unknown>, deps: NotesDeps): Promise<ToolAnswer> { + const id = trimmed(args.note_id); + const text = trimmed(args.text); + if (!NOTE_ID_RE.test(id)) return { text: "notes: reply needs note_id (n_…, as read shows it)", isError: true }; + if (!text) return { text: "notes: reply needs text — what changed", isError: true }; + const base = umtoolFrom(deps.env); + if (!base) return { text: NO_UMTOOL_TEXT, isError: true }; + const token = (deps.env.WORKER_TOKEN ?? "").trim(); + if (!token) { return { + text: + "notes: a reply needs WORKER_TOKEN (the editor's own, which umtool reads too) in this " + + "server's env: umtool writes an agent's reply only for that bearer token.", isError: true, + }; + } + let targetName = trimmed(args.target); + if (!targetName) { + const found = await openNoteTarget(deps, id); + if ("error" in found) return { text: found.error, isError: true }; + targetName = found.target; + } + const target = notesTarget(targetName); + if (!target) { + return { text: 'notes: target is as list names it — "sites/<site>/<report>" for an article, else a video project id', isError: true }; + } + const timeoutMs = deps.requestTimeoutMs ?? REQUEST_TIMEOUT_MS; + const q = new URLSearchParams({ [target.param]: target.value }); + try { + const res = await deps.fetch(`${base}/api/notes?${q.toString()}`, { + method: "POST", + headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, + body: JSON.stringify({ op: { op: "reply", id, text, resolve: args.resolve === true } }), + signal: AbortSignal.timeout(timeoutMs), + }); + const body = (await res.json().catch(() => null)) as + | { error?: string; note?: { status?: string; replies?: unknown[] } } + | null; + if (res.status === 401) { + return { + text: + `notes: umtool refused the token (HTTP 401): ${body?.error ?? "unauthorized"} — this server's ` + + "WORKER_TOKEN must be umtool's (the editor's own).", + isError: true, + }; + } + if (res.status !== 200) { + return { text: `notes: umtool refused (HTTP ${res.status}): ${body?.error ?? "no reason given"}`, isError: true }; + } + const n = body?.note; + return { text: - "notes: a reply is not written from here. umtool records every write through its HTTP " + - "route as the operator's, and an agent's reply must say it is an agent's — so it goes " + - "through umtool's CLI, from the repo checkout:\n\n" + - ` umtool notes reply ${id} ${JSON.stringify(text)}${args.resolve === true ? " --resolve" : ""}\n\n` + - "(`node umtool/bin/umtool.mjs notes reply …` when umtool is not on the PATH.) Edit the " + - "note's SOURCE file first (notes read shows it), regenerate, then reply.", + `Replied to ${id} on ${targetName} as the agent` + + (n?.status ? `; the note is ${n.status}` : "") + + (Array.isArray(n?.replies) ? ` (${n.replies.length} repl${n.replies.length === 1 ? "y" : "ies"})` : "") + + ".", }; + } catch (e) { + return { text: `notes: umtool at ${base} did not answer: ${describeFetchError(e, timeoutMs)}`, isError: true }; } +} + +export async function notesTool(args: Record<string, unknown>, deps: NotesDeps): Promise<ToolAnswer> { + const action = trimmed(args.action) || "list"; + if (action === "reply") return notesReply(args, deps); if (action === "list") { const r = await umtoolGet(deps, "/api/browse/decisions"); if (!r.ok) return { text: r.error, isError: true }; @@ -460,14 +531,15 @@ export const ARCHIVAL_TOOLS = [ '"list": every open note, grouped by target. action "read" with target (as list names ' + 'it: "sites/<site>/<report>" for an article, else a project id): each note with its anchor ' + "resolved and the SOURCE file to edit (status: open, resolved or all). action " + - '"reply" answers with the `umtool notes reply` command to run — umtool records a ' + - "reply sent over HTTP as the operator's, so an agent's reply goes through its CLI. " + - "Needs UMTOOL_URL.", + '"reply" with note_id and text (resolve: true closes it too) writes the reply in ' + + "umtool as the agent's — edit the note's SOURCE file and regenerate first. target is " + + "found from the open notes when omitted. Needs UMTOOL_URL; a reply needs WORKER_TOKEN " + + "(the editor's own, which umtool reads too).", inputSchema: { type: "object", properties: { action: { type: "string", enum: ["list", "read", "reply"], description: 'Default "list".' }, - target: { type: "string", description: 'read: as list names it — "sites/<site>/<report>" (an article) or a project id.' }, + target: { type: "string", description: 'read (and reply, optional): as list names it — "sites/<site>/<report>" (an article) or a project id.' }, status: { type: "string", enum: ["open", "resolved", "all"], description: "read: which notes (default open)." }, note_id: { type: "string", description: "reply: the note id (n_…)." }, text: { type: "string", description: "reply: what changed." }, diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts @@ -173,7 +173,8 @@ function archiveStep(): string { `hours; report the job, do not wait it out. \`channel_coverage\` answers ` + `what a channel holds by date and where its gaps are (a VOD mirror's videos ` + `by the day they were recorded). The operator's notes on articles and ` + - `video projects: \`notes\` (list, read; a reply is \`umtool notes reply\`). ` + + `video projects: \`notes\` (list, read; reply — after editing the note's ` + + `source and regenerating — writes the reply in umtool as the agent's). ` + `Settings, storage and deletes are not reachable from here — name the ` + `\`pnpm ops\` command instead.` ); diff --git a/umtool/app/api/notes/route.ts b/umtool/app/api/notes/route.ts @@ -1,6 +1,6 @@ import { errorResponse, targetFrom } from "@/lib/annotations/server"; import { readNotes } from "@/lib/annotations/store.mjs"; -import { writeNote } from "@/lib/annotations/targets.mjs"; +import { agentToken, postNoteOp } from "@/lib/annotations/agentAuth.mjs"; export const dynamic = "force-dynamic"; @@ -14,8 +14,11 @@ export const dynamic = "force-dynamic"; // { doc, token, note }. 409 when `token` is stale or the file on // disk is not a notes doc; 400 for a refused op or target. // -// Every write from here is the OPERATOR's. An agent writes through -// `umtool notes`, which stamps "agent"; there is no way to claim to be one here. +// A write from the page is the OPERATOR's. An agent's (the MCP's `notes` +// reply, release 23 F3) carries `Authorization: Bearer <WORKER_TOKEN>` and is +// stamped "agent"; any other Authorization header is a 401 +// (lib/annotations/agentAuth.mjs). `by` is never read from the body. The CLI, +// `umtool notes`, writes the file directly and stamps "agent" too. const NO_STORE = { "cache-control": "no-store" }; function params(request: Request) { @@ -40,11 +43,12 @@ export async function GET(request: Request) { export async function POST(request: Request) { try { const target = await targetFrom(params(request)); - const body = (await request.json().catch(() => null)) as { token?: unknown; op?: unknown } | null; - if (!body || typeof body.op !== "object" || body.op === null) return Response.json({ error: "body needs an op" }, { status: 400 }); - const token = typeof body.token === "string" ? body.token : null; - const out = await writeNote(target, body.op as Record<string, unknown>, { by: "operator", token }); - return Response.json(out, { headers: NO_STORE }); + const body = await request.json().catch(() => null); + const r = await postNoteOp(target, body, { + authorization: request.headers.get("authorization"), + workerToken: agentToken(), + }); + return Response.json(r.body, { status: r.status, headers: NO_STORE }); } catch (err) { return errorResponse(err); } diff --git a/umtool/docs/notes.md b/umtool/docs/notes.md @@ -29,6 +29,8 @@ from the working directory to the checkout. 4. Regenerate. 5. `umtool notes reply <id> "<what changed>" --resolve` — or reply without `--resolve` to ask a question. The operator sees agent replies badged "agent". + An agent on the MCP replies with its `notes` tool (action `reply`), which writes + through the app's route below as the agent's. **Never hand-edit `notes.json`.** The CLI and the app write through one store that validates, takes a lock, and refuses a stale write; a hand edit races the page and @@ -38,6 +40,15 @@ can lose a reply. If the recorded source is wrong, correct it: The same digest is served as text at `GET /api/notes/context?article=<site>/<report>` (or `?project=<id>`); the page's "Copy agent brief" copies it. +**An agent's write over HTTP** (release 23 F3). `POST /api/notes` stamps a write +"operator" when the request carries no `Authorization` header (the page), and +"agent" when it carries `Authorization: Bearer <WORKER_TOKEN>`; any other +`Authorization` header is a 401 and nothing is written. `by` is never read from the +body. umtool's `WORKER_TOKEN` is its environment's (an explicit empty value turns +the agent path off), else the first `editor/.env.local` / `editor/.env` of this +checkout, then of the main worktree, that names it — the editor's own token, as +`pnpm ops` reads it (`lib/annotations/agentAuth.mjs`). + ## Where notes live | Subject | File | @@ -108,5 +119,6 @@ section, with its original quote. | `lib/annotations/store.mjs` | read, lockfile (`notes.json.lock`, stale after 30 s), token, tmp+rename | | `lib/annotations/targets.mjs` | article / project → file, subject, source; `listNotesFiles` | | `lib/annotations/digest.mjs`, `cli.mjs` | the markdown digest and `umtool notes` | -| `app/api/notes/route.ts` | GET / POST (operator-stamped; 409 on a stale token) | +| `app/api/notes/route.ts` | GET / POST (operator-stamped, or agent-stamped for the bearer token; 409 on a stale token) | +| `lib/annotations/agentAuth.mjs` | who a POST is by (`noteWriter`), umtool's `WORKER_TOKEN` (`agentToken`), the POST (`postNoteOp`) | | `lib/annotations/useNotes.ts` | the page's hook | diff --git a/umtool/e2e/article-notes.spec.ts b/umtool/e2e/article-notes.spec.ts @@ -214,6 +214,29 @@ test("open notes are open decisions, linked to the note; ?note= opens on it", as await expect(page.locator(`[data-note-card='${id}']`)).toHaveAttribute("aria-current", "true"); }); +test("an agent's reply over HTTP (the MCP's): stamped agent for umtool's WORKER_TOKEN, 401 for another", async ({ page, request }) => { + await request.post("/api/notes?article=priv/polemic-alpha", { data: { op: { op: "add", text: "Say claimed.", anchor: { kind: "whole" } } } }); + const id = JSON.parse(readFileSync(NOTES, "utf8")).notes[0].id; + // The e2e server's WORKER_TOKEN (playwright.config.ts). + const wrong = await request.post("/api/notes?article=priv/polemic-alpha", { + headers: { authorization: "Bearer not-the-token" }, + data: { op: { op: "reply", id, text: "nope" } }, + }); + expect(wrong.status()).toBe(401); + const ok = await request.post("/api/notes?article=priv/polemic-alpha", { + headers: { authorization: "Bearer umtool-e2e-token" }, + data: { by: "operator", op: { op: "reply", id, text: "Changed it in the draft.", resolve: true } }, + }); + expect(ok.status()).toBe(200); + const note = JSON.parse(readFileSync(NOTES, "utf8")).notes[0]; + expect(note.replies.map((r: { author: string }) => r.author)).toEqual(["agent"]); + expect(note.resolvedBy).toBe("agent"); + + await page.goto(PAGE); + await page.getByRole("button", { name: /^resolved 1$/ }).click(); + await expect(page.locator("[data-note-card] [data-reply='agent']")).toContainText("Changed it in the draft."); +}); + test("writes outside a report are refused", async ({ request }) => { for (const q of ["article=priv/../pub", "article=priv/nope", "article=priv", "article=../x/y"]) { const r = await request.post(`/api/notes?${q}`, { data: { op: { op: "add", text: "x", anchor: { kind: "whole" } } } }); diff --git a/umtool/lib/annotations/agentAuth.mjs b/umtool/lib/annotations/agentAuth.mjs @@ -0,0 +1,149 @@ +// WHO IS WRITING A NOTE over HTTP (release 23 F3; ruled 2026-10-10: agents get +// their own write path, attributed "agent", never as the operator). +// +// The app's /api/notes POST stamps every write from the page as the +// OPERATOR's. An agent — the MCP's `notes` reply — writes through the same +// route with `Authorization: Bearer <WORKER_TOKEN>`, and its write is stamped +// "agent": +// +// no Authorization header "operator" (the page, as before) +// Bearer <umtool's WORKER_TOKEN> "agent" +// any other Authorization header 401, nothing written — including any +// bearer when umtool holds no token +// +// `by` is never read from the request body: who wrote a note is what the +// request proves, not what it says. +// +// umtool's WORKER_TOKEN is read the way the editor's clients read it (`pnpm +// ops`'s loadEditorEnv, release 19 A1): the environment — an explicit value, +// even "", wins — else the first of this checkout's `editor/.env.local`, +// `editor/.env`, then the main worktree's, that names it. The same secret the +// editor's /api/ops takes. Read per request: a token set in editor/.env after +// umtool started is honoured without a restart. + +import crypto from "node:crypto"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { REPO_ROOT } from "../paths.mjs"; +import { writeNote } from "./targets.mjs"; + +/** + * The value of one key in a dotenv text (`KEY=value`, `export KEY=value`, + * quotes stripped, an unquoted value ending at an inline comment), or + * undefined. scripts/archilyzer-ops.mjs parseDotenv's rules. + * @param {string} text + * @param {string} key + * @returns {string | undefined} + */ +export function dotenvValue(text, key) { + let out; + for (const raw of text.split(/\r?\n/)) { + const line = raw.trim(); + if (!line || line.startsWith("#")) continue; + const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line); + if (!m || m[1] !== key) continue; + let value = m[2].trim(); + const q = value[0]; + if ((q === '"' || q === "'") && value.length >= 2 && value.endsWith(q)) value = value.slice(1, -1); + else value = value.replace(/\s+#.*$/, ""); + out = value; + } + return out; +} + +/** + * The main worktree of a linked worktree, or null (read off disk, as + * scripts/archilyzer-ops.mjs mainWorktreeOf does). + * @param {string} root + */ +function mainWorktreeOf(root) { + try { + const m = /^gitdir:\s*(.+)$/m.exec(readFileSync(path.join(/* turbopackIgnore: true */ root, ".git"), "utf8")); + if (!m) return null; + const gitdir = path.resolve(/* turbopackIgnore: true */ root, m[1].trim()); + const common = path.resolve( + /* turbopackIgnore: true */ gitdir, + readFileSync(path.join(/* turbopackIgnore: true */ gitdir, "commondir"), "utf8").trim(), + ); + return path.dirname(common); + } catch { + return null; + } +} + +/** + * The editor env files consulted, in order. + * @param {string} [root] + * @returns {string[]} + */ +export function editorEnvFiles(root = REPO_ROOT) { + const roots = [root]; + const main = mainWorktreeOf(root); + if (main && path.resolve(/* turbopackIgnore: true */ main) !== path.resolve(/* turbopackIgnore: true */ root)) roots.push(main); + return roots.flatMap((r) => [ + path.join(/* turbopackIgnore: true */ r, "editor", ".env.local"), + path.join(/* turbopackIgnore: true */ r, "editor", ".env"), + ]); +} + +/** + * umtool's WORKER_TOKEN: the environment's, else the editor's env files'. "" + * when none is set — and then no bearer matches. + * @param {Record<string, string | undefined>} [env] + * @param {string[]} [files] + * @returns {string} + */ +export function agentToken(env = process.env, files = editorEnvFiles()) { + if (env.WORKER_TOKEN !== undefined) return env.WORKER_TOKEN; + for (const file of files) { + let text; + try { + text = readFileSync(file, "utf8"); + } catch { + continue; + } + const v = dotenvValue(text, "WORKER_TOKEN"); + if (v !== undefined) return v; + } + return ""; +} + +/** + * Who a request's Authorization header says is writing. + * @param {string | null | undefined} authorization + * @param {string} token umtool's WORKER_TOKEN ("" for none) + * @returns {{ ok: true, by: "operator" | "agent" } | { ok: false, status: 401, error: string }} + */ +export function noteWriter(authorization, token) { + if (authorization === null || authorization === undefined || authorization === "") return { ok: true, by: "operator" }; + const m = /^Bearer\s+(.+)$/i.exec(authorization); + if (!m) return { ok: false, status: 401, error: "notes: an Authorization header must be `Bearer <WORKER_TOKEN>`" }; + if (!token) { + return { ok: false, status: 401, error: "notes: umtool holds no WORKER_TOKEN, so no agent can write here" }; + } + const given = Buffer.from(m[1].trim()); + const want = Buffer.from(token); + if (given.length !== want.length || !crypto.timingSafeEqual(given, want)) { + return { ok: false, status: 401, error: "notes: that bearer token is not umtool's WORKER_TOKEN" }; + } + return { ok: true, by: "agent" }; +} + +/** + * The POST: one op on a target's notes, by whoever the header proves. A refusal + * is `{ status, body: { error } }`; a write `{ status: 200, body }` with what + * writeNote returns. A stale token or a refused op THROWS (the route's + * errorResponse gives each its status). + * @param {Parameters<typeof writeNote>[0]} target + * @param {unknown} body `{ token?, op }` — any `by` in it is ignored + * @param {{ authorization?: string | null, workerToken: string }} auth + */ +export async function postNoteOp(target, body, auth) { + const who = noteWriter(auth.authorization, auth.workerToken); + if (!who.ok) return { status: who.status, body: { error: who.error } }; + const b = /** @type {{ token?: unknown, op?: unknown } | null} */ (body && typeof body === "object" ? body : null); + if (!b || typeof b.op !== "object" || b.op === null) return { status: 400, body: { error: "body needs an op" } }; + const token = typeof b.token === "string" ? b.token : null; + const out = await writeNote(target, /** @type {Record<string, any>} */ (b.op), { by: who.by, token }); + return { status: 200, body: out }; +} diff --git a/umtool/lib/annotations/agentAuth.test.mjs b/umtool/lib/annotations/agentAuth.test.mjs @@ -0,0 +1,102 @@ +// The notes route's writer (release 23 F3): no Authorization is the +// operator, umtool's WORKER_TOKEN as a bearer is an agent, any other header is +// a 401 with nothing written, and `by` in the body is never believed. The +// POST's logic (postNoteOp) over a temp notes.json, and the token read. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { agentToken, dotenvValue, noteWriter, postNoteOp } from "./agentAuth.mjs"; + +const TOKEN = "notes-test-token"; +const SUBJECT = { kind: "article", site: "s1", report: "r1" }; + +async function target() { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-agent-auth-")); + return { dir, target: { file: path.join(dir, "notes.json"), subject: SUBJECT, source: async () => null } }; +} + +const ADD = { op: "add", text: "fix this", anchor: { kind: "whole" } }; + +test("no Authorization: the operator's write, as before", async () => { + const { dir, target: t } = await target(); + const r = await postNoteOp(t, { op: ADD }, { authorization: null, workerToken: TOKEN }); + assert.equal(r.status, 200); + assert.equal(r.body.note.author, "operator"); + await rm(dir, { recursive: true }); +}); + +test("umtool's WORKER_TOKEN as a bearer: the agent's write — a note, a reply, a resolve", async () => { + const { dir, target: t } = await target(); + const auth = { authorization: `Bearer ${TOKEN}`, workerToken: TOKEN }; + const add = await postNoteOp(t, { op: ADD }, { authorization: null, workerToken: TOKEN }); + const id = add.body.note.id; + const r = await postNoteOp(t, { op: { op: "reply", id, text: "done in drafts/x.json", resolve: true } }, auth); + assert.equal(r.status, 200); + assert.equal(r.body.note.replies[0].author, "agent"); + assert.equal(r.body.note.status, "resolved"); + assert.equal(r.body.note.resolvedBy, "agent"); + const own = await postNoteOp(t, { op: ADD }, auth); + assert.equal(own.body.note.author, "agent"); + await rm(dir, { recursive: true }); +}); + +test("a wrong bearer, a malformed header, or any bearer when umtool holds no token: 401, nothing written", async () => { + const { dir, target: t } = await target(); + for (const [authorization, workerToken] of [ + ["Bearer not-the-token", TOKEN], + [`Bearer ${TOKEN}x`, TOKEN], + [`Basic ${TOKEN}`, TOKEN], + [`Bearer ${TOKEN}`, ""], + ]) { + const r = await postNoteOp(t, { op: ADD }, { authorization, workerToken }); + assert.equal(r.status, 401, `${authorization} / ${workerToken || "(none)"}`); + assert.match(r.body.error, /^notes: /); + } + await assert.rejects(stat(t.file), /ENOENT/); + await rm(dir, { recursive: true }); +}); + +test("`by` in the body is never believed", async () => { + const { dir, target: t } = await target(); + const asOperator = await postNoteOp(t, { by: "agent", op: { ...ADD, by: "agent", author: "agent" } }, { authorization: null, workerToken: TOKEN }); + assert.equal(asOperator.body.note.author, "operator"); + const asAgent = await postNoteOp(t, { by: "operator", op: { ...ADD, by: "operator", author: "operator" } }, { authorization: `Bearer ${TOKEN}`, workerToken: TOKEN }); + assert.equal(asAgent.body.note.author, "agent"); + const doc = JSON.parse(await readFile(t.file, "utf8")); + assert.deepEqual(doc.notes.map((n) => n.author), ["operator", "agent"]); + await rm(dir, { recursive: true }); +}); + +test("a body with no op is a 400", async () => { + const { dir, target: t } = await target(); + assert.equal((await postNoteOp(t, null, { authorization: null, workerToken: TOKEN })).status, 400); + assert.equal((await postNoteOp(t, { token: "absent" }, { authorization: `Bearer ${TOKEN}`, workerToken: TOKEN })).status, 400); + await rm(dir, { recursive: true }); +}); + +test("noteWriter: the header alone decides", () => { + assert.deepEqual(noteWriter(undefined, TOKEN), { ok: true, by: "operator" }); + assert.deepEqual(noteWriter("", TOKEN), { ok: true, by: "operator" }); + assert.deepEqual(noteWriter(`bearer ${TOKEN}`, TOKEN), { ok: true, by: "agent" }); + assert.equal(noteWriter("Bearer x", TOKEN).ok, false); +}); + +test("agentToken: the environment first (even empty), else the editor's env files in order", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-agent-token-")); + const local = path.join(dir, ".env.local"); + const plain = path.join(dir, ".env"); + await writeFile(plain, "# the editor's\nOTHER=1\nexport WORKER_TOKEN=\"from-env-file\"\n"); + assert.equal(agentToken({ WORKER_TOKEN: "from-environment" }, [local, plain]), "from-environment"); + assert.equal(agentToken({ WORKER_TOKEN: "" }, [local, plain]), ""); + assert.equal(agentToken({}, [local, plain]), "from-env-file"); + await writeFile(local, "WORKER_TOKEN=from-local # comment\n"); + assert.equal(agentToken({}, [local, plain]), "from-local"); + assert.equal(agentToken({}, [path.join(dir, "missing")]), ""); + assert.equal(dotenvValue("A=1\nWORKER_TOKEN='x y'\n", "WORKER_TOKEN"), "x y"); + assert.equal(dotenvValue("A=1\n", "WORKER_TOKEN"), undefined); + await rm(dir, { recursive: true }); +});