neurastream 0.2.10 → 0.2.12

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/README.md CHANGED
@@ -170,6 +170,8 @@ Guard rules around it:
170
170
  - A stop the guard blocks posts nothing; when Main continues and really hands back later, that later stop posts the final text. A subagent session never posts, and a relaunch (the launcher's rollover) posts nothing.
171
171
  - The post never delays the stop decision: it times out at 5 seconds per chunk, makes one attempt, and writes one guard-log line when a channel fails. Long replies are split per channel (Discord 2000, Slack 3000 characters) on line boundaries where possible.
172
172
 
173
+ "Needs you" pings use the same channels so the owner learns on the phone that a decision is his: when a Main turn ends with an open plan whose `WAITING on owner:` line was not pinged before, neurastream posts `🔔 Needs you — <plan>: <question>` (with the `neurastream ui` phone-page link when `ui.enabled: true`), and when the guard refuses a Main tool call because it touches a protected guard file, it posts `🔓 Main needs an unlock to continue (<file>)` — the unlock ping at most once per 30 minutes, each waiting question once until its line changes or disappears, remembered in `<queue_state>/notify-waiting.json`. Every decision logs one `notify: needs-you posted|skipped (<why>)` guard-log line.
174
+
173
175
  ## Self-metrics
174
176
 
175
177
  `neurastream metrics report [--days N]` compares this window (the last `metrics.report_days`, default 7) with the one before it, writes `<paths.notes>/metrics.md`, and prints the same report. Worst change is marked `◀ worst`. The five numbers:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.10",
3
+ "version": "0.2.12",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -20,16 +20,17 @@ import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync,
20
20
  import { basename, dirname, join } from "node:path";
21
21
  import type { Decision } from "../../core/adapter.ts";
22
22
  import { loadConfig, type Config } from "../../core/config.ts";
23
- import { nowSec } from "../../core/clock.ts";
23
+ import { nowSec, strftime } from "../../core/clock.ts";
24
24
  import { runDetectorsGated } from "../../core/incident-detectors.ts";
25
25
  import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
26
- import { postReply } from "../../core/notify.ts";
26
+ import { notifyProviders, postReply } from "../../core/notify.ts";
27
27
  import { inboxPath } from "../../core/owner-ui.ts";
28
+ import { realTailscale } from "../../core/tailscale.ts";
28
29
  import { applyQueueEnv } from "../../core/queue/env.ts";
29
30
  import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
30
31
  import { readBlocks } from "../../core/metrics.ts";
31
32
  import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
32
- import { defaultCompletedResults, defaultRunSource, lastAssistantText } from "./sessions.ts";
33
+ import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
33
34
  import { packageJsonPath, packageVersion } from "./package-root.ts";
34
35
  import * as q from "../../core/queue/lib.ts";
35
36
  // Registers the plugin-command matcher into core's writeTargets (side effect).
@@ -60,6 +61,37 @@ function asString(v: unknown, fallback = ""): string {
60
61
  return typeof v === "string" ? v : fallback;
61
62
  }
62
63
 
64
+ /** The last assistant message of an omp event's `messages` array, as the adapter needs it: its
65
+ * joined text-block text and the shape that tells a real hand-back from a mid-run continuation
66
+ * (plan 20261025_0130). omp sends the reply in `session_stop.last_assistant_message` (falling
67
+ * back to the last assistant entry of `messages`) and in `agent_end.messages`; reading the
68
+ * session file instead lags a whole turn because session_stop fires BEFORE agent_end. */
69
+ interface EventReply {
70
+ text: string;
71
+ stopReason: string | null;
72
+ toolCalls: number;
73
+ }
74
+
75
+ function lastAssistantIn(messages: unknown): EventReply | null {
76
+ const arr = Array.isArray(messages) ? messages : [];
77
+ for (let i = arr.length - 1; i >= 0; i--) {
78
+ const m = asRecord(arr[i]);
79
+ if (m.role !== "assistant") continue;
80
+ const content = Array.isArray(m.content) ? m.content : [];
81
+ const text = content
82
+ .filter(c => asRecord(c).type === "text")
83
+ .map(c => asString(asRecord(c).text))
84
+ .join("\n")
85
+ .trim();
86
+ return {
87
+ text,
88
+ stopReason: typeof m.stopReason === "string" ? m.stopReason : null,
89
+ toolCalls: content.filter(c => asRecord(c).type === "toolCall").length,
90
+ };
91
+ }
92
+ return null;
93
+ }
94
+
63
95
  function asCtx(v: unknown): HostCtx {
64
96
  const r = asRecord(v);
65
97
  // The agent envelope only ever carries kind/id strings (original extensions read just those);
@@ -291,13 +323,37 @@ function writeOwnerInboxCursor(n: number): void {
291
323
  } catch {}
292
324
  }
293
325
 
294
- /** The user message one inbox record becomes, or null when it is not a page answer. */
326
+ /** The user message one inbox record becomes, or null when the record is not one Main can act on.
327
+ * Records without `kind` are page answers (the original shape). */
295
328
  export function ownerInboxMessage(rec: Record<string, unknown>): string | null {
296
- const plan = asString(rec.plan);
297
- const question = asString(rec.question);
298
- const answer = asString(rec.answer);
299
- if (!plan || !question || !answer) return null;
300
- return `Owner answered on the phone page — ${basename(plan)}: ${question} → ${answer}`;
329
+ const kind = rec.kind === undefined ? "answer" : asString(rec.kind);
330
+ const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
331
+ switch (kind) {
332
+ case "answer": {
333
+ const plan = asString(rec.plan);
334
+ const question = asString(rec.question);
335
+ const answer = asString(rec.answer);
336
+ if (!plan || !question || !answer) return null;
337
+ return `Owner answered on the phone page — ${basename(plan)}: ${question} → ${answer}`;
338
+ }
339
+ case "unlock": {
340
+ const minutes = num(rec.minutes);
341
+ const until = num(rec.until);
342
+ if (minutes === null || until === null) return null;
343
+ return `Owner unlocked the guards from the phone page for ${minutes} min (until ${strftime(until, "%H:%M")}). Do the step that waited on the unlock now.`;
344
+ }
345
+ case "lock":
346
+ return "Owner locked the guards from the phone page.";
347
+ case "reorder": {
348
+ const plan = asString(rec.plan);
349
+ const from = num(rec.from);
350
+ const to = num(rec.to);
351
+ if (!plan || from === null || to === null) return null;
352
+ return `Owner moved ${basename(plan)} from #${from} to #${to} on the phone page; INDEX.md has the new order — work by it.`;
353
+ }
354
+ default:
355
+ return null;
356
+ }
301
357
  }
302
358
 
303
359
  /** The JSONL rows after `cursor` (a row count), as records, plus the new cursor. A torn last row
@@ -354,10 +410,109 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
354
410
  let inboxTimer: unknown;
355
411
  const calls = new Map<string, number>(); // subagent call budget, by agent id
356
412
  const pending = new Map<string, Map<string, string>>(); // toolCallId -> plan snapshots
357
- // Chat notify (plan 20261024_2155): the last assistant text of the main session, and the text
358
- // a stop already posted (attempted) — one post per distinct text, never a retry loop.
359
- let lastReply: string | null = null;
413
+ // Chat notify (plans 20261024_2155, 20261025_0130): the text a hand-back already posted
414
+ // (attempted) — one post per distinct text, never a retry loop. The reply itself comes from
415
+ // the stop/agent_end event, never the session file (session_stop fires BEFORE agent_end, and
416
+ // omp skips it entirely while an async job is pending, so a file read lags a whole turn).
360
417
  let postedReply: string | null = null;
418
+ // Set by every session_stop path that returns block; the willContinue agent_end that omp then
419
+ // emits (sessionStopWillContinue) consumes it and posts nothing — a blocked stop's reply is a
420
+ // mid-work report, never a hand-back.
421
+ let stopBlocked = false;
422
+ // One guard-log line per notify decision: `notify: posted|skipped (<why>)`. Fire-and-forget:
423
+ // the decision never awaits the post; a failed or slow post logs one line and never blocks
424
+ // or retries.
425
+ const notifyHandback = (reply: EventReply | null, why: string): void => {
426
+ if (!reply || !reply.text) {
427
+ adapterLog(cfg, `notify: skipped (no reply text, ${why})`);
428
+ return;
429
+ }
430
+ if (reply.text === postedReply) {
431
+ adapterLog(cfg, `notify: skipped (duplicate, ${why})`);
432
+ return;
433
+ }
434
+ postedReply = reply.text;
435
+ adapterLog(cfg, `notify: posted (${why})`);
436
+ void postReply(reply.text, cfg).then(results => {
437
+ for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
438
+ });
439
+ };
440
+
441
+ // "Needs you" pings (P3b): the owner learns on Discord that a decision or an unlock is his —
442
+ // deterministic, no model call, Main session only, the same webhook path, fire-and-forget, one
443
+ // guard-log line per decision (`notify: needs-you posted|skipped (<why>)`).
444
+ const needsYouPost = (text: string, why: string): void => {
445
+ if (notifyProviders(cfg).length === 0) {
446
+ adapterLog(cfg, `notify: needs-you skipped (notify off, ${why})`);
447
+ return;
448
+ }
449
+ adapterLog(cfg, `notify: needs-you posted (${why})`);
450
+ void postReply(text, cfg).then(results => {
451
+ for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
452
+ });
453
+ };
454
+ // The phone-page link only when the page is on and this machine's MagicDNS name is known;
455
+ // computed at most once per process (tailscale status is a subprocess call).
456
+ let phonePageSuffix: string | null = null;
457
+ const phonePage = (): string => {
458
+ if (!cfg.ui.enabled) return "";
459
+ if (phonePageSuffix === null) {
460
+ const dns = realTailscale.dnsName();
461
+ phonePageSuffix = dns ? ` Answer on the phone page: http://${dns}:${cfg.ui.port}` : "";
462
+ }
463
+ return phonePageSuffix;
464
+ };
465
+ // WAITING: every Main turn end asks whether an open plan now waits on the owner (the same
466
+ // source the owner page lists). Keys are `plan file|waiting line`, remembered in
467
+ // <queue_state>/notify-waiting.json; a key whose line is gone is dropped, so the same question
468
+ // asked again later posts again. No waiting plans: no decision, no log line.
469
+ const waitingKeysFile = join(cfg.paths.queue_state, "notify-waiting.json");
470
+ const notifyWaitingPlans = (): void => {
471
+ const waiting = q.activePlans(cfg.paths.queue_index).filter(p => p.waiting && p.status === "open" && p.waitingLine);
472
+ let stored: string[] = [];
473
+ try {
474
+ const parsed: unknown = JSON.parse(readFileSync(waitingKeysFile, "utf8"));
475
+ if (Array.isArray(parsed)) stored = parsed.filter((k): k is string => typeof k === "string");
476
+ } catch {}
477
+ // Persist after reading: a key whose WAITING line is gone is dropped, so the same question
478
+ // asked again later posts again. No waiting plans: the set prunes to empty, no decision,
479
+ // no line.
480
+ const current: string[] = [];
481
+ const fresh: typeof waiting = [];
482
+ for (const p of waiting) {
483
+ const key = `${p.file}|${p.waitingLine}`;
484
+ current.push(key);
485
+ if (!stored.includes(key)) fresh.push(p);
486
+ }
487
+ try {
488
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
489
+ writeFileSync(waitingKeysFile, JSON.stringify(current));
490
+ } catch {}
491
+ if (current.length === 0) return;
492
+ if (fresh.length === 0) {
493
+ adapterLog(cfg, "notify: needs-you skipped (no new waiting lines)");
494
+ return;
495
+ }
496
+ for (const p of fresh) {
497
+ const title = p.text.match(/^# (.+)$/m)?.[1] ?? basename(p.file);
498
+ needsYouPost(`🔔 Needs you — ${title}: ${p.waitingLine}.${phonePage()}`, `waiting: ${basename(p.file)}`);
499
+ }
500
+ };
501
+ // UNLOCK: a protected-file refusal of a Main tool call means Main sits blocked until the owner
502
+ // unlocks — ping, at most once per 30 min.
503
+ let unlockPingMs = -Infinity;
504
+ const notifyUnlockNeeded = (reason: string): void => {
505
+ if (Date.now() - unlockPingMs < 30 * 60_000) {
506
+ adapterLog(cfg, "notify: needs-you skipped (unlock ping sent recently)");
507
+ return;
508
+ }
509
+ unlockPingMs = Date.now();
510
+ const target = basename(asString(reason.match(/plan-guard: (.+) is a protected guard file/)?.[1] ?? "guard file"));
511
+ needsYouPost(
512
+ `🔓 Main needs an unlock to continue (${target}). Tap "unlock ${cfg.guards.unlock_minutes}" on the phone page.`,
513
+ "protected-file refusal",
514
+ );
515
+ };
361
516
 
362
517
  pi.on("session_start", (_e, ctx) => {
363
518
  const c = asCtx(ctx);
@@ -444,7 +599,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
444
599
  { tool, input, cwd, agent, agentId: id, calls: n - 1, paths: [], writes: [], command: asString(input.command) },
445
600
  cfg,
446
601
  );
447
- if (!d.allow) return { block: true, reason: d.reason };
602
+ if (!d.allow) {
603
+ // P3b: Main refused on a protected guard file sits blocked until the owner unlocks.
604
+ if (!isSub && d.reason.includes("is a protected guard file. Only the owner changes it")) notifyUnlockNeeded(d.reason);
605
+ return { block: true, reason: d.reason };
606
+ }
448
607
  if (snap.size) pending.set(asString(e.toolCallId), snap);
449
608
  // The originals return nothing on a clean call; only warn injects carry an object.
450
609
  const out = toExtensionResult(d);
@@ -510,22 +669,20 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
510
669
  return undefined;
511
670
  });
512
671
 
513
- pi.on("session_stop", (_e, ctx) => {
672
+ pi.on("session_stop", (e, ctx) => {
514
673
  const c = asCtx(ctx);
515
674
  if (c.hasAgent && c.kind !== "main") return;
516
675
  // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
517
- if (relaunched) return undefined;
518
- // The stop hands the turn back to the owner: post Main's final reply, once per distinct
519
- // text. Fire-and-forget: the decision never awaits the post; a failed or slow post logs
520
- // one line and never blocks or retries.
521
- const notifyOwner = (): void => {
522
- const text = lastReply;
523
- if (!text || text === postedReply) return;
524
- postedReply = text;
525
- void postReply(text, cfg).then(results => {
526
- for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
527
- });
528
- };
676
+ if (relaunched) {
677
+ adapterLog(cfg, "notify: skipped (relaunch requested)");
678
+ return undefined;
679
+ }
680
+ // The stop hands the turn back to the owner: post the stop event's own final reply, once
681
+ // per distinct text. The reply comes from the event (last_assistant_message, falling back
682
+ // to the last assistant entry of messages), never the session file: omp fires session_stop
683
+ // BEFORE agent_end, so a file read would lag a whole turn.
684
+ const stopMsg = asRecord(e).last_assistant_message;
685
+ const reply = stopMsg ? lastAssistantIn([stopMsg]) : lastAssistantIn(asRecord(e).messages);
529
686
  // A pending rollover decides the stop and checkStop is not consulted: its queue, incident and cancel
530
687
  // blocks would hold Main at a wait the new session raises again through main-start, and its "spawn an
531
688
  // agent" text is refused while the rollover is pending.
@@ -534,6 +691,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
534
691
  const snap = rolloverSnapshot(rc);
535
692
  if (snap.state === "need-note") {
536
693
  adapterLog(cfg, "BLOCK stop: rollover need-note");
694
+ adapterLog(cfg, "notify: skipped (stop blocked: rollover need-note)");
695
+ stopBlocked = true;
537
696
  return { decision: "block", reason: noteRequestFor(rc, snap) };
538
697
  }
539
698
  if (snap.state === "ready" || snap.state === "wait-jobs") {
@@ -541,7 +700,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
541
700
  // Under the launcher a ready rollover starts now (not a hand-back to the owner);
542
701
  // plain omp waits for the owner's next message.
543
702
  const handsToOwner = !(snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && requestRelaunch(rc, notePath(rc.sessionId)));
544
- if (handsToOwner) notifyOwner();
703
+ if (handsToOwner) notifyHandback(reply, "allowed session_stop");
704
+ else adapterLog(cfg, "notify: skipped (relaunch requested)");
545
705
  return undefined;
546
706
  }
547
707
  }
@@ -549,9 +709,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
549
709
  callsSinceStop = d.state?.callsSinceStop ?? 0;
550
710
  idleStops = d.state?.idleStops ?? idleStops;
551
711
  if (d.allow) {
552
- notifyOwner();
712
+ notifyHandback(reply, "allowed session_stop");
553
713
  return undefined;
554
714
  }
715
+ adapterLog(cfg, "notify: skipped (stop blocked by guard)");
716
+ stopBlocked = true;
555
717
  return { decision: "block", reason: d.reason };
556
718
  });
557
719
 
@@ -740,20 +902,47 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
740
902
  }
741
903
  };
742
904
  pi.on("agent_end", (e, ctx) => onSizeCheck("agent_end", e, ctx));
743
- // The text a later allowed stop posts: the last assistant message of each terminal run end in
744
- // the main session (omp 18.11.1 sets willContinue on a non-terminal end). A blocked stop keeps
745
- // Main talking, so the final run end overwrites this before the stop that really hands back.
905
+ // Hand-back without a session_stop (plan 20261025_0130): while an async job is pending omp
906
+ // fires agent_end with willContinue:true and SKIPS session_stop — this deferred hand-back
907
+ // posts from the event's own messages. omp also sets willContinue after a BLOCKED stop
908
+ // (sessionStopWillContinue) and for todo/plan-mode/rewind continuations, so a post here needs
909
+ // both: no blocked stop just decided (the flag), and an async job really pending. A terminal
910
+ // end (willContinue unset) is not a hand-back: the session_stop that follows it decides. A
911
+ // mid-run continuation — tool calls, or a non-"stop" reason such as an auto-retry — posts
912
+ // nothing.
746
913
  pi.on("agent_end", (e, ctx) => {
747
914
  if (!isMain(ctx)) return;
748
- if (asRecord(e).willContinue === true) return;
749
- const rc = asRolloverCtx(ctx);
750
- if (!rc) return;
751
- const text = lastAssistantText(rc.sessionFile);
752
- lastReply = text.trim() ? text : null;
915
+ if (asRecord(e).willContinue !== true) return;
916
+ if (stopBlocked) {
917
+ stopBlocked = false;
918
+ adapterLog(cfg, "notify: skipped (stop blocked, agent_end)");
919
+ return;
920
+ }
921
+ const jobCount = asRolloverCtx(ctx)?.runningJobs().length ?? 0;
922
+ if (jobCount === 0) {
923
+ adapterLog(cfg, "notify: skipped (no pending job, agent_end)");
924
+ return;
925
+ }
926
+ const reply = lastAssistantIn(asRecord(e).messages);
927
+ if (!reply || !reply.text) {
928
+ adapterLog(cfg, "notify: skipped (no reply text, agent_end hand-back)");
929
+ return;
930
+ }
931
+ if (reply.stopReason !== "stop" || reply.toolCalls > 0) {
932
+ adapterLog(
933
+ cfg,
934
+ `notify: skipped (mid-run: stop reason ${reply.stopReason ?? "unknown"}${reply.toolCalls > 0 ? ` + ${reply.toolCalls} tool call(s)` : ""}, agent_end hand-back)`,
935
+ );
936
+ return;
937
+ }
938
+ notifyHandback(reply, "agent_end hand-back");
753
939
  });
754
- // Turn end: page answers that arrived during the turn go out now (P3b). Main only.
940
+ // Turn end: page answers that arrived during the turn go out (P3b), then open plans that now
941
+ // WAIT on the owner ping Discord (P3b). Main only.
755
942
  pi.on("agent_end", (_e, ctx) => {
756
- if (isMain(ctx)) deliverOwnerInbox(pi, cfg);
943
+ if (!isMain(ctx)) return;
944
+ deliverOwnerInbox(pi, cfg);
945
+ notifyWaitingPlans();
757
946
  });
758
947
 
759
948
  // omp is really shutting down: the exit-grace fallback must not fire.
@@ -49,37 +49,6 @@ function asObj(v: unknown): Record<string, unknown> | null {
49
49
  return typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
50
50
  }
51
51
 
52
- /** The joined text of the session file's last assistant message, trimmed; "" when there is none
53
- * (unreadable file, no assistant message, or a tool-use-only ending). */
54
- export function lastAssistantText(file: string): string {
55
- let text: string;
56
- try {
57
- text = readFileSync(file, "utf8");
58
- } catch {
59
- return "";
60
- }
61
- let out = "";
62
- for (const line of text.split("\n")) {
63
- if (!line.trim()) continue;
64
- let parsed: unknown;
65
- try {
66
- parsed = JSON.parse(line);
67
- } catch {
68
- continue;
69
- }
70
- const d = asObj(parsed);
71
- if (!d) continue;
72
- const m = asObj(d.message) ?? d;
73
- if (m.role !== "assistant") continue;
74
- const content = Array.isArray(m.content) ? m.content : [];
75
- const texts = content
76
- .filter((c): c is Record<string, unknown> => asObj(c) !== null && asObj(c)?.type === "text")
77
- .map(c => String(c.text ?? ""));
78
- out = texts.join("\n").trim();
79
- }
80
- return out;
81
- }
82
-
83
52
  function costOf(m: Record<string, unknown>): number {
84
53
  const u = asObj(m.usage);
85
54
  const c = u ? asObj(u.cost) : null;
@@ -259,12 +259,19 @@ function handleUnlock(cfg: Config, fields: Record<string, string>, login: string
259
259
  if (minutes !== "" && !/^\d+$/.test(minutes)) return textRes("minutes must be a number", 400);
260
260
  const result = chatUnlock(minutes === "" ? "unlock" : `unlock ${minutes}`, cfg, `ui:${login}`, "ui");
261
261
  if (!result.applied) return textRes("unlock refused: guards.chat_unlock is off", 409);
262
+ mkdirSync(stateDirPath(), { recursive: true });
263
+ appendFileSync(
264
+ inboxPath(),
265
+ `${JSON.stringify({ ts: nowSec(), kind: "unlock", minutes: result.minutes, until: result.until, login })}\n`,
266
+ );
262
267
  return redirect();
263
268
  }
264
269
 
265
270
  function handleLock(cfg: Config, login: string): Response {
266
271
  const result = chatUnlock("lock", cfg, `ui:${login}`, "ui");
267
272
  if (!result.applied) return textRes("lock refused: guards.chat_unlock is off", 409);
273
+ mkdirSync(stateDirPath(), { recursive: true });
274
+ appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "lock", login })}\n`);
268
275
  return redirect();
269
276
  }
270
277
 
@@ -621,6 +621,8 @@ export interface ChatUnlockResult {
621
621
  command?: "unlock" | "lock";
622
622
  /** For an unlock: the minutes the existing mtime window stays open (for the owner notice). */
623
623
  minutes?: number;
624
+ /** For an unlock: epoch seconds when the guard window closes (mtime + unlock_minutes). */
625
+ until?: number;
624
626
  }
625
627
 
626
628
  const CHAT_CMD = /^(unlock|lock)(?:\s+(\d+))?$/i;
@@ -657,7 +659,7 @@ export function chatUnlock(text: string, cfg: Config, source: string, word: "cha
657
659
  try {
658
660
  appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} UNLOCK ${word} source=${source} minutes=${n}\n`);
659
661
  } catch {}
660
- return { applied: true, command: "unlock", minutes: n };
662
+ return { applied: true, command: "unlock", minutes: n, until: Math.floor(past + minutes * 60) };
661
663
  }
662
664
 
663
665
  export function protectedHit(paths: string[]): string | null {