@melz0rs/worklist-mcp 0.0.0-stage → 1.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Worklist contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # worklist-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An MCP server that connects Claude Code (or any MCP client) to a **Worklist board**: a shared project
4
+ board of Projects, Journeys, work items, engineering Rules, review cards, questions, messages and
5
+ timelines, exposed as bounded tools an AI agent can call.
6
+
7
+ It is a **client and stores nothing.** The board lives behind an HTTP API run by your team; this
8
+ process holds no state between calls. Every tool is one or two bounded requests, and list results are
9
+ paginated by bytes as well as by rows so they always fit in the agent's context.
10
+
11
+ ## Install
12
+
13
+ You need two values from your board admin: the board's base URL and a token.
14
+
15
+ ```bash
16
+ claude mcp add worklist \
17
+ --env WORKLIST_URL=https://board.example.com \
18
+ --env WORKLIST_TOKEN=<your token> \
19
+ -- npx -y @melz0rs/worklist-mcp
20
+ ```
21
+
22
+ Requires Node.js 20 or newer.
23
+
24
+ ### Configuration
25
+
26
+ | variable | required | meaning |
27
+ |---|---|---|
28
+ | `WORKLIST_URL` | **yes** | The board API's base URL, e.g. `https://board.example.com`. There is no default: without it the server exits with a message. |
29
+ | `WORKLIST_TOKEN` | **yes** | Your bearer token, issued by the board admin. |
30
+ | `WORKLIST_INVENTORY_DIR` | no | Where purge/delete inventories are written. Defaults to `purge-inventories/` beside the installed package. |
31
+
32
+ ### Keep the token out of config files
33
+
34
+ A token pasted into `.mcp.json` or `~/.claude.json` sits in plain text and is easy to commit by
35
+ accident. Store it in your OS keychain and launch the server through a small wrapper that reads it:
36
+
37
+ ```bash
38
+ # macOS: store once
39
+ security add-generic-password -a "$USER" -s worklist-token -w '<your token>'
40
+ ```
41
+
42
+ ```bash
43
+ #!/bin/sh
44
+ # worklist-mcp-launch.sh
45
+ export WORKLIST_URL=https://board.example.com
46
+ export WORKLIST_TOKEN="$(security find-generic-password -a "$USER" -s worklist-token -w)"
47
+ exec npx -y @melz0rs/worklist-mcp
48
+ ```
49
+
50
+ ```bash
51
+ claude mcp add worklist -- /path/to/worklist-mcp-launch.sh
52
+ ```
53
+
54
+ On Linux, `secret-tool store` / `secret-tool lookup` (libsecret) plays the same role; on Windows, the
55
+ Credential Manager.
56
+
57
+ ## Permissions are the server's
58
+
59
+ A token may be board-wide or scoped to a single project. This client does not decide what you may
60
+ do: the server does. `worklist_projects_list` returns exactly the projects your token can touch, and
61
+ anything outside them is refused with a 403 and a plain reason. Destructive tools are guarded by a
62
+ dry-run plan and a confirmation token, and the server keeps its own checks.
63
+
64
+ ## Tools
65
+
66
+ | area | tools |
67
+ |---|---|
68
+ | Projects | `worklist_projects_list` / `_get` / `_create` / `_update` / `_delete` |
69
+ | Journeys | `worklist_journeys_list` / `_get` / `_create` / `_update` / `_park`, plus `worklist_journeys_delete_plan` / `worklist_journeys_delete` |
70
+ | Work items | `worklist_items_list` / `_get` / `_create` / `_update` / `_delete` |
71
+ | Rules | `worklist_rules_list` / `_get` / `_create` / `_update` / `_delete` |
72
+ | Purge | `worklist_purge_plan` / `worklist_purge_apply` (removes finished items from one Journey, dry run first) |
73
+ | Comm Center | `worklist_messages_list` / `_post` / `_reply` / `_mark_read` / `_attachment_get` (messages between people and their Claude sessions) |
74
+ | Review tab | `worklist_reviews_list` / `_publish` / `_attachment_get` / `_feedback_get` / `_assign_reviewer` / `_delete` / `_rules_list` |
75
+ | Feedback | `worklist_feedback_list` / `_post` / `_reply` / `_address`, `worklist_media_fetch` (an owner's verdicts on a Journey, and Claude's answers) |
76
+ | Questions | `worklist_questions_create` / `_list` / `_get` / `_withdraw` |
77
+ | Timeline | `worklist_timeline_get` / `_put`, `worklist_timeline_comments_list` / `worklist_timeline_comment` |
78
+ | Schedule | `worklist_schedule_list` / `_put` / `_delete`, `worklist_video_cycle` / `worklist_video_link` |
79
+ | Sessions | `worklist_heartbeat` / `worklist_heartbeats` (which agent sessions are alive, and on which machine) |
80
+
81
+ Each tool's description carries its full contract; the agent reads them on connect.
82
+
83
+ ## License
84
+
85
+ MIT
@@ -0,0 +1,107 @@
1
+ export const MCP_INLINE_RESPONSE_CAP_CHARS = 42_000;
2
+ export const LEAN_LIST_CAP_CHARS = 4_000;
3
+ export const LEAN_RECORD_CAP_CHARS = 12_000;
4
+ export const LEAN_FIELD_CAP_CHARS = 3_000;
5
+ export const LEAN_MESSAGES_CAP_CHARS = 10_000;
6
+ export const LEAN_SLICE_CAP_CHARS = 8_000;
7
+ export const LEAN_ROW_STRING_CAP_CHARS = 400;
8
+ export const LEAN_ERROR_CAP_CHARS = 600;
9
+ export const LEAN_SIBLING_PAGE_SIZE = 6;
10
+ export function dropEmpty(value) {
11
+ if (Array.isArray(value))
12
+ return value.map(dropEmpty).filter((v) => !isEmpty(v));
13
+ if (value && typeof value === "object") {
14
+ const out = {};
15
+ for (const [k, v] of Object.entries(value)) {
16
+ const d = dropEmpty(v);
17
+ if (!isEmpty(d))
18
+ out[k] = d;
19
+ }
20
+ return out;
21
+ }
22
+ return value;
23
+ }
24
+ const isEmpty = (v) => v === null || v === undefined || v === "" || (Array.isArray(v) && v.length === 0) || (typeof v === "object" && v !== null && !Array.isArray(v) && Object.keys(v).length === 0);
25
+ const WRITE_TOOLS = /^worklist_(?:(?:items|journeys|rules|projects)_(?:create|update|delete)|journeys_park|purge_apply|messages_(?:post|reply|mark_read)|feedback_(?:post|reply|address)|questions_(?:create|withdraw)|reviews_(?:publish|assign_reviewer|delete)|timeline_(?:put|comment)|heartbeat)$/;
26
+ const ID_KEYS = ["id", "message_id", "journey_id", "item_id", "review_id", "question_id", "reply_id", "entry_id"];
27
+ export function writeReceipt(body, args) {
28
+ const result = (body.result && typeof body.result === "object" ? body.result : {});
29
+ const out = { ok: result.ok !== false && body.ok !== false };
30
+ const scalar = (v) => typeof v === "number" || typeof v === "boolean" || (typeof v === "string" && v.length <= 200) || (v !== null && typeof v === "object" && !Array.isArray(v) && JSON.stringify(v).length <= 500);
31
+ for (const src of [body, result])
32
+ for (const [k, v] of Object.entries(src)) {
33
+ if (k === "ok" || k === "worklist" || k === "result" || out[k] !== undefined)
34
+ continue;
35
+ if (/(^|_)(rejected|refused)(_|$)/.test(k) && Array.isArray(v) && v.length) {
36
+ out[k] = v.slice(0, 10).map((x) => (typeof x === "string" ? capError(x) : x && typeof x === "object" ? Object.fromEntries(Object.entries(x).map(([a, b]) => [a, typeof b === "string" ? capError(b) : b])) : x));
37
+ continue;
38
+ }
39
+ if (scalar(v) || (k === "next_moves" && typeof v === "string"))
40
+ out[k] = v;
41
+ else if (Array.isArray(v) && (k === "written" || /(^|_)ids$/.test(k)) && v.every((x) => typeof x === "string" && x.length <= 40))
42
+ out[k] = v.slice(0, 50);
43
+ }
44
+ if (out.id === undefined) {
45
+ const written = result.written;
46
+ const id = (Array.isArray(written) && typeof written[0] === "string" ? written[0] : undefined) ?? ID_KEYS.map((k) => args[k]).find((v) => typeof v === "string");
47
+ if (id !== undefined)
48
+ out.id = id;
49
+ }
50
+ const record = (args.patch ?? args.record);
51
+ if (record && typeof record === "object")
52
+ out.changed = Object.keys(record).filter((k) => k !== "id");
53
+ if (typeof out.next_moves === "string" && out.next_moves.length > 700)
54
+ out.next_moves = `${out.next_moves.slice(0, 700)}…`;
55
+ return out;
56
+ }
57
+ export const capError = (message) => message.length <= LEAN_ERROR_CAP_CHARS ? message : `${message.slice(0, LEAN_ERROR_CAP_CHARS)}… [+${message.length - LEAN_ERROR_CAP_CHARS} chars cut]`;
58
+ export function clampRowStrings(body, how) {
59
+ const out = { ...body };
60
+ const cut = {};
61
+ const clamp = (v, path) => {
62
+ if (typeof v === "string") {
63
+ if (v.length <= LEAN_ROW_STRING_CAP_CHARS)
64
+ return v;
65
+ cut[path] = (cut[path] ?? 0) + 1;
66
+ return `${v.slice(0, LEAN_ROW_STRING_CAP_CHARS)}…[+${v.length - LEAN_ROW_STRING_CAP_CHARS}]`;
67
+ }
68
+ if (Array.isArray(v))
69
+ return v.map((x) => clamp(x, path));
70
+ if (v && typeof v === "object")
71
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, clamp(x, `${path}.${k}`)]));
72
+ return v;
73
+ };
74
+ for (const [k, v] of Object.entries(body))
75
+ if (Array.isArray(v))
76
+ out[k] = clamp(v, k);
77
+ if (Object.keys(cut).length)
78
+ out.clipped = { fields: Object.keys(cut), read_rest: how(Object.keys(cut)[0].split(".")[0]) };
79
+ return out;
80
+ }
81
+ export function leanResult(name, args, result) {
82
+ const first = result.content?.[0];
83
+ if (!first || first.type !== "text")
84
+ return result;
85
+ let parsed;
86
+ try {
87
+ parsed = JSON.parse(first.text);
88
+ }
89
+ catch {
90
+ return result.isError ? { ...result, content: [{ type: "text", text: capError(first.text) }] } : result;
91
+ }
92
+ const emit = (v) => ({ ...result, content: [{ type: "text", text: JSON.stringify(v) }] });
93
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
94
+ return emit(parsed);
95
+ let body = parsed;
96
+ if (result.isError)
97
+ return emit(dropEmpty({ ...body, error: typeof body.error === "string" ? capError(body.error) : body.error }));
98
+ if (WRITE_TOOLS.test(name)) {
99
+ const receipt = writeReceipt(body, args);
100
+ return receipt.ok === false ? { ...emit(receipt), isError: true } : emit(receipt);
101
+ }
102
+ if (!name.startsWith("worklist_messages_"))
103
+ body = dropEmpty(body);
104
+ if (/^worklist_(feedback_list|questions_list|reviews_list|heartbeats|timeline_comments_list|timeline_get)$/.test(name))
105
+ body = clampRowStrings(body, (key) => name === "worklist_feedback_list" ? "worklist_journeys_get {id: journey_id, field: \"feedback\", offset}" : name.startsWith("worklist_questions") ? "worklist_questions_get {id} reads the question and its answers in full" : name === "worklist_reviews_list" ? "worklist_reviews_feedback_get {review_id, id: the row's _id} (or id \"intro\") reads any cut text in full" : `re-call ${name} with a narrower filter`);
106
+ return emit(body);
107
+ }
@@ -0,0 +1,186 @@
1
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { basename, join, resolve } from "node:path";
4
+ const REASONING_PROP = { type: "string" };
5
+ const reasoningOf = (r) => (typeof r === "string" ? r : "");
6
+ export const FEEDBACK_TOOL_DEFS = [
7
+ { name: "worklist_feedback_list", description: "The PROJECT OWNER'S FEEDBACK on journeys — by default every entry that has NOT been addressed yet, board-wide, OLDEST FIRST. This is how you find out whether anything is owed to the owner before you start something new; an empty list means nothing is. Each entry carries its own `created_at` (the date the feedback is correct for — it is a verdict on the build that existed then, so it is never edited or superseded), the journey it is on, and, once dealt with, `addressed_at` plus the commit or work item that did it. Pass `include_addressed: true` to see the answered ones too, which is how you check whether a fix landed BEFORE or AFTER a given entry was written.", inputSchema: { type: "object", properties: { journey_id: { type: "string", pattern: "^j-\\d+$", description: "Only this journey's feedback." }, project_id: { type: "string", pattern: "^p-\\d+$" }, include_addressed: { type: "boolean", default: false, description: "Include entries already recorded as addressed. Off by default, so the plain call answers 'what is still owed'." }, page_size: { type: "integer", minimum: 1, maximum: 100, default: 50 }, cursor: { type: "string" } }, additionalProperties: false } },
8
+ { name: "worklist_feedback_post", description: "Write the project owner's feedback down FOR THEM, when they give a verdict in conversation after live-verifying rather than typing it into the web UI. It lands in the SAME stream a UI post does and has the SAME lifecycle: the journey leaves `user_review` and moves to `collecting_evidence` for you to attend to. IT IS RECORDED AS A TRANSCRIPTION, NOT AS THEIR TYPING — `text` must be their VERBATIM WORDS and nothing else (quote them; 'Rotary is clicking when I move the balance knob' is worth far more than 'owner reported an artefact on a control', because their phrasing carries which knob, what it sounded like and what they were doing). Anything YOU are adding — which build was installed, what had just changed — goes in `context`, never inside the quote. `said_at` is WHEN THEY SAID IT, not when you got round to writing it down: a fix that landed in between did not address it, and only this field can show that. Name the build they had with `installed_build`, or say `installed_build_unknown: true` — an invented sha is worse than an admitted gap.", inputSchema: { type: "object", properties: { journey_id: { type: "string", pattern: "^j-\\d+$" }, text: { type: "string", minLength: 1, description: "THEIR WORDS, VERBATIM. A quote, not a summary." }, said_at: { type: "string", description: "ISO timestamp of when THEY said it. Not when you wrote it down." }, context: { type: "string", description: "What YOU are adding around the quote: the installed build, what had just changed, what they were doing. Never a word of their quote." }, installed_build: { type: "string", description: "The commit sha or build id they had installed when they said it." }, installed_build_unknown: { type: "boolean", description: "Set TRUE when the installed build genuinely is not known. One of this and `installed_build` is required." }, relayed_by: { type: "string", default: "Claude", description: "Who transcribed it." }, attachments: { type: "array", maxItems: 6, description: "MEDIA POSTED WITH THE ENTRY — a measured render, a plot, a screenshot of the thing. Each item is { key, file_name, mime_type, size } and the KEY MUST ALREADY EXIST in this journey's store (it is one of this journey's feedback attachment keys); this tool does not upload. KEYS, NEVER URLS: the entry is append-only, so a presigned URL stored on it would rot with no way to repair it. The same bound the owner's own uploads get applies — an allow-listed content type and one shared size cap — and the server refuses a key belonging to another journey.", items: { type: "object", properties: { key: { type: "string" }, file_name: { type: "string" }, mime_type: { type: "string" }, size: { type: "number" } }, required: ["key", "file_name", "mime_type", "size"], additionalProperties: false } }, reasoning: REASONING_PROP }, required: ["journey_id", "text", "said_at"], additionalProperties: false } },
9
+ { name: "worklist_feedback_reply", description: "ANSWER one of the project owner's feedback entries — and this is how they find out you did. Posting a reply puts the journey straight back into their VERIFICATION QUEUE (status user_review) with a FRESH entered-at, at the BOTTOM, labelled so the row reads 'Claude replied' rather than a review checklist, so the owner sees it and can reply. They read replies under their verdict in the journey's feedback; listening pages go to the Review tab. Use it when you have something they must READ and answer — a question about what they meant, a finding that changes what they asked for, or what you did about it and what you need from them. It does NOT close the entry: closing is worklist_feedback_address, which needs a landed commit or work item. The reply is append-only and cannot be edited or deleted, like the verdict it hangs under.\n\nIT CAN CARRY IMAGES. Pass `attachments` as LOCAL FILE PATHS and this tool uploads them, stores them under the journey and hangs them on the reply — the owner sees them in the web UI, under your words, labelled \"Attached by Claude\". That is what makes three sentences enough: a plotted curve or a faceplate carries what the words cannot. It does NOT buy a fourth sentence. If any one file fails to upload the WHOLE reply is refused and nothing is posted, because an append-only reply pointing at a missing file could never be repaired.", inputSchema: { type: "object", properties: { journey_id: { type: "string", pattern: "^j-\\d+$" }, feedback_id: { type: "string", pattern: "^f-\\d+$", description: "The entry you are answering." }, text: { type: "string", minLength: 1, description: "What you are saying to the owner. THREE SENTENCES MAXIMUM — a standing rule, enforced: a longer reply is REFUSED. The owner reads this on the queue row, so lead with what you need from them and put the detail in status_evidence." }, author: { type: "string", default: "Claude", description: "Who is replying." }, attachments: { type: "array", maxItems: 6, description: "LOCAL FILE PATHS to attach to the reply — screenshots, plots, measured renders. THIS TOOL UPLOADS THEM: pass the path on disk, not a key and not a URL. At most 6, each an allow-listed image or audio type (png/jpeg/gif/webp, wav/mp3/m4a/aac/ogg/flac) under 64 MB. THE PICTURE IS WHY THIS EXISTS: a reply is THREE SENTENCES and a plotted curve carries what three sentences cannot — but it does NOT buy you a fourth sentence, the cap is unchanged. ALL OR NOTHING: if any one file fails to upload, the whole reply is REFUSED and nothing is posted, because a reply is append-only and one referencing a missing object could never be repaired.", items: { type: "string", minLength: 1 } }, reasoning: REASONING_PROP }, required: ["journey_id", "feedback_id", "text"], additionalProperties: false } },
10
+ { name: "worklist_feedback_address", description: "Record that ONE piece of feedback has been dealt with, and WHAT dealt with it. Needs the journey, the `feedback_id`, a one-line `note` saying what was actually done, and at least one of `commit` (the sha that landed the fix) or `item_id` (the worklist item that carried it) — 'addressed' with nothing to point at is a claim rather than a record. Pass `fix_landed_at` when you know it: a fix that landed BEFORE the feedback was written is REFUSED, because it answered a different question. An entry can be addressed once; if the owner is saying something new, that is new feedback, which only they post (or you relay with worklist_feedback_post).", inputSchema: { type: "object", properties: { journey_id: { type: "string", pattern: "^j-\\d+$" }, feedback_id: { type: "string", pattern: "^f-\\d+$" }, note: { type: "string", minLength: 1, description: "One line: what was actually done about it." }, commit: { type: "string", description: "The git sha that landed the fix (7-40 hex characters)." }, item_id: { type: "string", pattern: "^w-\\d+$", description: "The worklist item that carried the work." }, fix_landed_at: { type: "string", description: "ISO timestamp of when the fix landed. Refused if it is EARLIER than the feedback's own created_at." }, reasoning: REASONING_PROP }, required: ["journey_id", "feedback_id", "note"], additionalProperties: false } },
11
+ { name: "worklist_media_fetch", description: "FETCH ONE SCREENSHOT OR RECORDING the project owner attached to a piece of feedback, and LAND IT ON DISK so you can actually open it. Takes the `journey_id` and the attachment's `key` (every feedback entry that carries media lists them under `attachments`, each with its key, file_name, mime_type and size). It downloads the bytes through the board's own authenticated read and returns the LOCAL PATH it wrote them to.\n\nFOR AN IMAGE: open that path with your Read tool and LOOK AT IT. A screenshot the owner pasted is usually the fastest evidence in the whole record — it is the product's own UI, or the meter, or the artefact, at the moment they saw it.\n\nFOR AUDIO: *** YOU CANNOT LISTEN TO IT. *** There is no path by which you hear this file, and NEVER invent a transcription or a description of what it sounds like — that is a fabricated observation, and one about the exact thing their verdict turns on. What this tool does for audio is land a WAV or MP3 where your project's own measurement tools can read it: run it through them and MEASURE it. Every audio claim needs numbers from the project's own measurement tooling, not from a script written for the question and not from an impression. If you cannot measure the thing the owner is complaining about, say so and say what is missing; abstain rather than describe.\n\nThe fetch is authorised the same way reading the journey is: a key belongs to exactly one journey, and a token scoped to another project is refused.", inputSchema: { type: "object", properties: { journey_id: { type: "string", pattern: "^j-\\d+$" }, key: { type: "string", minLength: 1, description: "The attachment's `key` exactly as the feedback entry records it — as listed under the entry's `attachments`. Keys, not URLs: the record stores keys precisely because a presigned URL would have expired." }, out_dir: { type: "string", description: "Where to write it. Defaults to a `worklist-media/<journey_id>` folder under the MCP's state directory." } }, required: ["journey_id", "key"], additionalProperties: false } },
12
+ ];
13
+ export const FEEDBACK_TOOL_NAMES = new Set(FEEDBACK_TOOL_DEFS.map((t) => t.name));
14
+ async function feedbackRead(path, args, deps) {
15
+ const p = new URLSearchParams();
16
+ for (const [key, value] of Object.entries(args)) {
17
+ if (value === undefined || value === null || value === "" || key === "reasoning")
18
+ continue;
19
+ p.set(key, value === true ? "1" : String(value));
20
+ }
21
+ const doFetch = deps.fetchImpl ?? fetch;
22
+ const response = await doFetch(`${deps.base}${path}?${p}`, { headers: deps.headers(), cache: "no-store" });
23
+ const body = await response.json();
24
+ if (!response.ok)
25
+ throw new Error(body.error ?? `feedback read failed (${response.status})`);
26
+ return body;
27
+ }
28
+ const MAX_REPLY_SENTENCES = 3;
29
+ function countSentences(text) {
30
+ const masked = text.replace(/(\d)[.,](\d)/g, "$1\u0000$2");
31
+ return masked
32
+ .split(/\r?\n+/)
33
+ .flatMap((line) => line.split(/[.!?]+(?:\s|$)/))
34
+ .map((part) => part.trim())
35
+ .filter((part) => part.length > 0).length;
36
+ }
37
+ function assertReplyLength(text) {
38
+ const n = countSentences(text);
39
+ if (n <= MAX_REPLY_SENTENCES)
40
+ return;
41
+ throw new Error(`worklist_feedback_reply refused: this reply is ${n} sentences and THE RULE IS THREE SENTENCES, MAXIMUM (replies must stay concrete, 3 sentences MAX). The owner reads this on the queue row, so say what you need from them and cut the rest. Separate lines and bullets each count as a sentence. Put the detail in the journey's status_evidence, where it belongs, and keep the reply to what they must read.`);
42
+ }
43
+ async function fetchMedia(args, deps) {
44
+ const journey_id = String(args.journey_id ?? "");
45
+ const key = String(args.key ?? "");
46
+ if (!/^j-\d+$/.test(journey_id))
47
+ throw new Error("`journey_id` must look like `j-52`");
48
+ const marker = `/journeys/${journey_id}/feedback/`;
49
+ const at = key.indexOf(marker);
50
+ if (at <= 0 || !/^[a-z0-9_-]+$/.test(key.slice(0, at)) || key.includes(".."))
51
+ throw new Error(`that key does not belong to ${journey_id} — an attachment's key contains \`journeys/${journey_id}/feedback/\`, and it is the key's journey that authorises reading it. Read the entry's \`attachments\` and pass the key exactly as recorded.`);
52
+ const doFetch = deps.fetchImpl ?? fetch;
53
+ const url = `${deps.base}/api/internal/worklist/media?journey_id=${encodeURIComponent(journey_id)}&key=${encodeURIComponent(key)}`;
54
+ const response = await doFetch(url, { headers: deps.headers(), cache: "no-store" });
55
+ if (!response.ok) {
56
+ const body = await response.json().catch(() => ({}));
57
+ throw new Error(body.error ?? `that attachment could not be fetched (${response.status})`);
58
+ }
59
+ const contentType = response.headers.get("content-type") ?? "application/octet-stream";
60
+ const bytes = Buffer.from(await response.arrayBuffer());
61
+ const dir = typeof args.out_dir === "string" && args.out_dir.trim()
62
+ ? resolve(args.out_dir.trim())
63
+ : resolve(deps.mediaDir ?? join(tmpdir(), "worklist-media"), journey_id);
64
+ mkdirSync(dir, { recursive: true });
65
+ const path = resolve(dir, key.slice(at + marker.length).replace(/[^A-Za-z0-9._-]/g, "_"));
66
+ writeFileSync(path, bytes);
67
+ const audio = contentType.startsWith("audio/");
68
+ return {
69
+ path, content_type: contentType, bytes: bytes.byteLength, journey_id, key,
70
+ next_moves: audio
71
+ ? "THIS IS AUDIO AND YOU CANNOT LISTEN TO IT. Do not describe, transcribe or characterise what it sounds like — that would be a fabricated observation about the exact thing their verdict turns on. MEASURE it: run this path through your project's own measurement tools and quote the numbers — every audio claim needs them. If the quantity the owner is talking about cannot be measured yet, say so plainly — that is a gap to close, and abstaining is the correct answer until it is."
72
+ : "OPEN THIS PATH WITH YOUR READ TOOL AND LOOK AT IT. It is a screenshot the owner took of what they were seeing; read it as evidence, not as decoration, and say what is actually in it.",
73
+ };
74
+ }
75
+ const MAX_REPLY_ATTACHMENTS = 6;
76
+ function assertReplyAttachments(raw) {
77
+ if (raw === undefined)
78
+ return [];
79
+ if (!Array.isArray(raw)) {
80
+ const got = raw === null ? "null" : typeof raw === "string" ? `the string ${JSON.stringify(raw)}` : `a ${typeof raw}`;
81
+ throw new Error(`worklist_feedback_reply refused: \`attachments\` must be an ARRAY of local file paths and got ${got}. One file still goes in an array — \`attachments: ["/path/to/plot.png"]\`. Passed any other way it is silently ignored and the reply posts with NO media while reporting success, which on an append-only record cannot be repaired.`);
82
+ }
83
+ if (raw.length === 0)
84
+ throw new Error("worklist_feedback_reply refused: `attachments` is an EMPTY array. Omit it entirely for a reply with no media — an empty array asks for an upload of nothing and would post a reply you believed carried a picture.");
85
+ if (raw.length > MAX_REPLY_ATTACHMENTS)
86
+ throw new Error(`worklist_feedback_reply refused: ${raw.length} attachments, and a reply may carry at most ${MAX_REPLY_ATTACHMENTS} (the same bound the owner's own posts get). Attach the one or two that make the point; the rest belong in the journey's documents.`);
87
+ const paths = [];
88
+ for (const entry of raw) {
89
+ if (typeof entry !== "string" || !entry.trim())
90
+ throw new Error(`worklist_feedback_reply refused: every entry in \`attachments\` must be a non-empty LOCAL FILE PATH, and one is ${entry === null ? "null" : `a ${typeof entry}`}. This tool uploads the file — it does not take a stored key and it does not take a URL.`);
91
+ const path = resolve(entry.trim());
92
+ let size;
93
+ try {
94
+ const stat = statSync(path);
95
+ if (!stat.isFile())
96
+ throw new Error("not a file");
97
+ size = stat.size;
98
+ }
99
+ catch {
100
+ throw new Error(`worklist_feedback_reply refused: \`${entry}\` is not a readable file on this machine (resolved to ${path}). Nothing was uploaded and nothing was posted. Check the path before retrying.`);
101
+ }
102
+ if (size === 0)
103
+ throw new Error(`worklist_feedback_reply refused: \`${entry}\` is EMPTY (0 bytes). An empty attachment shows the owner nothing.`);
104
+ paths.push(path);
105
+ }
106
+ return paths;
107
+ }
108
+ async function uploadReplyMedia(journey_id, path, deps) {
109
+ const authorization = deps.headers().authorization;
110
+ const form = new FormData();
111
+ form.append("journey_id", journey_id);
112
+ form.append("file", new Blob([new Uint8Array(readFileSync(path))]), basename(path));
113
+ const doFetch = deps.fetchImpl ?? fetch;
114
+ const response = await doFetch(`${deps.base}/api/internal/worklist/media`, {
115
+ method: "POST", headers: { authorization }, body: form,
116
+ });
117
+ const body = await response.json().catch(() => ({}));
118
+ if (!response.ok)
119
+ throw new Error(String(body.error ?? `upload failed (${response.status})`));
120
+ if (typeof body.key !== "string" || !body.key)
121
+ throw new Error("the upload route answered without a `key`, so there is nothing the reply could reference");
122
+ return { key: body.key, file_name: body.file_name, mime_type: body.mime_type, size: body.size };
123
+ }
124
+ async function uploadAllOrRefuse(journey_id, paths, deps) {
125
+ const stored = [];
126
+ for (const path of paths) {
127
+ try {
128
+ stored.push(await uploadReplyMedia(journey_id, path, deps));
129
+ }
130
+ catch (error) {
131
+ const orphans = stored.map((a) => String(a.key));
132
+ throw new Error(`worklist_feedback_reply refused: \`${path}\` could not be uploaded (${error instanceof Error ? error.message : String(error)}). NOTHING WAS POSTED — no reply exists and the journey has not moved, because a reply is append-only and one referencing a file that is not there could never be repaired.${orphans.length ? ` ${orphans.length} file(s) DID upload and are now unreferenced objects: ${orphans.join(", ")} — they are harmless and nothing points at them, but they are named here rather than swallowed.` : ""} Fix the cause and call this again with the same text and the same paths.`);
133
+ }
134
+ }
135
+ return stored;
136
+ }
137
+ const ok = (payload) => ({ content: [{ type: "text", text: JSON.stringify(payload) }] });
138
+ export async function handleFeedbackTool(name, args, deps) {
139
+ const mutate = (record, reasoning) => deps.mutate(record, reasoning);
140
+ const assertIdShapes = deps.assertIdShapes;
141
+ if (name === "worklist_media_fetch") {
142
+ try {
143
+ return ok(await fetchMedia(args, deps));
144
+ }
145
+ catch (error) {
146
+ return { content: [{ type: "text", text: JSON.stringify({ error: error instanceof Error ? error.message : String(error) }) }], isError: true };
147
+ }
148
+ }
149
+ {
150
+ try {
151
+ assertIdShapes(args);
152
+ if (name === "worklist_feedback_list") {
153
+ const { include_addressed, ...rest } = args;
154
+ const body = await feedbackRead("/api/internal/worklist/feedback", { ...rest, ...(include_addressed ? { include_addressed: true } : {}) }, deps);
155
+ const rows = (body.feedback ?? []);
156
+ return ok({ ...body, next_moves: rows.length === 0
157
+ ? "No unaddressed feedback. Nothing is owed to the owner on this board; carry on with the work you were doing."
158
+ : `${rows.length} piece(s) of feedback are waiting. READ THE DATE on each one: it is a verdict on the build that existed then, so check whether your fix landed AFTER it before deciding it is already handled. When one is genuinely dealt with, record it with worklist_feedback_address (a note plus the commit or the work item) — an entry nobody closes stays on this list forever.` });
159
+ }
160
+ if (name === "worklist_feedback_post") {
161
+ const { journey_id, reasoning, relayed_by, ...rest } = args;
162
+ const result = await mutate({ id: journey_id, feedback_append: {
163
+ ...rest,
164
+ source: "producer_relayed_by_claude",
165
+ relayed_by: typeof relayed_by === "string" && relayed_by.trim() ? relayed_by.trim() : "Claude",
166
+ } }, reasoningOf(reasoning));
167
+ return ok({ ...result, recorded_as: "producer_relayed_by_claude",
168
+ next_moves: "Written down as a TRANSCRIPTION, not as their typing — a later session can see that you rendered their words and treat them as a lead rather than as primary evidence. The journey has left `user_review` if it was there. Now attend to it: when the fix LANDS, close the entry with worklist_feedback_address naming the commit, and pass `fix_landed_at` — it is checked against WHEN THEY SAID IT, so a fix that landed before they spoke will be refused. If you paraphrased rather than quoted them, say so to them now and post their actual words: the quote is the evidence." });
169
+ }
170
+ if (name === "worklist_feedback_reply") {
171
+ const { journey_id, reasoning, attachments, ...reply } = args;
172
+ assertReplyLength(String(reply.text ?? ""));
173
+ const paths = assertReplyAttachments(attachments);
174
+ const stored = paths.length ? await uploadAllOrRefuse(String(journey_id), paths, deps) : [];
175
+ const result = await mutate({ id: journey_id, feedback_reply: { ...reply, ...(stored.length ? { attachments: stored } : {}) } }, reasoningOf(reasoning));
176
+ return ok({ ...result, ...(stored.length ? { attachments: stored } : {}), next_moves: `Posted${stored.length ? ` with ${stored.length} attachment(s) stored and referenced BY KEY — the URL is derived when the owner opens the drawer, never stored, because the reply is append-only. They render under your words labelled "Attached by Claude", so they can never read as something the owner put there.` : ""}, and the journey is back in user_review (the owner's turn) with a fresh entered-at, labelled 'Claude replied', so they can tell it from a hand-over without opening it. It is now their turn: do not hand the same journey over again and do not re-reply while you are waiting. When they answer, it arrives as new feedback (worklist_feedback_list) and the journey leaves the queue by itself.` });
177
+ }
178
+ const { journey_id, reasoning, ...address } = args;
179
+ const result = await mutate({ id: journey_id, feedback_address: address }, reasoningOf(reasoning));
180
+ return ok({ ...result, next_moves: "Recorded. The entry keeps its original date and text — only the answer was added beside it. If this closed the last unaddressed feedback on the journey and the work is ready for the owner's ears again, hand it back with worklist_journeys_update { status: 'user_review' } and a fresh `review_checklist`." });
181
+ }
182
+ catch (error) {
183
+ return { content: [{ type: "text", text: JSON.stringify({ error: error instanceof Error ? error.message : String(error) }) }], isError: true };
184
+ }
185
+ }
186
+ }
@@ -0,0 +1,37 @@
1
+ export const HEARTBEAT_TOOL_DEFS = [
2
+ { name: "worklist_heartbeat", description: "Say THIS Claude session is alive, on every loop: its `session` name, the `machine` it runs on, whether Cubase / Ableton is open there RIGHT NOW (`daw`; check, never assume: Windows `tasklist | findstr /i cubase`, macOS `pgrep -xi cubase` / `pgrep -x Live`), a one-line `activity` (what you are doing or waiting on) and an optional `mode` (e.g. idle / mild / heavy). The server stamps the time and takes WHO from your token. Shown on the Review page's Sessions panel, where freshness is judged against your own beat interval, so beat at a steady rhythm.",
3
+ inputSchema: { type: "object", properties: {
4
+ session: { type: "string", minLength: 1, maxLength: 80, description: "This session's name, e.g. alice-claude." },
5
+ machine: { type: "string", minLength: 1, maxLength: 80, description: "This computer's short name, e.g. alice-pc." },
6
+ daw: { type: "object", properties: { cubase: { type: "boolean" }, ableton: { type: "boolean" } }, required: ["cubase", "ableton"], additionalProperties: false },
7
+ activity: { type: "string", maxLength: 240, description: "One line: what you are doing or waiting on." },
8
+ mode: { type: "string", maxLength: 80, description: "Optional load mode, e.g. idle / mild / heavy." }
9
+ },
10
+ required: ["session", "machine", "daw"], additionalProperties: false } },
11
+ { name: "worklist_heartbeats", description: "Read every machine and Claude session that has sent a heartbeat: each machine's DAW state (Cubase / Ableton open) and each session's last beat, interval and activity line.",
12
+ inputSchema: { type: "object", properties: {}, additionalProperties: false } },
13
+ ];
14
+ export const HEARTBEAT_TOOL_NAMES = new Set(HEARTBEAT_TOOL_DEFS.map((tool) => tool.name));
15
+ const ok = (value) => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
16
+ const err = (message) => ({ isError: true, content: [{ type: "text", text: JSON.stringify({ error: message }) }] });
17
+ export async function handleHeartbeatTool(name, args, deps) {
18
+ const url = `${deps.base.replace(/\/$/, "")}/api/internal/worklist/heartbeat`;
19
+ const doFetch = deps.fetchImpl ?? fetch;
20
+ try {
21
+ if (name === "worklist_heartbeat") {
22
+ const daw = (args.daw ?? {});
23
+ if (typeof args.session !== "string" || typeof args.machine !== "string" || typeof daw.cubase !== "boolean" || typeof daw.ableton !== "boolean")
24
+ return err("worklist_heartbeat needs `session`, `machine` and `daw: { cubase: true|false, ableton: true|false }` (check the processes, never assume)");
25
+ const response = await doFetch(url, { method: "POST", headers: { ...deps.headers(), "content-type": "application/json" },
26
+ body: JSON.stringify({ session: args.session, machine: args.machine, daw: { cubase: daw.cubase, ableton: daw.ableton }, activity: args.activity ?? "", mode: args.mode ?? "" }) });
27
+ const body = await response.json().catch(() => ({}));
28
+ return response.ok ? ok(body) : err(String(body.error ?? `heartbeat failed (${response.status})`));
29
+ }
30
+ const response = await doFetch(url, { headers: deps.headers(), cache: "no-store" });
31
+ const body = await response.json().catch(() => ({}));
32
+ return response.ok ? ok(body) : err(String(body.error ?? `read failed (${response.status})`));
33
+ }
34
+ catch (error) {
35
+ return err(error instanceof Error ? error.message : String(error));
36
+ }
37
+ }