@jjanczur/tyran 0.1.30 → 0.1.32

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,191 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * migrate — the repairs doctor can only ever REPORT.
4
+ *
5
+ * Every other finding doctor raises comes with a remedy the operator can run.
6
+ * `state-legacy-initiatives-dir` came with a sentence instead: "relocate the
7
+ * contents by hand, one initiative directory at a time". That is not a remedy,
8
+ * it is an instruction to do a careful thing carefully, and the installs that
9
+ * carry the finding are by definition the ones nobody has touched since 0.1.8.
10
+ *
11
+ * ## Why this is a separate script and not part of setup
12
+ *
13
+ * Moving an initiative's authored history is not a step that may happen as a
14
+ * side effect of something else. `scan-repo.mjs` seeds files that do not exist
15
+ * yet; this MOVES files that do, and the difference is the whole of the
16
+ * argument. So it is explicit, never automatic, never invoked by a hook, and
17
+ * it does nothing at all until asked twice — once by running it, once with
18
+ * `--apply`.
19
+ *
20
+ * ## The three rules it does not break
21
+ *
22
+ * 1. **Nothing is ever overwritten.** A destination that already exists is a
23
+ * CONFLICT: reported, skipped, and left exactly as it was, on both sides.
24
+ * Merging two directories that share a name is a decision only the
25
+ * operator can make, and making it silently would destroy the evidence
26
+ * needed to make it correctly.
27
+ * 2. **Nothing is ever deleted.** The legacy directory is removed only when
28
+ * it is empty, and only because it then holds nothing to lose. Anything
29
+ * skipped keeps its home.
30
+ * 3. **Everything is counted and named** (ADR-19 correction 1), including on
31
+ * a clean run. "Moved 4, skipped 0" and silence are different reports, and
32
+ * only one of them is evidence.
33
+ *
34
+ * Usage:
35
+ * node scripts/migrate.mjs [--dir <.tyran>] # say what WOULD move
36
+ * node scripts/migrate.mjs [--dir <.tyran>] --apply # move it
37
+ *
38
+ * Exit: 0 nothing to do or done · 1 conflicts were skipped · 2 usage or I/O.
39
+ */
40
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmdirSync, statSync } from 'node:fs';
41
+ import { join, resolve } from 'node:path';
42
+
43
+ import { escapeInvisible } from './invisible.mjs';
44
+
45
+ /** The pre-0.1.9 home of the initiative directories. */
46
+ export const LEGACY_DIR = 'initiatives';
47
+ /** Where they live now. */
48
+ export const STATE_DIR = 'state';
49
+
50
+ const show = (value) => escapeInvisible(String(value));
51
+
52
+ function isDirectory(path) {
53
+ try {
54
+ return statSync(path).isDirectory();
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * What moving this `.tyran` would do, without doing any of it.
62
+ *
63
+ * Pure apart from reading the directory listing, so the dry run and the real
64
+ * run are the SAME computation — a preview produced by different code from the
65
+ * thing it previews is a preview of nothing.
66
+ *
67
+ * Returns `{ moves, conflicts, legacy, present }`, where a move is
68
+ * `{ name, from, to }` and a conflict additionally carries `why`.
69
+ */
70
+ export function planMigration(dir) {
71
+ const root = resolve(dir);
72
+ const legacy = join(root, LEGACY_DIR);
73
+ const state = join(root, STATE_DIR);
74
+ if (!isDirectory(legacy)) return { moves: [], conflicts: [], legacy, state, present: false };
75
+
76
+ const moves = [];
77
+ const conflicts = [];
78
+ // Sorted, so two runs on one tree report in the same order and a diff of two
79
+ // reports is about the tree rather than about readdir's mood.
80
+ for (const name of readdirSync(legacy).sort()) {
81
+ const from = join(legacy, name);
82
+ const to = join(state, name);
83
+ if (existsSync(to)) {
84
+ conflicts.push({
85
+ name,
86
+ from,
87
+ to,
88
+ why: isDirectory(to)
89
+ ? 'an initiative of this name already lives under state/ — merging them is a decision only you can make'
90
+ : 'a FILE of this name already exists under state/',
91
+ });
92
+ continue;
93
+ }
94
+ moves.push({ name, from, to });
95
+ }
96
+ return { moves, conflicts, legacy, state, present: true };
97
+ }
98
+
99
+ /**
100
+ * Carry out a plan. Idempotent: a second run finds nothing left to move and
101
+ * reports exactly that, which is what makes it safe to re-run after fixing a
102
+ * conflict by hand.
103
+ */
104
+ export function applyMigration(plan) {
105
+ const done = [];
106
+ for (const move of plan.moves) {
107
+ mkdirSync(plan.state, { recursive: true });
108
+ // `renameSync` and not a copy: a copy leaves two copies of an append-only
109
+ // journal on disk, and the next writer picks whichever path it was given.
110
+ // Same filesystem is the normal case; EXDEV is reported, not worked around
111
+ // silently, because a cross-device move here means `.tyran/` is stitched
112
+ // together from two mounts and the operator needs to know that.
113
+ renameSync(move.from, move.to);
114
+ done.push(move);
115
+ }
116
+ // Only when empty, and only after the moves: this removes a directory that
117
+ // by construction now holds nothing.
118
+ let removed = false;
119
+ if (plan.present && readdirSync(plan.legacy).length === 0) {
120
+ rmdirSync(plan.legacy);
121
+ removed = true;
122
+ }
123
+ return { done, removed };
124
+ }
125
+
126
+ export function renderPlan(plan, { applied = false, removed = false } = {}) {
127
+ const lines = [];
128
+ if (!plan.present) {
129
+ lines.push(`migrate: no ${LEGACY_DIR}/ under ${show(plan.legacy.replace(/\/[^/]+$/, ''))} — nothing to migrate`);
130
+ return lines.join('\n');
131
+ }
132
+ const verb = applied ? 'moved' : 'would move';
133
+ for (const m of plan.moves) lines.push(` ${verb} ${show(m.name)} ${show(m.from)} -> ${show(m.to)}`);
134
+ for (const c of plan.conflicts) lines.push(` SKIP ${show(c.name)} ${show(c.why)}`);
135
+ lines.push(
136
+ `migrate: ${plan.moves.length} ${applied ? 'moved' : 'to move'}, ${plan.conflicts.length} skipped` +
137
+ (removed ? `, ${LEGACY_DIR}/ removed (it was empty)` : ''),
138
+ );
139
+ if (!applied && plan.moves.length > 0) lines.push('migrate: re-run with --apply to move them');
140
+ if (plan.conflicts.length > 0) {
141
+ lines.push(
142
+ 'migrate: a skipped initiative is left untouched on BOTH sides. Merge it by hand, then re-run — ' +
143
+ 'this script never overwrites and never deletes.',
144
+ );
145
+ }
146
+ return lines.join('\n');
147
+ }
148
+
149
+ function usage(message) {
150
+ if (message) console.error(`migrate: ${message}`);
151
+ console.error('usage: node scripts/migrate.mjs [--dir <.tyran>] [--apply]');
152
+ process.exit(2);
153
+ }
154
+
155
+ function main(argv) {
156
+ const args = argv.slice(2);
157
+ for (const arg of args) {
158
+ if (!['--dir', '--apply'].includes(arg) && arg.startsWith('--')) usage(`unknown flag ${arg}`);
159
+ }
160
+ const i = args.indexOf('--dir');
161
+ if (i !== -1 && args[i + 1] === undefined) usage('--dir needs a path');
162
+ const dir = i === -1 ? '.tyran' : args[i + 1];
163
+ const apply = args.includes('--apply');
164
+
165
+ let plan;
166
+ try {
167
+ plan = planMigration(dir);
168
+ } catch (error) {
169
+ console.error(`migrate: could not read ${show(dir)}: ${error.message}`);
170
+ process.exit(2);
171
+ }
172
+ if (!apply) {
173
+ console.log(renderPlan(plan));
174
+ process.exit(0);
175
+ }
176
+ let result;
177
+ try {
178
+ result = applyMigration(plan);
179
+ } catch (error) {
180
+ console.error(`migrate: ${error.message}`);
181
+ console.error('migrate: nothing after the failure was attempted; re-running is safe.');
182
+ process.exit(2);
183
+ }
184
+ console.log(renderPlan(plan, { applied: true, removed: result.removed }));
185
+ // A conflict is the one outcome that still needs a human, so it is the one
186
+ // that must not exit 0 — an automated caller has to be able to tell "done"
187
+ // from "done except for the part that mattered".
188
+ process.exit(plan.conflicts.length > 0 ? 1 : 0);
189
+ }
190
+
191
+ if (import.meta.url === `file://${process.argv[1]}`) main(process.argv);
@@ -60,6 +60,7 @@ import { checkStop } from './stop-check.mjs';
60
60
  import { readJournal } from './journal.mjs';
61
61
  import { GATE_PASS } from './project.mjs';
62
62
  import { withKeepAwake } from './keepawake.mjs';
63
+ import { SIDECAR_RELPATH, SIDECAR_FRESH_MS } from './usage-source.mjs';
63
64
  import { limitsOf } from './schema.mjs';
64
65
  import { parse } from './yaml-lite.mjs';
65
66
  import { escapeInvisible } from './invisible.mjs';
@@ -67,13 +68,12 @@ import { escapeInvisible } from './invisible.mjs';
67
68
  export const MARKER_RELPATH = join('.tyran', 'state', 'paused-until.json');
68
69
  export const RESUME_STATE_RELPATH = join('.tyran', 'state', 'resume.json');
69
70
  export const RESUME_LOG_RELPATH = join('.tyran', 'state', 'resume.log');
70
- export const SIDECAR_RELPATH = join('.tyran', 'state', 'usage.json');
71
+ export { SIDECAR_RELPATH, SIDECAR_FRESH_MS } from './usage-source.mjs';
71
72
 
72
73
  export const SESSION_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
73
74
  /** Short enough that an overslept machine fires soon after waking. */
74
75
  export const MAX_SLEEP_CHUNK_MS = 15 * 60 * 1000;
75
76
  /** Telemetry older than this is unknown; unknown means proceed. */
76
- export const SIDECAR_FRESH_MS = 10 * 60 * 1000;
77
77
  /** Babysitting ladder after a resume that visibly did not take. */
78
78
  export const RESUME_BACKOFFS_MS = Object.freeze([5 * 60 * 1000, 30 * 60 * 1000, 60 * 60 * 1000]);
79
79
  /** Hard ceiling on a single `claude -p` attempt before the babysitter reclaims it. */
@@ -0,0 +1,255 @@
1
+ /**
2
+ * pricing — the shipped list-price rate card, and what the subscription costs.
3
+ *
4
+ * Before this file, `pricing:` was hand-authored or absent, and absent was the
5
+ * normal case: a fresh install reported every figure as an em dash, and the
6
+ * whole Spend tab answered "how many tokens" but never "how much". Asking a
7
+ * non-engineer to transcribe fourteen models × four rates into YAML was never
8
+ * going to happen, so the numbers ship.
9
+ *
10
+ * TWO PROPERTIES MAKE THIS SMALL ENOUGH TO KEEP HONEST:
11
+ *
12
+ * 1. **Cache rates are fixed multiples of base input**, published as such:
13
+ * a 5-minute write is 1.25x, a 1-hour write is 2x, a read is 0.1x. Every
14
+ * row of the published table satisfies this exactly — checked in the tests,
15
+ * not assumed — so only `input` and `output` are written down here. Four
16
+ * numbers per model would be four chances to mistype one.
17
+ * 2. **The 1M context window is standard-priced.** "Claude 4.6 and later
18
+ * models include the full 1M token context window at standard pricing",
19
+ * so `claude-opus-5[1m]` is the same rate as `claude-opus-5` and the
20
+ * context variant can be normalised away rather than modelled.
21
+ *
22
+ * WHAT THIS DELIBERATELY DOES NOT MODEL, because guessing would be worse than
23
+ * an honest gap, and each of these makes the real bill HIGHER than reported:
24
+ *
25
+ * - **Fast mode** (Opus 5 / 4.8) is $10 in / $50 out, double standard. It is
26
+ * not visible in a transcript, so a fast-mode session is under-reported.
27
+ * - **US-pinned inference** (`inference_geo: "us"`) is a 1.1x multiplier on
28
+ * every category, also not in a transcript.
29
+ * - **Server-side tool charges** — web search is $10 per 1,000 searches on
30
+ * top of tokens. The ledger counts tokens, so those are missing.
31
+ * - **The Batch API's 50% discount**, which Claude Code does not use.
32
+ *
33
+ * Every one of those is a modifier on a session shape Claude Code does not
34
+ * normally produce, and naming them here is cheaper than a reader discovering
35
+ * their bill is larger than the board's number and concluding the board lies.
36
+ *
37
+ * Prices change. `RATE_CARD_ID` travels with every amount the ledger prints,
38
+ * so a stale figure is identifiable rather than merely wrong, and an operator
39
+ * who wants different numbers still writes `pricing:` — a config block always
40
+ * wins over these defaults.
41
+ */
42
+
43
+ /** Published multipliers on the base input rate. Not a guess — the pricing
44
+ * page states them as the definition of the cache columns. */
45
+ export const CACHE_MULTIPLIERS = Object.freeze({
46
+ cache_write: 1.25, // a 5-minute cache write
47
+ cache_write_1h: 2, // a 1-hour cache write
48
+ cache_read: 0.1, // a cache hit or refresh
49
+ });
50
+
51
+ /**
52
+ * The label that travels with every priced amount. Bump it when the numbers
53
+ * below change, so a cached `state/cost.json` from an older card is visibly
54
+ * older rather than silently different.
55
+ */
56
+ export const RATE_CARD_ID = 'list-2026-08';
57
+
58
+ /**
59
+ * Base input and output, $ per million tokens, keyed by NORMALISED model.
60
+ * Retired models are kept: a ledger reads historical transcripts, and dropping
61
+ * a rate would silently move old spend into the unpriced column.
62
+ */
63
+ export const LIST_PRICES = Object.freeze({
64
+ 'fable-5': { input: 10, output: 50 },
65
+ 'mythos-5': { input: 10, output: 50 },
66
+ 'opus-5': { input: 5, output: 25 },
67
+ 'opus-4-8': { input: 5, output: 25 },
68
+ 'opus-4-7': { input: 5, output: 25 },
69
+ 'opus-4-6': { input: 5, output: 25 },
70
+ 'opus-4-5': { input: 5, output: 25 },
71
+ 'opus-4-1': { input: 15, output: 75 },
72
+ 'opus-4': { input: 15, output: 75 },
73
+ 'sonnet-5': { input: 2, output: 10 },
74
+ 'sonnet-4-6': { input: 3, output: 15 },
75
+ 'sonnet-4-5': { input: 3, output: 15 },
76
+ 'sonnet-4': { input: 3, output: 15 },
77
+ 'haiku-4-5': { input: 1, output: 5 },
78
+ 'haiku-3-5': { input: 0.8, output: 4 },
79
+ });
80
+
81
+ /**
82
+ * What a bare family name resolves to. The CLI accepts `opus` and resolves it
83
+ * to the current generation; a transcript can carry either spelling, and in
84
+ * measured data the bare form is rare but not zero (12 of 4840 requests).
85
+ * Pricing it as the current generation is what the CLI actually did.
86
+ */
87
+ const BARE_ALIASES = Object.freeze({
88
+ opus: 'opus-5',
89
+ sonnet: 'sonnet-5',
90
+ haiku: 'haiku-4-5',
91
+ fable: 'fable-5',
92
+ mythos: 'mythos-5',
93
+ });
94
+
95
+ /**
96
+ * A transcript's `message.model` reduced to a rate-card key.
97
+ *
98
+ * Real values seen in live transcripts, all of which must land somewhere:
99
+ * `claude-opus-5`, `claude-opus-5[1m]`, `claude-opus-4-8`, `claude-fable-5`,
100
+ * `claude-sonnet-5`, `claude-haiku-4-5-20251001`, `opus`, `sonnet`,
101
+ * `<synthetic>`. The last is not a model and must NOT resolve — a synthetic
102
+ * record carries no tokens and pricing it would invent spend.
103
+ */
104
+ export function normalizeModel(id) {
105
+ if (typeof id !== 'string') return null;
106
+ let key = id.trim().toLowerCase();
107
+ if (key === '' || key.startsWith('<')) return null;
108
+ // `[1m]` and friends are context-window variants, and long context is
109
+ // standard-priced, so the variant carries no rate information.
110
+ key = key.replace(/\[[^\]]*\]$/, '');
111
+ key = key.replace(/^claude-/, '');
112
+ // A trailing release date (`-20251001`) identifies a snapshot, not a price.
113
+ key = key.replace(/-\d{8}$/, '');
114
+ key = key.replace(/-v\d+$/, '');
115
+ if (Object.prototype.hasOwnProperty.call(BARE_ALIASES, key)) return BARE_ALIASES[key];
116
+ return Object.prototype.hasOwnProperty.call(LIST_PRICES, key) ? key : null;
117
+ }
118
+
119
+ /**
120
+ * The five rates for one model id, or null when it is not a model we price.
121
+ * Null is not zero — the ledger's `unpriced` list depends on that distinction.
122
+ */
123
+ export function ratesFor(id) {
124
+ const key = normalizeModel(id);
125
+ if (key === null) return null;
126
+ const { input, output } = LIST_PRICES[key];
127
+ return {
128
+ input,
129
+ cache_write: scaled(input, CACHE_MULTIPLIERS.cache_write),
130
+ cache_write_1h: scaled(input, CACHE_MULTIPLIERS.cache_write_1h),
131
+ cache_read: scaled(input, CACHE_MULTIPLIERS.cache_read),
132
+ output,
133
+ };
134
+ }
135
+
136
+ /**
137
+ * One rate times its multiplier, rounded to the precision the published table
138
+ * actually uses.
139
+ *
140
+ * Binary floating point makes `3 * 0.1` into `0.30000000000000004`, and while
141
+ * the error is ~1e-17 of a dollar and could never move an amount, the number
142
+ * is also PRINTED — in the rate card the board shows and in any config this
143
+ * seeds. A rate that renders as `0.30000000000000004` reads as a bug in the
144
+ * money, which costs more trust than the digits are worth. Six decimal places
145
+ * is exact for every value in the table (the longest is 18.75).
146
+ */
147
+ function scaled(base, multiplier) {
148
+ return Math.round(base * multiplier * 1e6) / 1e6;
149
+ }
150
+
151
+ /**
152
+ * A rate table for exactly the model ids observed, so the ledger prices the
153
+ * spellings it actually saw rather than the ones we happened to anticipate.
154
+ * Unknown ids are simply absent, which is what puts them in `unpriced`.
155
+ */
156
+ export function defaultRateCard(modelIds) {
157
+ const table = Object.create(null);
158
+ for (const id of modelIds) {
159
+ const rates = ratesFor(id);
160
+ if (rates !== null) table[id] = rates;
161
+ }
162
+ return table;
163
+ }
164
+
165
+ // ------------------------------------------------------------ subscription
166
+
167
+ /**
168
+ * List price per month, in USD, for the plans Claude Code reports.
169
+ *
170
+ * This is what makes "what would this have cost on the API" mean something:
171
+ * on its own the API-equivalent figure is a number with nothing to compare it
172
+ * to, and a subscriber's real marginal cost per token is zero.
173
+ */
174
+ export const SUBSCRIPTION_USD = Object.freeze({
175
+ pro: 20,
176
+ max_5x: 100,
177
+ max_20x: 200,
178
+ });
179
+
180
+ /** How each plan should be named to a human. */
181
+ export const PLAN_LABELS = Object.freeze({
182
+ pro: 'Pro',
183
+ max_5x: 'Max 5x',
184
+ max_20x: 'Max 20x',
185
+ });
186
+
187
+ /**
188
+ * The plan, from the tier string Claude Code stores.
189
+ *
190
+ * Measured shape: `oauthAccount.organizationRateLimitTier` reads
191
+ * `default_claude_max_20x`. Matching is deliberately loose about the prefix
192
+ * and strict about the multiplier, because the prefix is the platform's
193
+ * business and the multiplier is the part that changes the price.
194
+ */
195
+ /**
196
+ * The start of the subscription period containing `now`, given the day the
197
+ * subscription was created — `YYYY-MM-DD`, or null when it cannot be derived.
198
+ *
199
+ * A plan is billed monthly on its anniversary, so "what have I spent this
200
+ * period" means "since the most recent anniversary at or before today". That
201
+ * is the only window whose comparison against the monthly price needs no
202
+ * arithmetic from the reader.
203
+ *
204
+ * SHORT MONTHS ARE THE WHOLE DIFFICULTY. A subscription created on the 31st
205
+ * has no 31st in February, and naive date maths rolls that into March 3rd —
206
+ * which lands in the FUTURE and produces a period that has not begun. Every
207
+ * overflowing day clamps to the last day of its month instead, which is what
208
+ * billing does. Tested at every boundary, because this is wrong once a year
209
+ * and silently.
210
+ */
211
+ export function periodStart(createdAt, now) {
212
+ // Strings only. `new Date(null)` is epoch zero, not an invalid date, so a
213
+ // null subscription date would otherwise produce a confident 1970
214
+ // anniversary and a window sweeping in everything ever recorded.
215
+ if (typeof createdAt !== 'string' || typeof now !== 'string') return null;
216
+ const created = new Date(createdAt);
217
+ const at = new Date(now);
218
+ if (!Number.isFinite(created.getTime()) || !Number.isFinite(at.getTime())) return null;
219
+ if (at < created) return null;
220
+
221
+ const anniversary = created.getUTCDate();
222
+ // Candidate: the anniversary within the current month. If that is still in
223
+ // the future, the period began in the previous month.
224
+ let year = at.getUTCFullYear();
225
+ let month = at.getUTCMonth();
226
+ if (clampedDay(year, month, anniversary) > at.getUTCDate()) {
227
+ month -= 1;
228
+ if (month < 0) {
229
+ month = 11;
230
+ year -= 1;
231
+ }
232
+ }
233
+ const day = clampedDay(year, month, anniversary);
234
+ const iso = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
235
+ // Never earlier than the subscription itself: the first period starts the
236
+ // day it was created, not on an anniversary that predates it.
237
+ const createdDay = createdAt.slice(0, 10);
238
+ return iso < createdDay ? createdDay : iso;
239
+ }
240
+
241
+ /** `day`, or the last day of that month when the month is too short for it. */
242
+ function clampedDay(year, month, day) {
243
+ const lastOfMonth = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
244
+ return Math.min(day, lastOfMonth);
245
+ }
246
+
247
+ export function planOfTier(tier) {
248
+ if (typeof tier !== 'string') return null;
249
+ const key = tier.trim().toLowerCase();
250
+ if (key === '') return null;
251
+ if (/max[_-]?20x/.test(key)) return 'max_20x';
252
+ if (/max[_-]?5x/.test(key)) return 'max_5x';
253
+ if (/\bpro\b|_pro$|^pro_/.test(key)) return 'pro';
254
+ return null;
255
+ }