@50arms/platform-mcp 0.1.460 → 0.1.462

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.
@@ -68,7 +68,7 @@ export function invalidCompactionReason(value) {
68
68
  // DX-5222: no default for a missing table - a frame from a dashboard that predates it is refused, never read as "no valves"
69
69
  if (!isRecord(c.valves))
70
70
  return "valves must be an object keyed by model id";
71
- // DX-6732: no default for a missing mode - a frame from a dashboard that predates it is refused, as with `valves`
71
+ // DX-6732 / DX-7133: no default for a missing mode - a frame from a dashboard that predates it is refused, as with `valves`
72
72
  if (c.mode !== "compact" && c.mode !== "clear")
73
73
  return `mode must be "compact" or "clear"`;
74
74
  for (const [modelId, size] of Object.entries(c.valves)) {
@@ -2,6 +2,8 @@
2
2
  * DX-7107 - the leftover-process wire shape, declared once: the machine daemon (`machine-daemon/leftovers.ts`) builds it, `POST /api/machines/report` reads it (`readLeftoverProcess`), and the dashboard turns it into the
3
3
  * reminder a session's stream writes (`src/issues/leftover-processes-message.ts`).
4
4
  */
5
+ /** How long the dashboard keeps a reminder for the session's stream to take; one nobody claimed within it is dropped, because the processes it names may be gone and their pids reused. */
6
+ export const LEFTOVER_REMINDER_TTL_MS = 10 * 60 * 1000;
5
7
  /** The daemon cuts a command line here, so the dashboard and the daemon agree on one length. */
6
8
  export const LEFTOVER_COMMAND_MAX_CHARS = 140;
7
9
  /**
package/dist/listen.js CHANGED
@@ -272,10 +272,10 @@ function isPersonsComment(event) {
272
272
  return event.origin === "operator" && event.release !== true;
273
273
  }
274
274
  /**
275
- * DX-5799: what the agent does with a person's comment. The person's comment shows the agent that received it, and the reply is ONE message the agent writes
276
- * twice: first a short acknowledgement of its own (`phase: "ack"`, so the person sees the comment was received), then its full answer (`phase: "reply"`) written
277
- * over the same message, so the answer never arrives as a separate comment. The text is written here, with the line the agent reads, so every session that
278
- * updates this package follows it without a plugin change.
275
+ * DX-5799: what the agent does with a person's comment. The person's comment shows the agent that received it, and the answer is a comment of its own under it
276
+ * (DX-7100, DEC-742) that the agent writes twice: first a short acknowledgement of its own (`phase: "ack"`, so the person sees the comment was received), then its
277
+ * full answer (`phase: "reply"`) written over that acknowledgement. A further answer is a new one of its own, never written over the first. The text is written here,
278
+ * with the line the agent reads, so every session that updates this package follows it without a plugin change.
279
279
  */
280
280
  export function replyInstruction(cardId, commentId) {
281
281
  return replyInstructionAt(`/api/issues/${cardId}/comments/${commentId}/reply`);
@@ -289,7 +289,7 @@ function subjectRef(event) {
289
289
  return typeof event.planId === "number" ? event.planRef : event.cardId;
290
290
  }
291
291
  function replyInstructionAt(path) {
292
- return `Answer it through its reply message: first call 50arms_api POST ${path} with {"phase":"ack","body":"<one short sentence of your own acknowledging it>"} so the person sees it was received, then do the work and call POST ${path} again with {"phase":"reply","body":"<your full answer>"}, which replaces your acknowledgement in the same message. A comment you already answered (its follow-up arrived after your answer) takes only another {"phase":"reply","body":"<your answer to the follow-up>"}, which is added as the next message; never send "ack" after an answer, and never answer with a separate comment`;
292
+ return `Answer it through its reply route: first call 50arms_api POST ${path} with {"phase":"ack","body":"<one short sentence of your own acknowledging it>"} so the person sees it was received, then do the work and call POST ${path} again with {"phase":"reply","body":"<your full answer>"}, which replaces your acknowledgement. Another event for a comment you already answered (a follow-up the person added to it before your answer) takes only another {"phase":"reply","body":"<your answer to the follow-up>"}, which is a new answer of its own under the comment, never written over the one you gave; never send "ack" after an answer, and never answer through the plain comment route`;
293
293
  }
294
294
  /** DX-6064: what a session does with a person's answer (or changed answer), so a decision never lives only in its conversation. */
295
295
  export const UPDATE_RECORDS_NOW = "Update every plan record and card this answer changes, this turn";
@@ -413,7 +413,7 @@ const FILED_NOT_READIED_INSTRUCTION = "Ready each now (order: depends_on), or op
413
413
  const FILED_NOT_READIED_LABEL = "Filed, not readied";
414
414
  /** DX-7127 - the label the review-runnable ids sit under, and what to do about them: the gate is no build and no person's answer, so a dependency never holds it. */
415
415
  const REVIEWABLE_LABEL = "Review runnable now";
416
- const REVIEWABLE_INSTRUCTION = "start each card's named gate review (its next PRE gate) now: a depends_on never holds a review";
416
+ const REVIEWABLE_INSTRUCTION = "start each card's named gate review (its next PRE gate): a depends_on never holds a review";
417
417
  function isNudgeCardRef(value) {
418
418
  return isRecord(value) && typeof value.id === "string" && typeof value.title === "string";
419
419
  }
@@ -456,7 +456,7 @@ function freeSlotsSentence(freeSlots) {
456
456
  if (freeSlots === null)
457
457
  return "Pacing sets no agent cap for this account.";
458
458
  if (freeSlots === 0)
459
- return "No agent slot is free now: start them as slots free.";
459
+ return "No agent slot is free now: start each review as a slot frees.";
460
460
  return `${freeSlots} agent slot${freeSlots === 1 ? " is" : "s are"} free now: start up to that many at once.`;
461
461
  }
462
462
  function queuedCardList(cards) {
@@ -17,12 +17,15 @@
17
17
  *
18
18
  * The ledger holds every Windows process of the table (a few hundred rows): a hot process nobody owns is told from one that is busy for its own reasons only by watching it, and a process with no row has no history.
19
19
  *
20
- * Each process is reminded at most once per {@link REMIND_INTERVAL_MS}, counted from a 200 answer that names its session delivered.
20
+ * Each process is reminded at most once per {@link REMIND_INTERVAL_MS}, counted from a 200 answer that names its session delivered. The dashboard keeps the reminder for a short window for the session's stream to take; "delivered" means
21
+ * the dashboard holds it, not that the session has read it. So a reminded process stays AWAITING, and each report asks the dashboard what became of it (`awaiting` in the post, `pending` and `expired` in the answer) until the stream took
22
+ * it or the window passed unclaimed: an expired one is sent again at the next report instead of waiting out {@link REMIND_INTERVAL_MS} unread (DX-7107).
21
23
  */
22
24
  import { existsSync, readdirSync, readFileSync } from "node:fs";
23
25
  import { homedir } from "node:os";
24
26
  import { join } from "node:path";
25
27
  import { LEFTOVER_COMMAND_MAX_CHARS } from "../leftover-wire.js";
28
+ import { BEAT_INTERVAL_MS } from "./beat.js";
26
29
  import { listProcesses, runCommand } from "../machine-toolkit/processes.js";
27
30
  export const FOLLOW_MIN_AGE_MS = 30 * 60 * 1000;
28
31
  export const HOT_CPU_FRACTION = 0.5;
@@ -33,6 +36,8 @@ export const REMIND_INTERVAL_MS = 6 * 60 * 60 * 1000;
33
36
  export const READER_GONE_MIN_AGE_MS = 2 * 60 * 1000;
34
37
  /** A failed environment read is not tried again for this long. */
35
38
  export const ENV_RETRY_BACKOFF_MS = 30 * 60 * 1000;
39
+ /** A report never names processes from a table older than this: three missed beats. A process that has since ended could otherwise be named in a reminder after a long outage of the process listing. */
40
+ export const SAMPLE_MAX_AGE_MS = 3 * BEAT_INTERVAL_MS;
36
41
  const MAX_CHAIN_HOPS = 32;
37
42
  const ENV_READ_TIMEOUT_MS = 20_000;
38
43
  const PS_TIMEOUT_MS = 20_000;
@@ -155,6 +160,7 @@ export function createLeftoverTracker(deps) {
155
160
  const ledger = new Map();
156
161
  let live = new Map();
157
162
  let liveSessionIds = new Set();
163
+ let sampledAtMs = null;
158
164
  let envRetryAfterMs = 0;
159
165
  let lastSessionIds = "";
160
166
  const parentRowOf = (row, byPid, msys) => {
@@ -204,7 +210,7 @@ export function createLeftoverTracker(deps) {
204
210
  const shell = parentRowOf(row, byPid, msys);
205
211
  if (follower)
206
212
  deps.log(`leftover: first sight of follower pid ${row.pid} ${row.name} (${shortCommand(row.commandLine)}), started ${row.startedAt.toISOString()}: launching shell ${shell === undefined ? "not running" : `pid ${shell.pid} ${shell.name}`}; owner ${owner ?? "none"}, chain ${walk}`);
207
- entry = { pid: row.pid, startedAtMs, owner, envChecked: false, shellKey: shell?.startedAt ? keyOf(shell.pid, shell.startedAt.getTime()) : null, unreachable: false, lastCpu100ns: null, lastSeenMs: nowMs, hotSinceMs: null, hotCpuStart100ns: null, hotStartWallMs: null, lastCpuPercent: null, remindedAtMs: null };
213
+ entry = { pid: row.pid, startedAtMs, owner, envChecked: false, shellKey: shell?.startedAt ? keyOf(shell.pid, shell.startedAt.getTime()) : null, unreachable: false, awaiting: false, disposition: null, lastCpu100ns: null, lastSeenMs: nowMs, hotSinceMs: null, hotCpuStart100ns: null, hotStartWallMs: null, lastCpuPercent: null, remindedAtMs: null };
208
214
  ledger.set(key, entry);
209
215
  }
210
216
  else if (entry.owner === null && owner !== null) {
@@ -237,6 +243,7 @@ export function createLeftoverTracker(deps) {
237
243
  ledger.delete(key);
238
244
  }
239
245
  live = nowLive;
246
+ sampledAtMs = nowMs;
240
247
  const sessionIds = [...liveSessionIds].sort().join(",");
241
248
  if (sessionIds !== lastSessionIds) {
242
249
  deps.log(`leftover: watching ${liveSessionIds.size} claude sessions: ${sessionIds}`);
@@ -266,6 +273,13 @@ export function createLeftoverTracker(deps) {
266
273
  const sessions = new Map();
267
274
  const reminded = new Map();
268
275
  const ownerless = [];
276
+ const awaiting = [...new Set([...ledger.values()].flatMap((e) => (e.awaiting && e.owner !== null ? [e.owner] : [])))].sort();
277
+ // DX-7107: after a failed sample the ledger still holds processes that may have ended since; a reminder names only what the table showed lately.
278
+ if (sampledAtMs === null || nowMs - sampledAtMs > SAMPLE_MAX_AGE_MS) {
279
+ if (sampledAtMs !== null)
280
+ deps.log(`leftover: the process table was last read ${Math.floor((nowMs - sampledAtMs) / 60_000)} min ago, so this report flags nothing`);
281
+ return { sessions: [], ownerless, reminded, awaiting };
282
+ }
269
283
  for (const [key, entry] of ledger) {
270
284
  const row = live.get(key);
271
285
  if (row === undefined)
@@ -275,8 +289,10 @@ export function createLeftoverTracker(deps) {
275
289
  const readerGone = follower && entry.shellKey !== null && !live.has(entry.shellKey) && ageMs >= READER_GONE_MIN_AGE_MS;
276
290
  const follow = follower && ageMs >= FOLLOW_MIN_AGE_MS;
277
291
  const hot = entry.owner !== null && entry.hotSinceMs !== null && nowMs - entry.hotSinceMs >= HOT_MIN_MS;
278
- if (!readerGone && !follow && !hot)
292
+ if (!readerGone && !follow && !hot) {
293
+ entry.disposition = null;
279
294
  continue;
295
+ }
280
296
  const process = {
281
297
  pid: entry.pid,
282
298
  command: shortCommand(row.commandLine),
@@ -284,14 +300,19 @@ export function createLeftoverTracker(deps) {
284
300
  cpu_percent: hot && entry.lastCpuPercent !== null ? Math.round(entry.lastCpuPercent) : null,
285
301
  why: readerGone ? "reader_gone" : follow ? "follow" : "cpu",
286
302
  };
287
- const flagged = `leftover: flagged pid ${entry.pid} ${row.name} (${process.why}, ${process.age_seconds} s old, owner ${entry.owner ?? "none"}):`;
303
+ // A process is logged when it is first flagged, when what becomes of it changes, and each time a reminder goes out; a standing answer (and "reminded recently", which only waits) is not repeated every report.
304
+ const note = (disposition, text, always = false) => {
305
+ if (text !== null && (always || entry.disposition !== disposition))
306
+ deps.log(`leftover: flagged pid ${entry.pid} ${row.name} (${process.why}, ${process.age_seconds} s old, owner ${entry.owner ?? "none"}): ${text}`);
307
+ entry.disposition = disposition;
308
+ };
288
309
  if (entry.owner === null) {
289
310
  ownerless.push({ ...process, reason: "no session found" });
290
- deps.log(`${flagged} no session found, so it goes to the orphan list`);
311
+ note("no session found", "no session found, so it goes to the orphan list");
291
312
  }
292
313
  else if (!liveSessionIds.has(entry.owner)) {
293
314
  ownerless.push({ ...process, reason: "session ended" });
294
- deps.log(`${flagged} its session has ended, so it goes to the orphan list`);
315
+ note("session ended", "its session has ended, so it goes to the orphan list");
295
316
  }
296
317
  else {
297
318
  if (entry.unreachable)
@@ -299,27 +320,42 @@ export function createLeftoverTracker(deps) {
299
320
  if (entry.remindedAtMs === null || nowMs - entry.remindedAtMs >= REMIND_INTERVAL_MS) {
300
321
  sessions.set(entry.owner, [...(sessions.get(entry.owner) ?? []), process]);
301
322
  reminded.set(entry.owner, [...(reminded.get(entry.owner) ?? []), key]);
302
- deps.log(`${flagged} the session is reminded in this report`);
323
+ note("reminded", "the session is reminded in this report", true);
303
324
  }
304
325
  else {
305
- deps.log(`${flagged} the session was reminded ${Math.floor((nowMs - entry.remindedAtMs) / 60_000)} min ago, so not again yet`);
326
+ note("not yet", null);
306
327
  }
307
328
  }
308
329
  }
309
- return { sessions: [...sessions].map(([session_id, processes]) => ({ session_id, processes })), ownerless, reminded };
330
+ return { sessions: [...sessions].map(([session_id, processes]) => ({ session_id, processes })), ownerless, reminded, awaiting };
310
331
  },
311
- settle(collection, undelivered, at) {
332
+ settle(collection, answer, at) {
333
+ for (const sessionId of collection.awaiting) {
334
+ const expired = answer.expired.includes(sessionId);
335
+ if (!expired && answer.pending.includes(sessionId))
336
+ continue;
337
+ for (const entry of ledger.values()) {
338
+ if (entry.owner !== sessionId || !entry.awaiting)
339
+ continue;
340
+ entry.awaiting = false;
341
+ if (expired)
342
+ entry.remindedAtMs = null;
343
+ }
344
+ deps.log(expired ? `leftover: the reminder of session ${sessionId} expired on the dashboard before its stream took it, so it is sent again at the next report` : `leftover: the stream of session ${sessionId} took its reminder`);
345
+ }
312
346
  for (const [sessionId, keys] of collection.reminded) {
347
+ const unreachable = answer.undelivered.includes(sessionId);
313
348
  for (const key of keys) {
314
349
  const entry = ledger.get(key);
315
350
  if (entry === undefined)
316
351
  continue;
317
352
  // An undelivered session is told to a person and asked again at the next report; the mark clears when the dashboard takes the reminder.
318
- entry.unreachable = undelivered.includes(sessionId);
319
- if (!entry.unreachable)
353
+ entry.unreachable = unreachable;
354
+ entry.awaiting = !unreachable;
355
+ if (!unreachable)
320
356
  entry.remindedAtMs = at.getTime();
321
357
  }
322
- deps.log(`leftover: the dashboard ${undelivered.includes(sessionId) ? "has no stream row for" : "took the reminder for"} session ${sessionId} (${keys.length} processes)`);
358
+ deps.log(`leftover: the dashboard ${unreachable ? "has no stream row for" : "took the reminder for"} session ${sessionId} (${keys.length} processes)`);
323
359
  }
324
360
  },
325
361
  };
@@ -327,7 +363,7 @@ export function createLeftoverTracker(deps) {
327
363
  /** The real tracker: the Windows process table (no WSL listing: its rows could not be mapped to a session), Git's `ps -W`, `~/.claude/sessions` and the environment read. The watchdog is Windows-only: on another platform nothing is ever watched. */
328
364
  export function createSystemLeftoverTracker(log, run = runCommand, platform = process.platform) {
329
365
  if (platform !== "win32")
330
- return { sample: async () => { }, collect: () => ({ sessions: [], ownerless: [], reminded: new Map() }), settle: () => { } };
366
+ return { sample: async () => { }, collect: () => ({ sessions: [], ownerless: [], reminded: new Map(), awaiting: [] }), settle: () => { } };
331
367
  return createLeftoverTracker({
332
368
  log,
333
369
  listing: (now) => listProcesses(now, run, platform, undefined, "never"),
@@ -4,7 +4,7 @@
4
4
  * machine.json — `{ machine_id }`: the stable id the daemon made at install (never the hostname).
5
5
  * machine-daemon.json — the dashboard URL, the machine id and its reporting bearer, owner-only (0600). The bearer is
6
6
  * the daemon's only credential; it is never printed or logged.
7
- * machine-daemon.log — what the daemon logs, one timestamped line each (DX-7107: the autostart entry runs headless, so stdout is lost); at most {@link DAEMON_LOG_MAX_BYTES}, then it moves to machine-daemon.log.1.
7
+ * machine-daemon.log — what the daemon logs, one timestamped line each (DX-7107: the autostart entry runs headless, so stdout is lost); at most {@link DAEMON_LOG_MAX_BYTES}, then it moves to machine-daemon.log.1; owner-only (0600), since a flagged line carries a process's command line.
8
8
  * machine-daemon-status.json — written after every beat and report: when it last beat, whether that beat landed, when the next is
9
9
  * due, and the last health report's time, outcome and error.
10
10
  * machine-daemon/ — the copies of the daemon and toolkit bundles the autostart entry runs (so a package update never changes a running file).
@@ -67,14 +67,21 @@ export function readJsonIfPresent(file) {
67
67
  return JSON.parse(readFileSync(file, "utf8"));
68
68
  }
69
69
  export const DAEMON_LOG_MAX_BYTES = 1024 * 1024;
70
- /** Appends `<iso time> <line>` to `file`. Past {@link DAEMON_LOG_MAX_BYTES} the file moves to `<file>.1` (replacing the older one) and a new one starts. A log that cannot be written is reported on stderr and never stops the daemon. */
70
+ /**
71
+ * Appends `<iso time> <line>` to `file`. Past {@link DAEMON_LOG_MAX_BYTES} the file moves to `<file>.1` (replacing the older one) and a new one starts. A log that cannot be written is reported on stderr and never stops the daemon.
72
+ * Owner-only like its sibling files (DX-7151): a line can carry a process's command line, which can hold a credential. A new file is created 0600, and a log already on disk is narrowed to it at the first write.
73
+ */
71
74
  export function createDaemonLog(file, now = () => new Date(), maxBytes = DAEMON_LOG_MAX_BYTES) {
75
+ let narrowed = false;
72
76
  return (line) => {
73
77
  try {
74
78
  mkdirSync(dirname(file), { recursive: true });
79
+ if (!narrowed && existsSync(file) && process.platform !== "win32")
80
+ chmodSync(file, 0o600);
81
+ narrowed = true;
75
82
  if (existsSync(file) && statSync(file).size >= maxBytes)
76
83
  renameSync(file, `${file}.1`);
77
- appendFileSync(file, `${now().toISOString()} ${line}\n`, "utf8");
84
+ appendFileSync(file, `${now().toISOString()} ${line}\n`, { encoding: "utf8", mode: 0o600 });
78
85
  }
79
86
  catch (err) {
80
87
  console.error(`[machine-daemon] cannot write ${file}: ${err instanceof Error ? err.message : String(err)}`);
@@ -217,6 +217,7 @@ import { homedir } from "node:os";
217
217
  import { join } from "node:path";
218
218
 
219
219
  // src/leftover-wire.ts
220
+ var LEFTOVER_REMINDER_TTL_MS = 10 * 60 * 1e3;
220
221
  var LEFTOVER_COMMAND_MAX_CHARS = 140;
221
222
 
222
223
  // src/machine-toolkit/processes.ts
@@ -303,6 +304,7 @@ var HOT_MIN_MS = 3 * 60 * 60 * 1e3;
303
304
  var REMIND_INTERVAL_MS = 6 * 60 * 60 * 1e3;
304
305
  var READER_GONE_MIN_AGE_MS = 2 * 60 * 1e3;
305
306
  var ENV_RETRY_BACKOFF_MS = 30 * 60 * 1e3;
307
+ var SAMPLE_MAX_AGE_MS = 3 * BEAT_INTERVAL_MS;
306
308
  var MAX_CHAIN_HOPS = 32;
307
309
  var ENV_READ_TIMEOUT_MS = 2e4;
308
310
  var PS_TIMEOUT_MS = 2e4;
@@ -402,6 +404,7 @@ function createLeftoverTracker(deps) {
402
404
  const ledger = /* @__PURE__ */ new Map();
403
405
  let live = /* @__PURE__ */ new Map();
404
406
  let liveSessionIds = /* @__PURE__ */ new Set();
407
+ let sampledAtMs = null;
405
408
  let envRetryAfterMs = 0;
406
409
  let lastSessionIds = "";
407
410
  const parentRowOf = (row, byPid, msys) => {
@@ -442,7 +445,7 @@ function createLeftoverTracker(deps) {
442
445
  if (entry === void 0) {
443
446
  const shell = parentRowOf(row, byPid, msys);
444
447
  if (follower) deps.log(`leftover: first sight of follower pid ${row.pid} ${row.name} (${shortCommand(row.commandLine)}), started ${row.startedAt.toISOString()}: launching shell ${shell === void 0 ? "not running" : `pid ${shell.pid} ${shell.name}`}; owner ${owner ?? "none"}, chain ${walk}`);
445
- entry = { pid: row.pid, startedAtMs, owner, envChecked: false, shellKey: shell?.startedAt ? keyOf(shell.pid, shell.startedAt.getTime()) : null, unreachable: false, lastCpu100ns: null, lastSeenMs: nowMs, hotSinceMs: null, hotCpuStart100ns: null, hotStartWallMs: null, lastCpuPercent: null, remindedAtMs: null };
448
+ entry = { pid: row.pid, startedAtMs, owner, envChecked: false, shellKey: shell?.startedAt ? keyOf(shell.pid, shell.startedAt.getTime()) : null, unreachable: false, awaiting: false, disposition: null, lastCpu100ns: null, lastSeenMs: nowMs, hotSinceMs: null, hotCpuStart100ns: null, hotStartWallMs: null, lastCpuPercent: null, remindedAtMs: null };
446
449
  ledger.set(key, entry);
447
450
  } else if (entry.owner === null && owner !== null) {
448
451
  entry.owner = owner;
@@ -470,6 +473,7 @@ function createLeftoverTracker(deps) {
470
473
  ledger.delete(key);
471
474
  }
472
475
  live = nowLive;
476
+ sampledAtMs = nowMs;
473
477
  const sessionIds = [...liveSessionIds].sort().join(",");
474
478
  if (sessionIds !== lastSessionIds) {
475
479
  deps.log(`leftover: watching ${liveSessionIds.size} claude sessions: ${sessionIds}`);
@@ -496,6 +500,11 @@ function createLeftoverTracker(deps) {
496
500
  const sessions = /* @__PURE__ */ new Map();
497
501
  const reminded = /* @__PURE__ */ new Map();
498
502
  const ownerless = [];
503
+ const awaiting = [...new Set([...ledger.values()].flatMap((e) => e.awaiting && e.owner !== null ? [e.owner] : []))].sort();
504
+ if (sampledAtMs === null || nowMs - sampledAtMs > SAMPLE_MAX_AGE_MS) {
505
+ if (sampledAtMs !== null) deps.log(`leftover: the process table was last read ${Math.floor((nowMs - sampledAtMs) / 6e4)} min ago, so this report flags nothing`);
506
+ return { sessions: [], ownerless, reminded, awaiting };
507
+ }
499
508
  for (const [key, entry] of ledger) {
500
509
  const row = live.get(key);
501
510
  if (row === void 0) continue;
@@ -504,7 +513,10 @@ function createLeftoverTracker(deps) {
504
513
  const readerGone = follower && entry.shellKey !== null && !live.has(entry.shellKey) && ageMs >= READER_GONE_MIN_AGE_MS;
505
514
  const follow = follower && ageMs >= FOLLOW_MIN_AGE_MS;
506
515
  const hot = entry.owner !== null && entry.hotSinceMs !== null && nowMs - entry.hotSinceMs >= HOT_MIN_MS;
507
- if (!readerGone && !follow && !hot) continue;
516
+ if (!readerGone && !follow && !hot) {
517
+ entry.disposition = null;
518
+ continue;
519
+ }
508
520
  const process2 = {
509
521
  pid: entry.pid,
510
522
  command: shortCommand(row.commandLine),
@@ -512,42 +524,57 @@ function createLeftoverTracker(deps) {
512
524
  cpu_percent: hot && entry.lastCpuPercent !== null ? Math.round(entry.lastCpuPercent) : null,
513
525
  why: readerGone ? "reader_gone" : follow ? "follow" : "cpu"
514
526
  };
515
- const flagged = `leftover: flagged pid ${entry.pid} ${row.name} (${process2.why}, ${process2.age_seconds} s old, owner ${entry.owner ?? "none"}):`;
527
+ const note = (disposition, text, always = false) => {
528
+ if (text !== null && (always || entry.disposition !== disposition)) deps.log(`leftover: flagged pid ${entry.pid} ${row.name} (${process2.why}, ${process2.age_seconds} s old, owner ${entry.owner ?? "none"}): ${text}`);
529
+ entry.disposition = disposition;
530
+ };
516
531
  if (entry.owner === null) {
517
532
  ownerless.push({ ...process2, reason: "no session found" });
518
- deps.log(`${flagged} no session found, so it goes to the orphan list`);
533
+ note("no session found", "no session found, so it goes to the orphan list");
519
534
  } else if (!liveSessionIds.has(entry.owner)) {
520
535
  ownerless.push({ ...process2, reason: "session ended" });
521
- deps.log(`${flagged} its session has ended, so it goes to the orphan list`);
536
+ note("session ended", "its session has ended, so it goes to the orphan list");
522
537
  } else {
523
538
  if (entry.unreachable) ownerless.push({ ...process2, reason: "session not on this dashboard" });
524
539
  if (entry.remindedAtMs === null || nowMs - entry.remindedAtMs >= REMIND_INTERVAL_MS) {
525
540
  sessions.set(entry.owner, [...sessions.get(entry.owner) ?? [], process2]);
526
541
  reminded.set(entry.owner, [...reminded.get(entry.owner) ?? [], key]);
527
- deps.log(`${flagged} the session is reminded in this report`);
542
+ note("reminded", "the session is reminded in this report", true);
528
543
  } else {
529
- deps.log(`${flagged} the session was reminded ${Math.floor((nowMs - entry.remindedAtMs) / 6e4)} min ago, so not again yet`);
544
+ note("not yet", null);
530
545
  }
531
546
  }
532
547
  }
533
- return { sessions: [...sessions].map(([session_id, processes]) => ({ session_id, processes })), ownerless, reminded };
548
+ return { sessions: [...sessions].map(([session_id, processes]) => ({ session_id, processes })), ownerless, reminded, awaiting };
534
549
  },
535
- settle(collection, undelivered, at) {
550
+ settle(collection, answer, at) {
551
+ for (const sessionId of collection.awaiting) {
552
+ const expired = answer.expired.includes(sessionId);
553
+ if (!expired && answer.pending.includes(sessionId)) continue;
554
+ for (const entry of ledger.values()) {
555
+ if (entry.owner !== sessionId || !entry.awaiting) continue;
556
+ entry.awaiting = false;
557
+ if (expired) entry.remindedAtMs = null;
558
+ }
559
+ deps.log(expired ? `leftover: the reminder of session ${sessionId} expired on the dashboard before its stream took it, so it is sent again at the next report` : `leftover: the stream of session ${sessionId} took its reminder`);
560
+ }
536
561
  for (const [sessionId, keys] of collection.reminded) {
562
+ const unreachable = answer.undelivered.includes(sessionId);
537
563
  for (const key of keys) {
538
564
  const entry = ledger.get(key);
539
565
  if (entry === void 0) continue;
540
- entry.unreachable = undelivered.includes(sessionId);
541
- if (!entry.unreachable) entry.remindedAtMs = at.getTime();
566
+ entry.unreachable = unreachable;
567
+ entry.awaiting = !unreachable;
568
+ if (!unreachable) entry.remindedAtMs = at.getTime();
542
569
  }
543
- deps.log(`leftover: the dashboard ${undelivered.includes(sessionId) ? "has no stream row for" : "took the reminder for"} session ${sessionId} (${keys.length} processes)`);
570
+ deps.log(`leftover: the dashboard ${unreachable ? "has no stream row for" : "took the reminder for"} session ${sessionId} (${keys.length} processes)`);
544
571
  }
545
572
  }
546
573
  };
547
574
  }
548
575
  function createSystemLeftoverTracker(log, run = runCommand, platform = process.platform) {
549
576
  if (platform !== "win32") return { sample: async () => {
550
- }, collect: () => ({ sessions: [], ownerless: [], reminded: /* @__PURE__ */ new Map() }), settle: () => {
577
+ }, collect: () => ({ sessions: [], ownerless: [], reminded: /* @__PURE__ */ new Map(), awaiting: [] }), settle: () => {
551
578
  } };
552
579
  return createLeftoverTracker({
553
580
  log,
@@ -742,10 +769,12 @@ function foldOwnerless(payload, ownerless) {
742
769
  }
743
770
  };
744
771
  }
745
- function undeliveredOf(text) {
772
+ function answerOf(text) {
746
773
  try {
747
- const { undelivered } = JSON.parse(text);
748
- return Array.isArray(undelivered) && undelivered.every((id) => typeof id === "string") ? undelivered : null;
774
+ const answer = JSON.parse(text);
775
+ const lists = ["undelivered", "pending", "expired"].map((name) => answer[name]);
776
+ if (!lists.every((l) => Array.isArray(l) && l.every((id) => typeof id === "string"))) return null;
777
+ return { undelivered: lists[0], pending: lists[1], expired: lists[2] };
749
778
  } catch {
750
779
  return null;
751
780
  }
@@ -768,16 +797,16 @@ function createReporter(deps) {
768
797
  const payload = foldOwnerless(reportPayload(await deps.runHealth()), found.ownerless);
769
798
  const reportError = "report_error" in payload ? payload.report_error : null;
770
799
  if (found.sessions.length > 0 || found.ownerless.length > 0) deps.log(`report at ${startedAt.toISOString()} carries reminders for ${found.sessions.length} sessions and ${found.ownerless.length} ownerless processes`);
771
- const sent = await postAsMachine(deps.config, deps.fetchFn, "/api/machines/report", found.sessions.length === 0 ? payload : { ...payload, leftovers: { sessions: found.sessions } });
800
+ const sent = await postAsMachine(deps.config, deps.fetchFn, "/api/machines/report", found.sessions.length === 0 && found.awaiting.length === 0 ? payload : { ...payload, leftovers: { sessions: found.sessions, awaiting: found.awaiting } });
772
801
  let outcome;
773
802
  let error = reportError ?? sent.error;
774
803
  if (sent.status === 200) {
775
804
  const stored = storedKind(sent.text);
776
- const undelivered = undeliveredOf(sent.text);
777
- if (undelivered !== null) deps.leftovers.settle(found, undelivered, startedAt);
778
- if (stored === null || undelivered === null) {
805
+ const answer = answerOf(sent.text);
806
+ if (answer !== null) deps.leftovers.settle(found, answer, startedAt);
807
+ if (stored === null || answer === null) {
779
808
  outcome = "failed";
780
- error = "the dashboard answered 200 without saying what it stored and which sessions it could not remind";
809
+ error = "the dashboard answered 200 without saying what it stored and what became of the reminders";
781
810
  deps.log(`report failed at ${startedAt.toISOString()}: ${error}`);
782
811
  } else if (stored === "report_error" && reportError === null) {
783
812
  outcome = "report-refused";
@@ -885,12 +914,15 @@ function readJsonIfPresent(file) {
885
914
  }
886
915
  var DAEMON_LOG_MAX_BYTES = 1024 * 1024;
887
916
  function createDaemonLog(file, now = () => /* @__PURE__ */ new Date(), maxBytes = DAEMON_LOG_MAX_BYTES) {
917
+ let narrowed = false;
888
918
  return (line) => {
889
919
  try {
890
920
  mkdirSync(dirname(file), { recursive: true });
921
+ if (!narrowed && existsSync2(file) && process.platform !== "win32") chmodSync(file, 384);
922
+ narrowed = true;
891
923
  if (existsSync2(file) && statSync(file).size >= maxBytes) renameSync(file, `${file}.1`);
892
924
  appendFileSync(file, `${now().toISOString()} ${line}
893
- `, "utf8");
925
+ `, { encoding: "utf8", mode: 384 });
894
926
  } catch (err) {
895
927
  console.error(`[machine-daemon] cannot write ${file}: ${err instanceof Error ? err.message : String(err)}`);
896
928
  }
@@ -443,7 +443,7 @@ function resolveToolkitVersion(stamped, readManifest) {
443
443
  return stamped ?? readManifest();
444
444
  }
445
445
  var readOwnManifest = () => JSON.parse(readFileSync2(new URL("../../package.json", import.meta.url), "utf8")).version;
446
- var TOOLKIT_VERSION = resolveToolkitVersion(false ? void 0 : "0.1.460", readOwnManifest);
446
+ var TOOLKIT_VERSION = resolveToolkitVersion(false ? void 0 : "0.1.462", readOwnManifest);
447
447
  function envelope(now) {
448
448
  return { contract_version: CONTRACT_VERSION, toolkit_version: TOOLKIT_VERSION, profile: PROFILE, measured_at: now.toISOString() };
449
449
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@50arms/platform-mcp",
3
- "version": "0.1.460",
3
+ "version": "0.1.462",
4
4
  "description": "Stdio MCP server fronting the 50 Arms dashboard API for agents (operator sessions and dispatched workers alike): the generic 50arms_api/50arms_api_list/50arms_api_spec tools reach any route the caller's credential may call, plus dedicated agent-specific tools (session_connect, request_permission, attach_file, and 50arms_slack_reply) (DX-3465, PLN-11 R-25).",
5
5
  "license": "MIT",
6
6
  "type": "module",