@cruxy/cli 1.9.0 → 1.11.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.
Files changed (51) hide show
  1. package/README.md +2 -2
  2. package/dist/agent/loop.js +16 -1
  3. package/dist/agent/session.js +73 -9
  4. package/dist/approval/classify.js +170 -40
  5. package/dist/approval/prompt.js +52 -6
  6. package/dist/approval/service.js +1 -11
  7. package/dist/budget/session-budget.js +10 -1
  8. package/dist/checkpoint/coverage.js +147 -4
  9. package/dist/cli/command-catalog.js +5 -1
  10. package/dist/cli/commands/config.js +18 -3
  11. package/dist/cli/commands/limits.js +76 -0
  12. package/dist/cli/commands/logs.js +149 -0
  13. package/dist/cli/commands/pr.js +11 -11
  14. package/dist/cli/commands/rollback.js +10 -2
  15. package/dist/cli/commands/run.js +25 -6
  16. package/dist/cli/commands/sessions.js +181 -0
  17. package/dist/cli/onboard.js +0 -9
  18. package/dist/cli/program.js +19 -1
  19. package/dist/cli/repl.js +25 -0
  20. package/dist/cli/session-commands.js +45 -2
  21. package/dist/cli/session-factory.js +31 -10
  22. package/dist/config/manager.js +91 -11
  23. package/dist/config/schema.js +194 -20
  24. package/dist/constants.js +12 -2
  25. package/dist/errors/constructors.js +84 -46
  26. package/dist/errors/types.js +6 -0
  27. package/dist/jobs/index.js +1 -0
  28. package/dist/jobs/log-renderer.js +10 -5
  29. package/dist/jobs/log-store.js +505 -0
  30. package/dist/jobs/manager.js +338 -18
  31. package/dist/mcp/client.js +16 -0
  32. package/dist/render/limits-report.js +213 -0
  33. package/dist/render/limits-view.js +125 -0
  34. package/dist/routing/index.js +1 -1
  35. package/dist/routing/router.js +34 -14
  36. package/dist/routing/types.js +0 -2
  37. package/dist/sandbox/service.js +9 -0
  38. package/dist/sandbox/types.js +15 -0
  39. package/dist/session/index.js +3 -1
  40. package/dist/session/list.js +20 -6
  41. package/dist/session/log.js +120 -21
  42. package/dist/session/prune.js +166 -0
  43. package/dist/session/resume.js +5 -0
  44. package/dist/subagent/orchestrator.js +87 -34
  45. package/dist/subagent/spawn-tool.js +11 -4
  46. package/dist/tools/schema-depth.js +18 -0
  47. package/dist/tui/limits-panel.js +53 -30
  48. package/dist/usage/collect.js +20 -1
  49. package/dist/usage/summary.js +48 -1
  50. package/dist/usage/types.js +52 -0
  51. package/package.json +2 -2
@@ -0,0 +1,213 @@
1
+ import { compactTokens } from "./units.js";
2
+ import { buildLimitsSummary } from "./limits-view.js";
3
+ /**
4
+ * Rendering `cruxy limits` (cli#138) — the session-less half of the P9 reading.
5
+ *
6
+ * WHY A COMMAND AND NOT A COLUMN IN `cruxy usage`. The two answer questions with
7
+ * no common denominator, and joining them produces a number that reads as
8
+ * authoritative while being about two different things: `usage/store.ts` counts
9
+ * this machine's last FIFTY RUNS — a count, not a duration — while the pool is a
10
+ * calendar month and a trailing 12h window, already inclusive of every other
11
+ * surface on the account. The gap is not a rounding error. A credential minted
12
+ * seconds earlier, with zero local runs behind it, reported 63% of its month
13
+ * already drawn from web chat and desktop; any ratio over those two numerators
14
+ * would have been wrong by nearly its whole value on day one.
15
+ *
16
+ * So `cruxy usage` keeps its local-only guarantee and this command makes the
17
+ * call. THE COMMAND SPLIT IS THE BOUNDARY, and it is worth saying plainly that
18
+ * the no-phone-home guard is not: that guard scans a named list of files, this
19
+ * file is deliberately not on it, and a green run of it proves nothing whatever
20
+ * about a file it was never pointed at. What keeps `cruxy usage` local is that
21
+ * the network lives in a different command, not that a test noticed.
22
+ *
23
+ * IT NAMES THE WINDOW RATHER THAN THE ABSTRACTION. The rail picks one window
24
+ * because it has room for one bar, and `session-budget.ts` picks one because
25
+ * admission has to spend against one — both are right, and both are choices a
26
+ * SURFACE has to make. A command has room for neither excuse: it prints
27
+ * `monthly` and `12h burst` by name, in the vocabulary `/budget` already uses,
28
+ * because "the binding window" is a phrase that at Free tier (where
29
+ * `burst.cap === monthly.cap`) resolves to the same window essentially always —
30
+ * an abstraction that never varies, costing the reader the one fact they came
31
+ * for.
32
+ */
33
+ /** Bar width. Wider than the rail's twelve cells; a command has the columns. */
34
+ const BAR_CELLS = 24;
35
+ /** The label each window goes by here — see the module comment on naming. */
36
+ const WINDOW_LABEL = {
37
+ month: "monthly",
38
+ burst: "12h burst",
39
+ };
40
+ /** Widest label, so every row's bar starts in the same column. */
41
+ const LABEL_COLS = Math.max(...Object.values(WINDOW_LABEL).map((l) => l.length));
42
+ function bar(theme, fraction) {
43
+ const filled = Math.round(Math.min(1, Math.max(0, fraction)) * BAR_CELLS);
44
+ return (theme.glyph.barFilled.repeat(filled) +
45
+ theme.glyph.barEmpty.repeat(BAR_CELLS - filled));
46
+ }
47
+ /**
48
+ * A percentage, right-aligned to the width of "100%", so the figures beside it
49
+ * start in the same column on every row. A ragged column reads as two unrelated
50
+ * numbers rather than one comparison, which is the whole point of stacking the
51
+ * windows.
52
+ */
53
+ function pct(fraction) {
54
+ return `${Math.round(fraction * 100)}%`.padStart(4);
55
+ }
56
+ /** 27.77 → "$27.77", 29 → "$29". Same rule the panel uses. */
57
+ function usd(n) {
58
+ return Number.isInteger(n) ? `$${n}` : `$${n.toFixed(2)}`;
59
+ }
60
+ /** "in 18d" / "in 4h", or nothing at all when there is no reset to state. */
61
+ function resetLabel(iso, now) {
62
+ if (!iso)
63
+ return undefined;
64
+ const at = Date.parse(iso);
65
+ if (Number.isNaN(at))
66
+ return undefined;
67
+ const ms = at - now;
68
+ if (ms <= 0)
69
+ return "resets now";
70
+ const minutes = Math.floor(ms / 60_000);
71
+ if (minutes < 60)
72
+ return `resets in ${Math.max(1, minutes)}m`;
73
+ const hours = Math.floor(minutes / 60);
74
+ if (hours < 24)
75
+ return `resets in ${hours}h`;
76
+ return `resets in ${Math.floor(hours / 24)}d`;
77
+ }
78
+ /**
79
+ * How long ago a reading was taken, as a whole sentence.
80
+ *
81
+ * "just now" is a real case here and is not one for the rail: the panel only
82
+ * ever says this past a five-minute staleness threshold, while a command probes
83
+ * and prints in the same breath. Rounding that up to "1m ago" would age a
84
+ * reading by a minute it did not have.
85
+ */
86
+ function readAgeLine(ms) {
87
+ const minutes = Math.floor(ms / 60_000);
88
+ if (minutes < 1)
89
+ return "read just now";
90
+ if (minutes < 60)
91
+ return `read ${minutes}m ago`;
92
+ const hours = Math.floor(minutes / 60);
93
+ return hours < 24
94
+ ? `read ${hours}h ago`
95
+ : `read ${Math.floor(hours / 24)}d ago`;
96
+ }
97
+ /** One window: name, bar, percentage, the figures, and its reset if it has one. */
98
+ function windowLine(theme, w, now) {
99
+ const style = w.tone === "danger"
100
+ ? theme.danger
101
+ : w.tone === "warn"
102
+ ? theme.warning
103
+ : theme.strong;
104
+ const label = WINDOW_LABEL[w.key].padEnd(LABEL_COLS);
105
+ const figures = `${compactTokens(w.window.used)} / ${compactTokens(w.window.cap)}`;
106
+ const reset = resetLabel(w.window.resetsAt, now);
107
+ return (` ${theme.strong(label)} ${style(bar(theme, w.fraction))} ` +
108
+ `${style(pct(w.fraction))} ${theme.muted(figures)}` +
109
+ (reset ? theme.muted(`${theme.sep}${reset}`) : ""));
110
+ }
111
+ function spendCapLine(theme, label, cap) {
112
+ const name = label === "ws" ? "workspace spend cap" : "key spend cap";
113
+ return theme.muted(` ${name} ${usd(cap.remaining)} of ${usd(cap.cap)} left`);
114
+ }
115
+ /**
116
+ * The whole report, or the one honest sentence when there is no reading.
117
+ *
118
+ * The three not-a-reading states are said three ways, on the same discipline the
119
+ * panel keeps: "still asking" must not read as "no limits", and neither may read
120
+ * as "your key is bad". A command exits after saying it, so each one also gets
121
+ * the next step rather than leaving the user to infer it from four words.
122
+ */
123
+ export function limitsReportLines(theme, state, now = Date.now()) {
124
+ if (state.status === "pending") {
125
+ return [theme.muted("the limits reading has not arrived yet")];
126
+ }
127
+ if (state.status === "error") {
128
+ switch (state.reason) {
129
+ case "unauthenticated":
130
+ return [
131
+ theme.warning("not signed in"),
132
+ theme.muted("run `cruxy login` to sign in"),
133
+ ];
134
+ // A different FACT from "not signed in", and the fact is the point: this
135
+ // user's setup was right and simply aged out. Sending them to look for
136
+ // what they configured wrong would be sending them after nothing.
137
+ case "expired":
138
+ return [
139
+ theme.warning("your sign-in has expired"),
140
+ theme.muted("run `cruxy login` to sign in again"),
141
+ ];
142
+ // The gateway ANSWERED — it has no limits to report. Telling this user to
143
+ // check their network would be the wrong errand entirely.
144
+ case "unsupported":
145
+ return [
146
+ theme.muted("this gateway does not report limits"),
147
+ theme.muted("nothing here is wrong with your setup or your network"),
148
+ ];
149
+ case "unreachable":
150
+ return [
151
+ theme.warning("could not reach the gateway"),
152
+ theme.muted("check your connection and try again"),
153
+ ];
154
+ }
155
+ }
156
+ const s = buildLimitsSummary(state.reading, now);
157
+ const lines = [
158
+ `${theme.heading(s.tier)} ${theme.muted(`${theme.glyph.sep} ${s.bucket}`)}`,
159
+ ];
160
+ if (s.windows.length > 0) {
161
+ lines.push("");
162
+ for (const w of s.windows)
163
+ lines.push(windowLine(theme, w, now));
164
+ // The unit, once, under the windows it applies to. Named because a bare
165
+ // "942.8k" invites being read as requests or as raw tokens, and it is
166
+ // neither: it is `(billable_input + output) × tier multiplier`, the unit the
167
+ // meter counts in and the only one anything enforces.
168
+ lines.push(theme.muted(` ${" ".repeat(LABEL_COLS)} weighted tokens`));
169
+ }
170
+ // Why there is nothing to draw, for the shapes that have nothing. Stated, not
171
+ // omitted: an empty section reads as a figure that failed to load.
172
+ if (s.noAllowance) {
173
+ lines.push("");
174
+ lines.push(` ${theme.muted(s.noAllowance)}`);
175
+ }
176
+ // What this credential could have and does not (cli#263). An offer, not a
177
+ // correction — a deliberate `--paste` user is on an apikey on purpose and
178
+ // should be able to read this line and correctly ignore it.
179
+ for (const note of s.notes) {
180
+ lines.push(` ${theme.muted(note)}`);
181
+ }
182
+ const pool = s.budget;
183
+ if (pool.kind === "pool") {
184
+ // Both stated whenever they exist. The rail shows them only when the pool is
185
+ // already low, because it has five lines; this has a terminal, and "what can
186
+ // I still run" is a fair question before the answer becomes urgent.
187
+ if (pool.mira) {
188
+ lines.push(theme.muted(` mira ${compactTokens(pool.mira.remaining)} of ${compactTokens(pool.mira.cap)} requests left${theme.sep}${pool.mira.window}`));
189
+ }
190
+ if (pool.blockedModels.length > 0) {
191
+ lines.push(theme.danger(` refusing: ${pool.blockedModels.join(", ")}`));
192
+ }
193
+ }
194
+ if (pool.kind === "credits") {
195
+ lines.push("");
196
+ lines.push(` ${theme.strong(usd(pool.remaining))} ${theme.muted(`of ${usd(pool.granted)} left`)}`);
197
+ const reset = resetLabel(pool.resetsAt, now);
198
+ if (reset)
199
+ lines.push(theme.muted(` ${reset}`));
200
+ }
201
+ if (s.rpm) {
202
+ lines.push(theme.muted(` rate ${s.rpm.remaining} of ${s.rpm.limit} requests/min`));
203
+ }
204
+ for (const { label, cap } of s.spendCaps) {
205
+ lines.push(spendCapLine(theme, label, cap));
206
+ }
207
+ // Always, not only past a staleness threshold. The rail is repainting and can
208
+ // afford to stay quiet while a figure is fresh; a command prints once and is
209
+ // read later, so the reading's age is part of what it said.
210
+ lines.push("");
211
+ lines.push(theme.muted(readAgeLine(s.ageMs)));
212
+ return lines;
213
+ }
@@ -0,0 +1,125 @@
1
+ import { usedFraction } from "../limits/index.js";
2
+ /**
3
+ * A metered credential's one missing capability, stated as availability
4
+ * (cli#263).
5
+ *
6
+ * KEYED OFF `bucket`, NOT off a missing credential expiry. The two look
7
+ * interchangeable and answer different questions: `bucket === "apikey"` says
8
+ * *this credential type cannot have a pool*, while a missing `keyMeta.expiresAt`
9
+ * says *we do not know this key's lifetime*. Absence is load-bearing for the
10
+ * second — every pre-existing key has no entry, and an admin-minted key
11
+ * genuinely never expires, so `config/credentials.ts` rests on absence meaning
12
+ * "unknown lifetime, never expired". Reusing it here would overload the one
13
+ * invariant the expiry design is built on, to answer a question `bucket` already
14
+ * answers exactly.
15
+ *
16
+ * AND IT IS AN OFFER, NOT A CORRECTION. `--paste` exists for the air-gapped
17
+ * machine and the deliberate long-lived admin key, and those users are on
18
+ * `apikey` on purpose. "Your key is wrong" would be false for them; a line that
19
+ * says what logging in ADDS is true for everyone and safely ignorable by anyone
20
+ * who does not want it. It is also not a start-up nag: `cli/commands/run.ts`
21
+ * owns the pre-session line for the expiry warning, and a second one there would
22
+ * teach people to skip both.
23
+ *
24
+ * Returns `undefined` the moment the bucket is anything else — including an
25
+ * `apikey` whose response this build could not read, where the honest answer is
26
+ * to advise nothing rather than to advise from a shape we did not understand.
27
+ */
28
+ export function poolAvailabilityNote(reading) {
29
+ if (reading.bucket !== "apikey")
30
+ return undefined;
31
+ if (reading.budget.kind !== "metered")
32
+ return undefined;
33
+ return "cruxy login adds a pool";
34
+ }
35
+ /** The tone a window's state maps to. `low` and `blocked` are different acts. */
36
+ function toneFor(state) {
37
+ if (state === "blocked")
38
+ return "danger";
39
+ if (state === "low")
40
+ return "warn";
41
+ return "normal";
42
+ }
43
+ /** A capped window, or nothing — never a fraction over a cap that isn't one. */
44
+ function toMeter(key, window, poolState) {
45
+ if (!window)
46
+ return undefined;
47
+ const fraction = usedFraction(window);
48
+ if (fraction === undefined)
49
+ return undefined;
50
+ return { key, window, fraction, tone: toneFor(window.state ?? poolState) };
51
+ }
52
+ /**
53
+ * Resolve one reading into {@link LimitsSummary}.
54
+ *
55
+ * Pure and synchronous: every value is read off the reading it is handed. The
56
+ * network already happened in `limits/cache.ts`, and the tri-state that wraps
57
+ * this (`pending` / `error` / `ready`) is deliberately NOT reduced here — a
58
+ * summary is what a *reading* means, and a caller with no reading has a
59
+ * different thing to say, in words that differ per surface.
60
+ */
61
+ export function buildLimitsSummary(reading, now) {
62
+ const budget = reading.budget;
63
+ const windows = [];
64
+ let noAllowance;
65
+ switch (budget.kind) {
66
+ case "pool": {
67
+ const month = toMeter("month", budget.monthly, budget.state);
68
+ const burst = toMeter("burst", budget.burst, budget.state);
69
+ if (month)
70
+ windows.push(month);
71
+ if (burst)
72
+ windows.push(burst);
73
+ // Unreachable through `reduceLimits` (an enforced pool with no readable
74
+ // window reduces to `unknown`), but the type permits it and inventing a
75
+ // fraction is the one thing no surface here may do while being defensive.
76
+ if (windows.length === 0)
77
+ noAllowance = "figures not reported";
78
+ break;
79
+ }
80
+ // Enterprise: a POSITIVE statement that there is no ceiling. Distinct from
81
+ // `unknown` below, and the distinction is the one that matters most in this
82
+ // file — "we lost track of your ceiling" rendered as "you have none" tells
83
+ // someone they are safe to spend at the exact moment we cannot say.
84
+ case "unenforced":
85
+ noAllowance = "pool not enforced";
86
+ break;
87
+ case "metered":
88
+ noAllowance = "no pool cap";
89
+ break;
90
+ case "credits":
91
+ // A dollar pool, and the only allowance that is not weighted tokens. It
92
+ // stays off `windows` for that reason: those are token windows, and a
93
+ // renderer that iterated them would print dollars in the tokens' unit.
94
+ break;
95
+ case "unknown":
96
+ noAllowance = "budget not reported";
97
+ break;
98
+ }
99
+ const spendCaps = [];
100
+ if (reading.keySpendCap)
101
+ spendCaps.push({ label: "key", cap: reading.keySpendCap });
102
+ if (reading.workspaceSpendCap)
103
+ spendCaps.push({ label: "ws", cap: reading.workspaceSpendCap });
104
+ const note = poolAvailabilityNote(reading);
105
+ return {
106
+ tier: reading.tier,
107
+ bucket: reading.bucket,
108
+ budget,
109
+ windows,
110
+ ...(noAllowance !== undefined ? { noAllowance } : {}),
111
+ notes: note ? [note] : [],
112
+ spendCaps,
113
+ // Only where it is the whole story. A rate limit beside a real allowance
114
+ // reads as part of it; beside a metered key's absence, it is the ceiling.
115
+ ...(budget.kind === "metered" && reading.chat
116
+ ? {
117
+ rpm: {
118
+ remaining: reading.chat.perKey.remaining,
119
+ limit: reading.chat.perKey.limit,
120
+ },
121
+ }
122
+ : {}),
123
+ ageMs: now - reading.readAt,
124
+ };
125
+ }
@@ -1,5 +1,5 @@
1
1
  export * from "./types.js";
2
- export { ConfigRouter, DEFAULT_TIER, routerForConfig, resolveTaskModel, } from "./router.js";
2
+ export { ConfigRouter, routerForConfig, resolveTaskModel } from "./router.js";
3
3
  export { MODEL_CHOICES, SessionModel, describeModelChoice, parseModelChoice, } from "./session-model.js";
4
4
  // `resolve.ts` (tier → wire model-id) is deliberately NOT re-exported: the
5
5
  // mapping is internal to routing, so it can never be reached from a user-facing
@@ -2,16 +2,11 @@ import { MODEL_TIERS } from "../brand/voice.js";
2
2
  import { routingTierUnavailable } from "../errors/index.js";
3
3
  import { resolveModelId } from "./resolve.js";
4
4
  import { AUTO_MODEL, } from "./types.js";
5
- /**
6
- * The tier a config resolves to when nothing else pins one down — mirrors the
7
- * gateway's `auto` fallback (`AUTO_FALLBACK_TIER` in the SDK), so an unrouted
8
- * cruxy session lands on exactly the tier it does today.
9
- */
10
- export const DEFAULT_TIER = "vaani";
11
5
  /**
12
6
  * The config-driven {@link Router}: maps a declared task class to a tier from
13
7
  * `{ default, map }`, and fails loud when the resolved tier is not offered. It
14
- * NEVER inspects prompt content — selection is purely `map[taskClass] ?? default`.
8
+ * NEVER inspects prompt content — selection is purely
9
+ * `map[taskClass] ?? default ?? null`.
15
10
  */
16
11
  export class ConfigRouter {
17
12
  cfg;
@@ -28,9 +23,17 @@ export class ConfigRouter {
28
23
  this.offered = new Set(offered);
29
24
  }
30
25
  select(taskClass) {
31
- // Explicit override, else the default an unmapped/unknown class is not an
32
- // error, it just takes the default (never a crash, never the cheapest).
33
- const tier = this.cfg.map[taskClass] ?? this.cfg.default;
26
+ // Explicit override, else the table's default, else DECLINE. An unmapped
27
+ // class is not an error and never a crash but with no `default` it is not
28
+ // a tier either. Declining means `auto`: the gateway routes that request
29
+ // (see `Router.select`), which is what a table saying nothing about a class
30
+ // actually asked for. Picking some tier here instead would be the same
31
+ // silent substitution the throw below refuses, just quieter — a user who
32
+ // wrote `map: { summarize: kavi }` and no default said nothing whatsoever
33
+ // about the other four classes, and "nothing" is not a vote for a tier.
34
+ const tier = this.cfg.map[taskClass] ?? this.cfg.default ?? null;
35
+ if (tier === null)
36
+ return null;
34
37
  // Fail loud: a configured tier the gateway does not offer is a usage error
35
38
  // to fix, NOT a silent substitution to some other tier (a user who asked for
36
39
  // mira reasoning must never be quietly handed kavi).
@@ -42,14 +45,16 @@ export class ConfigRouter {
42
45
  }
43
46
  /**
44
47
  * The base tier implied by the session's `model.model`: a real tier passes
45
- * through; `auto` (and any non-tier value) falls back to {@link DEFAULT_TIER}.
46
- * Used so that when a user has pinned a single tier, an opt-in routing table
47
- * that omits `routing.default` still defaults to THEIR tier, not a fixed one.
48
+ * through, and `auto` (or any non-tier value) implies none `undefined`, not a
49
+ * stand-in. Used so that when a user has pinned a single tier, an opt-in routing
50
+ * table that omits `routing.default` still defaults to THEIR tier, not a fixed
51
+ * one; and so that when they pinned nothing, the table does not acquire a
52
+ * default they never wrote.
48
53
  */
49
54
  function baseTierFromModel(model) {
50
55
  return MODEL_TIERS.includes(model)
51
56
  ? model
52
- : DEFAULT_TIER;
57
+ : undefined;
53
58
  }
54
59
  /**
55
60
  * Build a router from resolved config, or `null` when routing should stay
@@ -68,6 +73,21 @@ export function routerForConfig(config) {
68
73
  const configured = def !== undefined || Object.keys(map).length > 0;
69
74
  if (!configured)
70
75
  return null;
76
+ // The fill is deliberate in ONE direction. When `model.model` names a real
77
+ // tier the user declared a session-wide model, so a table without a `default`
78
+ // inherits it — dropping those classes to `auto` would substitute the
79
+ // gateway's judgement for a choice they made, which is the same wrong as
80
+ // substituting vaani for `auto`, from the other side. When it names no tier
81
+ // (`auto`, the schema default) `baseTierFromModel` returns undefined and the
82
+ // table keeps its silence.
83
+ //
84
+ // NOT DEAD CODE, despite looking it from the session path: `session-factory`
85
+ // hands this router to a `SessionModel` that consults it only while the choice
86
+ // is `auto` (session-factory.ts:341), and a `model.model` naming a tier makes
87
+ // the choice that tier — so the tier branch never fires there. `cruxy pr`
88
+ // calls `routerForConfig` directly (cli/commands/pr.ts:69) with no
89
+ // `SessionModel` in front of it, and that is where a pinned `model.model`
90
+ // reaches this line.
71
91
  return new ConfigRouter({
72
92
  default: def ?? baseTierFromModel(config.model.model),
73
93
  map,
@@ -20,8 +20,6 @@ export const TASK_CLASSES = [
20
20
  "plan",
21
21
  /** Commit / pull-request text generation. */
22
22
  "commit-msg",
23
- /** A cheap one-shot classification. */
24
- "classify",
25
23
  /** Context compaction / summarization. */
26
24
  "summarize",
27
25
  ];
@@ -53,6 +53,15 @@ export class SandboxService {
53
53
  * (surfacing the pull via U.4), then delegates to the runtime. A container
54
54
  * that fails to start throws a coded error; an ordinary non-zero command exit
55
55
  * comes back as a normal {@link ExecResult} — exit code is truth.
56
+ *
57
+ * ONE POLICY PER SESSION, not per action. `SandboxRuntime.exec` takes a policy
58
+ * argument and this one does not: {@link create} resolved it once from config
59
+ * + cwd and every call here runs under that same {@link IsolationPolicy}. So a
60
+ * caller cannot tighten the box for a particular command — no argument does
61
+ * it, and reaching around to the runtime would bypass the image memoization.
62
+ * Per-action confinement is a new seam here, not a parameter that already
63
+ * exists; recorded because the shape of `SandboxRuntime.exec` suggests
64
+ * otherwise at a glance.
56
65
  */
57
66
  async exec(command, opts) {
58
67
  await this.ensureImage();
@@ -9,6 +9,21 @@
9
9
  * sandbox contains what an approved command is able to do; it does not replace
10
10
  * the decision to run it.
11
11
  *
12
+ * ── It bounds the EXECUTION surface, and only that ──
13
+ * Worth saying in the words that get misread: this is not "the session runs
14
+ * confined." `ToolContext.sandbox` is consulted at exactly two call sites —
15
+ * `tools/shell/exec.ts` (`execShell`) and `testing/run-tests-tool.ts` — so
16
+ * `run_command` and `run_tests` are the whole of what a container ever bounds.
17
+ * `write_file`, `edit_file`, and `apply_patch` call the filesystem directly and
18
+ * run on the HOST in every mode, sandbox or no sandbox; their bound is the C.26
19
+ * path confinement plus the C.32 checkpoint, not this boundary.
20
+ *
21
+ * That distinction is load-bearing wherever a rule is stated in terms of
22
+ * confinement: a slogan like "an auto-approving mode runs confined" reads as
23
+ * covering file writes and does not. See the cli#194 section in
24
+ * `approval/classify.ts` for what a mode rule keyed on this boundary would and
25
+ * would not have bought.
26
+ *
12
27
  * Execution is abstracted behind {@link SandboxRuntime} (Docker ships; podman /
13
28
  * none slot in without touching call sites), and the neutral {@link ExecResult}
14
29
  * matches what host execution conceptually returns so `run_command`/`run_tests`
@@ -8,6 +8,7 @@
8
8
  * - `log.ts` — the writer: one line per event, `0600`, non-fatal on failure;
9
9
  * - `replay.ts` — the fold back to state, tolerant of torn/unknown lines;
10
10
  * - `list.ts` — what the picker and the TUI sidebar both read;
11
+ * - `prune.ts` — retention: what the tree is allowed to keep (#257);
11
12
  * - `resume.ts` — `--resume <id>` and the bare-`--resume` picker;
12
13
  * - `paths.ts` — the layout, including the subtrees reserved for P3+.
13
14
  */
@@ -16,6 +17,7 @@ export { SessionLog } from "./log.js";
16
17
  export { defaultExportName, exportMarkdown, } from "./export.js";
17
18
  export { foldEvents, readEvents, readMeta, replaySession } from "./replay.js";
18
19
  export { redactMessages } from "./redact.js";
19
- export { findSession, isAmbiguous, listSessionRefs, listSessions, matchSessionRefs, summarizeSession, } from "./list.js";
20
+ export { findSession, isAmbiguous, listSessionRefs, listSessions, matchSessionRefs, sessionFilesByRecency, summarizeSession, } from "./list.js";
21
+ export { pruneSessions, } from "./prune.js";
20
22
  export { cwdMismatchWarning, describeSession, loadResume, priorDirectoriesWarning, relativeAge, resolveSessionId, resumeById, resumePicker, shortId, PICKER_LIMIT, } from "./resume.js";
21
23
  export { KNOWN_EVENT_KINDS, SESSION_FILE_VERSION, ResumedEventSchema, SessionEventSchema, SessionMetaSchema, } from "./types.js";
@@ -31,7 +31,7 @@ function toTitle(text) {
31
31
  * picker asks for ten". It was not. {@link listSessions} summarized EVERY file
32
32
  * and sliced afterwards, so the limit bounded the rows and not the work; a
33
33
  * project of 200 sessions paid 200 full parses to show 10. The limit now bounds
34
- * the work (see {@link sessionRefsByRecency}), which is what finally makes that
34
+ * the work (see {@link sessionFilesByRecency}), which is what finally makes that
35
35
  * sentence true. A sidecar index is still the answer if per-file cost ever
36
36
  * stops being acceptable — but the ordering fix had to come first, because an
37
37
  * index would have made the same mistake faster.
@@ -108,8 +108,19 @@ export function summarizeSession(file) {
108
108
  * Missing directory → empty list (not an error: no sessions yet is normal). A
109
109
  * file that vanishes between the `readdir` and the `stat` is skipped rather
110
110
  * than throwing — listing races an active session by definition.
111
+ *
112
+ * EXPORTED for `prune.ts` (#257), which needs exactly this and nothing more:
113
+ * mtime ordering is what both bounds consume, and a second scan in the pruner
114
+ * would reintroduce the duplication #255 removed. It is the ONLY directory walk
115
+ * over a project's sessions — keep it that way.
116
+ *
117
+ * The `.jsonl` filter and the `isFile` test are load-bearing beyond tidiness.
118
+ * `subagents/` lives in this same directory (reserved by `paths.ts` for #172
119
+ * item 1), `statSync` succeeds on a directory, and everything this returns is
120
+ * something prune will consider deleting. Anything added here is added to that
121
+ * set.
111
122
  */
112
- function sessionRefsByRecency(cwd) {
123
+ export function sessionFilesByRecency(cwd) {
113
124
  const dir = projectDir(cwd);
114
125
  let names;
115
126
  try {
@@ -124,7 +135,10 @@ function sessionRefsByRecency(cwd) {
124
135
  continue;
125
136
  const file = path.join(dir, name);
126
137
  try {
127
- files.push({ file, mtimeMs: statSync(file).mtimeMs });
138
+ const stat = statSync(file);
139
+ if (!stat.isFile())
140
+ continue;
141
+ files.push({ file, mtimeMs: stat.mtimeMs, size: stat.size });
128
142
  }
129
143
  catch {
130
144
  continue; // deleted mid-listing
@@ -140,7 +154,7 @@ function sessionRefsByRecency(cwd) {
140
154
  * capped at `limit`.
141
155
  *
142
156
  * `limit` bounds the WORK, not just the rows. Files are ordered by mtime first
143
- * (cheap — see {@link sessionRefsByRecency}) and summarized one at a time until
157
+ * (cheap — see {@link sessionFilesByRecency}) and summarized one at a time until
144
158
  * `limit` valid summaries exist, so the picker asking for ten reads ten files
145
159
  * and not two hundred.
146
160
  *
@@ -153,7 +167,7 @@ function sessionRefsByRecency(cwd) {
153
167
  */
154
168
  export function listSessions(cwd, limit = Infinity) {
155
169
  const summaries = [];
156
- for (const { file } of sessionRefsByRecency(cwd)) {
170
+ for (const { file } of sessionFilesByRecency(cwd)) {
157
171
  if (summaries.length >= limit)
158
172
  break;
159
173
  const summary = summarizeSession(file);
@@ -178,7 +192,7 @@ export function listSessions(cwd, limit = Infinity) {
178
192
  */
179
193
  export function listSessionRefs(cwd) {
180
194
  const refs = [];
181
- for (const { file, mtimeMs } of sessionRefsByRecency(cwd)) {
195
+ for (const { file, mtimeMs } of sessionFilesByRecency(cwd)) {
182
196
  const meta = readMeta(file);
183
197
  if (meta)
184
198
  refs.push({ sessionId: meta.sessionId, file, mtimeMs });