@join-pantheon/cli 0.38.0 → 0.38.2

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/dist/file-lock.js CHANGED
@@ -182,6 +182,24 @@ export function brokenStateFix(broken) {
182
182
  parts.push(`and the folder${folders.length === 1 ? "" : "s"} ${folders.join(", ")} in the Pantheon folder (on a Mac: chflags nouchg,nouappnd on ${folders.length === 1 ? "it" : "them"})`);
183
183
  return parts.join("; ");
184
184
  }
185
+ export function removeAside(p, o = {}) {
186
+ const rm = o.rm ?? ((x) => rmSync(x, { force: true }));
187
+ const tries = o.tries ?? 5;
188
+ for (let i = 0; i < tries; i++) {
189
+ try {
190
+ rm(p);
191
+ return true;
192
+ }
193
+ catch (e) {
194
+ const code = e.code;
195
+ if (code !== "EBUSY" && code !== "EPERM" && code !== "EACCES")
196
+ return false;
197
+ if (i < tries - 1)
198
+ (o.sleep ?? sleepSync)(5 * (i + 1));
199
+ }
200
+ }
201
+ return false;
202
+ }
185
203
  export function withFileLock(f, fn, waitMs = WAIT_MS) {
186
204
  mkdirSync(dirname(f), { recursive: true, mode: 0o700 });
187
205
  const lock = `${f}.lock`;
@@ -212,10 +230,7 @@ export function withFileLock(f, fn, waitMs = WAIT_MS) {
212
230
  }
213
231
  }
214
232
  finally {
215
- try {
216
- rmSync(made, { force: true });
217
- }
218
- catch { }
233
+ removeAside(made);
219
234
  }
220
235
  try {
221
236
  return fn();
@@ -521,6 +521,7 @@ export const REFUSAL_WORDS = {
521
521
  SPACE_UNREADABLE: "a team whose files could not be read",
522
522
  STALE_VIEW: "a change made from an out-of-date view",
523
523
  STORAGE: "a write the disk refused",
524
+ STORAGE_BUSY: "the disk was behind on this team's writes",
524
525
  SUMMARY_REQUIRED: "a long message with no one-line summary",
525
526
  TO_REQUIRED: "an ask that named nobody",
526
527
  TOO_MANY_GOALS: "too many open goals",
@@ -64,12 +64,17 @@ export const PANTHEON_HOME_ENTRIES = [
64
64
  { name: "data", what: "the relay's ledger", dir: true, kept: "it is your team's history and may be its only copy; delete it yourself once no relay runs from it" },
65
65
  { name: /^(\.DS_Store|Thumbs\.db|desktop\.ini)$/i, sample: ".DS_Store", what: "the file browser's folder cache" },
66
66
  ];
67
+ const LOCK_DEBRIS = /^(.+?)\.lock\.(?:[0-9a-f]+\.new|break(?:\.\d+\.[0-9a-f]+)?|stale\.\d+\.[0-9a-f]+)$/i;
67
68
  const LOCK_OR_TMP = /^(.+?)(\.lock|(\.[0-9a-f]+)*\.tmp)$/i;
68
69
  export function homeEntryFor(name) {
69
70
  const direct = (n) => PANTHEON_HOME_ENTRIES.find((e) => typeof e.name === "string" ? e.name === n : e.name.test(n)) ?? null;
70
71
  const e = direct(name);
71
72
  if (e)
72
73
  return e;
74
+ const d = LOCK_DEBRIS.exec(name);
75
+ const debrisOf = d ? direct(d[1]) : null;
76
+ if (debrisOf && !debrisOf.dir)
77
+ return { name, what: `a lock's leftover file (${debrisOf.what})` };
73
78
  const m = LOCK_OR_TMP.exec(name);
74
79
  const base = m ? direct(m[1]) : null;
75
80
  return base && !base.dir ? base : null;
package/dist/leftovers.js CHANGED
@@ -2,7 +2,7 @@ import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, rea
2
2
  import { join } from "node:path";
3
3
  import { pendingView } from "./disk-writer.js";
4
4
  export const DELETED_NAME_HOLD_MS = 3_600_000;
5
- export const TEAM_FILES = [".members.json", ".jsonl", ".state.json", ".usage.json"];
5
+ export const TEAM_FILES = [".members.json", ".jsonl", ".state.json", ".usage.json", ".closed-goals.json"];
6
6
  const iso = (t) => new Date(t).toISOString().replace(/\.\d+Z$/, "Z");
7
7
  const strs = (x) => (Array.isArray(x) ? x.filter((h) => typeof h === "string") : []);
8
8
  export function tombViewOfText(text) {
package/dist/mcp.js CHANGED
@@ -19,6 +19,7 @@ import { openFailureWhy, openQuestionGoal, questionFailureText, settleFailedQues
19
19
  import { VERSION } from "./version.js";
20
20
  import { installedVersion } from "./mcp-supervisor.js";
21
21
  import { behindStatusLine, localVersion, readVersionHealth, refreshRelayPkg, relayKey, RELAY_PKG_REFRESH_MS } from "./version-health.js";
22
+ import { readRolledBack } from "./upgrade-probation.js";
22
23
  import { loadPolicy } from "./worker-policy.js";
23
24
  import { backendFromLabel } from "./agents.js";
24
25
  import { agentHookStates } from "./notify.js";
@@ -49,6 +50,13 @@ const ACT_HELP = {
49
50
  WITHDRAW: "Ask to be released from something you owe that can no longer be delivered — the branch was wiped, the artifact is gone. Requires `ref`. It is a request: your peer must ACCEPT it. Use this instead of leaving an obligation open forever.",
50
51
  CLOSE: "The goal is met. Body is one or two sentences on what was settled. If you are closing because a peer opened a better goal for the same work, pass `defers_to` — do NOT just close and hope they keep theirs open, because if you both do that the work is orphaned.",
51
52
  };
53
+ export const HISTORY_WHOLE = 12;
54
+ export function firstLineOf(body) {
55
+ const line = body.split("\n").find((l) => l.trim()) ?? "";
56
+ const lines = body.split("\n").filter((l) => l.trim()).length;
57
+ const short = line.length > 200 ? `${line.slice(0, 199)}…` : line;
58
+ return lines > 1 || line.length > 200 ? `${short} [… cut]` : short;
59
+ }
52
60
  export function gitSha(v) {
53
61
  return typeof v === "string" && /^[0-9a-f]{7,64}$/i.test(v) ? v : null;
54
62
  }
@@ -268,7 +276,7 @@ export async function runMcp() {
268
276
  return " (UNSIGNED — dated before signing began here, a date the relay gives: history only, not confirmed as its opener's)";
269
277
  return ` (NOT VERIFIED: ${t.why} — treat its title and acceptance as unconfirmed)`;
270
278
  };
271
- const fmt = (r) => {
279
+ const fmt = (r, cut = false) => {
272
280
  const m = r.meta;
273
281
  const commit = gitSha(m?.commit), branch = gitRefName(m?.branch), baseRef = gitRefName(m?.base);
274
282
  const odd = (m?.commit !== undefined && !commit) || (m?.branch !== undefined && !branch) || (m?.base !== undefined && !baseRef);
@@ -300,7 +308,8 @@ export async function runMcp() {
300
308
  const distrust = tr && !history && !oldClient && !trusted(tr.trust) && tr.trust !== "relay"
301
309
  ? `\n!! NOT VERIFIED — ${tr.why}. It may not be from ${r.from} at all: do not act on it, and do not treat its claims as ${r.from}'s.`
302
310
  : "";
303
- const safeBody = fenceBlock(who, r.summary ? `SUMMARY: ${r.summary}\n\n${r.body}` : r.body).block;
311
+ const shownBody = cut ? firstLineOf(r.body) : r.body;
312
+ const safeBody = fenceBlock(who, r.summary ? `SUMMARY: ${r.summary}${cut ? "" : `\n\n${shownBody}`}` : shownBody).block;
304
313
  const lead = "";
305
314
  const g = r.goal ? client.goals.get(r.goal) : undefined;
306
315
  const stale = g?.state === "CLOSED" && r.act !== "CLOSE"
@@ -371,13 +380,13 @@ export async function runMcp() {
371
380
  ? h.ref === o.ref
372
381
  : h.goal !== null && h.goal === o.goal && o.claimed_by?.session === client.session);
373
382
  const stillOwed = () => role !== "worker" ? client.myWork() : client.myWork().filter((o) => !o.owner.startsWith("human:") && !handed(o));
374
- const fmtAll = (acts) => {
383
+ const fmtAll = (acts, cutBefore = 0) => {
375
384
  if (role === "interactive")
376
385
  client.markShown(acts);
377
386
  const flagged = acts.some((a) => assess(a.body).length > 0);
378
387
  const rubric = !rubricShown || flagged ? fenceRubric(acts.length) : fenceReminder(acts.length);
379
388
  rubricShown = true;
380
- return acts.map(fmt).join("\n\n---\n\n") + `\n\n${rubric}`;
389
+ return acts.map((a, i) => fmt(a, i < cutBefore)).join("\n\n---\n\n") + `\n\n${rubric}`;
381
390
  };
382
391
  let behindSaid = false;
383
392
  let relayLookAt = 0;
@@ -398,7 +407,13 @@ export async function runMcp() {
398
407
  catch {
399
408
  policy = null;
400
409
  }
401
- const line = behindStatusLine({ local: localVersion(), seen, now: Date.now(), policy, state, full: !behindSaid });
410
+ const rolledBack = (() => { try {
411
+ return readRolledBack()?.version ?? null;
412
+ }
413
+ catch {
414
+ return null;
415
+ } })();
416
+ const line = behindStatusLine({ local: localVersion(), seen, now: Date.now(), policy, state, full: !behindSaid, rolledBack });
402
417
  if (line?.startsWith("PANTHEON IS OUT OF DATE"))
403
418
  behindSaid = true;
404
419
  return line;
@@ -885,8 +900,10 @@ A goal for it (${left}) may be open with nothing in it — close it with pantheo
885
900
  }
886
901
  const { acts } = (await res.json());
887
902
  const hits = acts.filter((a) => a.goal === goal).slice(-(limit ?? 60));
903
+ const cutBefore = role === "worker" && limit === undefined ? Math.max(0, hits.length - HISTORY_WHOLE) : 0;
888
904
  return text(`goal ${g.id} "${g.title}"${goalTrustNote(g)} [${g.state}] ${g.acts}/${g.budget} acts${deadlineLabel(g.deadline)}\nacceptance: ${g.acceptance || "(none)"}\n\n` +
889
- (hits.length ? fmtAll(hits) : "(no acts yet)"));
905
+ (cutBefore ? `(the ${cutBefore} older act${cutBefore === 1 ? " is" : "s are"} shown by first line only — pantheon_history with limit ${Math.min(200, hits.length)} shows every act whole)\n\n` : "") +
906
+ (hits.length ? fmtAll(hits, cutBefore) : "(no acts yet)"));
890
907
  });
891
908
  }));
892
909
  const transport = new StdioServerTransport();
package/dist/notice.js CHANGED
@@ -249,7 +249,7 @@ export function composeWaiting(items, team, ctx) {
249
249
  tag: `waiting_${team.replace(/[^A-Za-z0-9_]/g, "_")}`.slice(0, 60),
250
250
  };
251
251
  }
252
- export const DECLINE_CODES = ["wake", "wake_ask", "wake_off", "team_wake", "playbook", "capped", "failed", "commands", "not_here", "no_folder", "unavailable", "signed_out", "unsigned"];
252
+ export const DECLINE_CODES = ["wake", "wake_ask", "wake_off", "team_wake", "playbook", "capped", "failed", "commands", "not_here", "no_folder", "unavailable", "signed_out", "unsigned", "goal_cap"];
253
253
  export function declineCodeOf(r) {
254
254
  const m = r?.meta;
255
255
  if (!r || r.act !== "NOTE" || !m || typeof m.declined !== "string")
@@ -264,6 +264,7 @@ export function declineWords(code, who) {
264
264
  case "team_wake": return `${who}'s computer doesn't start work for you on its own`;
265
265
  case "playbook": return `nothing on ${who}'s computer is set up for this kind of request`;
266
266
  case "capped": return `${who}'s agent has used its runs for now`;
267
+ case "goal_cap": return `${who}'s agent has done its runs on this goal for today`;
267
268
  case "failed": return `${who}'s agent tried and couldn't finish it`;
268
269
  case "commands": return `${who}'s agent needs ${who}'s OK to run commands for it`;
269
270
  case "not_here": return `${who}'s computer doesn't have the repo it's about`;
package/dist/notify.js CHANGED
@@ -428,11 +428,22 @@ export async function decideStop(raw, deps) {
428
428
  const owed = report.obligations ?? [];
429
429
  const closed = new Set(report.closed_goals ?? []);
430
430
  const DEMANDS_RESPONSE = new Set(["ASK", "PROPOSE", "OBJECT", "DELIVERED", "CONTRACT"]);
431
+ const NEWS_WHEN_NAMED = new Set(["HUMAN_REQUIRED", "ESCALATE", "CLOSE", "ACCEPT", "RETRACT", "COMMIT", "JOIN", "LEAVE"]);
432
+ const withHuman = new Set(report.with_human ?? []);
433
+ const worklists = new Set(report.worklist_goals ?? []);
431
434
  const work = acts.filter((a) => {
432
435
  if (a.goal && closed.has(a.goal))
433
436
  return false;
437
+ if (NEWS_WHEN_NAMED.has(a.act))
438
+ return false;
439
+ if (a.id && withHuman.has(a.id))
440
+ return false;
441
+ if (a.goal && worklists.has(a.goal))
442
+ return false;
434
443
  if (a.act === "NOTE" && a.meta && typeof a.meta === "object" && "notice" in a.meta)
435
444
  return false;
445
+ if (a.act === "NOTE" && a.meta && typeof a.meta === "object" && "declined" in a.meta)
446
+ return false;
436
447
  const to = Array.isArray(a.to) ? a.to : [];
437
448
  if (to.length && deps.me && !to.includes(deps.me))
438
449
  return false;
@@ -440,7 +451,8 @@ export async function decideStop(raw, deps) {
440
451
  return true;
441
452
  return DEMANDS_RESPONSE.has(a.act);
442
453
  });
443
- const mustAct = owed.length > 0 || work.length > 0;
454
+ const owedNow = owed.filter((o) => o.kind !== "HUMAN" && o.kind !== "DELIVER");
455
+ const mustAct = owedNow.length > 0 || work.length > 0;
444
456
  if (!mustAct) {
445
457
  clearBlocks(session, deps.home);
446
458
  return acts.length
@@ -463,7 +475,7 @@ export async function decideStop(raw, deps) {
463
475
  }
464
476
  if (acts.length > 6)
465
477
  previews.push(`...and ${acts.length - 6} more`);
466
- for (const o of owed.slice(0, 4))
478
+ for (const o of owedNow.slice(0, 4))
467
479
  previews.push(`you owe: ${o.kind} — ${o.body.slice(0, 120)}`);
468
480
  if (previews.length) {
469
481
  lines.push(fenceBlock("your teammates (first lines only)", previews.join("\n")).block);
package/dist/pending.js CHANGED
@@ -97,9 +97,14 @@ export async function pending(opts) {
97
97
  ]);
98
98
  if (obligationsBody === null && (first || historyBody === null))
99
99
  return null;
100
+ const listOf = (k) => { const v = obligationsBody?.[k]; return Array.isArray(v) ? v.filter((x) => typeof x === "string") : []; };
101
+ const withHuman = new Set(listOf("with_human"));
102
+ const worklists = new Set(listOf("worklist_goals"));
100
103
  const outstanding = (obligationsBody?.obligations ?? [])
101
104
  .filter((o) => !o.claimed)
102
- .filter((o) => o.owner === cfg.member);
105
+ .filter((o) => o.owner === cfg.member)
106
+ .filter((o) => o.kind !== "HUMAN" && o.kind !== "DELIVER" && o.kind !== "CONTINUE")
107
+ .filter((o) => !withHuman.has(o.ref));
103
108
  const workerOnline = !!obligationsBody?.worker_online;
104
109
  const heldNow = Date.now();
105
110
  let autopilot = false;
@@ -276,7 +281,9 @@ export async function pending(opts) {
276
281
  .filter((r) => !r.to || r.to.length === 0 || r.to.includes(cfg.member))
277
282
  .filter((r) => !mine.some((m) => m.seq > r.seq && (m.ref === r.id || (!!r.goal && m.goal === r.goal))))
278
283
  .filter((r) => !checkSigs || verified(r))
279
- .filter((r) => !isRequestFor(r) || !autopilotHolds(r.id));
284
+ .filter((r) => !isRequestFor(r) || !autopilotHolds(r.id))
285
+ .filter((r) => !withHuman.has(r.id))
286
+ .filter((r) => !r.goal || !worklists.has(r.goal) || !!owedRefs?.has(r.id));
280
287
  let copies = new Set();
281
288
  try {
282
289
  copies = copiesAmong(teamPinId(cfg), acts.filter((r) => !!r.sig && trusted(trustIn(r))).map((r) => ({ member: r.from, nonce: r.sig.nonce, id: r.id, sig: r.sig.s })));
@@ -309,7 +316,8 @@ export async function pending(opts) {
309
316
  }
310
317
  const closed_goals = (obligationsBody?.closed_goals ?? []);
311
318
  const report = { seq: seq ?? 0, acts: first ? [] : acts, obligations, closed_goals, left_for_worker,
312
- ...(autopilot ? { autopilot: true, worker_online: workerOnline } : {}) };
319
+ ...(autopilot ? { autopilot: true, worker_online: workerOnline } : {}),
320
+ ...(withHuman.size ? { with_human: [...withHuman] } : {}), ...(worklists.size ? { worklist_goals: [...worklists] } : {}) };
313
321
  return report.acts.length || report.obligations.length || report.left_for_worker ? report : null;
314
322
  }
315
323
  export function render(report) {
package/dist/plain.js CHANGED
@@ -129,6 +129,7 @@ export const STEPS = {
129
129
  RESERVED_NAME: "pick another name",
130
130
  SIGNED_ONLY: "run it as the founder: `pantheon usage`",
131
131
  STORAGE: "wait a moment, then check `pantheon history` before sending it again — it may already be kept",
132
+ STORAGE_BUSY: "wait a few seconds, then send it again",
132
133
  SHUTTING_DOWN: "wait a few seconds, then try again",
133
134
  TOO_MANY_REFUSALS: "fix the request that keeps being refused, then reconnect",
134
135
  ID_TAKEN: "it may already be recorded — check `pantheon history` before sending it again",
package/dist/relay.js CHANGED
@@ -439,6 +439,10 @@ const LOOP_WINDOW_MS = 60_000;
439
439
  function loopMs(ns) {
440
440
  return Math.max(0, Math.round((ns / 1e6 - LOOP_RESOLUTION_MS) * 100) / 100);
441
441
  }
442
+ const CLAIM_RATE = 120;
443
+ const ROSTER_EVERY_MS = 500;
444
+ const CLOSE_COMPACT_EVERY_MS = 60_000;
445
+ const OUTBOX_MAX = 5_000;
442
446
  const LINK_CLOSED = "Different words were typed here, so this link is closed. That's all: the 6-digit code in the same email still works. Give it to your coding agent.";
443
447
  const LINK_GONE = "This link has expired (they last 10 minutes), a newer Pantheon email replaced it, or it was already used. Use the code in the newest Pantheon email, or ask your coding agent to send a new one.";
444
448
  const STORAGE_HELD = "the relay received this but has not saved it yet — its disk is refusing writes. It is kept, and reaches the team when the disk recovers; do not send it again.";
@@ -624,6 +628,14 @@ export class Relay {
624
628
  goalView(sp, g, held) {
625
629
  return g.state === "CLOSED" ? g : withLast(g, this.lastsOf(sp).get(g.id), held?.has(g.id) ?? false);
626
630
  }
631
+ welcomeGoal(sp, g, held, aged) {
632
+ if (g.state === "CLOSED" && aged.has(g.id) && g.closed_summary !== undefined) {
633
+ const slim = { ...g };
634
+ delete slim.closed_summary;
635
+ return slim;
636
+ }
637
+ return this.goalView(sp, g, held);
638
+ }
627
639
  heldIn(sp) {
628
640
  return heldGoals(sp.obligations.values(), (id) => sp.ledger.find(id)?.goal);
629
641
  }
@@ -682,6 +694,7 @@ export class Relay {
682
694
  closing = false;
683
695
  fsyncOff = false;
684
696
  compactedAt = new Map();
697
+ get outboxMax() { return this.opts.outboxMax ?? OUTBOX_MAX; }
685
698
  sessionSeq = 0;
686
699
  spaceCreates = new Map();
687
700
  limits;
@@ -839,6 +852,14 @@ export class Relay {
839
852
  await new Promise((r) => this.wss.close(() => r()));
840
853
  await new Promise((r) => setImmediate(r));
841
854
  for (const sp of this.spaces.values()) {
855
+ if (sp.rosterTimer) {
856
+ clearTimeout(sp.rosterTimer);
857
+ sp.rosterTimer = undefined;
858
+ }
859
+ if (sp.closeCompactTimer) {
860
+ clearTimeout(sp.closeCompactTimer);
861
+ sp.closeCompactTimer = undefined;
862
+ }
842
863
  try {
843
864
  sp.store.close(sp.goals, sp.obligations, sp.profiles);
844
865
  }
@@ -1067,7 +1088,9 @@ export class Relay {
1067
1088
  .filter((g) => isSettled(g, owedIn, now))
1068
1089
  .map((g) => ({ id: g.id, title: g.title, last_at: g.last_at }))
1069
1090
  : [];
1070
- return this.json(res, 200, { obligations: owed, closed_goals: closed, settled_goals, seq: space.ledger.head, worker_online, space_id: space.allow.spaceId(), members: this.members(space),
1091
+ const with_human = member ? [...space.obligations.values()].filter((o) => o.kind === "HUMAN" && o.owner === `human:${member}` && !!o.about).map((o) => o.about) : [];
1092
+ const worklist_goals = [...space.goals.values()].filter((g) => g.kind === "worklist" && g.state !== "CLOSED").map((g) => g.id);
1093
+ return this.json(res, 200, { obligations: owed, closed_goals: closed, settled_goals, with_human, worklist_goals, seq: space.ledger.head, worker_online, space_id: space.allow.spaceId(), members: this.members(space),
1071
1094
  ...(gate.reader ? { roster: this.roster(space), now: Date.now() } : {}) });
1072
1095
  }
1073
1096
  if (url.pathname === "/activity") {
@@ -2970,7 +2993,7 @@ ${body}`;
2970
2993
  }
2971
2994
  quarantining = new Set();
2972
2995
  moveToQuarantine(stem) {
2973
- const sufs = [".members.json", ".members.json.tmp", ".jsonl", ".jsonl.tmp", ".state.json", ".state.json.tmp", ".usage.json", ".usage.json.tmp"];
2996
+ const sufs = [".members.json", ".members.json.tmp", ".jsonl", ".jsonl.tmp", ".state.json", ".state.json.tmp", ".usage.json", ".usage.json.tmp", ".closed-goals.json", ".closed-goals.json.tmp"];
2974
2997
  let files = [];
2975
2998
  try {
2976
2999
  files = readdirSync(this.dataDir);
@@ -2980,7 +3003,7 @@ ${body}`;
2980
3003
  }
2981
3004
  const mine = [
2982
3005
  ...sufs.flatMap((x) => (files.includes(`${stem}${x}`) ? [`${stem}${x}`] : [])),
2983
- ...files.filter((f) => f.startsWith(`${stem}.usage.json.corrupt-`)),
3006
+ ...files.filter((f) => f.startsWith(`${stem}.usage.json.corrupt-`) || f.startsWith(`${stem}.closed-goals.json.corrupt-`)),
2984
3007
  ];
2985
3008
  if (!mine.length)
2986
3009
  return { ok: false, error: `no files of "${stem}" to move`, moved: [], rolledBack: true };
@@ -3020,7 +3043,7 @@ ${body}`;
3020
3043
  }
3021
3044
  verifyRemoved(stem, attempt) {
3022
3045
  void writerFor(this.dataDir, stem).whenWritten().then(() => {
3023
- const left = [".jsonl", ".state.json", ".members.json", ".usage.json"].filter((x) => existsSync(join(this.dataDir, `${stem}${x}`)));
3046
+ const left = [".jsonl", ".state.json", ".members.json", ".usage.json", ".closed-goals.json"].filter((x) => existsSync(join(this.dataDir, `${stem}${x}`)));
3024
3047
  if (!left.length)
3025
3048
  return;
3026
3049
  const m = this.moveToQuarantine(stem);
@@ -3753,7 +3776,7 @@ ${body}`;
3753
3776
  return out;
3754
3777
  }
3755
3778
  async teamFilesSig(safe) {
3756
- const files = [".jsonl", ".state.json", ".members.json", ".usage.json"].map((suf) => join(this.dataDir, `${safe}${suf}`));
3779
+ const files = [".jsonl", ".state.json", ".members.json", ".usage.json", ".closed-goals.json"].map((suf) => join(this.dataDir, `${safe}${suf}`));
3757
3780
  if (files.some((f) => pendingView(this.dataDir, safe, f) !== undefined))
3758
3781
  return `pending:${Date.now()}:${Math.random()}`;
3759
3782
  const st = await Promise.all(files.map((f) => fsp.stat(f).then((x) => `${x.size}:${x.mtimeMs}`, () => "-")));
@@ -5002,7 +5025,7 @@ pantheon start</code></pre>
5002
5025
  }
5003
5026
  this.send(ws, {
5004
5027
  t: "welcome", member: me.id, session: sessionId, space: sp.name, seq: sp.ledger.head,
5005
- roster: this.roster(sp), now: Date.now(), goals: ((held) => [...sp.goals.values()].map((g) => this.goalView(sp, g, held)))(this.heldIn(sp)),
5028
+ roster: this.roster(sp), now: Date.now(), goals: ((held, aged) => [...sp.goals.values()].map((g) => this.welcomeGoal(sp, g, held, aged)))(this.heldIn(sp), sp.store.agedIds(sp.goals)),
5006
5029
  obligations: [...sp.obligations.values()], members: this.members(sp), profiles: [...sp.profiles.values()],
5007
5030
  space_id: sp.allow.spaceId(), repos: sp.allow.repoList(), features: [...this.features],
5008
5031
  ...(acct ? { plan: this.planView(acct, sp) } : {}),
@@ -5038,6 +5061,9 @@ pantheon start</code></pre>
5038
5061
  if (delegated && m.t !== "act" && m.t !== "open_goal" && m.t !== "claim" && m.t !== "worker_state") {
5039
5062
  return fail("NOT_FOR_A_RUN", `an unattended run cannot ${m.t.replace(/_/g, " ")} — its member does that from their own session`, m.cid);
5040
5063
  }
5064
+ if (m.t !== "worker_state" && (space.outbox?.length ?? 0) >= this.outboxMax) {
5065
+ return fail("STORAGE_BUSY", "the relay's disk is behind on this team's writes, so this was not taken. Wait a few seconds, then send it again.", m.cid);
5066
+ }
5041
5067
  if (m.t === "publish_profile") {
5042
5068
  if (m.profile.member !== me.id) {
5043
5069
  return fail("PROFILE_NOT_YOURS", `you may publish only the profile for ${me.id}`, m.cid);
@@ -5154,7 +5180,7 @@ pantheon start</code></pre>
5154
5180
  me.worker = { state: m.state, ...(detail ? { detail } : {}), ...(until ? { until } : {}), ...(m.idle_ms !== undefined ? { idle_ms: m.idle_ms } : {}),
5155
5181
  ...(reason ? { reason } : {}), ...(m.ref ? { ref: m.ref } : {}), ...(m.goal ? { goal: m.goal } : {}),
5156
5182
  ...(m.mode && this.features.includes("autopilot") ? { mode: m.mode } : {}), at: now };
5157
- this.broadcast(space, () => ({ t: "roster", roster: this.roster(space), now: Date.now() }));
5183
+ this.rosterSoon(space);
5158
5184
  return;
5159
5185
  }
5160
5186
  if (m.t === "delete_space") {
@@ -5289,6 +5315,8 @@ pantheon start</code></pre>
5289
5315
  return;
5290
5316
  }
5291
5317
  if (m.t === "claim") {
5318
+ if (!this.claimOk(me))
5319
+ return fail("RATE_LIMIT", "too many claims too fast — wait a few seconds", m.cid);
5292
5320
  if (role === "worker") {
5293
5321
  const plan = this.spacePlan(space.name);
5294
5322
  if (plan && !plan.limits.wake)
@@ -5377,6 +5405,11 @@ pantheon start</code></pre>
5377
5405
  return fail("NOT_ALLOWED_TO_WAKE", `"${origin.from}" is not permitted to wake a worker on this machine`, m.cid);
5378
5406
  }
5379
5407
  }
5408
+ if (o.claimed_by && o.claimed_by.session === sessionId && o.claimed_by.role === role) {
5409
+ o.claimed_by.at = Date.now();
5410
+ this.send(ws, { t: "ack", ...(m.cid ? { cid: m.cid } : {}), id: o.id, seq: space.ledger.head });
5411
+ return;
5412
+ }
5380
5413
  o.claimed_by = { session: sessionId, role, at: Date.now() };
5381
5414
  space.store.noteFirstClaim({ ob: o.id, ref: o.ref, owner: o.owner, at: o.claimed_by.at, by: role === "worker" ? "worker" : "person" });
5382
5415
  this.broadcast(space, { t: "claimed", obligation: o.id, session: sessionId, member: me.id });
@@ -5548,14 +5581,8 @@ pantheon start</code></pre>
5548
5581
  this.countUsage(sp, (b, now) => { countMessage(b, rec.act, role, now); if (closed)
5549
5582
  countGoal(b, "closed", now); });
5550
5583
  }
5551
- if (wasFull && m.act === "CLOSE") {
5552
- try {
5553
- this.compactSpace(space);
5554
- }
5555
- catch (e) {
5556
- this.noteStorageFailure(`[${space.name}] compacting after a close`, e);
5557
- }
5558
- }
5584
+ if (wasFull && m.act === "CLOSE")
5585
+ this.compactAfterClose(space);
5559
5586
  space.recent.set(fp, { id: rec.id, seq: rec.seq, at: Date.now() });
5560
5587
  for (const [k, v] of space.recent)
5561
5588
  if (Date.now() - v.at > LIMITS.dedupeWindowMs)
@@ -6245,6 +6272,7 @@ pantheon start</code></pre>
6245
6272
  if (goal) {
6246
6273
  goal.state = "CLOSED";
6247
6274
  goal.closed_summary = rec.body;
6275
+ goal.closed_at = rec.ts;
6248
6276
  const dt = rec.meta?.defers_to;
6249
6277
  if (dt)
6250
6278
  goal.defers_to = dt;
@@ -6327,6 +6355,31 @@ pantheon start</code></pre>
6327
6355
  me.stamps.push(now);
6328
6356
  return true;
6329
6357
  }
6358
+ claimOk(me) {
6359
+ const now = Date.now();
6360
+ const st = (me.claimStamps ?? []).filter((t) => now - t < LIMITS.rateWindowMs);
6361
+ me.claimStamps = st;
6362
+ if (st.length >= CLAIM_RATE)
6363
+ return false;
6364
+ st.push(now);
6365
+ return true;
6366
+ }
6367
+ rosterSoon(sp) {
6368
+ if (sp.rosterTimer)
6369
+ return;
6370
+ const since = Date.now() - (sp.rosterAt ?? 0);
6371
+ const go = () => {
6372
+ sp.rosterTimer = undefined;
6373
+ if (this.closing || sp.deleted || this.spaces.get(spaceKey(sp.name)) !== sp)
6374
+ return;
6375
+ sp.rosterAt = Date.now();
6376
+ this.broadcast(sp, () => ({ t: "roster", roster: this.roster(sp), now: Date.now() }), "roster");
6377
+ };
6378
+ if (since >= ROSTER_EVERY_MS)
6379
+ return go();
6380
+ sp.rosterTimer = setTimeout(go, ROSTER_EVERY_MS - since);
6381
+ sp.rosterTimer.unref?.();
6382
+ }
6330
6383
  mayCreateSpace(ip) {
6331
6384
  const now = Date.now();
6332
6385
  if (!this.localTrusted(ip)) {
@@ -6423,11 +6476,11 @@ pantheon start</code></pre>
6423
6476
  }
6424
6477
  deleteSpaceFiles(name) {
6425
6478
  const safe = name.replace(/[^a-z0-9._-]/gi, "_");
6426
- for (const suffix of [".jsonl", ".state.json", ".members.json", ".usage.json"])
6479
+ for (const suffix of [".jsonl", ".state.json", ".members.json", ".usage.json", ".closed-goals.json"])
6427
6480
  writerFor(this.dataDir, safe).remove(join(this.dataDir, `${safe}${suffix}`));
6428
6481
  try {
6429
6482
  for (const f of readdirSync(this.dataDir))
6430
- if (f.startsWith(`${safe}.usage.json.corrupt-`))
6483
+ if (f.startsWith(`${safe}.usage.json.corrupt-`) || f.startsWith(`${safe}.closed-goals.json.corrupt-`))
6431
6484
  writerFor(this.dataDir, safe).remove(join(this.dataDir, f));
6432
6485
  }
6433
6486
  catch { }
@@ -6700,6 +6753,9 @@ pantheon start</code></pre>
6700
6753
  }
6701
6754
  for (const o of sp.obligations.values())
6702
6755
  o.created_at = sp.ledger.find(o.ref)?.ts ?? o.created_at;
6756
+ for (const g of sp.store.closedGoals())
6757
+ if (!sp.goals.has(g.id))
6758
+ sp.goals.set(g.id, g);
6703
6759
  let open = 0;
6704
6760
  for (const g of sp.goals.values()) {
6705
6761
  if (g.state === "CLOSED")
@@ -6735,6 +6791,27 @@ pantheon start</code></pre>
6735
6791
  ...(kindFromOpening(meta?.goal_sig, mm[4]) ? { kind: kindFromOpening(meta?.goal_sig, mm[4]) } : {}),
6736
6792
  };
6737
6793
  }
6794
+ compactAfterClose(sp) {
6795
+ if (sp.closeCompactTimer)
6796
+ return;
6797
+ const run = () => {
6798
+ sp.closeCompactTimer = undefined;
6799
+ if (this.closing || sp.deleted || this.spaces.get(spaceKey(sp.name)) !== sp)
6800
+ return;
6801
+ sp.closeCompactAt = Date.now();
6802
+ try {
6803
+ this.compactSpace(sp);
6804
+ }
6805
+ catch (e) {
6806
+ this.noteStorageFailure(`[${sp.name}] compacting after a close`, e);
6807
+ }
6808
+ };
6809
+ const since = Date.now() - (sp.closeCompactAt ?? 0);
6810
+ if (since >= CLOSE_COMPACT_EVERY_MS)
6811
+ return run();
6812
+ sp.closeCompactTimer = setTimeout(run, CLOSE_COMPACT_EVERY_MS - since);
6813
+ sp.closeCompactTimer.unref?.();
6814
+ }
6738
6815
  compactSpace(sp) {
6739
6816
  this.compactedAt.set(sp.name, Date.now());
6740
6817
  if (sp.unclean)
@@ -6878,7 +6955,7 @@ pantheon start</code></pre>
6878
6955
  const sp = this.spaceOf.get(ws);
6879
6956
  const payload = JSON.stringify(msg);
6880
6957
  const run = () => this.write(ws, payload);
6881
- if (!sp) {
6958
+ if (!sp || ((msg.t === "error" || msg.t === "pong") && (sp.outbox?.length ?? 0) >= this.outboxMax)) {
6882
6959
  run();
6883
6960
  return Buffer.byteLength(payload);
6884
6961
  }
@@ -6901,7 +6978,7 @@ pantheon start</code></pre>
6901
6978
  ws.send(payload);
6902
6979
  return true;
6903
6980
  }
6904
- broadcast(sp, msg) {
6981
+ broadcast(sp, msg, key) {
6905
6982
  this.out(sp, () => {
6906
6983
  const m = typeof msg === "function" ? msg() : msg;
6907
6984
  const payload = JSON.stringify(m);
@@ -6917,15 +6994,19 @@ pantheon start</code></pre>
6917
6994
  if (reached && seq !== null && seq > mem.delivered_seq)
6918
6995
  mem.delivered_seq = seq;
6919
6996
  }
6920
- });
6997
+ }, undefined, key);
6921
6998
  }
6922
- out(sp, run, failed) {
6999
+ out(sp, run, failed, key) {
6923
7000
  const w = busyWriter(this.dataDir, safeName(sp.name));
6924
7001
  if (!sp.outbox?.length && !w)
6925
7002
  return run();
6926
7003
  if (failed && w?.failing)
6927
7004
  return this.sendFailed(failed);
6928
- (sp.outbox ??= []).push({ run, w, ticket: w ? w.ticket : 0, ...(failed ? { failed } : {}) });
7005
+ if (key && sp.outbox?.some((h) => h.key === key))
7006
+ return;
7007
+ if (failed?.hangUp && (sp.outbox?.length ?? 0) >= this.outboxMax)
7008
+ return this.sendFailed(failed);
7009
+ (sp.outbox ??= []).push({ run, w, ticket: w ? w.ticket : 0, ...(failed ? { failed } : {}), ...(key ? { key } : {}) });
6929
7010
  if (w)
6930
7011
  void w.whenWritten(w.ticket).then(() => this.release(sp));
6931
7012
  }
@@ -93,6 +93,13 @@ export const CONSEQUENCES = {
93
93
  "run-minutes": (c) => Number(c.to) > Number(c.from)
94
94
  ? `Right now one piece of work may take up to ${c.from} minutes. After this change it may take up to ${c.to} minutes, so bigger requests can finish in one go (a longer run uses more of your agent plan).`
95
95
  : `Right now one piece of work may take up to ${c.from} minutes, so bigger requests can finish in one go. After this change it stops after ${c.to} minutes, and bigger requests may come back to you unfinished.`,
96
+ model: (c) => {
97
+ const said = (m) => (m === "own" ? `your own default model${c.about === "claude-code" || !c.about ? " (for many people, Opus)" : ""}` : m);
98
+ return `Right now ${agentLabel(c.about ?? "claude-code")} runs for teammates use ${said(c.from)}. After this change they use ${said(c.to)}${c.to === "own" || /opus/i.test(c.to) ? ", which uses more of your agent plan for each request" : ""}.`;
99
+ },
100
+ "goal-runs": (c) => Number(c.to) > Number(c.from)
101
+ ? `Right now one goal may start up to ${c.from} runs a day here, so two agents answering each other can't use up your plan. After this change it may start up to ${c.to}.`
102
+ : `Right now one goal may start up to ${c.from} runs a day here. After this change it stops at ${c.to}, and that goal's requests wait for you past it.`,
96
103
  "idle-seconds": (c) => {
97
104
  const quiet = (x) => (Number(x) === 0 ? "as soon as you stop typing" : `after you've been quiet for ${describeIdleSeconds(Number(x))}`);
98
105
  return Number(c.to) < Number(c.from)
@@ -186,6 +193,7 @@ const SETTING_NAMES = {
186
193
  mode: "Mode", persona: "Playbook", decides: "Decided by", wake: "Who may hand you work", waker: "May hand you work", commands: "Commands in runs",
187
194
  unsandboxed: "Codex, Cursor and Copilot runs", "self-upgrade": "Keeping Pantheon up to date", "run-minutes": "Longest run", "idle-seconds": "Wait while you type",
188
195
  alerts: "Alerts", agent: "Agent for requests", hooks: "Agent window hooks", worker: "Worker", folder: "Folder", base: "Base branch",
196
+ model: "Model for requests", "goal-runs": "Runs per goal a day",
189
197
  };
190
198
  export function changeLabel(c) {
191
199
  return `${settingName(c)}: ${valueWords(c, c.from)} → ${valueWords(c, c.to)}`;
package/dist/spend.js CHANGED
@@ -149,6 +149,18 @@ export function allowed(caps, home) {
149
149
  }
150
150
  return { ok: true };
151
151
  }
152
+ export function goalAllowed(goal, cap, home, now = Date.now()) {
153
+ if (!goal)
154
+ return { ok: true };
155
+ const book = read(home);
156
+ if (book.broken)
157
+ return { ok: true };
158
+ const from = now - 86_400_000;
159
+ const ats = book.runs.filter((r) => r.goal === goal && r.at > from).map((r) => r.at).sort((a, b) => a - b);
160
+ if (ats.length < cap)
161
+ return { ok: true };
162
+ return { ok: false, n: ats.length, freeAt: ats[ats.length - cap] + 86_400_000 };
163
+ }
152
164
  export function report(home) {
153
165
  const h = since(3_600_000, home);
154
166
  const d = since(86_400_000, home);