@join-pantheon/cli 0.37.2 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,207 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { readStateText, withFileLock } from "./file-lock.js";
4
+ import { atomicWrite } from "./worker-policy.js";
5
+ import { BUDGET } from "./notice.js";
6
+ export const WATCHED = ["worker", "notifier"];
7
+ export const LOOP_WINDOW_MS = 10 * 60_000;
8
+ export const LOOP_STARTS = 3;
9
+ export const HEALTHY_AFTER_CONNECT_MS = 60_000;
10
+ export const STEADY_AFTER_MS = 10 * 60_000;
11
+ export const LOOP_STALE_MS = 60 * 60_000;
12
+ export const EXPECTED_EXIT_CODES = [0, 129, 130, 143];
13
+ export const startsPath = (home) => join(home ?? process.env.PANTHEON_HOME ?? join(homedir(), ".pantheon"), "service-starts.json");
14
+ const isTime = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
15
+ const episode = (v) => {
16
+ const e = v;
17
+ if (!e || !isTime(e.since) || !isTime(e.last) || typeof e.starts !== "number" || e.starts < 0)
18
+ return undefined;
19
+ return { since: e.since, starts: Math.min(Math.floor(e.starts), 1e6), last: e.last, ...(isTime(e.alerted_at) ? { alerted_at: e.alerted_at } : {}) };
20
+ };
21
+ export function readStarts(home) {
22
+ let raw;
23
+ try {
24
+ raw = JSON.parse(readStateText(startsPath(home)));
25
+ }
26
+ catch {
27
+ return {};
28
+ }
29
+ const out = {};
30
+ for (const k of WATCHED) {
31
+ const r = raw?.[k];
32
+ if (!r || typeof r !== "object")
33
+ continue;
34
+ const rec = { starts: Array.isArray(r.starts) ? r.starts.filter(isTime).slice(-50) : [] };
35
+ if (isTime(r.healthy_at))
36
+ rec.healthy_at = r.healthy_at;
37
+ const loop = episode(r.loop);
38
+ if (loop)
39
+ rec.loop = loop;
40
+ const last = episode(r.last_loop);
41
+ const ended = r.last_loop?.ended_at;
42
+ if (last && isTime(ended))
43
+ rec.last_loop = { ...last, ended_at: ended };
44
+ out[k] = rec;
45
+ }
46
+ return out;
47
+ }
48
+ function update(home, fn) {
49
+ const file = startsPath(home);
50
+ let result;
51
+ const write = () => { const s = readStarts(home); result = fn(s); atomicWrite(file, JSON.stringify(s, null, 2) + "\n"); };
52
+ let ran = false;
53
+ try {
54
+ withFileLock(file, () => { ran = true; write(); }, 2_000);
55
+ }
56
+ catch (e) {
57
+ if (ran)
58
+ throw e;
59
+ write();
60
+ }
61
+ return result;
62
+ }
63
+ export function recordStart(kind, o = {}) {
64
+ const now = o.now ?? Date.now();
65
+ return update(o.home, (s) => {
66
+ const rec = s[kind] ?? { starts: [] };
67
+ if (rec.loop && now - rec.loop.last >= LOOP_STALE_MS) {
68
+ rec.last_loop = { ...rec.loop, ended_at: rec.loop.last };
69
+ delete rec.loop;
70
+ }
71
+ rec.starts = [...rec.starts.filter((t) => now - t < LOOP_WINDOW_MS && t <= now), now];
72
+ if (rec.loop) {
73
+ rec.loop.starts += 1;
74
+ rec.loop.last = now;
75
+ }
76
+ else if (rec.starts.length >= LOOP_STARTS)
77
+ rec.loop = { since: rec.starts[0], starts: rec.starts.length, last: now };
78
+ s[kind] = rec;
79
+ const loop = rec.loop ?? null;
80
+ if (loop && !loop.alerted_at) {
81
+ loop.alerted_at = now;
82
+ return { loop: { ...loop }, alert: true };
83
+ }
84
+ return { loop: loop ? { ...loop } : null, alert: false };
85
+ });
86
+ }
87
+ export function markHealthy(kind, o = {}) {
88
+ const now = o.now ?? Date.now();
89
+ try {
90
+ return update(o.home, (s) => {
91
+ const rec = s[kind] ?? { starts: [] };
92
+ const ended = rec.loop ?? null;
93
+ rec.starts = [];
94
+ rec.healthy_at = now;
95
+ if (ended)
96
+ rec.last_loop = { ...ended, ended_at: now };
97
+ delete rec.loop;
98
+ s[kind] = rec;
99
+ return ended;
100
+ });
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ }
106
+ export function markExpectedExit(kind, o = {}) {
107
+ if (!readStarts(o.home)[kind]?.starts.length)
108
+ return;
109
+ try {
110
+ update(o.home, (s) => { const rec = s[kind]; if (rec)
111
+ rec.starts = []; });
112
+ }
113
+ catch { }
114
+ }
115
+ export function stopIsExpected(kind, o = {}) {
116
+ if (kind === "worker" || kind === "notifier")
117
+ markExpectedExit(kind, o);
118
+ }
119
+ export function activeLoop(kind, o = {}) {
120
+ const loop = (o.file ?? readStarts(o.home))[kind]?.loop;
121
+ if (!loop)
122
+ return null;
123
+ return (o.now ?? Date.now()) - loop.last < LOOP_STALE_MS ? loop : null;
124
+ }
125
+ const NAME = { worker: "worker", notifier: "desktop alerts" };
126
+ const span = (ms) => { const m = Math.max(1, Math.round(ms / 60_000)); return m < 90 ? `${m} minute${m === 1 ? "" : "s"}` : `${Math.round(m / 60)} hours`; };
127
+ export function loopLine(kind, loop, now = Date.now()) {
128
+ const what = kind === "worker" ? "teammates' requests wait for you meanwhile" : "you may miss decisions meanwhile";
129
+ return `Pantheon's ${NAME[kind]} keeps stopping — it has restarted ${loop.starts} times in ${span(Math.max(now, loop.last) - loop.since)} without staying up, so ${what}. pantheon doctor shows why`;
130
+ }
131
+ export function crashLoopLine(home, now = Date.now()) {
132
+ const file = readStarts(home);
133
+ for (const k of WATCHED) {
134
+ const l = activeLoop(k, { now, file });
135
+ if (l)
136
+ return loopLine(k, l, now);
137
+ }
138
+ return null;
139
+ }
140
+ export function composeCrashLoop(kind, loop, o = {}) {
141
+ const heading = kind === "worker" ? "Pantheon's worker keeps stopping" : "Pantheon's alerts keep stopping";
142
+ const body = kind === "worker"
143
+ ? `It has restarted ${loop.starts} times in ${span((o.now ?? Date.now()) - loop.since)}, so teammates' requests wait for you. Run pantheon doctor: it shows why and what to do.`
144
+ : `Desktop alerts have restarted ${loop.starts} times in ${span((o.now ?? Date.now()) - loop.since)}, so you may miss decisions. Run pantheon doctor: it shows why and what to do.`;
145
+ return {
146
+ kind: "worker_failed", who: "Pantheon · this computer", heading, context: "",
147
+ body: body.length <= BUDGET.body ? body : `${body.slice(0, BUDGET.body - 1)}…`,
148
+ ttl: 0, sound: false, tag: `pantheon_loop_${kind}`,
149
+ ...((o.os ?? process.platform) === "win32" ? {} : { fix: { label: "Show me how", dir: o.dir ?? homedir(), lines: ["pantheon doctor"], why: heading } }),
150
+ };
151
+ }
152
+ let tracking = null;
153
+ export function trackService(kind, o = {}) {
154
+ const now = o.now ?? Date.now;
155
+ let r = { loop: null, alert: false };
156
+ try {
157
+ r = recordStart(kind, { ...(o.home ? { home: o.home } : {}), now: now() });
158
+ }
159
+ catch { }
160
+ tracking = { kind, ...(o.home ? { home: o.home } : {}), startedAt: now(), healthy: false, expectExit: false, connected: false, timers: [] };
161
+ const t = tracking;
162
+ if (!o.passive) {
163
+ const steady = setTimeout(() => healthyNow(t), STEADY_AFTER_MS);
164
+ steady.unref?.();
165
+ t.timers.push(steady);
166
+ process.on("exit", (code) => { if (!t.healthy && (t.expectExit || EXPECTED_EXIT_CODES.includes(code)))
167
+ markExpectedExit(t.kind, t.home ? { home: t.home } : {}); });
168
+ exitOnStopSignals();
169
+ }
170
+ if (r.alert && r.loop) {
171
+ try {
172
+ o.onLoop?.(r.loop);
173
+ }
174
+ catch { }
175
+ }
176
+ return r;
177
+ }
178
+ export function exitOnStopSignals(proc = process) {
179
+ for (const [sig, code] of [["SIGTERM", 143], ["SIGHUP", 129]]) {
180
+ try {
181
+ proc.on(sig, () => { if (proc.listenerCount(sig) <= 1)
182
+ proc.exit(code); });
183
+ }
184
+ catch { }
185
+ }
186
+ }
187
+ function healthyNow(t) {
188
+ if (t.healthy)
189
+ return;
190
+ t.healthy = true;
191
+ markHealthy(t.kind, t.home ? { home: t.home } : {});
192
+ }
193
+ export function noteServiceConnected() {
194
+ const t = tracking;
195
+ if (!t || t.healthy || t.connected)
196
+ return;
197
+ t.connected = true;
198
+ const timer = setTimeout(() => healthyNow(t), HEALTHY_AFTER_CONNECT_MS);
199
+ timer.unref?.();
200
+ t.timers.push(timer);
201
+ }
202
+ export function expectServiceExit() { if (tracking)
203
+ tracking.expectExit = true; }
204
+ export function resetServiceTracking() { if (tracking)
205
+ for (const t of tracking.timers)
206
+ clearTimeout(t); tracking = null; }
207
+ //# sourceMappingURL=crash-loop.js.map
package/dist/doctor.js CHANGED
@@ -27,9 +27,10 @@ import { goneLine, leaveCommand, removalKey, removalRefusal, removals, removalWo
27
27
  import { agentById, chooseAgent, describeChoice, detectAvailable, folderReaderLine, knownUserBinary, unattendedReadiness, unattendedRefusal, skippedSummary, SANDBOXED_FOR_UNATTENDED } from "./agents.js";
28
28
  import { loginShellLookup, npmSpawn, onPathNamed, which, whichWindows } from "./which.js";
29
29
  import { VERSION } from "./version.js";
30
- import { borrowedScheduler, realSys, serviceInstalled, servicesUnavailable } from "./service.js";
30
+ import { borrowedScheduler, realSys, serviceInstalled, serviceLogFile, servicesUnavailable } from "./service.js";
31
31
  import { statusDir } from "./status-nudge.js";
32
32
  import { CONN_FRESH_MS } from "./conn-report.js";
33
+ import { activeLoop, loopLine, readStarts, WATCHED } from "./crash-loop.js";
33
34
  export function ownProcesses() {
34
35
  const borrowed = (() => { try {
35
36
  return borrowedScheduler();
@@ -205,6 +206,36 @@ function repoBoundToTeam(cfg) {
205
206
  return false;
206
207
  }
207
208
  }
209
+ export function crashLoopRows(o = {}) {
210
+ const now = o.now ?? Date.now();
211
+ const file = readStarts(o.home);
212
+ const rows = [];
213
+ const tail = o.logTail ?? ((kind) => {
214
+ try {
215
+ const lines = readFileSync(serviceLogFile(kind), "utf8").split("\n").map((l) => l.trim()).filter(Boolean).slice(-40);
216
+ return [...lines].reverse().find((l) => /error|!|fail|cannot|refused|throw/i.test(l)) ?? lines[lines.length - 1] ?? null;
217
+ }
218
+ catch {
219
+ return null;
220
+ }
221
+ });
222
+ for (const kind of WATCHED) {
223
+ const name = kind === "worker" ? "worker restarts" : "alerts restarts";
224
+ const loop = activeLoop(kind, { now, file });
225
+ if (loop) {
226
+ const said = tail(kind);
227
+ rows.push({ level: "warn", name, detail: `${loopLine(kind, loop, now).replace(/\. pantheon doctor shows why$/, "")}${said ? `. Its log last said: ${said.slice(0, 300)}` : ""}`,
228
+ fix: `pantheon logs ${kind} shows the whole log. If the line above names a cause you can fix (a setting, a sign-in, a full disk), fix it; otherwise run pantheon upgrade (an older build may be the cause) and then pantheon service restart ${kind}`,
229
+ share: `${kind} restarted ${loop.starts} times without staying up` });
230
+ continue;
231
+ }
232
+ const last = file[kind]?.last_loop;
233
+ if (last && now - last.ended_at < 24 * 3_600_000) {
234
+ rows.push({ level: "pass", name, detail: `it kept restarting earlier (${last.starts} times), and has stayed up since ${new Date(last.ended_at).toLocaleString()}`, share: `${kind} recovered from a restart loop` });
235
+ }
236
+ }
237
+ return rows;
238
+ }
208
239
  export async function doctor(projectDir) {
209
240
  const out = [];
210
241
  const add = (level, name, detail, fix, share) => out.push({ level, name, detail, ...(fix ? { fix } : {}), ...(share ? { share } : {}) });
@@ -275,6 +306,8 @@ export async function doctor(projectDir) {
275
306
  add("warn", "connections", stuck.map((x) => x.line).join("; "), "if the relay answers (the relay check below), these are stuck, not waiting out an outage: restart each as said. If the relay is down, they come back by themselves once it is up.", `${stuck.length} process${stuck.length === 1 ? "" : "es"} without the relay for over 2 min (${[...new Set(stuck.map((x) => x.role))].join(", ")})`);
276
307
  }
277
308
  }
309
+ for (const r of crashLoopRows())
310
+ add(r.level, r.name, r.detail, r.fix, r.share);
278
311
  let cfg = null;
279
312
  try {
280
313
  cfg = load() ?? (() => { const f = loadAll(); const m = Object.values(f?.spaces ?? {})[0]; return f && m ? configFor(f, m, null) : null; })();
@@ -600,6 +633,10 @@ export async function doctor(projectDir) {
600
633
  try {
601
634
  const res = await fetch(health, { signal: AbortSignal.timeout(5000) });
602
635
  const body = (await relayJson(res, health));
636
+ if (typeof body.pkg === "string") {
637
+ const { recordRelayPkg } = await import("./version-health.js");
638
+ recordRelayPkg(cfg.relay, body.pkg);
639
+ }
603
640
  await certRow(true);
604
641
  if (!body.ok && body.storage) {
605
642
  const since = body.storage.at ? ` (since ${new Date(body.storage.at).toLocaleString()})` : "";
@@ -632,6 +669,10 @@ export async function doctor(projectDir) {
632
669
  }
633
670
  catch (e) {
634
671
  const msg = e.message;
672
+ if (sandboxOffline()) {
673
+ add("warn", "relay", "not checked: this shell is Codex's sandbox, which has no network, so nothing here says whether this computer reaches the relay", "coding agent: run pantheon doctor again with network access, asking your person to approve it", "not checked (an offline sandbox)");
674
+ return out;
675
+ }
635
676
  const c = await certRow(false);
636
677
  const nx = c?.publicCa === false && worthCertificateCheck(e) ? interceptionExplanation(c) : explainNetError(e, health);
637
678
  if (nx) {
@@ -950,4 +991,7 @@ export function shareBlock(checks, now = new Date()) {
950
991
  `send it to ${FEEDBACK_ADDRESS} with one line on what you expected to happen`,
951
992
  ].join("\n");
952
993
  }
994
+ export function sandboxOffline(env = process.env) {
995
+ return env.CODEX_SANDBOX_NETWORK_DISABLED === "1";
996
+ }
953
997
  //# sourceMappingURL=doctor.js.map
@@ -36,11 +36,11 @@ export function codeEmailHtml(code, purpose, link) {
36
36
  <span style="font-family:'Space Mono',Menlo,Consolas,'Liberation Mono',monospace;font-size:38px;line-height:1.1;letter-spacing:.26em;font-weight:700;color:#f1e7d3">${code}</span>
37
37
  </td>
38
38
  </tr></table>
39
- <p style="margin:22px 0 0;font-family:'Space Mono',Menlo,Consolas,'Liberation Mono',monospace;font-size:15px;line-height:1.65;color:#26221f">Enter it where the terminal is waiting, to ${action}. Or run:</p>
39
+ <p style="margin:22px 0 0;font-family:'Space Mono',Menlo,Consolas,'Liberation Mono',monospace;font-size:15px;line-height:1.65;color:#26221f">Give it to your coding agent, or enter it where the terminal is waiting, to ${action}. Or run:</p>
40
40
  </td></tr>
41
41
  <tr><td class="px" style="padding:12px 40px 6px"><table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td style="background:#1b1917;border-radius:8px;padding:13px 16px;font-family:'Space Mono',Menlo,Consolas,'Liberation Mono',monospace;font-size:14px;line-height:1.75;color:#f1e7d3;word-break:break-all"><span style="color:#e36f55">$</span> pantheon verify ${code}</td></tr></table></td></tr>
42
42
  ${link ? ` <tr><td class="px" style="padding:18px 40px 6px">
43
- <p style="margin:0 0 12px;font-family:'Space Mono',Menlo,Consolas,'Liberation Mono',monospace;font-size:15px;line-height:1.65;color:#26221f">Or confirm in your browser. You will type the two words your screen shows.</p>
43
+ <p style="margin:0 0 12px;font-family:'Space Mono',Menlo,Consolas,'Liberation Mono',monospace;font-size:15px;line-height:1.65;color:#26221f">Or confirm in your browser. You will type the two words in capitals that your coding agent (or terminal) showed you when it sent this email.</p>
44
44
  <a href="${esc(link)}" style="display:inline-block;background:#e36f55;color:#1b1917;border-radius:8px;padding:12px 20px;font-family:'Space Mono',Menlo,Consolas,monospace;font-size:15px;font-weight:700;text-decoration:none">Confirm it's you</a>
45
45
  </td></tr>` : ""}
46
46
  <tr><td class="px" style="padding:22px 40px 32px">
package/dist/email.js CHANGED
@@ -8,10 +8,10 @@ function subjectAndBody(code, purpose, link) {
8
8
  ``,
9
9
  `Your verification code is ${code}.`,
10
10
  ``,
11
- `Enter it where the terminal is waiting, to ${action}. Or run:`,
11
+ `Give it to your coding agent, or enter it where the terminal is waiting, to ${action}. Or run:`,
12
12
  ` pantheon verify ${code}`,
13
13
  ``,
14
- ...(link ? [`Or confirm in your browser — you will type the two words your screen shows:`, ` ${link}`, ``] : []),
14
+ ...(link ? [`Or confirm in your browser. You will type the two words in capitals that your coding agent (or terminal) showed you when it sent this email:`, ` ${link}`, ``] : []),
15
15
  `The code expires in 10 minutes and works once. If you did not ask for it,`,
16
16
  `ignore this email: nothing happens without the code.`,
17
17
  ``,
@@ -12,10 +12,11 @@ export function finishItems(f) {
12
12
  out.push({
13
13
  says: "No coding agent is installed on this machine, so nothing is connected to your team yet.",
14
14
  fix: `${r?.code === "no_agent" ? r.fix.replace(/\.$/, "") : "Install Claude Code, Codex, Cursor, Copilot or Kiro"} — then run: pantheon install --user`,
15
+ blocks: true,
15
16
  });
16
17
  }
17
18
  else if (!wired.length) {
18
- out.push({ says: "No agent on this machine could be connected to Pantheon (see the lines above).", fix: "fix what they say, then run: pantheon install --user" });
19
+ out.push({ says: "No agent on this machine could be connected to Pantheon (see the lines above).", fix: "fix what they say, then run: pantheon install --user", blocks: true });
19
20
  }
20
21
  for (const t of f.tools.filter((x) => rowFailed(x.status) && !(AGENT_ROWS.has(x.tool) && !wired.length))) {
21
22
  out.push({ says: `${t.tool} was not set up: ${t.status.replace(/^(failed|could not install):?\s*/i, "")}`, fix: "fix that, then run: pantheon install --user" });
@@ -24,24 +25,36 @@ export function finishItems(f) {
24
25
  const m = /^installed, not running:\s*(.*)$/i.exec(t.status);
25
26
  const svc = SERVICE_OF[t.tool];
26
27
  if (m && svc)
27
- out.push({ says: `The ${t.tool === "notifications" ? "desktop alerts" : t.tool} ${t.tool === "notifications" ? "are" : "is"} installed but not running (${m[1]}).`, fix: `pantheon service restart ${svc}` });
28
+ out.push({ says: `The ${t.tool === "notifications" ? "desktop alerts" : t.tool} ${t.tool === "notifications" ? "are" : "is"} installed but not running (${m[1]}).`, fix: `pantheon service restart ${svc}`, ...(svc === "worker" ? { blocks: true } : {}) });
28
29
  }
29
30
  if (r && !(r.code === "no_agent" && !attempted.length)) {
30
31
  if (r.code === "not_signed_in" && r.agent) {
31
32
  const label = r.short.replace(/ isn't signed in$/, "");
32
- out.push({ says: `${label} is signed out, so teammates' requests can't run here while you're away.`, fix: r.fix, signIn: r.agent });
33
+ out.push({ says: `${label} is signed out, so teammates' requests can't run here while you're away.`, fix: r.fix, signIn: r.agent, blocks: true });
33
34
  }
34
35
  else
35
- out.push({ says: r.says, fix: r.fix });
36
+ out.push({ says: r.says, fix: r.fix, blocks: true });
36
37
  }
37
38
  const rowSaid = out.some((i) => /^The worker is installed but not running|^worker was not set up/.test(i.says));
38
39
  if (f.workerWanted && (f.served ?? 0) > 0 && f.worker && !(f.worker.installed && f.worker.loaded) && !rowSaid) {
39
40
  out.push(f.worker.installed
40
- ? { says: "Your worker is installed but not running, so teammates' requests wait for you while you're away.", fix: "pantheon service restart worker" }
41
- : { says: "Your worker isn't installed, so teammates' requests wait for you while you're away.", fix: "pantheon service install worker" });
41
+ ? { says: "Your worker is installed but not running, so teammates' requests wait for you while you're away.", fix: "pantheon service restart worker", blocks: true }
42
+ : { says: "Your worker isn't installed, so teammates' requests wait for you while you're away.", fix: "pantheon service install worker", blocks: true });
43
+ }
44
+ const alertsSaid = out.some((i) => /^The desktop alerts are installed but not running|^notifications was not set up/.test(i.says));
45
+ if (f.alerts && !(f.alerts.installed && f.alerts.loaded) && !alertsSaid) {
46
+ out.push(f.alerts.installed
47
+ ? { says: "Desktop alerts are installed but not running, so you won't hear when a teammate needs you.", fix: "pantheon service restart notifier" }
48
+ : { says: "Desktop alerts aren't installed, so you won't hear when a teammate needs you.", fix: "pantheon service install notifier" });
42
49
  }
43
50
  if (f.workerWanted && f.served === 0) {
44
- out.push({ says: `Nothing on this machine is bound to "${f.team}", so your worker has nothing to work in while you're away.`, fix: `from the folder you work in (a repo, or a folder of docs): pantheon use ${f.team} --here` });
51
+ out.push({
52
+ says: `This computer can't take your teammates' requests yet: no folder on it is linked to "${f.team}", so your worker has nothing to work in.`,
53
+ fix: f.agentShell && f.linkLine
54
+ ? `ask your person which folder they work in for "${f.team}" — a repo, or a folder of documents; never pick one for them (the ones found here are listed above) — then run, with that folder: ${f.linkLine}`
55
+ : `from the folder you work in (a repo, or a folder of docs): pantheon use ${f.team} --here`,
56
+ blocks: true, needsFolder: true,
57
+ });
45
58
  }
46
59
  if (f.windows?.length) {
47
60
  const self = f.windows.filter((w) => w.self);
@@ -55,6 +68,11 @@ export function finishItems(f) {
55
68
  if (hook && /codex: run \/hooks/i.test(hook.status) && !rowFailed(hook.status) && !/^skipped/i.test(hook.status)) {
56
69
  out.push({ says: "Codex skips Pantheon's wake-up hook until you approve it.", fix: "in Codex, run /hooks once and approve it" });
57
70
  }
71
+ if (f.agentShell) {
72
+ for (const i of out)
73
+ if (/^pantheon service (restart|install) /.test(i.fix))
74
+ i.fix = `${i.fix} (coding agent: ask your person to approve running this outside your sandbox — a sandbox can't start background services)`;
75
+ }
58
76
  if (f.pending > 0) {
59
77
  out.push({ says: `${f.pending === 1 ? "A change" : `${f.pending} changes`} to your setup ${f.pending === 1 ? "waits" : "wait"} for you to confirm.`, fix: "pantheon changes" });
60
78
  }
@@ -194,15 +194,19 @@ function codeSent(cmd, deps, s) {
194
194
  ? `A code was sent to ${s.email} ${s.reused} min ago — use that one. ${SPAM}`
195
195
  : `Sent a 6-digit code to ${s.email}. ${SPAM}${s.dev ? " (A dev relay: the code is in its log.)" : ""}`;
196
196
  const who = s.account === "new" ? `This makes a new account, ${s.username}.` : `This signs this computer in to your account.`;
197
+ const tell = s.words
198
+ ? `Check your email (and spam) for a message from Pantheon. Either tell me the 6-digit code in it, or open its link and type these two words there: ${s.words.toUpperCase()}`
199
+ : `Check your email (and spam) for a message from Pantheon, and tell me the 6-digit code in it.`;
197
200
  return {
198
201
  kind: "needs_person", needs: "code",
199
- lines: [head, who, `When the person has the code, run: ${nxt}`,
200
- ...(s.words ? [`Or they open the link in that email and type these two words there: ${s.words.toUpperCase()} — then run: ${cont}`] : []),
202
+ lines: [head, who, `Say this to the person, word for word: "${tell}"`, `When the person has the code, run: ${nxt}`,
203
+ ...(s.words ? [`If they typed the words in the link instead, run: ${cont}`] : []),
201
204
  `Wrong address? Run the first command again with the right --email.`],
202
205
  json: {
203
206
  needs: "code", sent_to: s.email, account: s.account,
204
207
  ...(s.username ? { username: s.username } : {}),
205
208
  ...(s.reused ? { reused: true } : {}),
209
+ tell_person: tell,
206
210
  next: nxt,
207
211
  ...(s.words ? { link: true, words: s.words, next_link: cont } : {}),
208
212
  },
@@ -0,0 +1,104 @@
1
+ import { statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import { commonCodeRoots, reposUnder } from "./repo-find.js";
5
+ import { folderFacts, folderRefusal, isTemporaryRefusal } from "./folder-guard.js";
6
+ export function teamLinked(all, spaceId) {
7
+ if (!all || !spaceId)
8
+ return false;
9
+ return Object.values(all.bindings ?? {}).some((b) => b.space === spaceId);
10
+ }
11
+ export function shownPath(p, home = homedir(), pp = path) {
12
+ const rel = pp.relative(home, p);
13
+ if (rel === "")
14
+ return "~";
15
+ if (!rel.startsWith("..") && !pp.isAbsolute(rel))
16
+ return `~${pp.sep}${rel}`;
17
+ return p;
18
+ }
19
+ const repoName = (r) => (r.origin ? r.origin.replace(/\.git$/i, "").split(/[/:]/).filter(Boolean).pop() : null) || path.basename(r.root);
20
+ function lastUsed(root) {
21
+ for (const f of [path.join(root, ".git", "index"), path.join(root, ".git")]) {
22
+ try {
23
+ return statSync(f).mtimeMs;
24
+ }
25
+ catch { }
26
+ }
27
+ return 0;
28
+ }
29
+ export function folderChoices(o) {
30
+ const home = o.home ?? homedir();
31
+ const facts = o.facts ?? folderFacts();
32
+ const budget = { left: o.budget ?? 6000 };
33
+ const roots = [];
34
+ const here = folderRefusal(o.cwd, facts);
35
+ if (!here || here.kind === "catch-all")
36
+ roots.push([o.cwd, 2]);
37
+ for (const r of commonCodeRoots(home))
38
+ roots.push([r, 3]);
39
+ for (const n of ["Desktop", "Documents"]) {
40
+ const d = path.join(home, n);
41
+ try {
42
+ if (statSync(d).isDirectory())
43
+ roots.push([d, 2]);
44
+ }
45
+ catch { }
46
+ }
47
+ const seen = new Set();
48
+ const out = [];
49
+ const unbound = new Set(o.all?.unbound ?? []);
50
+ for (const [root, depth] of roots) {
51
+ for (const r of reposUnder(root, depth, budget)) {
52
+ if (seen.has(r.root))
53
+ continue;
54
+ seen.add(r.root);
55
+ const held = o.all?.bindings?.[r.fingerprint];
56
+ if (held && held.space !== o.spaceId)
57
+ continue;
58
+ if (unbound.has(r.fingerprint))
59
+ continue;
60
+ if (isTemporaryRefusal(folderRefusal(r.root, facts)))
61
+ continue;
62
+ out.push({ path: r.root, name: repoName(r), shown: shownPath(r.root, home), shared: r.shared, at: lastUsed(r.root) });
63
+ }
64
+ }
65
+ return out.sort((a, b) => b.at - a.at).slice(0, o.limit ?? 6).map(({ at: _at, ...c }) => c);
66
+ }
67
+ export function folderArg(p, platform = process.platform) {
68
+ if (platform === "win32")
69
+ return /^[A-Za-z0-9._\\/:@+=,-]+$/.test(p) ? p : `"${p}"`;
70
+ return /^[A-Za-z0-9._/:@+=,-]+$/.test(p) ? p : `'${p.replace(/'/g, `'\\''`)}'`;
71
+ }
72
+ const oneLine = (t) => t.replace(/\s+\(Command Prompt: .*\)$/, "");
73
+ export const NAMED_FOLDER = "<the folder they name>";
74
+ export function notLinkedWhy(refusal) {
75
+ if (!refusal)
76
+ return null;
77
+ const why = refusal.why.replace(/;.*$/, "");
78
+ return why.charAt(0).toUpperCase() + why.slice(1);
79
+ }
80
+ export function folderAsk(o) {
81
+ const line = (dir) => o.command(`use ${o.team} --here --folder ${dir === NAMED_FOLDER ? `'${NAMED_FOLDER}'` : folderArg(dir, o.platform)}`);
82
+ const head = `This computer can't take your teammates' requests yet: no folder on it is linked to "${o.team}".`;
83
+ const message = `${o.why ? `${o.why}, so it was not linked. ` : ""}${head} Ask your person which folder they work in for "${o.team}" — never pick one for them — then run the line for it.`;
84
+ const other = line(NAMED_FOLDER);
85
+ const skip = "None for now: teammates' requests wait until your person opens their agent themselves.";
86
+ const lines = [
87
+ ...(o.why ? [`${o.why}, so it was not linked to "${o.team}".`] : []),
88
+ head,
89
+ `Ask your person which folder they work in for "${o.team}" — never pick one for them — then run the line for it:`,
90
+ ...o.choices.flatMap((c, i) => [` ${i + 1}. ${c.name} ${c.shown}${c.shared ? "" : " (no remote: nothing delivered from it can be fetched by a teammate)"}`, ` ${line(c.path)}`]),
91
+ ` ${o.choices.length ? "Another folder" : "A folder"} they name — a repo, or a folder of documents (the worker answers questions from a copy of it and keeps anything it writes as drafts):`,
92
+ ` ${other}`,
93
+ ` ${skip}`,
94
+ ];
95
+ return {
96
+ lines,
97
+ json: {
98
+ reason: "pick_folder", needs: "folder", team: o.team, message,
99
+ folders: o.choices.map((c) => ({ folder: c.path, name: c.name, shared: c.shared, next: oneLine(line(c.path)) })),
100
+ other_folder: oneLine(other), skip,
101
+ },
102
+ };
103
+ }
104
+ //# sourceMappingURL=folder-ask.js.map
@@ -18,7 +18,17 @@ export function weekIn(starts, now, ts) {
18
18
  export function weekOf(now, ts) {
19
19
  return okTime(now) ? weekIn(weekStarts(now), now, ts) : -1;
20
20
  }
21
- const emptyValue = (partial) => ({ asks: 0, answered: 0, byWorker: 0, byPerson: 0, answerMs: [], decisions: 0, decided: 0, decisionMs: [], delivered: 0, partial });
21
+ const emptyValue = (partial) => ({ asks: 0, answered: 0, byWorker: 0, byPerson: 0, answerMs: [], decisions: 0, decided: 0, decisionMs: [], delivered: 0, quick: 0, unpicked: 0, partial });
22
+ export const PICKUP_MS = 5 * 60_000;
23
+ export const UNPICKED_AFTER_MS = 60 * 60_000;
24
+ export function pickedUpAt(ix, ask, claimAt) {
25
+ let at = claimAt.get(ask.id) ?? null;
26
+ const askedOf = ask.to ?? [];
27
+ for (const k of ix.allKids.get(ask.id) ?? [])
28
+ if (k.from !== ask.from && (askedOf.length === 0 || askedOf.includes(k.from)) && (at === null || k.ts < at))
29
+ at = k.ts;
30
+ return at;
31
+ }
22
32
  function usageSum(book, from, to, f) {
23
33
  if (!book || !okTime(from) || !okTime(to))
24
34
  return 0;
@@ -58,6 +68,13 @@ function* teamWeeksSteps(input, slice = 5_000) {
58
68
  messages[k] = usageSum(input.usage, b.from, Math.min(b.to, now + 1), (d) => d.by_worker + d.by_person);
59
69
  }
60
70
  const value = [emptyValue(partial[0]), emptyValue(partial[1])];
71
+ const claimAt = new Map();
72
+ for (const c of input.claims ?? [])
73
+ if (okTime(c.at)) {
74
+ const was = claimAt.get(c.ref);
75
+ if (was === undefined || c.at < was)
76
+ claimAt.set(c.ref, c.at);
77
+ }
61
78
  let n = 0;
62
79
  for (const r of ix.recs) {
63
80
  if (++n % slice === 0)
@@ -82,6 +99,11 @@ function* teamWeeksSteps(input, slice = 5_000) {
82
99
  else
83
100
  v.byPerson++;
84
101
  }
102
+ const up = pickedUpAt(ix, r, claimAt);
103
+ if (up !== null && up - r.ts <= PICKUP_MS)
104
+ v.quick++;
105
+ if (up === null && now - r.ts > UNPICKED_AFTER_MS)
106
+ v.unpicked++;
85
107
  }
86
108
  else if (r.act === "ESCALATE" || r.act === "HUMAN_REQUIRED") {
87
109
  v.decisions++;
@@ -185,6 +207,7 @@ export function founderView(input) {
185
207
  medianAnswerMs: meds((t, k) => t.value[k].answerMs),
186
208
  decisions: pair((t, k) => t.value[k].decisions), decided: pair((t, k) => t.value[k].decided), medianDecisionMs: meds((t, k) => t.value[k].decisionMs),
187
209
  delivered: pair((t, k) => t.value[k].delivered),
210
+ quick: pair((t, k) => t.value[k].quick ?? 0), unpicked: pair((t, k) => t.value[k].unpicked ?? 0),
188
211
  partial: [teams.some((t) => t.value[0].partial), teams.some((t) => t.value[1].partial)],
189
212
  },
190
213
  growth: {
@@ -486,6 +486,27 @@ export function narrowPolicy(before, now, keepAsks = askedHere) {
486
486
  keys.push(`${f}: ${lost} removed`);
487
487
  }
488
488
  }
489
+ for (const f of ["revoked", "usedOnce"]) {
490
+ const br = obj(b[f]), nr = obj(now[f]);
491
+ const merged = { ...nr };
492
+ let lost = 0;
493
+ for (const [k, v] of Object.entries(br))
494
+ if (!(k in nr) || !same(nr[k], v)) {
495
+ merged[k] = v;
496
+ lost++;
497
+ }
498
+ if (lost) {
499
+ out[f] = merged;
500
+ keys.push(`${f}: ${lost} removed`);
501
+ }
502
+ }
503
+ if (before !== undefined && !same(b.born, now.born)) {
504
+ if (b.born === undefined)
505
+ delete out.born;
506
+ else
507
+ out.born = b.born;
508
+ keys.push(b.born === undefined ? "born added (taken back)" : "born changed");
509
+ }
489
510
  const bt = obj(b.wakeTeamFlag), nt = obj(now.wakeTeamFlag);
490
511
  const flags = {};
491
512
  for (const [k, v] of Object.entries(nt)) {
@@ -40,6 +40,8 @@ export const PANTHEON_HOME_ENTRIES = [
40
40
  { name: /^invites-sent\.json$/, sample: "invites-sent.json", what: "the invites this machine made, hashed (for the joined alert)" },
41
41
  { name: /^known-members\.json$/, sample: "known-members.json", what: "the teammates this machine has already said joined" },
42
42
  { name: "update-check.json", what: "the update check's cache" },
43
+ { name: "relay-version.json", what: "which release your team's relay runs, as this machine last read it, and the update alerts already shown" },
44
+ { name: "service-starts.json", what: "when the worker and alerts last started, to notice one that keeps stopping" },
43
45
  { name: "uri-key", what: "the key pantheon:// links are signed with" },
44
46
  { name: "board.json", what: "the board's state" },
45
47
  { name: "hook-intent.json", what: "the hook intent" },