@jjanczur/tyran 0.1.31 → 0.1.33

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,135 @@
1
+ /**
2
+ * platform-usage — subscription usage read from Claude Code's own config,
3
+ * for the case where the statusline never fires.
4
+ *
5
+ * THE PROBLEM THIS EXISTS FOR, measured rather than supposed. The usage gate
6
+ * reads `.tyran/state/usage.json`; only `statusline.mjs` writes it; the
7
+ * statusline writes only when the platform's payload carries `rate_limits`;
8
+ * and on a real machine that block is ABSENT — it is populated from
9
+ * `anthropic-ratelimit-unified-*` response headers that are not always sent.
10
+ * So no sidecar had ever been written anywhere on that machine, and a config
11
+ * carrying `limits: mode: 'pause'` had never once been able to fire. The gate
12
+ * fails open, so nothing ever said so: overnight mode was silently inert.
13
+ *
14
+ * Meanwhile `~/.claude.json` carries `cachedUsageUtilization` with the same
15
+ * two windows. Reading it removes the statusline from the critical path — and
16
+ * with it the one onboarding step no script can perform, since registering a
17
+ * statusline means writing the operator's own settings file.
18
+ *
19
+ * WHY A STALE READING IS STILL WORTH ACTING ON, which is the whole design.
20
+ * That cache is refreshed by the platform on its own schedule; measured at 83
21
+ * minutes old during heavy continuous use. Under the gate's ten-minute
22
+ * freshness rule it would be discarded every time and this would fix nothing.
23
+ *
24
+ * But usage within a window only ever goes UP. So a reading taken inside the
25
+ * window that is still running is a LOWER BOUND on usage now:
26
+ *
27
+ * - reading says >= threshold -> the true value is also >= threshold,
28
+ * so pausing is correct;
29
+ * - reading says < threshold -> the true value may be higher, so we may
30
+ * fail to pause — which is exactly what
31
+ * happens today, and is the safe direction.
32
+ *
33
+ * Acting on it is therefore never WORSE than ignoring it, and often better.
34
+ * The bound holds only while the window has not rolled: a reading of 95% taken
35
+ * before a reset says nothing about the fresh window after it, and acting on
36
+ * it would pause a session that has its full allowance. So a reading whose
37
+ * own `resets_at` has passed is discarded — that check is what makes the rest
38
+ * of this safe, and it is tested directly.
39
+ *
40
+ * Shape note: this file speaks the SIDECAR's language, not the platform's.
41
+ * `cachedUsageUtilization` reports `utilization` (0-100) and `resets_at` as an
42
+ * ISO string; the sidecar and the gate use `used_percentage` and epoch
43
+ * SECONDS. Converting here means the gate has one shape to reason about.
44
+ */
45
+ import { readFileSync } from 'node:fs';
46
+ import { homedir } from 'node:os';
47
+ import { join } from 'node:path';
48
+
49
+ /**
50
+ * Where the statusline writes and everything else reads.
51
+ *
52
+ * This path had THREE spellings — `statusline.mjs` (the writer),
53
+ * `overnight.mjs` (the scheduler) and `usage-gate.mjs` (the hook) each
54
+ * declared their own — and the freshness window had two. That is ADR-21's
55
+ * named defect in the one place it would be hardest to notice: nothing fails
56
+ * when they agree, and when they stop agreeing the symptom is a pause that
57
+ * silently never fires. Adding a fourth module here without collapsing them
58
+ * would have made it worse, so they collapse to these.
59
+ */
60
+ export const SIDECAR_RELPATH = join('.tyran', 'state', 'usage.json');
61
+
62
+ /** Telemetry older than this is unknown, and unknown fails open. */
63
+ export const SIDECAR_FRESH_MS = 10 * 60 * 1000;
64
+
65
+ /** Where Claude Code keeps the config this reads. */
66
+ export const CLAUDE_CONFIG_RELPATH = '.claude.json';
67
+
68
+ /** Refuse to parse anything larger; measured at 65 KB on a real machine. */
69
+ const MAX_BYTES = 4 * 1024 * 1024;
70
+
71
+ /** The two windows the gate knows about, in the platform's spelling. */
72
+ const WINDOW_KEYS = Object.freeze(['five_hour', 'seven_day']);
73
+
74
+ function ownField(obj, name) {
75
+ return obj !== null && typeof obj === 'object' && Object.prototype.hasOwnProperty.call(obj, name)
76
+ ? obj[name]
77
+ : undefined;
78
+ }
79
+
80
+ /**
81
+ * One window, converted to the sidecar's shape, or null.
82
+ *
83
+ * `nowMs` decides whether the reading still describes a running window. A
84
+ * window whose reset has passed is not stale data, it is data about a
85
+ * DIFFERENT window, and no amount of freshness reasoning rescues it.
86
+ */
87
+ export function windowFrom(node, nowMs) {
88
+ const used = ownField(node, 'utilization');
89
+ const resetsRaw = ownField(node, 'resets_at');
90
+ if (typeof used !== 'number' || !Number.isFinite(used) || used < 0) return null;
91
+ if (typeof resetsRaw !== 'string') return null;
92
+ const resetsMs = Date.parse(resetsRaw);
93
+ if (!Number.isFinite(resetsMs)) return null;
94
+ // The bound only holds inside the window the reading was taken in.
95
+ if (resetsMs <= nowMs) return null;
96
+ return { used_percentage: used, resets_at: Math.floor(resetsMs / 1000) };
97
+ }
98
+
99
+ /**
100
+ * The platform's own usage cache, in sidecar shape, or null when it cannot be
101
+ * used. Never throws: this is read from inside a PreToolUse hook, and a hook
102
+ * that throws on a malformed config file stops the repository's work over
103
+ * telemetry it was only consulting.
104
+ *
105
+ * Measured cost: 0.29 ms to read and parse 65 KB, against the gate's 4-second
106
+ * budget and a hook process spawn that costs an order of magnitude more. No
107
+ * caching layer is warranted and none is here.
108
+ */
109
+ export function readPlatformUsage({ home = homedir(), readFile = readFileSync, nowMs = Date.now() } = {}) {
110
+ let doc;
111
+ try {
112
+ const raw = readFile(join(home, CLAUDE_CONFIG_RELPATH), 'utf8');
113
+ if (typeof raw !== 'string' || raw.length > MAX_BYTES) return null;
114
+ doc = JSON.parse(raw);
115
+ } catch {
116
+ // Absent, unreadable, not JSON, not signed in. One answer for all of them.
117
+ return null;
118
+ }
119
+ const utilization = ownField(ownField(doc, 'cachedUsageUtilization'), 'utilization');
120
+ if (utilization === null || typeof utilization !== 'object') return null;
121
+
122
+ const out = {};
123
+ for (const key of WINDOW_KEYS) {
124
+ const window = windowFrom(ownField(utilization, key), nowMs);
125
+ if (window !== null) out[key] = window;
126
+ }
127
+ if (Object.keys(out).length === 0) return null;
128
+
129
+ // `written_at` is the moment the reading is TRUE OF, which is now: the
130
+ // bound above is a statement about the present, derived from a past
131
+ // measurement. Stamping the platform's own fetch time here would hand the
132
+ // gate a document its freshness rule discards, reintroducing the bug.
133
+ // What the reading cannot support is a RESUME, and the gate is told so.
134
+ return { written_at: new Date(nowMs).toISOString(), lower_bound: true, source: 'claude.json', ...out };
135
+ }
@@ -5,7 +5,7 @@ description: The depth half of a review - the dimensions a diff is read against
5
5
  # Code review — reading depth
6
6
 
7
7
  > This is HOW a diff is read. WHAT the verdict looks like belongs to
8
- > `tyran:reviewer` — binary APPROVE or CHANGES-REQUESTED, numbered executable
8
+ > `tyran:reviewer` — APPROVE, REVISED or CHANGES-REQUESTED, numbered executable
9
9
  > counterexamples, a re-review that first checks the previous round's findings
10
10
  > are pinned as tests, and a section naming what was not checked. Do not
11
11
  > restate any of that here; two definitions of "reviewed" drift apart, and the
@@ -452,6 +452,32 @@ open one.
452
452
  a lease still held by an agent that has already reported. An orphaned lease
453
453
  blocks the next initiative from a resource nobody is using, and the person
454
454
  who hits it has no way to know it is stale.
455
+ - **Close the initiative when it is closed**, with the retrospective recorded
456
+ and the leases released:
457
+
458
+ ```bash
459
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/journal.mjs" append <abs-journal> checkpoint <init> \
460
+ --actor conductor --data '{"phase":"closed","next_steps":[]}'
461
+ ```
462
+
463
+ `append ... checkpoint`, not a `checkpoint` subcommand — there is no such
464
+ subcommand, and the first draft of this line invented one. It would have
465
+ printed a usage block and closed nothing.
466
+
467
+ This is one line and it is load-bearing. The projection closes every still-
468
+ open spawn on a closing checkpoint, which is what stops an agent that
469
+ finished weeks ago from reading as live work, and it is the only signal any
470
+ reader has that an initiative is DONE rather than abandoned mid-flight.
471
+
472
+ Measured across 63 real journals: **9 ever received one**, while 43 sat
473
+ waiting on a question nobody answered. Nothing had ever told you to write
474
+ it — the fold that consumes it shipped, and the event that triggers it was
475
+ never emitted by anything, so the feature has been inert since it landed.
476
+
477
+ A closing checkpoint is not the same as "every ticket merged". Say it when
478
+ the work is over, including when it is over because it was abandoned — an
479
+ initiative someone walked away from is finished too, and saying so is what
480
+ keeps the board honest about which of them are still waiting on you.
455
481
  - **A usage-gate refusal is a wind-down order, not an obstacle.** Near the
456
482
  subscription window the gate refuses everything except checkpointing;
457
483
  its refusal text IS the checklist — follow it verbatim, in order, then
@@ -77,6 +77,31 @@ is a `staging` branch with CI. That looks like P2 — I release to staging on
77
77
  my own, production stays yours. Confirm, or say P1 and I only ever touch
78
78
  branches."
79
79
 
80
+ ### If they are not an engineer, ask the ONE question instead
81
+
82
+ Sales and marketing people run this now. `questions` is written for someone
83
+ who knows what an autonomy class is, and four entries shaped `field: source`
84
+ is where a non-expert stops. The same scan carries a `plain` object built for
85
+ them — **one** question, its evidence in ordinary words, two options at most,
86
+ and a `derived` list of what Tyran settled for itself.
87
+
88
+ Use it whenever the operator has given you any sign they are not an engineer,
89
+ and when you are unsure. It costs a fluent reader nothing: everything in
90
+ `questions` is still in the config with its provenance, and `plain.evidence`
91
+ keeps the raw git sentence for anyone who wants the numbers.
92
+
93
+ Read `plain.question`, `plain.because`, then the options with
94
+ `plain.recommended` marked. Then read the `derived` lines out as decisions,
95
+ not as questions — those are the things the repository already answered, and
96
+ re-asking them is what makes setup feel like an interrogation. Close with
97
+ `plain.note`, which says how the one class Tyran will never infer is actually
98
+ reached, and that the dashboard can change all of it later.
99
+
100
+ The three questions you are NOT asking them are deliberate: the package
101
+ manager is a fact, the validation commands are a fact or an honest gap, and
102
+ the `CLAUDE.md` line is a paste they can see. A question someone cannot
103
+ answer is not a safeguard; it is a place to give up.
104
+
80
105
  One flagged question is the `CLAUDE.md` pointer, and it is a question rather
81
106
  than an edit on purpose. Tyran writes `CLAUDE.md` only inside its own
82
107
  `tyran:rules` fence, and only through `mistakes.mjs promote --law`, which
@@ -106,6 +131,56 @@ still lives in the plugin and updates keep reaching it. Mention that it lands
106
131
  in their repo and will show up in their next commit — a file appearing in
107
132
  someone's working tree unannounced is a bad way to meet a tool.
108
133
 
134
+ ## 4b. Make the secrets gate satisfiable, and say what it found
135
+
136
+ The gate refuses every commit and push until `gitleaks` exists. Install it
137
+ before anything needs it, rather than letting the first commit fail with a
138
+ prerequisite the operator may not be able to meet:
139
+
140
+ ```bash
141
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/ensure-gitleaks.mjs"
142
+ ```
143
+
144
+ Pinned and checksummed, into `~/.tyran/bin/`; it is a no-op when the machine
145
+ already has one, and PATH still wins.
146
+
147
+ **Then look, before they hit it.** A repository whose history already contains
148
+ a secret is common and the gate handles it badly by surprise: nothing is
149
+ scanned until someone EDITS the file that holds it, and then every commit
150
+ touching that file is refused, permanently, with no hint that the cause is
151
+ years old. Run a scan and say plainly what is there.
152
+
153
+ If there are pre-existing findings, explain the choice in the operator's
154
+ words, and do not make it for them:
155
+
156
+ - a tracked `.gitleaks-baseline.json` tells the gate "these exact findings are
157
+ known" — new secrets are still caught, and because it is tracked the
158
+ suppression appears in a diff instead of being an invisible local file;
159
+ - **but a baseline makes the tool quiet, it does not make the key safe.** If
160
+ the repository is public, that key is already burned and the real fix is
161
+ rotating it. Say this once, here, rather than letting them discover it after
162
+ they have relied on the baseline.
163
+
164
+ ## 4c. Turn the dashboard on
165
+
166
+ Setup is not finished until they have SEEN something. Everything above is
167
+ files on disk; the board is where any of it becomes legible, and it was the
168
+ one thing installation never actually reached.
169
+
170
+ ```bash
171
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/board.mjs" --dir .tyran --serve --write --open
172
+ ```
173
+
174
+ `--open` launches their browser; `--write` is what makes the **Settings** tab
175
+ able to edit `config.yaml` and the autonomy policy from the page. Tell them
176
+ that tab exists and what it covers — profile, autonomy class, tiers,
177
+ validation commands, shared zones, overnight limits — because for someone who
178
+ would rather not hand-edit YAML in their own repository, that tab is the
179
+ entire configuration story and they will not guess it is there.
180
+
181
+ It holds the terminal while it serves. Say so, and say that Ctrl-C stops it
182
+ and the board is still there next time.
183
+
109
184
  ## 5. Validate and report
110
185
 
111
186
  ```bash
@@ -166,18 +241,29 @@ copies of the config. Stage explicit paths until this commit exists.
166
241
 
167
242
  Overnight mode (https://jjanczur.github.io/tyran/overnight/) pauses autonomous work near the
168
243
  subscription usage limit and resumes after the window resets. It is OFF by
169
- default because its telemetry is a statusline the plugin cannot install:
170
- `.claude/settings.json` in user scope is the operator's file, and the policy
171
- gate refuses agents writing the in-repo one — so print the snippet with the
172
- plugin path RESOLVED and let the human paste it:
244
+ default, and turning it on is now **one edit to `.tyran/config.yaml`** — the
245
+ Settings tab will do it — because the gate reads the platform's own usage
246
+ cache in `~/.claude.json` when no statusline is installed.
247
+
248
+ That fallback is why this step is short. Until it existed, the telemetry came
249
+ only from a statusline the plugin cannot install (`.claude/settings.json` in
250
+ user scope is the operator's file, and the gate refuses agents writing the
251
+ in-repo one), so overnight mode's real prerequisite was a paste — and on an
252
+ install that skipped it the pause failed open and said nothing.
253
+
254
+ Show the `limits:` block to enable (`mode: 'pause'` — quoted, since bare
255
+ `off`/`on` are YAML booleans), and say that `doctor --state` reports
256
+ `limit-telemetry-missing` only when NO telemetry is reachable at all, which
257
+ usually means signed out rather than misconfigured.
258
+
259
+ A statusline is still worth offering to anyone who wants the sharpest
260
+ possible pause: it is session-scoped and refreshed every few seconds, where
261
+ the platform's cache is refreshed on its own schedule and has been measured
262
+ over an hour old. Print the snippet with the plugin path RESOLVED and let the
263
+ human paste it — never attempt the settings write yourself, the refusal is the
264
+ boundary working:
173
265
 
174
266
  ```json
175
267
  { "statusLine": { "type": "command",
176
268
  "command": "node <resolved-plugin-root>/scripts/statusline.mjs" } }
177
269
  ```
178
-
179
- Then show the `limits:` block to enable (`mode: 'pause'` — quoted, bare
180
- `off`/`on` are YAML booleans) and note that `doctor --state` reports
181
- `limit-telemetry-missing` if the pause is configured while the statusline is
182
- not installed. Do not attempt the settings write yourself; the refusal is
183
- the boundary working.