@jjanczur/tyran 0.1.45 → 0.1.47

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.
@@ -36,6 +36,7 @@
36
36
  * dead writes no state to be inconsistent with.
37
37
  */
38
38
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
39
+ import { homedir } from 'node:os';
39
40
  import { join, dirname, resolve, basename } from 'node:path';
40
41
  import { fileURLToPath } from 'node:url';
41
42
  import { checkHooks, DEFAULT_PLUGIN_ROOT } from './hooks-check.mjs';
@@ -279,6 +280,9 @@ export const SEVERITY_BY_CODE = Object.freeze(
279
280
  'limit-pause-stale': 'warning',
280
281
  'limit-resume-watcher-dead': 'warning',
281
282
  'limit-telemetry-missing': 'warning',
283
+ 'limit-watcher-absent': 'warning',
284
+ 'limit-near': 'warning',
285
+ 'limit-statusline-stale': 'warning',
282
286
  }),
283
287
  );
284
288
 
@@ -1850,19 +1854,120 @@ export function overnightFindings(dir, { now = null, configDoc = null, usageFall
1850
1854
  finding(
1851
1855
  'limit-telemetry-missing',
1852
1856
  show(sidecarPath),
1853
- `limits.mode is "${show(limits.mode)}" and NO usage telemetry is reachable — the sidecar is ` +
1857
+ `limits.mode is "${show(limits.mode)}" and NO usage PERCENTAGE is reachable — the sidecar is ` +
1854
1858
  `${sidecar === null ? 'absent' : 'over a day old'} and the platform's own cache in ~/.claude.json ` +
1855
- 'carries no window that is still running. The gate fails open without one, so the configured ' +
1856
- 'pause protects nothing. Usually this means the account is signed out, or the platform has not ' +
1857
- 'reported usage yet; see https://jjanczur.github.io/tyran/overnight/',
1859
+ 'carries no window that is still running. So nothing can stop this run EARLY: the threshold you ' +
1860
+ 'configured cannot be compared against anything, and the gate fails open. The wall itself is still ' +
1861
+ 'detected from the session transcript once it is hit, so the wind-down and the scheduled resume ' +
1862
+ 'survive — what is lost is the clean stop before the limit, not the whole feature. Usually this ' +
1863
+ 'means the account is signed out, or the platform has stopped reporting a percentage at all; ' +
1864
+ 'see https://jjanczur.github.io/tyran/overnight/',
1858
1865
  `node scripts/statusline.mjs --sidecar-only # optional: a statusline is fresher, but no longer required`,
1859
1866
  ),
1860
1867
  );
1861
1868
  }
1862
1869
  }
1870
+
1871
+ // A MARKER WITH NOBODY WAITING FOR IT. The wind-down is six steps the model
1872
+ // executes, and step 5 is the one that arms the resume — so a session killed
1873
+ // after step 4, or one that never read the refusal, leaves a pause that
1874
+ // ends only when someone notices. Nothing reported that: `limit-pause-stale`
1875
+ // fires only once `resume_at` has ALREADY passed, which is the morning after.
1876
+ if (marker !== null && resume === null) {
1877
+ findings.push(
1878
+ finding(
1879
+ 'limit-watcher-absent',
1880
+ show(markerPath),
1881
+ 'a pause is in force and NOTHING is waiting for the reset — no resume.json beside it. The wind-down ' +
1882
+ 'stopped before it scheduled the resume, so this run restarts only when a human starts a session',
1883
+ `node scripts/overnight.mjs schedule --dir ${sq(dirname(resolve(dir)))}`,
1884
+ ),
1885
+ );
1886
+ }
1887
+
1888
+ // `warn` PROMISED TO SURFACE and never did. The gate returns PASS on warn
1889
+ // — "surfacing is doctor's job" — and doctor did not compare a percentage
1890
+ // against a threshold anywhere, so `warn` differed from `off` in nothing an
1891
+ // operator could see. This is that comparison, and it is doctor's alone: no
1892
+ // KERNEL edit is needed for a mode whose whole contract is "never deny".
1893
+ const limitsForWarn = knowsLimits(configDoc);
1894
+ if (limitsForWarn !== null && limitsForWarn.mode !== 'off') {
1895
+ const reading = readJsonIfSmall(sidecarPath) ?? usageFallback();
1896
+ for (const [key, threshold, label] of [
1897
+ ['seven_day', limitsForWarn.weekly_pause_at_percent, 'weekly'],
1898
+ ['five_hour', limitsForWarn.pause_at_percent, 'five-hour'],
1899
+ ]) {
1900
+ const used = reading?.[key]?.used_percentage;
1901
+ if (typeof used !== 'number' || used < threshold) continue;
1902
+ findings.push(
1903
+ finding(
1904
+ 'limit-near',
1905
+ show(sidecarPath),
1906
+ `the ${label} usage window is at ${show(String(Math.round(used)))}% against a threshold of ` +
1907
+ `${show(String(threshold))}% — ` +
1908
+ (limitsForWarn.mode === 'warn'
1909
+ ? 'limits.mode is "warn", so nothing will stop; work runs until the platform cuts it off'
1910
+ : 'the gate winds unsupervised work down from here'),
1911
+ `node scripts/overnight.mjs status --dir ${sq(dirname(resolve(dir)))}`,
1912
+ ),
1913
+ );
1914
+ break; // the binding window is enough; two lines about one wall is noise
1915
+ }
1916
+ }
1917
+
1863
1918
  return findings;
1864
1919
  }
1865
1920
 
1921
+ /**
1922
+ * The statusline the operator registered, pinned to a plugin version that is
1923
+ * no longer the one running.
1924
+ *
1925
+ * MEASURED, which is why this exists: a real machine had
1926
+ * `~/.claude/plugins/cache/tyran/tyran/0.1.29/scripts/statusline.mjs` in its
1927
+ * user settings while 0.1.45 was installed. The old path still existed, so
1928
+ * nothing failed — but a plugin cache is not an archive, and the day that
1929
+ * directory is pruned the statusline silently stops writing the sidecar. The
1930
+ * symptom is the one this whole area is about: a configured pause that never
1931
+ * fires and says nothing.
1932
+ *
1933
+ * Read-only and best-effort: the file belongs to the operator, and a doctor
1934
+ * that throws on a settings file it was only inspecting is worse than one that
1935
+ * says nothing about it.
1936
+ */
1937
+ export function statuslineFindings({ home = homedir(), version = null, readFile = readFileSync } = {}) {
1938
+ let command;
1939
+ try {
1940
+ const doc = JSON.parse(readFile(join(home, '.claude', 'settings.json'), 'utf8'));
1941
+ command = doc?.statusLine?.command;
1942
+ } catch {
1943
+ return [];
1944
+ }
1945
+ if (typeof command !== 'string' || !command.includes('statusline.mjs')) return [];
1946
+ const pinned = /plugins[/\\]cache[/\\]tyran[/\\]tyran[/\\]([0-9][^/\\]*)[/\\]/.exec(command);
1947
+ if (pinned === null || version === null || pinned[1] === version) return [];
1948
+ return [
1949
+ finding(
1950
+ 'limit-statusline-stale',
1951
+ show(join(home, '.claude', 'settings.json')),
1952
+ `your statusLine command points into the plugin cache for version ${show(pinned[1])}, but ${show(version)} ` +
1953
+ 'is running. That directory is a cache, not an archive: when it is pruned the statusline stops writing ' +
1954
+ 'usage telemetry and the pause it feeds silently stops firing',
1955
+ 'edit ~/.claude/settings.json and repoint statusLine at the version you run (or drop it — the platform cache and the transcript are read without it)',
1956
+ ),
1957
+ ];
1958
+ }
1959
+
1960
+ /** The plugin version actually running, or null. Read from the manifest next
1961
+ * to this script, so it cannot disagree with what `claude plugin update` sees. */
1962
+ function pluginVersion() {
1963
+ try {
1964
+ const here = dirname(fileURLToPath(import.meta.url));
1965
+ return JSON.parse(readFileSync(join(here, '..', '.claude-plugin', 'plugin.json'), 'utf8'))?.version ?? null;
1966
+ } catch {
1967
+ return null;
1968
+ }
1969
+ }
1970
+
1866
1971
  function readJsonIfSmall(path) {
1867
1972
  try {
1868
1973
  if (!existsSync(path) || statSync(path).size > 64 * 1024) return null;
@@ -1896,6 +2001,9 @@ export function runStateChecks({
1896
2001
  staleHours = DEFAULT_STALE_HOURS,
1897
2002
  run = null,
1898
2003
  usageFallback = () => readPlatformUsage(),
2004
+ // The operator's home, injectable so a test never reads the real one. The
2005
+ // statusline check is the only thing in this file that leaves the repo.
2006
+ statuslineHome = homedir(),
1899
2007
  } = {}) {
1900
2008
  const root = resolve(dir);
1901
2009
  if (!existsSync(root)) {
@@ -2116,6 +2224,17 @@ export function runStateChecks({
2116
2224
  checked.push(worktrees.checked);
2117
2225
 
2118
2226
  findings.push(...overnightFindings(dir, { now, configDoc, usageFallback }));
2227
+ // The one check that reads a file OUTSIDE the repository — the statusline
2228
+ // lives in the operator's own settings, which is why no installer can write
2229
+ // it and why nothing else notices when it rots.
2230
+ //
2231
+ // Gated on the feature being ON, for two reasons that point the same way: a
2232
+ // stale statusline in a repo that never enabled overnight mode is not
2233
+ // actionable, and a machine-scoped warning raised inside every repo-scoped
2234
+ // run would follow the operator into projects it says nothing about.
2235
+ if (knowsLimits(configDoc)?.mode !== undefined && knowsLimits(configDoc).mode !== 'off') {
2236
+ findings.push(...statuslineFindings({ version: pluginVersion(), home: statuslineHome }));
2237
+ }
2119
2238
  checked.push('overnight: checked');
2120
2239
 
2121
2240
  const trackedLeases = trackedLeaseFiles(gitRun, basename(root));
@@ -119,7 +119,7 @@ export const DATA_KNOWN = Object.freeze({
119
119
  gate: Object.freeze([
120
120
  'kind', 'result', 'evidence', 'evidence_ref', 'ticket', 'question', 'recommendation', 'default',
121
121
  'reason', 'signals', 'code', 'would_be', 'initiative_inferred_from',
122
- 'answer', 'answer_mode', 'decision', 'via',
122
+ 'answer', 'answer_mode', 'decision', 'via', 'blocking',
123
123
  ]),
124
124
  review: Object.freeze(['ticket', 'verdict', 'by']),
125
125
  merge: Object.freeze(['ticket', 'sha', 'mode']),
@@ -857,7 +857,10 @@ export function nextAskKind(events) {
857
857
  * the second question then replaces the first on the fold's kind-keyed Map —
858
858
  * silent loss, in an append-only file that can never be corrected.
859
859
  */
860
- export function raiseAsk(file, { init, actor = 'conductor', question, recommendation = null, default: dflt = null, ticket = null }) {
860
+ export function raiseAsk(
861
+ file,
862
+ { init, actor = 'conductor', question, recommendation = null, default: dflt = null, ticket = null, blocking = false },
863
+ ) {
861
864
  if (typeof question !== 'string' || question.trim().length === 0) {
862
865
  throw new Error('ask requires a non-empty --question (what is the operator being asked?)');
863
866
  }
@@ -868,7 +871,25 @@ export function raiseAsk(file, { init, actor = 'conductor', question, recommenda
868
871
  if (ticket != null) data.ticket = ticket;
869
872
  data.question = question;
870
873
  if (recommendation != null) data.recommendation = recommendation;
874
+ // A RECOMMENDATION IS A DEFAULT unless the asker names a different one.
875
+ //
876
+ // The two fields are not the same thing — the recommendation is what the
877
+ // agent thinks is right, the default is what ships if nobody ever answers,
878
+ // and they legitimately differ ("switch to per-seat" vs "keep flat fee").
879
+ // But an ask that records only a recommendation was recording an opinion
880
+ // with no fallback, which read on the board as `blocking · no safe
881
+ // default` and stopped the queue on a question its own author had already
882
+ // answered.
883
+ //
884
+ // Derived at the MINT, not at every read: the journal then says what would
885
+ // ship, and the board's blocking/decision split keeps meaning "neither
886
+ // field was supplied" — a genuinely un-defaultable question.
871
887
  if (dflt != null) data.default = dflt;
888
+ else if (recommendation != null) data.default = recommendation;
889
+ // Marks the questions that must wake a human even under `unattended.mode:
890
+ // on`: the irreversible, the outward-facing, and the ones that spend
891
+ // money. Only written when true, so an ordinary ask is unchanged on disk.
892
+ if (blocking === true) data.blocking = true;
872
893
  return appendUnderLock(file, { ev: 'gate', init, actor, data }, snapshot);
873
894
  });
874
895
  }
@@ -1028,6 +1049,14 @@ function parseFlags(args, allowed) {
1028
1049
  if (args[i].startsWith('--')) {
1029
1050
  const name = args[i].slice(2);
1030
1051
  if (!allowed.includes(name)) throw new Error(`unknown flag --${name}`);
1052
+ // A switch takes no value. Without this the parser would swallow the
1053
+ // NEXT argument as `--blocking`'s value — silently, since `ask`'s
1054
+ // positionals are read from `rest` and one missing element there is a
1055
+ // usage error blamed on the wrong flag.
1056
+ if (BOOLEAN_FLAGS.includes(name)) {
1057
+ flags[name] = true;
1058
+ continue;
1059
+ }
1031
1060
  const value = args[++i];
1032
1061
  if (value === undefined || value.startsWith('--')) {
1033
1062
  throw new Error(`flag --${name} requires a value`);
@@ -1038,6 +1067,9 @@ function parseFlags(args, allowed) {
1038
1067
  return { flags, rest };
1039
1068
  }
1040
1069
 
1070
+ /** Flags that are switches: present means true, and they consume no value. */
1071
+ const BOOLEAN_FLAGS = ['blocking'];
1072
+
1041
1073
  const CMD_FLAGS = {
1042
1074
  append: ['actor', 'data'],
1043
1075
  query: ['ev', 'init', 'ticket', 'limit'],
@@ -1046,7 +1078,7 @@ const CMD_FLAGS = {
1046
1078
  tail: [],
1047
1079
  'open-spawns': [],
1048
1080
  'close-spawn': ['actor', 'verdict', 'reason'],
1049
- ask: ['actor', 'ticket', 'question', 'recommendation', 'default'],
1081
+ ask: ['actor', 'ticket', 'question', 'recommendation', 'default', 'blocking'],
1050
1082
  };
1051
1083
 
1052
1084
  /**
@@ -1065,7 +1097,7 @@ export const JOURNAL_USAGE = [
1065
1097
  ' journal.mjs validate <file> · next-id <file> <prefix> · tail <file>',
1066
1098
  ' journal.mjs open-spawns <file>',
1067
1099
  ' journal.mjs close-spawn <file> <init> <agent> --reason R [--verdict V] [--actor A]',
1068
- ' journal.mjs ask <file> <init> --question Q [--recommendation R] [--default D] [--ticket T] [--actor A]',
1100
+ ' journal.mjs ask <file> <init> --question Q [--recommendation R] [--default D] [--ticket T] [--actor A] [--blocking]',
1069
1101
  '',
1070
1102
  // The `--data` contract varies per event and lived only in a table no
1071
1103
  // command printed. A field run discovered it by rejection, one failed
@@ -1198,6 +1230,7 @@ function main() {
1198
1230
  recommendation: flags.recommendation ?? null,
1199
1231
  default: flags.default ?? null,
1200
1232
  ticket: flags.ticket ?? null,
1233
+ blocking: flags.blocking === true,
1201
1234
  });
1202
1235
  console.log(emit(written));
1203
1236
  return;
@@ -45,22 +45,25 @@
45
45
  * numbers.
46
46
  *
47
47
  * CLI:
48
- * node overnight.mjs schedule [--dir <repo>] [--prompt <text>] [--cmd <exe>] [--force-resume]
48
+ * node overnight.mjs schedule [--dir <repo>] [--prompt <text>] [--cmd <exe>] [--force-resume]
49
+ * node overnight.mjs watch-limit [--dir <repo>] [--once] [--poll-ms <n>] # detect the wall with no session alive
49
50
  * node overnight.mjs status [--dir <repo>]
50
51
  * node overnight.mjs cancel [--dir <repo>] [--clear]
51
52
  * node overnight.mjs --wait [--dir <repo>] # internal (the watcher)
52
53
  * Exit: 0 ok/held · 1 refused (no marker, already scheduled, STOP) · 2 usage/IO
53
54
  */
54
55
  import { spawn, execFile } from 'node:child_process';
55
- import { existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
56
+ import { existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
56
57
  import { join, resolve } from 'node:path';
57
58
  import { realpathSync } from 'node:fs';
58
59
  import { fileURLToPath } from 'node:url';
59
60
  import { checkStop } from './stop-check.mjs';
60
- import { readJournal } from './journal.mjs';
61
+ import { append, readJournal } from './journal.mjs';
61
62
  import { GATE_PASS } from './project.mjs';
62
63
  import { withKeepAwake } from './keepawake.mjs';
63
64
  import { SIDECAR_RELPATH, SIDECAR_FRESH_MS } from './usage-source.mjs';
65
+ import { readTranscriptRejection, WINDOW_KEYS } from './usage-transcript.mjs';
66
+ import { pauseMarkerFrom, writePauseMarker } from './usage-marker.mjs';
64
67
  import { limitsOf } from './schema.mjs';
65
68
  import { parse } from './yaml-lite.mjs';
66
69
  import { escapeInvisible } from './invisible.mjs';
@@ -689,10 +692,201 @@ function doCancel(repo, flags) {
689
692
  }
690
693
  }
691
694
 
695
+ // ------------------------------------------------- watching for the wall
696
+
697
+ /**
698
+ * How often the standalone watcher looks for a wall. Cheap by construction —
699
+ * see `usage-transcript.mjs` for the three bounds on what it opens.
700
+ */
701
+ export const LIMIT_POLL_MS = 60 * 1000;
702
+
703
+ /** Slug shape shared with `doWait`: what may become a directory name. */
704
+ const INIT_RE = /^[A-Za-z0-9._-]{1,80}$/;
705
+
706
+ /**
707
+ * The initiative a pause belongs to: the one whose journal was written last.
708
+ *
709
+ * The gate learns this from the session that is being refused. Nothing is
710
+ * being refused here — that is the whole point of this path — so the most
711
+ * recently advanced journal is the best available answer, and a wrong guess
712
+ * costs a checkpoint filed against the wrong initiative rather than a missed
713
+ * resume: `runWaitLoop` re-reads `marker.init` only to look for evidence that
714
+ * somebody already came back.
715
+ */
716
+ export function activeInitiative(repo, { readdir = readdirSync, stat = statSync } = {}) {
717
+ const root = join(repo, '.tyran', 'state');
718
+ let entries;
719
+ try {
720
+ entries = readdir(root, { withFileTypes: true });
721
+ } catch {
722
+ return null;
723
+ }
724
+ let best = null;
725
+ for (const entry of entries) {
726
+ if (!entry.isDirectory() || !INIT_RE.test(entry.name)) continue;
727
+ try {
728
+ const mtime = stat(join(root, entry.name, 'journal.jsonl')).mtimeMs;
729
+ if (best === null || mtime > best.mtime) best = { init: entry.name, mtime };
730
+ } catch {
731
+ /* a directory with no journal is not an initiative */
732
+ }
733
+ }
734
+ return best === null ? null : best.init;
735
+ }
736
+
737
+ /**
738
+ * The window a transcript reading should pause on, in `trippedWindow`'s shape.
739
+ *
740
+ * The weekly one governs when both are walled, for the reason the gate gives:
741
+ * waiting out the five-hour refill just hits the weekly wall again.
742
+ */
743
+ export function wallOf(reading) {
744
+ if (reading === null || typeof reading !== 'object') return null;
745
+ for (const window of ['seven_day', ...WINDOW_KEYS.filter((w) => w !== 'seven_day')]) {
746
+ const node = reading[window];
747
+ if (node === null || typeof node !== 'object') continue;
748
+ if (typeof node.resets_at !== 'number' || !Number.isFinite(node.resets_at)) continue;
749
+ return {
750
+ window,
751
+ used_percentage: typeof node.used_percentage === 'number' ? node.used_percentage : 100,
752
+ resets_at: node.resets_at,
753
+ // Exact, not a bound: this is the window closing at a known second, so
754
+ // the scheduler may act on it. See `usage-transcript.mjs`.
755
+ lower_bound: false,
756
+ };
757
+ }
758
+ return null;
759
+ }
760
+
761
+ /**
762
+ * One look for the wall, and the pause if there is one.
763
+ *
764
+ * WHY THIS EXISTS AT ALL. The gate can only refuse a session that is still
765
+ * calling tools. After a five-hour wall there is no such session: the
766
+ * conductor's own request was the one rejected, so it cannot write its
767
+ * checkpoint, cannot run the wind-down, and cannot arm a resume. Measured on
768
+ * this machine — walled at 19:25 with the window resetting at 20:00, and the
769
+ * first real answer at 20:30, because the reset was nobody's job.
770
+ *
771
+ * Returns what it did rather than printing it, so the board server can call
772
+ * the same function on its refresh timer.
773
+ */
774
+ export function limitSweep(repo, { nowMs = Date.now(), readTranscript = readTranscriptRejection, notify = notifyDesktop } = {}) {
775
+ const limits = readLimitsFile(repo);
776
+ if (limits === null || limits.mode === 'off') return { action: 'none', reason: 'limits-off' };
777
+ if (checkStop(repo).stopped) return { action: 'none', reason: 'stop-brake' };
778
+
779
+ // An existing marker means the gate already saw this, or a previous sweep
780
+ // did. Writing a second one would move `resume_at` forward on every poll —
781
+ // a pause that recedes as you approach it.
782
+ const existing = readSmallJson(join(repo, MARKER_RELPATH));
783
+ if (existing !== null) {
784
+ const resumeAtMs = Date.parse(typeof existing.resume_at === 'string' ? existing.resume_at : '');
785
+ if (!Number.isFinite(resumeAtMs) || resumeAtMs > nowMs) return { action: 'none', reason: 'already-paused' };
786
+ }
787
+
788
+ let reading;
789
+ try {
790
+ reading = readTranscript({ repoRoot: repo, nowMs });
791
+ } catch {
792
+ // Telemetry is consulted, never depended on — the same contract the gate
793
+ // keeps. A watcher that dies on a malformed transcript is a watcher that
794
+ // is not there on the night it was needed.
795
+ return { action: 'none', reason: 'unreadable' };
796
+ }
797
+ const tripped = wallOf(reading);
798
+ if (tripped === null) return { action: 'none', reason: 'no-wall' };
799
+
800
+ const init = activeInitiative(repo);
801
+ const marker = pauseMarkerFrom(tripped, limits, nowMs, reading.session_id, init, 'transcript');
802
+ writePauseMarker(repo, marker);
803
+ log(repo, `wall: window=${tripped.window} resets_at=${tripped.resets_at} session=${marker.session_id ?? 'unknown'}`);
804
+
805
+ // The journal is what makes this visible as a PAUSE rather than as a run
806
+ // that simply stopped. Best-effort: a locked or unwritable journal must not
807
+ // cost the marker that was already written, which is what arms the resume.
808
+ const journalPath = journalPathFor(repo, init);
809
+ if (journalPath !== null && existsSync(journalPath)) {
810
+ try {
811
+ append(journalPath, {
812
+ ev: 'checkpoint',
813
+ init,
814
+ actor: 'overnight-watcher',
815
+ data: {
816
+ phase: 'usage-limit-pause',
817
+ next_steps: [
818
+ `the ${tripped.window === 'seven_day' ? 'weekly' : 'five-hour'} window is exhausted; it resets ${marker.resume_at}`,
819
+ 'this pause was detected from the transcript AFTER the wall — no wind-down ran, so open work may be uncommitted',
820
+ 'on resume: close the open usage-limit gate with result: passed, then re-read STATE.md before spawning anything',
821
+ ],
822
+ },
823
+ });
824
+ append(journalPath, {
825
+ ev: 'gate',
826
+ init,
827
+ actor: 'overnight-watcher',
828
+ data: { kind: 'usage-limit', result: 'WAITING_ON_RESET', reason: `${tripped.window} window exhausted; resets ${marker.resume_at}` },
829
+ });
830
+ } catch {
831
+ log(repo, 'wall: journal append failed — the marker stands and the resume is still armed');
832
+ }
833
+ }
834
+
835
+ const windowName = tripped.window === 'seven_day' ? 'weekly' : 'five-hour';
836
+ notify('Tyran: hit the usage limit', `The ${windowName} window is exhausted. Resuming automatically ${marker.resume_at}.`);
837
+ return { action: 'paused', reason: 'wall', marker };
838
+ }
839
+
840
+ function doWatchLimit(repo, flags) {
841
+ const limits = readLimitsFile(repo);
842
+ if (limits.mode === 'off') {
843
+ console.error(
844
+ 'overnight: limits.mode is "off" in .tyran/config.yaml — nothing to watch for.\n' +
845
+ ' set limits.mode: pause to have the wall detected and the resume armed.',
846
+ );
847
+ process.exit(1);
848
+ }
849
+ const pollMs = typeof flags['poll-ms'] === 'number' ? flags['poll-ms'] : LIMIT_POLL_MS;
850
+
851
+ const sweepOnce = () => {
852
+ const result = limitSweep(repo);
853
+ if (result.action === 'paused') {
854
+ console.log(`overnight: wall detected on the ${result.marker.window} window — resuming ${result.marker.resume_at}`);
855
+ // Arm the resume through the ordinary path, so the hold policy, the
856
+ // keep-awake warning and the babysitting ladder are the ones the
857
+ // operator already has, not a second implementation of them.
858
+ doSchedule(repo, flags);
859
+ return true;
860
+ }
861
+ return false;
862
+ };
863
+
864
+ if (flags.once === true) {
865
+ if (!sweepOnce()) console.log('overnight: no wall in force');
866
+ return;
867
+ }
868
+
869
+ console.log(`overnight: watching for the usage wall every ${Math.round(pollMs / 1000)}s (Ctrl-C to stop)`);
870
+ const timer = setInterval(() => {
871
+ try {
872
+ if (sweepOnce()) {
873
+ clearInterval(timer);
874
+ // doSchedule spawned the resume watcher; this process has done its job.
875
+ process.exit(0);
876
+ }
877
+ } catch (err) {
878
+ log(repo, `watch-limit: ${err.message}`);
879
+ }
880
+ }, pollMs);
881
+ timer.unref?.();
882
+ // Without this the unref'd timer lets the process exit immediately.
883
+ process.stdin.resume?.();
884
+ }
885
+
692
886
  // ------------------------------------------------------------------- CLI
693
887
 
694
- const BOOLEAN_FLAGS = ['force-resume', 'clear', 'wait'];
695
- const NUMERIC_FLAGS = ['chunk-ms', 'backoff-ms'];
888
+ const BOOLEAN_FLAGS = ['force-resume', 'clear', 'wait', 'once'];
889
+ const NUMERIC_FLAGS = ['chunk-ms', 'backoff-ms', 'poll-ms'];
696
890
  const VALUE_FLAGS = ['dir', 'prompt', 'cmd', ...NUMERIC_FLAGS];
697
891
 
698
892
  function parseArgs(argv) {
@@ -725,7 +919,8 @@ function parseArgs(argv) {
725
919
  const SELF = fileURLToPath(import.meta.url);
726
920
 
727
921
  async function main() {
728
- const usage = 'usage: overnight.mjs <schedule|status|cancel> [--dir <repo>] · schedule [--force-resume] [--prompt <t>] [--cmd <exe>] · cancel [--clear]';
922
+ const usage =
923
+ 'usage: overnight.mjs <schedule|watch-limit|status|cancel> [--dir <repo>] · schedule [--force-resume] [--prompt <t>] [--cmd <exe>] · watch-limit [--once] [--poll-ms N] · cancel [--clear]';
729
924
  let parsed;
730
925
  try {
731
926
  parsed = parseArgs(process.argv.slice(2));
@@ -738,6 +933,7 @@ async function main() {
738
933
  const repo = resolve(typeof flags.dir === 'string' ? flags.dir : process.cwd());
739
934
  const command = flags.wait === true ? '--wait' : positionals[0];
740
935
  if (command === 'schedule') return doSchedule(repo, flags);
936
+ if (command === 'watch-limit') return doWatchLimit(repo, flags);
741
937
  if (command === '--wait') return doWait(repo, flags);
742
938
  if (command === 'status') return doStatus(repo);
743
939
  if (command === 'cancel') return doCancel(repo, flags);
@@ -620,6 +620,12 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
620
620
  question: data.question ?? null,
621
621
  recommendation: data.recommendation ?? null,
622
622
  default: data.default ?? null,
623
+ // The asker's "this one must wake a human". It rides the fold for
624
+ // the same reason the three fields above do — and this one is not
625
+ // decoration: it is what `answer.mjs auto` refuses on, so a gate
626
+ // fold that dropped it would auto-accept the very questions their
627
+ // author marked as needing a person.
628
+ blocking: data.blocking === true,
623
629
  count: (prev?.count ?? 0) + 1,
624
630
  // Gate results are keyed by `kind`, so the latest one wins the slot —
625
631
  // and a re-run that passes therefore ERASED the refusal that came
@@ -869,6 +875,10 @@ export function boardOf(state, { staleHours = DEFAULT_STALE_HOURS } = {}) {
869
875
  question: g.question ?? null,
870
876
  recommendation: g.recommendation ?? null,
871
877
  default: g.default ?? null,
878
+ // Projected, not merely stored: this is what `answer.mjs auto` reads
879
+ // to refuse an ask under `unattended.mode: on`, and the refusal has to
880
+ // work from the PROJECTION — the sweep never re-reads raw gates.
881
+ blocking: g.blocking === true,
872
882
  since: g.ts ?? null,
873
883
  });
874
884
  }
@@ -385,6 +385,13 @@ export function scanRepo(dir, { run = gitRunner(dir) } = {}) {
385
385
  resume_margin_minutes: 5,
386
386
  keep_awake: false,
387
387
  },
388
+ // Same argument as `limits:` above, and the same default: written in full
389
+ // so the Settings tab has keys to patch, and OFF because answering an
390
+ // operator's questions on their behalf is a behaviour change they choose.
391
+ unattended: {
392
+ mode: 'off',
393
+ answer: 'recommendation',
394
+ },
388
395
  // The dashboard, ON. Written in full for the same reason `limits:` is —
389
396
  // the Settings tab patches keys that exist and will not invent them — but
390
397
  // with the opposite default, because the argument for OFF does not apply.
@@ -98,7 +98,7 @@ export function validateConfig(doc) {
98
98
  const errors = [];
99
99
  if (!isPlainObject(doc)) return ['config must be a mapping'];
100
100
 
101
- const known = ['profile', 'autonomy', 'tiers', 'validation', 'shared_zones', 'budget', 'main_writable_paths', 'boundaries', 'limits', 'pricing', 'spend', 'board'];
101
+ const known = ['profile', 'autonomy', 'tiers', 'validation', 'shared_zones', 'budget', 'main_writable_paths', 'boundaries', 'limits', 'unattended', 'pricing', 'spend', 'board'];
102
102
  for (const key of Object.keys(doc)) {
103
103
  if (!known.includes(key)) errors.push(`${key}: unknown top-level key`);
104
104
  }
@@ -238,6 +238,25 @@ export function validateConfig(doc) {
238
238
  }
239
239
  }
240
240
 
241
+ // Unattended delivery: what an open question does when nobody is awake.
242
+ // Operator-written policy, never scanner-inferred — no provenance wrapper.
243
+ if ('unattended' in doc) {
244
+ if (!isPlainObject(doc.unattended)) errors.push('unattended: must be a mapping');
245
+ else {
246
+ const unattended = doc.unattended;
247
+ if (unattendedMode(unattended.mode) === null) {
248
+ errors.push(`unattended.mode: required, one of ${UNATTENDED_MODES.join(' | ')} (bare on/off are fine — YAML reads them as booleans and both spellings are accepted)`);
249
+ }
250
+ if ('answer' in unattended && !UNATTENDED_ANSWER.includes(unattended.answer)) {
251
+ errors.push(`unattended.answer: must be one of ${UNATTENDED_ANSWER.join(' | ')}`);
252
+ }
253
+ const knownUnattended = ['mode', 'answer'];
254
+ for (const key of Object.keys(unattended)) {
255
+ if (!knownUnattended.includes(key)) errors.push(`unattended.${key}: unknown key`);
256
+ }
257
+ }
258
+ }
259
+
241
260
  // What a model costs per million tokens. Operator-written from a vendor's
242
261
  // price list — never scanner-inferred, so no provenance wrapper, exactly
243
262
  // like `limits:`. Absent means the cost report shows tokens and no money,
@@ -431,6 +450,63 @@ export function limitsOf(doc) {
431
450
  };
432
451
  }
433
452
 
453
+ export const UNATTENDED_MODES = Object.freeze(['off', 'on']);
454
+ export const UNATTENDED_ANSWER = Object.freeze(['recommendation', 'default']);
455
+
456
+ /**
457
+ * `mode` as one of `UNATTENDED_MODES`, or null if it is not a mode at all.
458
+ *
459
+ * BOOLEANS ARE ACCEPTED, and this is the one place in this file that bends.
460
+ * `yaml-lite.mjs` resolves bare `on` to `true` and bare `off` to `false` — the
461
+ * YAML 1.1 rule — so `mode: on`, the spelling every operator will type first,
462
+ * arrives here as a boolean and would be rejected with "must be one of off |
463
+ * on" against a config that LOOKS exactly right. `limits.mode` lives with that
464
+ * by carrying `# quoted — bare off/on are YAML booleans` next to every
465
+ * occurrence, which is a comment defending a trap rather than removing it.
466
+ *
467
+ * A two-value switch does not need the trap. Both spellings mean the same
468
+ * thing and both are normalised here, so there is still exactly one value
469
+ * downstream.
470
+ */
471
+ export function unattendedMode(value) {
472
+ if (value === true) return 'on';
473
+ if (value === false) return 'off';
474
+ return UNATTENDED_MODES.includes(value) ? value : null;
475
+ }
476
+
477
+ /**
478
+ * The unattended block with defaults applied.
479
+ *
480
+ * WHAT THIS SWITCHES ON, stated plainly because it is the one setting in this
481
+ * file that decides something on the operator's behalf. With `mode: on`, an
482
+ * open question is answered by the agent's own recommendation the moment it is
483
+ * raised, and the run keeps going. That is the point: overnight means you went
484
+ * to sleep expecting shipped work, and a queue of questions nobody was awake
485
+ * to read is a night spent parked.
486
+ *
487
+ * The `default` field promised "what ships if nobody ever answers" since the
488
+ * ask protocol was written, and until this existed NOTHING ever took it — it
489
+ * fired only when a human clicked a button, at which point somebody was awake
490
+ * and the promise was moot.
491
+ *
492
+ * TWO REFUSALS ARE MECHANICAL, not prompt-level, and they are what make this
493
+ * safe enough to switch on: an ask with no recommendation is never
494
+ * auto-answered (nobody wrote down what to do), and an ask raised with
495
+ * `--blocking` is never auto-answered (its author said this one must wake
496
+ * you). Everything auto-answered is journalled as `answer_mode: unattended`,
497
+ * so the morning is one scan of the ledger rather than an archaeology.
498
+ *
499
+ * Off by default, in every template: it is a behaviour change an operator
500
+ * chooses, and `.tyran/STOP` still outranks it.
501
+ */
502
+ export function unattendedOf(doc) {
503
+ const unattended = isPlainObject(doc) && isPlainObject(doc.unattended) ? doc.unattended : {};
504
+ return {
505
+ mode: unattendedMode(unattended.mode) ?? 'off',
506
+ answer: UNATTENDED_ANSWER.includes(unattended.answer) ? unattended.answer : 'recommendation',
507
+ };
508
+ }
509
+
434
510
  /**
435
511
  * The four things a request is billed for. All four are REQUIRED on any model
436
512
  * an operator prices: a table carrying three of them would price the fourth at