@jjanczur/tyran 0.1.14 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/scripts/board.mjs CHANGED
@@ -98,7 +98,10 @@ export function readInitiativeBoards(tyranDir) {
98
98
  errors.push({ name, error: `0 readable events and ${damage} — the journal is damaged` });
99
99
  continue;
100
100
  }
101
- initiatives.push({ name, state, board: boardOf(state) });
101
+ // `journal` is returned, not re-derived by consumers: answer.mjs writes
102
+ // to the file this function already located, so there is one rule for
103
+ // where an initiative's journal lives (ADR-21).
104
+ initiatives.push({ name, journal, state, board: boardOf(state) });
102
105
  } catch (err) {
103
106
  errors.push({ name, error: String(err?.message ?? err) });
104
107
  }
@@ -41,7 +41,9 @@ import { fileURLToPath } from 'node:url';
41
41
  import { checkHooks, DEFAULT_PLUGIN_ROOT } from './hooks-check.mjs';
42
42
  import { readJournal, validateJournal, pairSpawns, tail } from './journal.mjs';
43
43
  import {
44
+ boardOf,
44
45
  checkFile,
46
+ fold,
45
47
  inline,
46
48
  naturalCompare,
47
49
  renderProjections,
@@ -161,6 +163,9 @@ export const SEVERITY_BY_CODE = Object.freeze(
161
163
  'spawn-duplicate': 'warning',
162
164
  'spawn-orphan-report': 'warning',
163
165
  'agent-name-unusable': 'warning',
166
+ // operator asks
167
+ 'ask-open': 'info',
168
+ 'ask-stale': 'warning',
164
169
  // leases
165
170
  'lease-open': 'info',
166
171
  'lease-orphan': 'warning',
@@ -512,6 +517,7 @@ function checkInitiative(stateDir, name, { now, staleHours }) {
512
517
  guard('journal integrity', () => journalIntegrity(journalPath, at, read));
513
518
  guard('one initiative per file', () => initiativeScope(journalPath, at, name, events));
514
519
  guard('open spawns', () => spawnFindings(journalPath, at, name, events, reference, staleHours));
520
+ guard('operator asks', () => askFindings(journalPath, at, read, reference));
515
521
  guard('leases', () => leaseFindings(journalPath, at, events, reference));
516
522
  guard('projections', () => projectionFindings(journalPath, dir, at, read));
517
523
 
@@ -760,6 +766,53 @@ function spawnFindings(journalPath, at, dirName, events, reference, staleHours)
760
766
  return findings;
761
767
  }
762
768
 
769
+ /**
770
+ * How long an operator ask may stand before it is a finding. A module
771
+ * constant, not a config key: the threshold is measured in journal time and
772
+ * nobody has yet needed a different one.
773
+ */
774
+ export const DEFAULT_ASK_STALE_HOURS = 72;
775
+
776
+ /**
777
+ * Questions waiting on a human. The queue is `boardOf`'s — the same one
778
+ * BOARD.md prints and `answer.mjs` closes — so doctor cannot disagree with
779
+ * the board about what is still open (ADR-18).
780
+ *
781
+ * Same reference clock as spawns: the journal's own last event unless `--now`
782
+ * says otherwise, which is what the SessionStart probe passes it for.
783
+ */
784
+ function askFindings(journalPath, at, read, reference) {
785
+ const findings = [];
786
+ const { asks } = boardOf(fold(read));
787
+ // The trailer is a `#` comment, not a parenthetical: a fix string is pasted
788
+ // into a shell verbatim, and `(…)` is a subshell whose parse fails before
789
+ // anything runs — the operator gets a syntax error instead of the sheet.
790
+ const answerHint =
791
+ `node scripts/answer.mjs render --dir ${sq(dirname(dirname(dirname(resolve(journalPath)))))}` +
792
+ ' # fill the answer: lines, then apply';
793
+ for (const ask of [...asks].sort((a, b) => naturalCompare(String(a.kind), String(b.kind)))) {
794
+ const question = ask.question == null ? '' : ` — "${show(ask.question)}"`;
795
+ const waited = reference === null || ask.since == null ? null : hoursBetween(String(ask.since), reference);
796
+ if (waited !== null && waited >= DEFAULT_ASK_STALE_HOURS) {
797
+ findings.push(
798
+ finding(
799
+ 'ask-stale',
800
+ at,
801
+ `${show(ask.kind)} has been waiting on the operator for ${waited.toFixed(1)} h of journal time ` +
802
+ `(asked ${show(ask.since)}, journal now at ${show(reference)}; threshold ${DEFAULT_ASK_STALE_HOURS} h)` +
803
+ question,
804
+ answerHint,
805
+ ),
806
+ );
807
+ continue;
808
+ }
809
+ findings.push(
810
+ finding('ask-open', at, `${show(ask.kind)} is waiting on the operator (asked ${show(ask.since)})${question}`, answerHint),
811
+ );
812
+ }
813
+ return findings;
814
+ }
815
+
763
816
  const EXPIRY_KEYS = Object.freeze(['expires', 'expires_at', 'until']);
764
817
 
765
818
  function leaseFindings(journalPath, at, events, reference) {
@@ -1228,6 +1281,13 @@ export const OVERNIGHT_RUNTIME_FILES = Object.freeze([
1228
1281
  'usage.json',
1229
1282
  ]);
1230
1283
 
1284
+ /**
1285
+ * The ask queue's own two files at state/ level: the sheet the operator edits
1286
+ * and the session record the SessionStart probe writes. Repo-global by
1287
+ * nature — the sheet spans every initiative — so they cannot live inside one.
1288
+ */
1289
+ export const ASK_QUEUE_FILES = Object.freeze(['ANSWERS.md', 'conductor.json']);
1290
+
1231
1291
  /**
1232
1292
  * Overnight-mode consistency: the pause marker, the resume watcher, and the
1233
1293
  * telemetry a configured gate depends on. Deterministic: staleness questions
@@ -1450,6 +1510,7 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1450
1510
  // gitignored) and are checked by overnightFindings instead.
1451
1511
  if (OVERNIGHT_RUNTIME_FILES.includes(name)) continue;
1452
1512
  if (CROSS_BOARD_FILES.includes(name)) continue; // generated by board.mjs at this level, by design
1513
+ if (ASK_QUEUE_FILES.includes(name)) continue; // the sheet and the session record, by design
1453
1514
  findings.push(
1454
1515
  finding(
1455
1516
  'state-stray-file',
@@ -17,6 +17,7 @@
17
17
  * node journal.mjs tail <file> # last checkpoint + open items
18
18
  * node journal.mjs open-spawns <file> # agents with no report or review yet
19
19
  * node journal.mjs close-spawn <file> <init> <agent> --reason R [--verdict V]
20
+ * node journal.mjs ask <file> <init> --question Q [--default D] [--ticket T]
20
21
  * Exit: 0 ok · 1 validation/finding error · 2 usage/IO error
21
22
  */
22
23
  import {
@@ -104,7 +105,17 @@ export const DATA_ENUMS = Object.freeze({
104
105
  * material belongs in NOTES.md with a reference here. `validateJournal`
105
106
  * reports historical oversizes as warnings only (no retroactive errors).
106
107
  */
107
- export const CAPPED_DATA_KEYS = Object.freeze({ detail: 2000, claim: 2000, proof: 2000 });
108
+ export const CAPPED_DATA_KEYS = Object.freeze({
109
+ detail: 2000,
110
+ claim: 2000,
111
+ proof: 2000,
112
+ // The ask fields. They reach BOARD.md, board.html and the answer sheet, so
113
+ // an uncapped one is a document-sized cell in three artefacts at once.
114
+ question: 2000,
115
+ recommendation: 2000,
116
+ default: 2000,
117
+ answer: 2000,
118
+ });
108
119
 
109
120
  /**
110
121
  * A journal-derived value on its way into a HUMAN-READABLE MESSAGE.
@@ -580,6 +591,55 @@ export function closeSpawn(file, { init, agent, actor = 'conductor', verdict = '
580
591
  });
581
592
  }
582
593
 
594
+ // ------------------------------------------------------- operator asks
595
+
596
+ /**
597
+ * An ask is a `gate` whose `kind` IS its id. One kind, one question, forever.
598
+ *
599
+ * Anchored on purpose: `fold()` keys gates by kind with last-write-wins, so a
600
+ * kind that merely CONTAINS `Q-<n>` (`usage-limit-Q-99`) must not raise the
601
+ * next id — it would leave the true maximum free and the next ask would
602
+ * overwrite an older question on that Map with nothing objecting.
603
+ */
604
+ export const ASK_KIND_RE = /^Q-(\d+)$/;
605
+
606
+ /** Pure: the next free ask id over a journal's own gate kinds. */
607
+ export function nextAskKind(events) {
608
+ let max = 0;
609
+ for (const e of events) {
610
+ if (e?.ev !== 'gate') continue;
611
+ const m = ASK_KIND_RE.exec(String(e?.data?.kind ?? ''));
612
+ if (m) max = Math.max(max, Number(m[1]));
613
+ }
614
+ return `Q-${max + 1}`;
615
+ }
616
+
617
+ /**
618
+ * Raise an operator ask: mint the id and append the gate under ONE lock.
619
+ *
620
+ * The id is NOT `data.id` and is not issued by `ID_ISSUED_FOR`: it is the gate
621
+ * `kind`, so no new event type exists and the closed set stays as it is. Two
622
+ * agents asking in the same millisecond get two ids because the read, the
623
+ * mint and the write share this lock; minting outside it gives them one, and
624
+ * the second question then replaces the first on the fold's kind-keyed Map —
625
+ * silent loss, in an append-only file that can never be corrected.
626
+ */
627
+ export function raiseAsk(file, { init, actor = 'conductor', question, recommendation = null, default: dflt = null, ticket = null }) {
628
+ if (typeof question !== 'string' || question.trim().length === 0) {
629
+ throw new Error('ask requires a non-empty --question (what is the operator being asked?)');
630
+ }
631
+ mkdirSync(dirname(resolve(file)), { recursive: true });
632
+ return withLock(file, () => {
633
+ const snapshot = readJournal(file);
634
+ const data = { kind: nextAskKind(snapshot.events), result: 'WAITING_ON_OPERATOR' };
635
+ if (ticket != null) data.ticket = ticket;
636
+ data.question = question;
637
+ if (recommendation != null) data.recommendation = recommendation;
638
+ if (dflt != null) data.default = dflt;
639
+ return appendUnderLock(file, { ev: 'gate', init, actor, data }, snapshot);
640
+ });
641
+ }
642
+
583
643
  /**
584
644
  * Read all events. A truncated (crash-interrupted) FINAL line is discarded
585
645
  * and reported via `truncatedTail`; a malformed line anywhere else is a
@@ -753,6 +813,7 @@ const CMD_FLAGS = {
753
813
  tail: [],
754
814
  'open-spawns': [],
755
815
  'close-spawn': ['actor', 'verdict', 'reason'],
816
+ ask: ['actor', 'ticket', 'question', 'recommendation', 'default'],
756
817
  };
757
818
 
758
819
  /**
@@ -835,6 +896,22 @@ function main() {
835
896
  console.log(emit(openSpawns(file), 2));
836
897
  return;
837
898
  }
899
+ case 'ask': {
900
+ const [file, init] = rest;
901
+ if (!file || !init) throw new UsageError();
902
+ // a missing --question gets raiseAsk's specific message, not a usage
903
+ // dump: the flag is the whole content of the command.
904
+ const written = raiseAsk(file, {
905
+ init,
906
+ actor: flags.actor ?? 'conductor',
907
+ question: flags.question ?? '',
908
+ recommendation: flags.recommendation ?? null,
909
+ default: flags.default ?? null,
910
+ ticket: flags.ticket ?? null,
911
+ });
912
+ console.log(emit(written));
913
+ return;
914
+ }
838
915
  case 'close-spawn': {
839
916
  const [file, init, agent] = rest;
840
917
  if (!file || !init || !agent) throw new UsageError();
@@ -858,6 +935,7 @@ function main() {
858
935
  ' journal.mjs validate <file> · next-id <file> <prefix> · tail <file>\n' +
859
936
  ' journal.mjs open-spawns <file>\n' +
860
937
  ' journal.mjs close-spawn <file> <init> <agent> --reason R [--verdict V] [--actor A]\n' +
938
+ ' journal.mjs ask <file> <init> --question Q [--recommendation R] [--default D] [--ticket T] [--actor A]\n' +
861
939
  '\n' +
862
940
  // The `--data` contract varies per event and lived only in a table no
863
941
  // command printed. A field run discovered it by rejection, one failed
@@ -58,6 +58,7 @@ import { realpathSync } from 'node:fs';
58
58
  import { fileURLToPath } from 'node:url';
59
59
  import { checkStop } from './stop-check.mjs';
60
60
  import { readJournal } from './journal.mjs';
61
+ import { GATE_PASS } from './project.mjs';
61
62
  import { withKeepAwake } from './keepawake.mjs';
62
63
  import { limitsOf } from './schema.mjs';
63
64
  import { parse } from './yaml-lite.mjs';
@@ -110,8 +111,9 @@ export function skipReason({ stopped, markerExists, journalEvents, pausedAtIso }
110
111
  // Only this pause's gate events count: a gate closed before pausedAt
111
112
  // belongs to an earlier cycle and says nothing about the current one.
112
113
  if (e?.ev === 'gate' && e?.data?.kind === 'usage-limit' && ts > pausedAt) {
113
- const result = String(e?.data?.result ?? '').toLowerCase();
114
- gateOpen = !['pass', 'passed', 'ok', 'green', 'approved', 'closed', 'answered'].includes(result);
114
+ // The pass set is project.mjs's, imported: a copy here would let the
115
+ // watcher and the projection disagree about whether a gate is closed.
116
+ gateOpen = !GATE_PASS.has(String(e?.data?.result ?? '').toLowerCase());
115
117
  }
116
118
  if (e?.ev === 'checkpoint' && ts > pausedAt && e?.data?.phase !== 'usage-limit-pause') laterCheckpoint = true;
117
119
  }
@@ -41,8 +41,15 @@ const GENERATED_HEADER =
41
41
  '<!-- GENERATED by tyran scripts/project.mjs - DO NOT EDIT. Source of truth: journal.jsonl -->\n' +
42
42
  '<!-- Regenerate: node scripts/project.mjs <journal.jsonl> --out-dir <dir> -->\n';
43
43
 
44
- /** Gate results that count as closed. Anything else keeps the gate OPEN. */
45
- const GATE_PASS = new Set(['pass', 'passed', 'ok', 'green', 'approved', 'closed', 'answered']);
44
+ /**
45
+ * Gate results that count as closed. Anything else keeps the gate OPEN.
46
+ *
47
+ * Exported because `overnight.skipReason` needs the same seven strings, and a
48
+ * hand-copied literal there is a second spelling of one rule (ADR-21): adding
49
+ * a pass result here while the watcher kept the old list would make it resume
50
+ * a session whose gate this module already considers closed.
51
+ */
52
+ export const GATE_PASS = new Set(['pass', 'passed', 'ok', 'green', 'approved', 'closed', 'answered']);
46
53
 
47
54
  /** A gate result that means "a human owes an answer" — the board's queue. */
48
55
  export const WAITING_RE = /^waiting[_-]?on[_-]?(operator|owner|human)$/i;
@@ -961,12 +968,17 @@ function renderState(state) {
961
968
  );
962
969
 
963
970
  parts.push('\n## Open gates\n\n');
971
+ // The Question column is what a resumed conductor reads. Without it this
972
+ // table says THAT the initiative is waiting on the operator and never what
973
+ // it asked, which costs a re-litigation of the question after every
974
+ // compaction. `fold` already carries it; ordinary gates render an em dash.
964
975
  parts.push(
965
976
  table(
966
- ['Gate', 'Latest result', 'At', 'Evidence'],
977
+ ['Gate', 'Latest result', 'Question', 'At', 'Evidence'],
967
978
  sortByKey(state.openGates, (g) => g.kind).map((g) => [
968
979
  inline(g.kind),
969
980
  inline(g.result),
981
+ inline(g.question),
970
982
  inline(g.ts),
971
983
  inline(g.evidence),
972
984
  ]),
@@ -595,6 +595,12 @@ export const STATE_GITIGNORE_LINES = Object.freeze([
595
595
  'state/resume.json',
596
596
  'state/resume.log',
597
597
  'state/usage.json',
598
+ // The ask queue's two runtime files: a session id and a pid that mean
599
+ // nothing in another clone, and a sheet whose answers already live in the
600
+ // journal — committing either makes every parallel merge conflict on state
601
+ // that was stale the moment it was written.
602
+ 'state/conductor.json',
603
+ 'state/ANSWERS.md',
598
604
  ]);
599
605
  const STATE_GITIGNORE_BODY =
600
606
  '# Runtime files, never history. Leases record who holds a worktree or a\n' +
package/scripts/tiers.mjs CHANGED
@@ -91,6 +91,12 @@ export const ROLE_TIERS = Object.freeze({
91
91
  acceptance: { eco: 'deep', balanced: 'top', full: 'top' },
92
92
  retro: { eco: 'work', balanced: 'work', full: 'deep' },
93
93
  bookkeeping: { eco: 'cheap', balanced: 'cheap', full: 'cheap' },
94
+ // ADVISORY. The conductor is the operator's own session, and no plugin can
95
+ // change a running session's model — so this row records the choice in the
96
+ // one file where model names may live and the CLI says out loud, on stderr,
97
+ // that it cannot enforce it. A row that silently did nothing would be worse
98
+ // than no row: it would read as configuration.
99
+ conductor: { eco: 'deep', balanced: 'top', full: 'top' },
94
100
  });
95
101
 
96
102
  /**
@@ -104,6 +110,9 @@ export const ROLE_TIERS = Object.freeze({
104
110
  export const ROLE_FLOOR = Object.freeze({
105
111
  'security-review': 'top',
106
112
  arbitration: 'top',
113
+ // One weak coordinator spends a whole team's budget on the wrong plan, and
114
+ // the floor is what `--profile eco --risk low` cannot shift out of.
115
+ conductor: 'deep',
107
116
  });
108
117
 
109
118
  export const ROLES = Object.freeze(Object.keys(ROLE_TIERS));
@@ -286,6 +295,14 @@ function main() {
286
295
  `"${escapeInvisible(role)}" has a floor that cannot be lowered`,
287
296
  );
288
297
  }
298
+ // STDERR, like every other note here: stdout is the resolved value and the
299
+ // skill parses it.
300
+ if (role === 'conductor') {
301
+ console.error(
302
+ 'tiers: `conductor` is ADVISORY. The conductor is your own session and no plugin can ' +
303
+ 'change its model mid-flight — this is the tier your config says it should be running.',
304
+ );
305
+ }
289
306
  console.error(`tiers: ${role} @ ${profile}/${risk} -> ${resolved.tier} · effort ${resolved.effort}`);
290
307
  if (field === 'json') console.log(JSON.stringify(resolved));
291
308
  else if (Object.hasOwn(resolved, field)) console.log(resolved[field]);
@@ -283,12 +283,33 @@ open one.
283
283
  (XL); product, visual and irreversible decisions, put in plain language
284
284
  with your recommendation; anything hard to undo or visible outside the
285
285
  repo. **"Shall I continue?" is forbidden.**
286
- **Every question to the operator lands in the journal before (or as) you
287
- ask it**: a `gate` event, `result: WAITING_ON_OPERATOR`, `data` carrying
288
- `question`, `recommendation`, `default` and `ticket` when it has one — a
289
- question that lives only in chat has to be re-litigated after every
290
- compaction. When answered, append the same `kind` with `result: answered`
291
- plus a `decision` recording the answer in the operator's words.
286
+ **Every question to the operator is raised with one command, and the
287
+ command mints its id:**
288
+ `node ${CLAUDE_PLUGIN_ROOT}/scripts/journal.mjs ask <abs-journal> <init>
289
+ --question '...' --recommendation '...' --default '...' [--ticket T-n]`.
290
+ It appends the `gate` — `kind: Q-<n>`, `result: WAITING_ON_OPERATOR` —
291
+ under the journal's write lock, so two agents asking in the same moment get
292
+ two ids rather than one. A question that lives only in chat has to be
293
+ re-litigated after every compaction; a question written as a bare `kind` of
294
+ your own invention collides with the next one that shares it, and the older
295
+ question is lost with nothing objecting anywhere.
296
+ - **Always record a `default`** — what ships if nobody ever answers. It is
297
+ what the operator accepts by leaving an answer blank, and it is the only
298
+ reason a queue of fifteen questions takes ten minutes instead of an hour.
299
+ An ask with no default is a question the operator must stop and think
300
+ about; spend that budget deliberately.
301
+ - **Do not park an asked ticket.** An ask that names a ticket already puts
302
+ it in the board's `waiting-operator` lane. A `ticket.status` override on
303
+ top of it **overrules** that lane and hides the question's own ticket —
304
+ measured in our own demo fixture, which showed `waiting-operator (0)`
305
+ while a question was open.
306
+ - **Never spin on an open ask.** Raise it, take the next schedulable
307
+ ticket, and let the operator answer in their own time. You do not close
308
+ it: `node ${CLAUDE_PLUGIN_ROOT}/scripts/answer.mjs apply` writes the
309
+ `decision` and the closing `gate` in the operator's own words. When the
310
+ operator answers you in chat instead, append that pair yourself — same
311
+ `kind`, `result: answered`, plus a `decision` whose text begins
312
+ `Q-<n>: ` — and say in your next report that you did.
292
313
  **Check the brake before every spawn and every merge:**
293
314
  `node ${CLAUDE_PLUGIN_ROOT}/scripts/stop-check.mjs` — exit 1 means the
294
315
  operator created `.tyran/STOP`. Halt, report where you got to, and do not