@cohortapp/agent-sdk 2.18.19 → 2.18.21
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/bin/cohort-mcp.mjs +16 -4
- package/lib/channels/inbox-item.mjs +17 -1
- package/lib/cli/doctor-checks.mjs +19 -0
- package/lib/engine/mcp/client.mjs +6 -2
- package/lib/engine/mcp/supervisor.mjs +43 -4
- package/lib/mcp/server.mjs +127 -5
- package/lib/mcp/staleness.mjs +331 -0
- package/lib/org/inbound/project.mjs +23 -0
- package/lib/org/work-ledger.mjs +28 -0
- package/package.json +1 -1
- package/scripts/local-triggers/autoupdate.sh +43 -0
- package/scripts/poller/inbox-scan-poller.mjs +9 -0
- package/scripts/poller/utils.mjs +14 -1
package/bin/cohort-mcp.mjs
CHANGED
|
@@ -75,7 +75,19 @@ const server = createMcpServer({
|
|
|
75
75
|
});
|
|
76
76
|
server.start();
|
|
77
77
|
|
|
78
|
-
// Exit cleanly when the client goes away (stdin closes).
|
|
79
|
-
process
|
|
80
|
-
|
|
81
|
-
|
|
78
|
+
// Exit cleanly when the client goes away (stdin closes). `server.stop()` first,
|
|
79
|
+
// so this process withdraws its state/mcp/servers/<pid>.json registry record —
|
|
80
|
+
// the one thing that tells `maestro doctor` which version each live MCP server
|
|
81
|
+
// is actually running. A SIGKILL leaves the record behind by definition; the
|
|
82
|
+
// doctor row drops records whose pid is gone, so a leftover is inert.
|
|
83
|
+
const bye = () => {
|
|
84
|
+
try {
|
|
85
|
+
server.stop();
|
|
86
|
+
} catch {
|
|
87
|
+
/* never block the exit */
|
|
88
|
+
}
|
|
89
|
+
process.exit(0);
|
|
90
|
+
};
|
|
91
|
+
process.stdin.on("end", bye);
|
|
92
|
+
process.on("SIGINT", bye);
|
|
93
|
+
process.on("SIGTERM", bye);
|
|
@@ -120,7 +120,7 @@ export function yamlScalar(s) {
|
|
|
120
120
|
const QUOTED_SCALAR_FIELDS = [
|
|
121
121
|
"id", "service", "channel", "channel_id", "sender", "sender_id",
|
|
122
122
|
"sender_privilege", "timestamp", "subject", "thread_id", "raw_ref", "kind",
|
|
123
|
-
"event_kind", "direct_reason", "scope_id", "channel_kind", "channel_type",
|
|
123
|
+
"event_kind", "author_kind", "direct_reason", "scope_id", "channel_kind", "channel_type",
|
|
124
124
|
"event_type",
|
|
125
125
|
];
|
|
126
126
|
|
|
@@ -279,6 +279,22 @@ export function eventToInboxItem(ev) {
|
|
|
279
279
|
item.event_kind = sanitizeYamlField(chainKind);
|
|
280
280
|
}
|
|
281
281
|
|
|
282
|
+
// THE AUTHOR'S KIND ("HUMAN" | "AI_AGENT"), by the same rule and for a
|
|
283
|
+
// measured reason. `lib/org/work-ledger.mjs` sends `authorKind` to hq's board
|
|
284
|
+
// gate, whose clause 2 refuses a row for an agent author; this converter
|
|
285
|
+
// enumerates its fields, so before this line the kind `project.mjs` resolved
|
|
286
|
+
// died HERE and the ledger's `undefined` became the string "HUMAN". Every seat
|
|
287
|
+
// therefore asserted a human author for every ask — which is how an agent's
|
|
288
|
+
// own "Archived, logged." minted board rows on 2026-09-30.
|
|
289
|
+
//
|
|
290
|
+
// Read off the event, not the org projection: `project.mjs` stamps it at top
|
|
291
|
+
// level next to `sender`, and only when `facts.memberKinds` PROVED it. An
|
|
292
|
+
// unknown kind stays absent rather than defaulting, because a wrong assertion
|
|
293
|
+
// here would cost a legitimate row.
|
|
294
|
+
if (ev.author_kind === "HUMAN" || ev.author_kind === "AI_AGENT") {
|
|
295
|
+
item.author_kind = ev.author_kind;
|
|
296
|
+
}
|
|
297
|
+
|
|
282
298
|
// THE DIRECTEDNESS REASON, for the same reason and by the same rule.
|
|
283
299
|
//
|
|
284
300
|
// `lib/org/inbound/directedness.mjs` does real work to answer WHY an event is
|
|
@@ -36,6 +36,7 @@ import { readSeatEngine } from "../runtime/adapter.mjs";
|
|
|
36
36
|
import { sessionLiveness, SESSION_STALE_MS } from "../telemetry/collect.mjs";
|
|
37
37
|
import { CONSOLE_KEY_REMEDY, SEAT_AUTH_VARS, REQUIRE_CONSOLE_KEY_VAR, seatAuthVerdict } from "./seat-auth.mjs";
|
|
38
38
|
import { CLAUDE_BIN_CANDIDATES, isSafeExecutable } from "../claude-bin.mjs";
|
|
39
|
+
import { SERVER_REGISTRY_REL, mcpServerRows } from "../mcp/staleness.mjs";
|
|
39
40
|
|
|
40
41
|
export const SDK_PACKAGE = "@cohortapp/agent-sdk";
|
|
41
42
|
/** The SDK checkout this module ships in — the source of the shipped hook copies. */
|
|
@@ -525,6 +526,7 @@ function agentFirstName(cwd) {
|
|
|
525
526
|
* @param {() => string[]} [o.listPlists] names in ~/Library/LaunchAgents
|
|
526
527
|
* @param {(agentRoot:string)=>object} [o.probeClaude]
|
|
527
528
|
* @param {(agentRoot:string)=>string} [o.seatEngine] the seat's runtime.engine (default: config/agent.json)
|
|
529
|
+
* @param {(pid:number)=>boolean} [o.pidAlive] is a pid running (default: process.kill(pid,0))
|
|
528
530
|
* @returns {Promise<Array<{level:"ok"|"warn"|"fail", msg:string}>>}
|
|
529
531
|
*/
|
|
530
532
|
export async function runDoctorChecks(o = {}) {
|
|
@@ -697,6 +699,23 @@ export async function runDoctorChecks(o = {}) {
|
|
|
697
699
|
rows.push(binRow);
|
|
698
700
|
}
|
|
699
701
|
|
|
702
|
+
// ── Cohort MCP servers: which version is each one RUNNING? (§3.1) ─────────
|
|
703
|
+
//
|
|
704
|
+
// Not "is one installed" — every other row here would have passed on the seat
|
|
705
|
+
// that spent three weeks enforcing a retired governance rule. A stdio MCP
|
|
706
|
+
// server has no launchd label, no port and nothing in the upgrade path that
|
|
707
|
+
// ends it, so the ONLY way to ask is the record each server writes at boot
|
|
708
|
+
// (lib/mcp/server.mjs → state/mcp/servers/<pid>.json). Records whose pid is
|
|
709
|
+
// gone are dropped, so a SIGKILLed server's leftover file is inert.
|
|
710
|
+
{
|
|
711
|
+
const dir = join(cwd, SERVER_REGISTRY_REL);
|
|
712
|
+
const files = (() => { try { return readdirSync(dir).filter((f) => f.endsWith(".json")); } catch { return []; } })();
|
|
713
|
+
const records = files.map((f) => safeJson(join(dir, f))).filter(Boolean);
|
|
714
|
+
const alive = o.pidAlive || ((pid) => { try { process.kill(pid, 0); return true; } catch { return false; } });
|
|
715
|
+
const installedSdk = (() => { try { return JSON.parse(readFileSync(join(cwd, "node_modules", "@cohortapp", "agent-sdk", "package.json"), "utf8")).version || ""; } catch { return ""; } })();
|
|
716
|
+
for (const row of mcpServerRows({ records, installed: installedSdk, pidAlive: alive })) rows.push(row);
|
|
717
|
+
}
|
|
718
|
+
|
|
700
719
|
// ── Main session job (§3.1) ───────────────────────────────────────────────
|
|
701
720
|
const listPlists = o.listPlists || (() => { try { return readdirSync(join(homedir(), "Library", "LaunchAgents")); } catch { return []; } });
|
|
702
721
|
const loaded = parseLaunchctlList(tryExec("launchctl", ["list"], { timeout: 4000 }));
|
|
@@ -51,7 +51,7 @@ export const DEFAULT_TOOL_TIMEOUT_MS = 10 * 60_000;
|
|
|
51
51
|
const MAX_LIST_PAGES = 100;
|
|
52
52
|
|
|
53
53
|
/**
|
|
54
|
-
* @typedef {{ok:true, content:string, images?:Array<{mediaType:string, data:string}>}|{ok:false, error:string}} ToolOutcome
|
|
54
|
+
* @typedef {{ok:true, content:string, images?:Array<{mediaType:string, data:string}>}|{ok:false, error:string, code?:number}} ToolOutcome
|
|
55
55
|
* @typedef {Object} McpConnection
|
|
56
56
|
* @property {string} name
|
|
57
57
|
* @property {string} protocolVersion
|
|
@@ -241,7 +241,11 @@ async function connect(config, deps, baseEnv) {
|
|
|
241
241
|
function rpcFailure(error, what) {
|
|
242
242
|
switch (error.kind) {
|
|
243
243
|
case "rpc":
|
|
244
|
-
|
|
244
|
+
// The CODE travels, not only the sentence. A caller that must react to
|
|
245
|
+
// a specific refusal — mcp/supervisor.mjs restarts a server that
|
|
246
|
+
// answers STALE_SDK (-32010) — should switch on the number rather than
|
|
247
|
+
// grep an English message that a copy-edit can change.
|
|
248
|
+
return { ok: false, code: error.code, error: `MCP server "${name}" refused ${what}: ${error.message} (code ${error.code})` };
|
|
245
249
|
case "aborted":
|
|
246
250
|
return { ok: false, error: `${what} was cancelled.` };
|
|
247
251
|
case "timeout":
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* lib/engine/mcp/supervisor.mjs — a crashed stdio server gets one
|
|
2
|
+
* lib/engine/mcp/supervisor.mjs — a crashed OR STALE stdio server gets one
|
|
3
|
+
* restart per run.
|
|
3
4
|
*
|
|
4
5
|
* A stdio MCP server that dies (a crash, an out-of-memory kill) takes its
|
|
5
6
|
* tools with it. The supervisor wraps a connection with the same interface;
|
|
@@ -9,6 +10,18 @@
|
|
|
9
10
|
* crash, with a note that the restart was already used. HTTP servers are not
|
|
10
11
|
* restarted (their process is not ours; each request already reconnects).
|
|
11
12
|
*
|
|
13
|
+
* STALE CODE IS THE SECOND REASON TO RESTART, and the one that motivated it.
|
|
14
|
+
* A stdio server is a child of its client: it has no launchd label, nothing in
|
|
15
|
+
* the seat's upgrade path ends it, and ESM resolves its module graph exactly
|
|
16
|
+
* once — so it serves whatever it booted with for as long as the client lives.
|
|
17
|
+
* On 2026-09-30 one cohort-mcp server on this seat had been up 20 days and ~24
|
|
18
|
+
* releases, enforcing an AI-disclosure rule retired in 2.18.9. It now refuses
|
|
19
|
+
* with STALE_SDK (lib/mcp/staleness.mjs) instead of deciding on retired code —
|
|
20
|
+
* and a refusal nothing acts on is just a better-worded outage, so this is what
|
|
21
|
+
* acts on it: the server is restarted (its restart budget applies, so a server
|
|
22
|
+
* that comes back stale is reported, not looped) and the call is retried on the
|
|
23
|
+
* fresh process. The client heals without a human reading a transcript.
|
|
24
|
+
*
|
|
12
25
|
* If the restarted server lists different tools, `toolsChanged` is set so the
|
|
13
26
|
* run re-lists them at its next turn boundary.
|
|
14
27
|
*
|
|
@@ -16,6 +29,7 @@
|
|
|
16
29
|
*/
|
|
17
30
|
|
|
18
31
|
import { connectMcpServer } from "./client.mjs";
|
|
32
|
+
import { STALE_SDK } from "../../mcp/staleness.mjs";
|
|
19
33
|
|
|
20
34
|
export const MAX_RESTARTS_PER_RUN = 1;
|
|
21
35
|
|
|
@@ -34,9 +48,14 @@ export function superviseConnection(config, deps, first, { connect = connectMcpS
|
|
|
34
48
|
let restarting = null;
|
|
35
49
|
const toolNames = (/** @type any */ c) => JSON.stringify(c.tools.map((/** @type any */ t) => t.name));
|
|
36
50
|
|
|
37
|
-
/**
|
|
38
|
-
|
|
39
|
-
|
|
51
|
+
/**
|
|
52
|
+
* @param {boolean} [force] restart a server that is still ALIVE — the stale
|
|
53
|
+
* case, where the process answers perfectly and is the problem.
|
|
54
|
+
* @returns {Promise<{ok:true, restarted:boolean, exhausted:boolean}|{ok:false, error:string}>}
|
|
55
|
+
*/
|
|
56
|
+
const ensure = async (force = false) => {
|
|
57
|
+
if (closed || config.transport !== "stdio") return { ok: true, restarted: false, exhausted: false };
|
|
58
|
+
if (!force && current.isAlive()) return { ok: true, restarted: false, exhausted: false };
|
|
40
59
|
if (restarts >= maxRestarts) return { ok: true, restarted: false, exhausted: true };
|
|
41
60
|
if (!restarting) {
|
|
42
61
|
restarting = (async () => {
|
|
@@ -56,6 +75,8 @@ export function superviseConnection(config, deps, first, { connect = connectMcpS
|
|
|
56
75
|
};
|
|
57
76
|
|
|
58
77
|
const note = `(The MCP server "${config.name}" had stopped; it was restarted for this call.)`;
|
|
78
|
+
const staleNote = `(The MCP server "${config.name}" was running retired code; it was restarted onto the installed version for this call.)`;
|
|
79
|
+
const stillStaleNote = `(The MCP server "${config.name}" was restarted and is STILL running retired code — the SDK on disk is not the one it loads. No client-side restart fixes that: run \`maestro doctor\`.)`;
|
|
59
80
|
const exhaustedNote = ` It was already restarted once in this run and is not restarted again.`;
|
|
60
81
|
|
|
61
82
|
/**
|
|
@@ -67,6 +88,24 @@ export function superviseConnection(config, deps, first, { connect = connectMcpS
|
|
|
67
88
|
const e = await ensure();
|
|
68
89
|
if (!e.ok) return { ok: false, error: e.error };
|
|
69
90
|
const r = await op();
|
|
91
|
+
// STALE_SDK: the server answered, and its answer is that its own code is
|
|
92
|
+
// retired. Restarting it is the remedy it names, so take it here rather
|
|
93
|
+
// than asking a human to read the refusal.
|
|
94
|
+
if (!r.ok && /** @type any */ (r).code === STALE_SDK && !e.restarted) {
|
|
95
|
+
const s = await ensure(true);
|
|
96
|
+
if (!s.ok) return { ok: false, error: `${r.error}\n\n${s.error}` };
|
|
97
|
+
if (s.restarted) {
|
|
98
|
+
const again = await op();
|
|
99
|
+
if (again.ok) return { ...again, content: `${again.content}\n\n${staleNote}` };
|
|
100
|
+
// A replacement that is ALSO stale is not a client-side fault and not
|
|
101
|
+
// worth another restart: the install on disk is the old one. Say that,
|
|
102
|
+
// rather than claiming a restart onto "the installed version" that did
|
|
103
|
+
// not change anything.
|
|
104
|
+
const note = /** @type any */ (again).code === STALE_SDK ? stillStaleNote : staleNote;
|
|
105
|
+
return { ...again, error: `${again.error}\n\n${note}` };
|
|
106
|
+
}
|
|
107
|
+
if (s.exhausted) return { ...r, error: `${r.error}${exhaustedNote}` };
|
|
108
|
+
}
|
|
70
109
|
if (e.restarted) return r.ok ? { ...r, content: `${r.content}\n\n${note}` } : { ...r, error: `${r.error}\n\n${note}` };
|
|
71
110
|
if (e.exhausted && !r.ok) return { ...r, error: `${r.error}${exhaustedNote}` };
|
|
72
111
|
return r;
|
package/lib/mcp/server.mjs
CHANGED
|
@@ -36,7 +36,9 @@
|
|
|
36
36
|
"use strict";
|
|
37
37
|
|
|
38
38
|
import { createInterface } from "node:readline";
|
|
39
|
-
import { readFileSync } from "node:fs";
|
|
39
|
+
import { readFileSync, statSync, mkdirSync, rmSync } from "node:fs";
|
|
40
|
+
import { dirname, join } from "node:path";
|
|
41
|
+
import { writeJsonAtomic } from "../fs-atomic.mjs";
|
|
40
42
|
import {
|
|
41
43
|
getOrgTools,
|
|
42
44
|
isOrgTool,
|
|
@@ -46,6 +48,16 @@ import {
|
|
|
46
48
|
import { methodDef } from "../org/protocol.mjs";
|
|
47
49
|
import { REDACTED, isSensitiveParamName, maskTextString } from "../security/redact.mjs";
|
|
48
50
|
import { appendActionAudit } from "../action-executor.js";
|
|
51
|
+
import {
|
|
52
|
+
STALE_SDK,
|
|
53
|
+
STALE_EXEMPT_TOOLS,
|
|
54
|
+
STALE_GATE_ENV,
|
|
55
|
+
sdkStaleness,
|
|
56
|
+
staleGateEnabled,
|
|
57
|
+
staleReason,
|
|
58
|
+
makeCachedVersion,
|
|
59
|
+
serverRecordRel,
|
|
60
|
+
} from "./staleness.mjs";
|
|
49
61
|
|
|
50
62
|
/**
|
|
51
63
|
* Deep, key-aware redaction for escape-hatch results (belt-and-braces §1.3):
|
|
@@ -73,6 +85,34 @@ const ECHOED_VERSIONS = new Set(["2025-06-18", "2025-03-26", "2024-11-05"]);
|
|
|
73
85
|
/** Serialized tool-result cap (chain reads can be large). */
|
|
74
86
|
export const MAX_RESULT_BYTES = 200 * 1024;
|
|
75
87
|
|
|
88
|
+
/**
|
|
89
|
+
* The version whose CODE is in this process, captured when this module graph
|
|
90
|
+
* resolved. Correct by construction: nothing can change the modules already in
|
|
91
|
+
* the ESM cache, so whatever package.json said at load time is what is running.
|
|
92
|
+
*
|
|
93
|
+
* serverVersion() below re-reads package.json per call — which is what made a
|
|
94
|
+
* 20-day-old server report the version installed that morning. Keep these two
|
|
95
|
+
* distinct; collapsing them back into one read is the bug (staleness.mjs).
|
|
96
|
+
*/
|
|
97
|
+
const LOADED_SDK_VERSION = serverVersion();
|
|
98
|
+
|
|
99
|
+
/** package.json, resolved once — the stamp and the read must name the same file. */
|
|
100
|
+
const PKG_URL = new URL("../../package.json", import.meta.url);
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* What is installed NOW, asked on every tools/call. A stat decides whether to
|
|
104
|
+
* re-read, so the cost per call is one statSync rather than a readFileSync +
|
|
105
|
+
* JSON.parse, and the answer is still exact on the first call after an install
|
|
106
|
+
* (see makeCachedVersion — no TTL, the stamp is compared).
|
|
107
|
+
*/
|
|
108
|
+
const onDiskSdkVersion = makeCachedVersion({
|
|
109
|
+
stamp: () => {
|
|
110
|
+
const st = statSync(PKG_URL);
|
|
111
|
+
return `${st.mtimeMs}:${st.size}:${st.ino}`;
|
|
112
|
+
},
|
|
113
|
+
read: serverVersion,
|
|
114
|
+
});
|
|
115
|
+
|
|
76
116
|
/** JSON-RPC error codes. */
|
|
77
117
|
const PARSE_ERROR = -32700;
|
|
78
118
|
const METHOD_NOT_FOUND = -32601;
|
|
@@ -126,14 +166,37 @@ export function capResultText(text) {
|
|
|
126
166
|
* @param {Function} [o.screenImpl] injected send-gate (tests)
|
|
127
167
|
* @param {Function} [o.appendAudit] injected audit writer (tests)
|
|
128
168
|
* @param {boolean} [o.emailAvailable] override the email-family gate (tests)
|
|
169
|
+
* @param {Record<string,string|undefined>} [o.env] ambient env (default process.env) — reads COHORT_MCP_STALE_GATE
|
|
129
170
|
*/
|
|
130
171
|
export function createMcpServer(o = {}) {
|
|
131
172
|
const log = typeof o.log === "function" ? o.log : (lvl, m) => process.stderr.write(`[cohort-mcp:${lvl}] ${m}\n`);
|
|
132
173
|
const appendAudit = typeof o.appendAudit === "function" ? o.appendAudit : appendActionAudit;
|
|
133
174
|
const cfg = resolveOrgToolConfig({ agentRoot: o.agentRoot, orgConfig: o.orgConfig });
|
|
134
175
|
const sessionId = `mcp:${process.pid}`;
|
|
176
|
+
const env = o.env || process.env;
|
|
177
|
+
const staleGate = staleGateEnabled(env);
|
|
135
178
|
let initializedVersion = null;
|
|
136
179
|
let rl = null;
|
|
180
|
+
let announcedStale = false;
|
|
181
|
+
|
|
182
|
+
if (!staleGate) {
|
|
183
|
+
log("warn", `${STALE_GATE_ENV} is off — this server will serve tool calls even after the SDK on disk moves under it`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Is this process serving retired code AND armed to refuse? One statSync per
|
|
188
|
+
* ask (onDiskSdkVersion). Logged once per process, not per call: the reason
|
|
189
|
+
* string is long and a stale server is asked many times.
|
|
190
|
+
*/
|
|
191
|
+
function isStale() {
|
|
192
|
+
if (!staleGate) return false;
|
|
193
|
+
const s = sdkStaleness({ loaded: LOADED_SDK_VERSION, onDisk: onDiskSdkVersion() });
|
|
194
|
+
if (s.stale && !announcedStale) {
|
|
195
|
+
announcedStale = true;
|
|
196
|
+
log("error", staleReason(s));
|
|
197
|
+
}
|
|
198
|
+
return s.stale;
|
|
199
|
+
}
|
|
137
200
|
|
|
138
201
|
if (!cfg.token) {
|
|
139
202
|
log(
|
|
@@ -166,7 +229,11 @@ export function createMcpServer(o = {}) {
|
|
|
166
229
|
const name = params && typeof params.name === "string" ? params.name : "";
|
|
167
230
|
const args = (params && params.arguments && typeof params.arguments === "object" ? params.arguments : {}) || {};
|
|
168
231
|
|
|
169
|
-
// Unknown / inactive tool → error result (audited as denied).
|
|
232
|
+
// Unknown / inactive tool → error result (audited as denied). FIRST, ahead
|
|
233
|
+
// of the staleness gate: a misspelled tool name is a misspelled tool name
|
|
234
|
+
// whether or not this process is stale, and answering STALE_SDK to it hides
|
|
235
|
+
// the caller's actual mistake and writes an audit row for a tool that does
|
|
236
|
+
// not exist.
|
|
170
237
|
const active = activeTools().some((t) => t.name === name);
|
|
171
238
|
if (!name || !isOrgTool(name) || !active) {
|
|
172
239
|
audit({ tool: name || "(none)", status: "denied", denied: true, input: args });
|
|
@@ -177,6 +244,20 @@ export function createMcpServer(o = {}) {
|
|
|
177
244
|
return;
|
|
178
245
|
}
|
|
179
246
|
|
|
247
|
+
// STALE CODE REFUSES TO ACT. Checked per call, not at boot: the upgrade
|
|
248
|
+
// lands under a server that is already running, so boot is the one moment
|
|
249
|
+
// the answer is always "fresh". The per-call cost is a statSync, not a read
|
|
250
|
+
// (onDiskSdkVersion above). The report-and-recover tools stay served —
|
|
251
|
+
// STALE_EXEMPT_TOOLS says why — and COHORT_MCP_STALE_GATE=off disarms the
|
|
252
|
+
// whole thing for one process without a release.
|
|
253
|
+
if (isStale() && !STALE_EXEMPT_TOOLS.includes(name)) {
|
|
254
|
+
const reason = staleReason(sdkStaleness({ loaded: LOADED_SDK_VERSION, onDisk: onDiskSdkVersion() }));
|
|
255
|
+
log("error", reason);
|
|
256
|
+
audit({ tool: name, status: "denied", denied: true, input: args });
|
|
257
|
+
replyError(id, STALE_SDK, reason);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
|
|
180
261
|
const frame = await executeOrgTool(name, args, {
|
|
181
262
|
agentRoot: cfg.agentRoot,
|
|
182
263
|
orgConfig: o.orgConfig,
|
|
@@ -241,16 +322,21 @@ export function createMcpServer(o = {}) {
|
|
|
241
322
|
reply(id, {
|
|
242
323
|
protocolVersion: initializedVersion,
|
|
243
324
|
capabilities: { tools: {} },
|
|
244
|
-
serverInfo: { name: "cohort-mcp", title: "Cohort org server", version:
|
|
325
|
+
serverInfo: { name: "cohort-mcp", title: "Cohort org server", version: LOADED_SDK_VERSION },
|
|
245
326
|
});
|
|
246
327
|
return;
|
|
247
328
|
}
|
|
248
329
|
case "ping":
|
|
249
330
|
reply(id, {});
|
|
250
331
|
return;
|
|
251
|
-
case "tools/list":
|
|
252
|
-
|
|
332
|
+
case "tools/list": {
|
|
333
|
+
// A stale server must not advertise 145 tools of which all but the
|
|
334
|
+
// exempt few refuse: a client that lists and then calls would be told
|
|
335
|
+
// the surface is current and find out per call.
|
|
336
|
+
const listed = isStale() ? activeTools().filter((t) => STALE_EXEMPT_TOOLS.includes(t.name)) : activeTools();
|
|
337
|
+
reply(id, { tools: listed.map(toMcpTool) });
|
|
253
338
|
return;
|
|
339
|
+
}
|
|
254
340
|
case "tools/call":
|
|
255
341
|
if (!params || typeof params !== "object") {
|
|
256
342
|
replyError(id, INVALID_PARAMS, "tools/call: params required");
|
|
@@ -290,7 +376,42 @@ export function createMcpServer(o = {}) {
|
|
|
290
376
|
}
|
|
291
377
|
}
|
|
292
378
|
|
|
379
|
+
/**
|
|
380
|
+
* The registry file — one per live server, naming the version whose code it
|
|
381
|
+
* is actually running. This is the ONLY way anything outside the process can
|
|
382
|
+
* learn that: a stdio MCP server has no launchd label, no port and no pid
|
|
383
|
+
* file of its own, which is precisely why a 20-day-old one went unnoticed.
|
|
384
|
+
* `maestro doctor` reads the directory (lib/cli/doctor-checks.mjs) and drops
|
|
385
|
+
* records whose pid is gone. Fail-open in both directions — a seat with an
|
|
386
|
+
* unwritable state dir still serves tools.
|
|
387
|
+
*/
|
|
388
|
+
const recordPath = cfg.agentRoot ? join(cfg.agentRoot, serverRecordRel(process.pid)) : "";
|
|
389
|
+
function publishRecord() {
|
|
390
|
+
if (!recordPath) return;
|
|
391
|
+
try {
|
|
392
|
+
mkdirSync(dirname(recordPath), { recursive: true });
|
|
393
|
+
writeJsonAtomic(recordPath, {
|
|
394
|
+
pid: process.pid,
|
|
395
|
+
ppid: process.ppid,
|
|
396
|
+
version: LOADED_SDK_VERSION,
|
|
397
|
+
startedAt: new Date().toISOString(),
|
|
398
|
+
staleGate,
|
|
399
|
+
});
|
|
400
|
+
} catch {
|
|
401
|
+
/* the registry is an observability aid; never let it break a server */
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
function withdrawRecord() {
|
|
405
|
+
if (!recordPath) return;
|
|
406
|
+
try {
|
|
407
|
+
rmSync(recordPath, { force: true });
|
|
408
|
+
} catch {
|
|
409
|
+
/* */
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
293
413
|
function start() {
|
|
414
|
+
publishRecord();
|
|
294
415
|
rl = createInterface({ input: o.input, crlfDelay: Infinity });
|
|
295
416
|
// Serialise handling so responses keep request order (MCP clients pair by
|
|
296
417
|
// id, but ordered frames make transcripts deterministic + testable).
|
|
@@ -304,6 +425,7 @@ export function createMcpServer(o = {}) {
|
|
|
304
425
|
}
|
|
305
426
|
|
|
306
427
|
function stop() {
|
|
428
|
+
withdrawRecord();
|
|
307
429
|
try {
|
|
308
430
|
rl?.close();
|
|
309
431
|
} catch {
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* staleness.mjs — does this process's CODE match the SDK on disk?
|
|
3
|
+
*
|
|
4
|
+
* THE INCIDENT THIS EXISTS FOR (2026-09-30). A DM was refused by the org MCP
|
|
5
|
+
* server with "AI-disclosure required: posture disclose-always (default)
|
|
6
|
+
* mandates proactive disclosure on first contact" — a rule that had been scoped
|
|
7
|
+
* to external first contacts on 2026-09-24 (ff13b32, released 2.18.9) and was
|
|
8
|
+
* present in every copy on disk: the repo, the installed package, and the
|
|
9
|
+
* seat's own policies/ai-disclosure.yaml. Calling the installed gate DIRECTLY
|
|
10
|
+
* with the same arguments returned {allow:true}.
|
|
11
|
+
*
|
|
12
|
+
* Measured, not assumed. With one real cohort-mcp server running on pipes:
|
|
13
|
+
*
|
|
14
|
+
* - rewrite lib/org/tool-surface.mjs on disk to rename a tool; the RUNNING
|
|
15
|
+
* server still lists 145 tools with the old name and none with the new one,
|
|
16
|
+
* across a second tools/list. A FRESH server on the same bytes lists the
|
|
17
|
+
* new name and not the old one. The running process serves the module graph
|
|
18
|
+
* it resolved at boot; ESM has no invalidation and nothing re-reads.
|
|
19
|
+
* - rewrite package.json's version to a sentinel; the SAME running server's
|
|
20
|
+
* next initialize reports the SENTINEL, because serverVersion() re-read
|
|
21
|
+
* package.json from the filesystem on every handshake.
|
|
22
|
+
*
|
|
23
|
+
* So the two halves disagreed and the server reported the fresh half: it ran
|
|
24
|
+
* arbitrarily old code while announcing the currently installed version. That
|
|
25
|
+
* is what hid the fault for three weeks and eleven releases, and it is the
|
|
26
|
+
* general shape — the MCP server is a stdio child of an MCP client, it has no
|
|
27
|
+
* launchd label, and nothing in the upgrade path ends it. On this seat one such
|
|
28
|
+
* server had been up 20 days and ~24 releases while reporting 2.18.20.
|
|
29
|
+
*
|
|
30
|
+
* The fix is to stop reporting the fresh half and to stop serving once the two
|
|
31
|
+
* diverge. This module is the pure decision; the reads live in server.mjs.
|
|
32
|
+
*
|
|
33
|
+
* ═══ DOES AN UPGRADE REACH IT? EVERY LONG-LIVED PROCESS ON A SEAT ═══════════
|
|
34
|
+
*
|
|
35
|
+
* Measured on this seat, 2026-09-30, installed 2.18.20 at 13:15:53 local.
|
|
36
|
+
* "Reached" means the process is running the code the seat reports.
|
|
37
|
+
*
|
|
38
|
+
* PROCESS LIFECYCLE UPGRADE REACHES IT?
|
|
39
|
+
* ───────────────────────────── ──────────────────── ──────────────────────
|
|
40
|
+
* daemon (ai.maestro.*-daemon) launchd KeepAlive YES — autoupdate.sh
|
|
41
|
+
* restart_daemon kickstarts
|
|
42
|
+
* it. Its pid started 6 s
|
|
43
|
+
* after the install.
|
|
44
|
+
* 30 periodic/calendar jobs launchd StartInterval YES, structurally — each
|
|
45
|
+
* (poll-relay, inbox-processor, / StartCalendar, run is a fresh `node`, so
|
|
46
|
+
* backlog-executor, the daily/ short-lived per run it loads whatever is on
|
|
47
|
+
* weekly/quarterly cadences, …) disk. No restart step
|
|
48
|
+
* exists or is needed.
|
|
49
|
+
* front-door session launchd KeepAlive ONLY VIA THE NOTICE, and
|
|
50
|
+
* (ai.maestro.*-session → supervisor + it is leaking. autoupdate
|
|
51
|
+
* supervisor → `claude`) resumed `claude` deliberately never kills
|
|
52
|
+
* it (§3.10); it writes
|
|
53
|
+
* upgrade-notice.json and
|
|
54
|
+
* the session is asked to
|
|
55
|
+
* restart "at an idle
|
|
56
|
+
* moment". This seat's
|
|
57
|
+
* supervisor had been up
|
|
58
|
+
* 4 d 21 h across FIVE
|
|
59
|
+
* releases (2.18.15 →
|
|
60
|
+
* 2.18.20) without taking
|
|
61
|
+
* one. A session that never
|
|
62
|
+
* goes idle never upgrades.
|
|
63
|
+
* cohort-mcp (stdio) child of an MCP NO, from the seat's side.
|
|
64
|
+
* client; lives as Not a launchd job, no
|
|
65
|
+
* long as its client label to kickstart, no
|
|
66
|
+
* supervisor of its own. It
|
|
67
|
+
* ends only when its client
|
|
68
|
+
* exits — so it inherits
|
|
69
|
+
* its client's staleness.
|
|
70
|
+
* Two on this seat: one
|
|
71
|
+
* 4 d 21 h old under the
|
|
72
|
+
* front door, and one 20
|
|
73
|
+
* DAYS old (≥19 releases,
|
|
74
|
+
* 2.12.0 → 2.18.20) under a
|
|
75
|
+
* hand-started `claude` in
|
|
76
|
+
* a terminal, which no
|
|
77
|
+
* supervisor owns at all.
|
|
78
|
+
* That is the one that
|
|
79
|
+
* refused the DM. The
|
|
80
|
+
* refusal below is what
|
|
81
|
+
* makes this row RECOVER:
|
|
82
|
+
* lib/engine/mcp/
|
|
83
|
+
* supervisor.mjs restarts
|
|
84
|
+
* a stdio server that
|
|
85
|
+
* answers STALE_SDK and
|
|
86
|
+
* retries the call, so a
|
|
87
|
+
* Cohort-engine client
|
|
88
|
+
* heals without a human.
|
|
89
|
+
* slack-socket launchd KeepAlive YES, from this release —
|
|
90
|
+
* autoupdate.sh's
|
|
91
|
+
* restart_socket_mode
|
|
92
|
+
* kickstarts it after the
|
|
93
|
+
* health gate passes. It
|
|
94
|
+
* was the same shape as the
|
|
95
|
+
* daemon and absent from
|
|
96
|
+
* restart_daemon, which is
|
|
97
|
+
* why a fix used to land
|
|
98
|
+
* everywhere except the
|
|
99
|
+
* process holding the Slack
|
|
100
|
+
* socket open.
|
|
101
|
+
* playwright-mcp child of an MCP N/A — not SDK code, but
|
|
102
|
+
* client (24 d here) the same lifecycle, so
|
|
103
|
+
* the same reasoning would
|
|
104
|
+
* apply to any future
|
|
105
|
+
* first-party stdio server.
|
|
106
|
+
*
|
|
107
|
+
* The pattern: launchd jobs that are SHORT-LIVED are safe for free, the two
|
|
108
|
+
* long-lived jobs the upgrade kickstarts are safe, and everything else — the
|
|
109
|
+
* session, its MCP children, and any `claude` a human started by hand — is
|
|
110
|
+
* running whatever it booted with.
|
|
111
|
+
*
|
|
112
|
+
* WHY A VERSION COMPARISON IS THE RIGHT TEST. It is not that every release
|
|
113
|
+
* changes something the caller depends on — most do not. It is that the
|
|
114
|
+
* process cannot know WHICH modules changed, and the failure mode of guessing
|
|
115
|
+
* wrong is a governance gate enforcing a retired rule. A version comparison is
|
|
116
|
+
* the one question answerable from inside the process, and it is conservative
|
|
117
|
+
* in the safe direction.
|
|
118
|
+
*
|
|
119
|
+
* ═══ WHY THE REFUSAL IS NARROW, AND WHO HEARS IT ════════════════════════════
|
|
120
|
+
*
|
|
121
|
+
* A refusal that takes the whole tool surface down is not a safety measure, it
|
|
122
|
+
* is the incident again with a better error message. The first draft of this
|
|
123
|
+
* module refused EVERY tool but org_describe, with no exemption for the channel
|
|
124
|
+
* by which the agent could say so — so on a seat whose front door demonstrably
|
|
125
|
+
* does not restart for days, the remedy printed in the refusal ("run `maestro
|
|
126
|
+
* session restart`") could only be delivered by a human who happened to read a
|
|
127
|
+
* client transcript. Three things keep that from happening:
|
|
128
|
+
*
|
|
129
|
+
* 1. STALE_EXEMPT_TOOLS keeps the REPORT-AND-RECOVER path served. Telling a
|
|
130
|
+
* colleague the seat is broken, raising an escalation and reading the
|
|
131
|
+
* session's own state are how the fault gets out of the process; a retired
|
|
132
|
+
* send-gate screening one such message wrong is a far smaller harm than a
|
|
133
|
+
* seat that silently stops being able to speak. Everything that MOVES the
|
|
134
|
+
* org's state — board, tasks, books, files, decisions — still refuses.
|
|
135
|
+
* 2. The refusal is CONSUMED, not merely thrown. lib/engine/mcp/supervisor.mjs
|
|
136
|
+
* treats STALE_SDK from a stdio server as a restart-and-retry (its restart
|
|
137
|
+
* budget applies), and `maestro doctor` grows a row per live server from
|
|
138
|
+
* the registry this module names, so an operator sees "3 servers, one on
|
|
139
|
+
* 2.12.0" instead of one error buried in one transcript.
|
|
140
|
+
* 3. COHORT_MCP_STALE_GATE=off turns the whole refusal off, per process. A
|
|
141
|
+
* new gate that can strand 16 seats needs a switch that does not require
|
|
142
|
+
* a release to flip.
|
|
143
|
+
*/
|
|
144
|
+
|
|
145
|
+
"use strict";
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* JSON-RPC server-error code for "this process is running retired code".
|
|
149
|
+
* Inside the reserved implementation-defined server range (-32000..-32099) and
|
|
150
|
+
* distinct from the transport errors in server.mjs.
|
|
151
|
+
*/
|
|
152
|
+
export const STALE_SDK = -32010;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Tools that stay served while stale — the REPORT-AND-RECOVER path.
|
|
156
|
+
*
|
|
157
|
+
* `org_describe` mirrors the entrypoint's token rule (bin/cohort-mcp.mjs: "A
|
|
158
|
+
* missing token does NOT exit: org_describe stays served … MCP clients surface
|
|
159
|
+
* per-call errors far better than a dead server").
|
|
160
|
+
*
|
|
161
|
+
* The other three exist because the first draft did not have them, and the
|
|
162
|
+
* consequence was circular: the refusal's own remedy is "tell someone to
|
|
163
|
+
* restart this client", and `messaging_send` was refused. `escalation_raise` is
|
|
164
|
+
* the same errand at a higher tier, and `session_status` is how the agent reads
|
|
165
|
+
* what to restart. All three are reads or say-so — none of them moves money,
|
|
166
|
+
* signs anything, or writes the org's record of work.
|
|
167
|
+
*
|
|
168
|
+
* Everything else refuses, because nothing here can know which modules moved.
|
|
169
|
+
*/
|
|
170
|
+
export const STALE_EXEMPT_TOOLS = Object.freeze([
|
|
171
|
+
"org_describe",
|
|
172
|
+
"session_status",
|
|
173
|
+
"messaging_send",
|
|
174
|
+
"escalation_raise",
|
|
175
|
+
]);
|
|
176
|
+
|
|
177
|
+
/** The env var that disables the refusal for one process. */
|
|
178
|
+
export const STALE_GATE_ENV = "COHORT_MCP_STALE_GATE";
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Pure. Is the refusal armed for this process? Anything but an explicit off
|
|
182
|
+
* word leaves it on: a typo must not silently disarm a governance gate.
|
|
183
|
+
*
|
|
184
|
+
* @param {Record<string,string|undefined>} [env]
|
|
185
|
+
* @returns {boolean}
|
|
186
|
+
*/
|
|
187
|
+
export function staleGateEnabled(env = {}) {
|
|
188
|
+
const v = String(env[STALE_GATE_ENV] ?? "").trim().toLowerCase();
|
|
189
|
+
return !(v === "off" || v === "0" || v === "false" || v === "no" || v === "disabled");
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Pure. `loaded` is the version whose code is in memory (captured when the
|
|
194
|
+
* module graph resolved); `onDisk` is what is installed now.
|
|
195
|
+
*
|
|
196
|
+
* Unreadable or unparseable versions are NOT stale: a version this process
|
|
197
|
+
* cannot read is not evidence that it is behind, and failing closed on an
|
|
198
|
+
* unreadable package.json would brick every seat whose install is mid-write.
|
|
199
|
+
*
|
|
200
|
+
* @param {{loaded?: string, onDisk?: string}} args
|
|
201
|
+
* @returns {{stale: boolean, loaded: string, onDisk: string}}
|
|
202
|
+
*/
|
|
203
|
+
export function sdkStaleness({ loaded, onDisk } = {}) {
|
|
204
|
+
const l = typeof loaded === "string" ? loaded.trim() : "";
|
|
205
|
+
const d = typeof onDisk === "string" ? onDisk.trim() : "";
|
|
206
|
+
const unknown = !l || !d || l === "0.0.0" || d === "0.0.0";
|
|
207
|
+
return { stale: unknown ? false : l !== d, loaded: l, onDisk: d };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Pure. The operator-facing reason. Names both versions, the remedy, and the
|
|
212
|
+
* fact that the advertised tool list is not the served one — the person who
|
|
213
|
+
* sees this is looking at a client UI with no other clue. The remedy is a
|
|
214
|
+
* session restart, not an SDK reinstall: the SDK on disk is already correct.
|
|
215
|
+
*
|
|
216
|
+
* @param {{loaded: string, onDisk: string}} s
|
|
217
|
+
* @returns {string}
|
|
218
|
+
*/
|
|
219
|
+
export function staleReason({ loaded, onDisk }) {
|
|
220
|
+
return (
|
|
221
|
+
`stale SDK: this MCP server loaded ${loaded} and ${onDisk} is installed. ` +
|
|
222
|
+
`A stdio MCP server serves the modules it resolved at boot, so it is running retired code ` +
|
|
223
|
+
`— including governance gates. Only ${STALE_EXEMPT_TOOLS.join(", ")} stay served, and tools/list ` +
|
|
224
|
+
`advertises only those while stale. Restart the MCP client (for a front door: \`maestro session restart\`) ` +
|
|
225
|
+
`to relaunch it on ${onDisk}.`
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/* ══════════════════════ THE REGISTRY: who is running what ═══════════════════
|
|
230
|
+
*
|
|
231
|
+
* A refusal nothing reads is invisible, and invisibility is what let the
|
|
232
|
+
* original gap run three weeks. There is no way to ask a seat "what version is
|
|
233
|
+
* each of your MCP servers on" from outside a process that has no launchd
|
|
234
|
+
* label and no port — so each server writes one small file naming its pid and
|
|
235
|
+
* the version it LOADED, and removes it on exit. `maestro doctor` reads the
|
|
236
|
+
* directory, drops records whose pid is gone, and reports one row per live
|
|
237
|
+
* server. That is the surface an operator (or a cadence) can actually look at.
|
|
238
|
+
*/
|
|
239
|
+
|
|
240
|
+
/** Registry directory, relative to the agent root. */
|
|
241
|
+
export const SERVER_REGISTRY_REL = "state/mcp/servers";
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Pure. One record's path, relative to the agent root.
|
|
245
|
+
* @param {number|string} pid
|
|
246
|
+
* @returns {string}
|
|
247
|
+
*/
|
|
248
|
+
export function serverRecordRel(pid) {
|
|
249
|
+
return `${SERVER_REGISTRY_REL}/${String(pid).replace(/[^0-9]/g, "") || "0"}.json`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Pure. Doctor rows for the MCP servers this seat is running.
|
|
254
|
+
*
|
|
255
|
+
* `records` are whatever parsed out of the registry — a record with no numeric
|
|
256
|
+
* pid or no version is dropped rather than reported, because a half-written or
|
|
257
|
+
* hand-edited file is not evidence about a process. `pidAlive` decides which
|
|
258
|
+
* records still describe something: a server killed with SIGKILL leaves its
|
|
259
|
+
* file behind, and a reaped pid can be reused, so a live pid whose record
|
|
260
|
+
* predates the reuse is possible — it is a warn, never a fail, on its own.
|
|
261
|
+
*
|
|
262
|
+
* @param {{records?: Array<object>, installed?: string, pidAlive?: (pid:number)=>boolean}} o
|
|
263
|
+
* @returns {Array<{level:"ok"|"warn"|"fail", msg:string}>}
|
|
264
|
+
*/
|
|
265
|
+
export function mcpServerRows({ records = [], installed = "", pidAlive = () => false } = {}) {
|
|
266
|
+
const live = [];
|
|
267
|
+
for (const r of records) {
|
|
268
|
+
const pid = Number(r && r.pid);
|
|
269
|
+
const version = typeof (r && r.version) === "string" ? r.version.trim() : "";
|
|
270
|
+
if (!Number.isInteger(pid) || pid <= 0 || !version) continue;
|
|
271
|
+
if (!pidAlive(pid)) continue;
|
|
272
|
+
live.push({ pid, version, startedAt: r && r.startedAt ? String(r.startedAt) : "" });
|
|
273
|
+
}
|
|
274
|
+
if (live.length === 0) {
|
|
275
|
+
return [{ level: "ok", msg: "Cohort MCP servers: none running (nothing to be stale)" }];
|
|
276
|
+
}
|
|
277
|
+
const inst = String(installed || "").trim();
|
|
278
|
+
const stale = live.filter((s) => sdkStaleness({ loaded: s.version, onDisk: inst }).stale);
|
|
279
|
+
if (stale.length === 0) {
|
|
280
|
+
return [{ level: "ok", msg: `Cohort MCP servers: ${live.length} running, all on the installed ${inst || "version"}` }];
|
|
281
|
+
}
|
|
282
|
+
const detail = stale
|
|
283
|
+
.map((s) => `pid ${s.pid} on ${s.version}${s.startedAt ? ` (since ${s.startedAt})` : ""}`)
|
|
284
|
+
.join(", ");
|
|
285
|
+
return [
|
|
286
|
+
{
|
|
287
|
+
level: "fail",
|
|
288
|
+
msg:
|
|
289
|
+
`Cohort MCP servers: ${stale.length} of ${live.length} running retired code — ${detail}; ` +
|
|
290
|
+
`installed is ${inst || "unreadable"}. A stdio MCP server serves the modules it resolved at boot and ` +
|
|
291
|
+
`nothing in the upgrade path ends it, so its governance gates are the old ones. Restart the CLIENT ` +
|
|
292
|
+
`(front door: \`maestro session restart\`; a hand-started \`claude\` in a terminal: quit and relaunch it)`,
|
|
293
|
+
},
|
|
294
|
+
];
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* A version reader that re-reads only when the file actually changed.
|
|
299
|
+
*
|
|
300
|
+
* server.mjs asks "what is installed now" on EVERY tools/call, and the first
|
|
301
|
+
* draft answered with a readFileSync + JSON.parse each time. Its comment
|
|
302
|
+
* defended that as "the same one serverVersion() already did per handshake" —
|
|
303
|
+
* but a handshake happens once per server lifetime and a tool call happens
|
|
304
|
+
* continuously, so the two frequencies are orders of magnitude apart. A stat is
|
|
305
|
+
* ~an order of magnitude cheaper than read+parse, and the stamp is compared, so
|
|
306
|
+
* correctness does not depend on a TTL: the very next call after an install
|
|
307
|
+
* sees the new version.
|
|
308
|
+
*
|
|
309
|
+
* `stamp()` returns a change-detecting string (mtime + size + inode) or null
|
|
310
|
+
* when the file cannot be stat'ed, in which case the read happens — an
|
|
311
|
+
* unreadable stat must never freeze a stale answer in place.
|
|
312
|
+
*
|
|
313
|
+
* @param {{stamp: () => string|null, read: () => string}} o
|
|
314
|
+
* @returns {() => string}
|
|
315
|
+
*/
|
|
316
|
+
export function makeCachedVersion({ stamp, read }) {
|
|
317
|
+
let seen = null;
|
|
318
|
+
let value = "";
|
|
319
|
+
return () => {
|
|
320
|
+
let s = null;
|
|
321
|
+
try {
|
|
322
|
+
s = stamp();
|
|
323
|
+
} catch {
|
|
324
|
+
s = null;
|
|
325
|
+
}
|
|
326
|
+
if (s !== null && s === seen) return value;
|
|
327
|
+
value = read();
|
|
328
|
+
seen = s;
|
|
329
|
+
return value;
|
|
330
|
+
};
|
|
331
|
+
}
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
"use strict";
|
|
37
37
|
|
|
38
38
|
import { SURFACES } from "./surfaces.mjs";
|
|
39
|
+
import { authorKindOf } from "./directedness.mjs";
|
|
39
40
|
|
|
40
41
|
/** Blank-safe string. */
|
|
41
42
|
function s(v) {
|
|
@@ -88,6 +89,8 @@ export function toMessageEvent(o = {}) {
|
|
|
88
89
|
const subject = subjectDetail ? `${def.subject}: ${subjectDetail}` : def.subject;
|
|
89
90
|
|
|
90
91
|
const from = resolveFrom(hydrated, c, facts);
|
|
92
|
+
// "" when the directory read degraded — see the note at `author_kind` below.
|
|
93
|
+
const authorKind = authorKindOf(facts, from.id);
|
|
91
94
|
const scope = scopeFor(verdict.surface, channelKind, def.scope);
|
|
92
95
|
|
|
93
96
|
const ev = {
|
|
@@ -114,6 +117,26 @@ export function toMessageEvent(o = {}) {
|
|
|
114
117
|
channel_id: channelId,
|
|
115
118
|
channel_label: channelLabel,
|
|
116
119
|
sender: s(from.name || from.id),
|
|
120
|
+
// THE AUTHOR'S KIND, when the directory PROVES it.
|
|
121
|
+
//
|
|
122
|
+
// hq's board gate (`src/server/work/threshold.ts` clause 2) refuses a row
|
|
123
|
+
// for an AI_AGENT author — "agent↔agent chatter is coordination, not a work
|
|
124
|
+
// request" — and that clause was UNREACHABLE from this plane for as long as
|
|
125
|
+
// it has existed. Nothing on a seat machine ever set an author kind, so
|
|
126
|
+
// `lib/org/work-ledger.mjs` turned the resulting `undefined` into the string
|
|
127
|
+
// "HUMAN" and every seat asserted a human author for every ask, always. On
|
|
128
|
+
// 2026-09-30 that let each seat's own closing status line ("Archived,
|
|
129
|
+
// logged.") mint a board row in an agent↔agent DM, a row every eighty
|
|
130
|
+
// seconds for eleven turns, titled with the raw sentence.
|
|
131
|
+
//
|
|
132
|
+
// `facts.memberKinds` is the one `member.list` the facts pass already makes,
|
|
133
|
+
// keyed by member id AND slug. OMITTED, never guessed, when that read
|
|
134
|
+
// degraded (`authorKindOf` returns "") — an absent field keeps the previous
|
|
135
|
+
// shape exactly, and hq now resolves the kind server-side from the message
|
|
136
|
+
// row anyway, so a blank here costs nothing and a WRONG value here would
|
|
137
|
+
// cost the refusal. This field is the poll lane's defence in depth, not the
|
|
138
|
+
// load-bearing guard.
|
|
139
|
+
...(authorKind ? { author_kind: authorKind } : {}),
|
|
117
140
|
is_reply: Boolean(hydrated.isReply),
|
|
118
141
|
thread_context: hydrated.threadContext != null ? hydrated.threadContext : null,
|
|
119
142
|
// VOICE_NOTE_OVERLAY (2026-09-26): attachment metadata from the hydrator rides on the event so
|
package/lib/org/work-ledger.mjs
CHANGED
|
@@ -204,6 +204,34 @@ export async function recordWorkStep(a = {}) {
|
|
|
204
204
|
// refused by name, and a seat that got its local classifier wrong loses a
|
|
205
205
|
// well-shaped prompt rather than opening a row it should not have.
|
|
206
206
|
collective: isRollCallItem(a.item),
|
|
207
|
+
// THE AUTHOR'S KIND, and WHAT THIS LINE CAN AND CANNOT SEE.
|
|
208
|
+
//
|
|
209
|
+
// hq's `work/threshold.ts` clause 2 refuses a row for an AI_AGENT author.
|
|
210
|
+
// Until 2026-09-30 this line could only ever produce "HUMAN": nothing on a
|
|
211
|
+
// seat machine set `author_kind`, so the field was structurally
|
|
212
|
+
// unreachable and the fallback below was the only branch that ran. Every
|
|
213
|
+
// seat asserted a human author for every ask, the clause never fired, and
|
|
214
|
+
// each seat's own closing status line ("Archived, logged.") minted a board
|
|
215
|
+
// row in an agent↔agent DM — one every eighty seconds for eleven turns.
|
|
216
|
+
//
|
|
217
|
+
// `lib/org/inbound/project.mjs` now stamps the kind from
|
|
218
|
+
// `facts.memberKinds`, and it survives the YAML round trip
|
|
219
|
+
// (`lib/channels/inbox-item.mjs` → `scripts/poller/utils.mjs` →
|
|
220
|
+
// `scripts/poller/inbox-scan-poller.mjs`);
|
|
221
|
+
// `lib/org/inbound/author-kind.test.mjs` pins that end to end, because an
|
|
222
|
+
// unreachable field is exactly the drift that made this line lie for as
|
|
223
|
+
// long as it existed. (That citation read `inbound-author-kind.test.mjs`,
|
|
224
|
+
// a file that has never existed — the same prose-vs-executable drift this
|
|
225
|
+
// comment is warning about, inside the comment whose job is to stop it.
|
|
226
|
+
// Written as a REPO-ROOT-RELATIVE PATH now, so `grep` finds it or fails.)
|
|
227
|
+
//
|
|
228
|
+
// STILL NOT THE LOAD-BEARING GUARD, deliberately. The fallback is "HUMAN"
|
|
229
|
+
// rather than "unknown" because a degraded directory read must not cost a
|
|
230
|
+
// real ask its row, and hq re-resolves the kind SERVER-SIDE from the
|
|
231
|
+
// message row regardless of what this says — an authenticated caller may
|
|
232
|
+
// not assert that a message another member wrote was written by a person.
|
|
233
|
+
// This is defence in depth for the poll lane: right when we know, silent
|
|
234
|
+
// when we do not, and never the thing the invariant rests on.
|
|
207
235
|
authorKind: a.item && a.item.author_kind === "AI_AGENT" ? "AI_AGENT" : "HUMAN",
|
|
208
236
|
deferred: a.deferred === true,
|
|
209
237
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cohortapp/agent-sdk",
|
|
3
|
-
"version": "2.18.
|
|
3
|
+
"version": "2.18.21",
|
|
4
4
|
"description": "Cohort Agent SDK — autonomous AI colleague runtime. Deploy senior AI colleagues on dedicated Mac minis, wired to the Cohort operating surface.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -137,6 +137,17 @@
|
|
|
137
137
|
# is the front door meanwhile; doctor and `maestro upgrade --verify` say what
|
|
138
138
|
# to do).
|
|
139
139
|
#
|
|
140
|
+
# WHICH PROCESSES A RELEASE ACTUALLY REACHES. Two jobs on a seat are
|
|
141
|
+
# LONG-LIVED and therefore serve the code they booted with: the daemon and
|
|
142
|
+
# slack-socket (a Socket Mode websocket held open for the job's whole life).
|
|
143
|
+
# Both are kickstarted — the daemon by restart_daemon, slack-socket by
|
|
144
|
+
# restart_socket_mode after the health gate passes on a real version hop. Every
|
|
145
|
+
# other launchd job is short-lived per run and takes the new code for free. The
|
|
146
|
+
# front-door session and, through it, every stdio MCP server it spawns are
|
|
147
|
+
# reached ONLY by the notice below; lib/mcp/staleness.mjs is the in-process
|
|
148
|
+
# backstop for when that notice is not taken (a stale MCP server refuses to act
|
|
149
|
+
# rather than deciding on retired governance code).
|
|
150
|
+
#
|
|
140
151
|
# The front-door session (ai.maestro.<first>-session) is NEVER restarted or
|
|
141
152
|
# killed here: after a HEALTHY upgrade this writes
|
|
142
153
|
# state/session/upgrade-notice.json {from,to,at}; the session's feed
|
|
@@ -330,6 +341,7 @@ FATAL_RE='\[DAEMON\] uncaughtException:|\[daemon\] Fatal:|\[wrapper\] FATAL:|ERR
|
|
|
330
341
|
HEALTH_REASON="" # set by is_healthy on failure; a phrase, no quotes
|
|
331
342
|
DAEMON_LABEL=""
|
|
332
343
|
SESSION_LABEL=""
|
|
344
|
+
SOCKET_LABEL="" # ai.maestro.<first>-slack-socket — the OTHER long-lived KeepAlive job; see restart_socket_mode
|
|
333
345
|
# The pure daemon-revive decision (lib/session/revive.mjs) run by revive_daemon
|
|
334
346
|
# below — the on-host backstop for a daemon that is DOWN, which a live daemon
|
|
335
347
|
# can never observe about itself. Defined up here (not with SESSION_STALE_S,
|
|
@@ -531,6 +543,13 @@ resolve_labels(){ # AFTER the upgrade: its reconcile may have just installed the
|
|
|
531
543
|
[ -n "$DAEMON_LABEL" ] && [ -f "$HOME/Library/LaunchAgents/$DAEMON_LABEL.plist" ] || DAEMON_LABEL=""
|
|
532
544
|
p="$(first_plist session "$AGENT_DIR/scripts/local-triggers/plists")"
|
|
533
545
|
SESSION_LABEL="$(basename "$p" .plist 2>/dev/null)"
|
|
546
|
+
# The slack-socket job, resolved the same way as the daemon: generated set
|
|
547
|
+
# first, ~/Library/LaunchAgents as the fallback, and it only counts when its
|
|
548
|
+
# plist is actually installed.
|
|
549
|
+
p="$(first_plist slack-socket "$AGENT_DIR/scripts/local-triggers/plists")"
|
|
550
|
+
[ -n "$p" ] || p="$(first_plist slack-socket "$HOME/Library/LaunchAgents")"
|
|
551
|
+
SOCKET_LABEL="$(basename "$p" .plist 2>/dev/null)"
|
|
552
|
+
[ -n "$SOCKET_LABEL" ] && [ -f "$HOME/Library/LaunchAgents/$SOCKET_LABEL.plist" ] || SOCKET_LABEL=""
|
|
534
553
|
}
|
|
535
554
|
label_loaded(){ # $1 = label — measured in the gui domain (right from ssh too); `launchctl list <label>` only when print could not answer
|
|
536
555
|
local out rc
|
|
@@ -551,6 +570,28 @@ restart_daemon(){
|
|
|
551
570
|
if [ -z "$DAEMON_LABEL" ]; then log "no -daemon plist under ~/Library/LaunchAgents — nothing to kickstart (maestro upgrade installs it; doctor will say)"; return 0; fi
|
|
552
571
|
launchctl kickstart -k "gui/$UID_/$DAEMON_LABEL" >> "$LOG" 2>&1 || log "WARN: kickstart $DAEMON_LABEL nonzero"
|
|
553
572
|
}
|
|
573
|
+
restart_socket_mode(){ # the OTHER long-lived KeepAlive job, after a version hop
|
|
574
|
+
# WHY THIS EXISTS. A launchd job whose process is SHORT-LIVED takes a new
|
|
575
|
+
# release for free — each run is a fresh `node`. Only two jobs on a seat are
|
|
576
|
+
# long-lived: the daemon, which restart_daemon kickstarts, and slack-socket,
|
|
577
|
+
# which holds a Socket Mode websocket open for its whole life and was absent
|
|
578
|
+
# from every restart path. So a fix could land on the daemon, on all 30
|
|
579
|
+
# periodic jobs and on the front door, and still not reach the process that
|
|
580
|
+
# receives Slack events — silently, with the seat reporting the new version.
|
|
581
|
+
#
|
|
582
|
+
# Called only after a real version hop AND after the health gate passed: a
|
|
583
|
+
# release that is about to be rolled back must not reach this socket, and a
|
|
584
|
+
# re-run on the same version must not cost the seat its websocket.
|
|
585
|
+
resolve_labels
|
|
586
|
+
if [ -z "$SOCKET_LABEL" ]; then log "no -slack-socket plist under ~/Library/LaunchAgents — nothing to kickstart (this seat does not run Socket Mode)"; return 0; fi
|
|
587
|
+
# An UNLOADED job is a deliberate stop, not something to start behind the
|
|
588
|
+
# operator's back (the same rule revive_session follows for the front door).
|
|
589
|
+
label_loaded "$SOCKET_LABEL" || { log "slack-socket $SOCKET_LABEL is installed but not loaded — leaving it stopped"; return 0; }
|
|
590
|
+
launchctl kickstart -k "gui/$UID_/$SOCKET_LABEL" >> "$LOG" 2>&1 \
|
|
591
|
+
&& log "slack-socket $SOCKET_LABEL kickstarted onto the installed code (a KeepAlive socket holder serves the code it booted with)" \
|
|
592
|
+
|| log "WARN: kickstart $SOCKET_LABEL nonzero — it is still on the previous code (launchctl kickstart -k gui/$UID_/$SOCKET_LABEL)"
|
|
593
|
+
return 0
|
|
594
|
+
}
|
|
554
595
|
session_beating(){ # is the front door actually ANSWERING, not merely loaded?
|
|
555
596
|
# `session_reconciled` asks whether the job is loaded and a supervisor process
|
|
556
597
|
# is alive. Both were true on the seats that went silent: on 2026-09-24 three
|
|
@@ -957,6 +998,7 @@ if [ "$CUR" = "$LATEST" ] || [ "$(printf '%s\n%s\n' "$CUR" "$LATEST" | sort -V |
|
|
|
957
998
|
# A real version hop: complete it the way an automatic one completes —
|
|
958
999
|
# the notice tells the session to restart itself onto the new code.
|
|
959
1000
|
log "OK: daemon now on $CUR (was $STALE_FROM) — the manual upgrade is complete"
|
|
1001
|
+
restart_socket_mode
|
|
960
1002
|
write_upgrade_notice "$STALE_FROM" "$CUR"
|
|
961
1003
|
write_last "$STALE_FROM" "$CUR" true true "" true
|
|
962
1004
|
elif [ -n "$STALE_FROM" ]; then
|
|
@@ -1124,6 +1166,7 @@ if is_healthy; then
|
|
|
1124
1166
|
if [ -n "$SESSION_LABEL" ] && ! session_reconciled; then REASON="${REASON:-session-reconcile-failed}"; fi
|
|
1125
1167
|
log "OK: healthy on $LATEST${REASON:+ ($REASON)}"
|
|
1126
1168
|
sibling_job_audit
|
|
1169
|
+
restart_socket_mode
|
|
1127
1170
|
write_upgrade_notice "$CUR" "$LATEST"
|
|
1128
1171
|
write_last "$CUR" "$LATEST" true true "$REASON"
|
|
1129
1172
|
migrate_poller_plist
|
|
@@ -124,6 +124,15 @@ export function parseInboxItemYaml(body) {
|
|
|
124
124
|
// obligation binds identically on the push and poll lanes.
|
|
125
125
|
const eventKind = scalar("event_kind");
|
|
126
126
|
if (eventKind) item.event_kind = eventKind;
|
|
127
|
+
|
|
128
|
+
// THE AUTHOR'S KIND, read back for `lib/org/work-ledger.mjs` → hq's board
|
|
129
|
+
// gate. Only the two values the gate understands are accepted: an item whose
|
|
130
|
+
// `author_kind` is junk is treated as UNKNOWN (absent) rather than passed
|
|
131
|
+
// through, so a malformed line cannot assert an author kind hq would trust.
|
|
132
|
+
const authorKind = scalar("author_kind");
|
|
133
|
+
if (authorKind === "HUMAN" || authorKind === "AI_AGENT") {
|
|
134
|
+
item.author_kind = authorKind;
|
|
135
|
+
}
|
|
127
136
|
// The directedness verdict's own reason, and the surface's subject id. Same
|
|
128
137
|
// rule as `event_kind`: attached only when the writer knew, so a non-org item
|
|
129
138
|
// keeps exactly its old shape. `intake.fromInboxItem` PREFERS `direct_reason`
|
package/scripts/poller/utils.mjs
CHANGED
|
@@ -178,7 +178,7 @@ function renameLiveInbox(item, service, agentRoot, suffix) {
|
|
|
178
178
|
const YAML_SAFE_SCALARS = [
|
|
179
179
|
"id", "service", "channel", "channel_id", "sender", "sender_id",
|
|
180
180
|
"sender_privilege", "timestamp", "subject", "thread_id", "raw_ref", "kind",
|
|
181
|
-
"event_kind", "direct_reason", "scope_id", "channel_kind", "channel_type",
|
|
181
|
+
"event_kind", "author_kind", "direct_reason", "scope_id", "channel_kind", "channel_type",
|
|
182
182
|
"event_type",
|
|
183
183
|
];
|
|
184
184
|
|
|
@@ -255,6 +255,19 @@ raw_ref: "${item.raw_ref || ""}"
|
|
|
255
255
|
yaml += `event_kind: "${item.event_kind}"\n`;
|
|
256
256
|
}
|
|
257
257
|
|
|
258
|
+
// THE AUTHOR'S KIND, written only when the projection PROVED it, by the same
|
|
259
|
+
// "absent means unknown" rule as `kind` and `event_kind` above.
|
|
260
|
+
//
|
|
261
|
+
// This writer enumerates its fields, as the note above says — so the kind that
|
|
262
|
+
// `lib/org/inbound/project.mjs` resolves from `facts.memberKinds` died at this
|
|
263
|
+
// boundary, and `lib/org/work-ledger.mjs` then told hq's board gate "HUMAN"
|
|
264
|
+
// for every ask any seat ever saw. hq's gate refuses a row for an AI_AGENT
|
|
265
|
+
// author; unreachable from the poll lane, it could not refuse the agent↔agent
|
|
266
|
+
// status lines that minted a board row every eighty seconds on 2026-09-30.
|
|
267
|
+
if (item.author_kind) {
|
|
268
|
+
yaml += `author_kind: "${item.author_kind}"\n`;
|
|
269
|
+
}
|
|
270
|
+
|
|
258
271
|
// THE DIRECTEDNESS REASON and THE SURFACE'S SUBJECT ID, for exactly the reason
|
|
259
272
|
// above: this writer enumerates its fields, so anything not named here dies at
|
|
260
273
|
// the YAML boundary and the poll lane behaves differently from the push lane.
|