@jjanczur/tyran 0.1.11 → 0.1.13

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.
@@ -29,18 +29,25 @@ import {
29
29
  import { dirname, join, resolve } from 'node:path';
30
30
  import { fileURLToPath } from 'node:url';
31
31
  import { readJournal, pairSpawns } from './journal.mjs';
32
- import { escapeInvisible } from './invisible.mjs';
32
+ import { escapeInvisible, jsonEscapeInvisible } from './invisible.mjs';
33
33
 
34
34
  /** Projection file names. Both are fully generated — never hand-edited. */
35
35
  export const STATE_FILE = 'STATE.md';
36
36
  export const PROGRESS_FILE = 'PROGRESS.md';
37
+ export const BOARD_FILE = 'BOARD.md';
38
+ export const BOARD_JSON_FILE = 'board.json';
37
39
 
38
40
  const GENERATED_HEADER =
39
41
  '<!-- GENERATED by tyran scripts/project.mjs - DO NOT EDIT. Source of truth: journal.jsonl -->\n' +
40
42
  '<!-- Regenerate: node scripts/project.mjs <journal.jsonl> --out-dir <dir> -->\n';
41
43
 
42
44
  /** Gate results that count as closed. Anything else keeps the gate OPEN. */
43
- const GATE_PASS = new Set(['pass', 'passed', 'ok', 'green', 'approved', 'closed']);
45
+ const GATE_PASS = new Set(['pass', 'passed', 'ok', 'green', 'approved', 'closed', 'answered']);
46
+
47
+ /** A gate result that means "a human owes an answer" — the board's queue. */
48
+ export const WAITING_RE = /^waiting[_-]?on[_-]?(operator|owner|human)$/i;
49
+ /** A gate kind that means "paused on the subscription window" (overnight mode). */
50
+ export const PAUSED_RE = /usage[-_]?limit/i;
44
51
 
45
52
  /** Longest inline value rendered in a cell or list item, in codepoints. */
46
53
  const MAX_CELL = 160;
@@ -260,6 +267,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
260
267
  findings: [],
261
268
  // `ticket.status` events naming a ticket no other event mentions
262
269
  unknownOverrides: [],
270
+ unknownErrorTickets: [],
263
271
  };
264
272
 
265
273
  /**
@@ -310,6 +318,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
310
318
  review: null,
311
319
  merge: null,
312
320
  override: null,
321
+ error: null,
313
322
  lastTs: seenTs ?? null,
314
323
  });
315
324
  }
@@ -411,6 +420,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
411
420
  const t = ticketOf(data.ticket, ts);
412
421
  t.report = { verdict: data.verdict ?? null, ts, by: data.agent ?? actor };
413
422
  t.override = null; // a lifecycle event outranks a hand-set lane
423
+ t.error = null;
414
424
  }
415
425
  if (data.agent != null) closeAgent(state, data.agent);
416
426
  break;
@@ -471,6 +481,13 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
471
481
  result: data.result ?? null,
472
482
  ts,
473
483
  evidence: data.evidence_ref ?? data.evidence ?? null,
484
+ // extra data keys are legal on append; the ask fields ride along so
485
+ // the board's waiting-operator queue can render the question with
486
+ // its recommendation and default (absent on ordinary gates).
487
+ ticket: data.ticket ?? null,
488
+ question: data.question ?? null,
489
+ recommendation: data.recommendation ?? null,
490
+ default: data.default ?? null,
474
491
  count: (prev?.count ?? 0) + 1,
475
492
  });
476
493
  break;
@@ -482,6 +499,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
482
499
  const t = ticketOf(data.ticket ?? '(no ticket)', ts);
483
500
  t.review = { verdict: data.verdict ?? null, by: data.by ?? actor, ts };
484
501
  t.override = null;
502
+ t.error = null;
485
503
  clearBlockagesOn(state, t.id);
486
504
  // The review is the REVIEWER's completion event, as a report is the
487
505
  // implementer's: pairSpawns closes the reviewer's spawn on `data.by`,
@@ -495,6 +513,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
495
513
  const t = ticketOf(data.ticket ?? '(no ticket)', ts);
496
514
  t.merge = { sha: data.sha ?? null, mode: data.mode ?? null, ts };
497
515
  t.override = null;
516
+ t.error = null;
498
517
  clearBlockagesOn(state, t.id);
499
518
  break;
500
519
  }
@@ -520,9 +539,25 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
520
539
  case 'retro.entry':
521
540
  state.retro.push({ kind: data.kind ?? null, target: data.target ?? null, confidence: data.confidence ?? null, ts });
522
541
  break;
523
- case 'error':
542
+ case 'error': {
524
543
  state.errors.push({ class: data.class ?? null, detail: data.detail ?? null, ts, actor });
544
+ // `data.ticket` is optional metadata on an error, so a typo here is a
545
+ // typo nothing rejected at append. Binding it to a ticket the journal
546
+ // has never seen would MINT that ticket, and a minted ticket is one
547
+ // the denominator counts and no `merge` can ever close — the headline
548
+ // percent falls and never recovers. Same rule as `ticket.status`
549
+ // above, for the same reason; the error itself is still rendered in
550
+ // the Errors table either way, so nothing is lost by not binding it.
551
+ if (data.ticket != null) {
552
+ const key = String(data.ticket);
553
+ if (state.tickets.has(key)) {
554
+ ticketOf(key, ts).error = { class: data.class ?? null, detail: data.detail ?? null, ts };
555
+ } else {
556
+ state.unknownErrorTickets.push({ ticket: key, ts });
557
+ }
558
+ }
525
559
  break;
560
+ }
526
561
  default:
527
562
  state.unknownTypes.set(ev, (state.unknownTypes.get(ev) ?? 0) + 1);
528
563
  }
@@ -552,6 +587,215 @@ export function ticketStatus(t) {
552
587
  return 'open';
553
588
  }
554
589
 
590
+ // ------------------------------------------------------------------ board
591
+
592
+ /** Lane order, strongest verdicts first. The board renders one section per
593
+ * lane; a ticket lands in exactly ONE, by the precedence in `boardOf`. */
594
+ export const LANES = Object.freeze([
595
+ 'waiting-operator',
596
+ 'paused-limit',
597
+ 'blocked',
598
+ 'changes-requested',
599
+ 'in-review',
600
+ 'in-progress',
601
+ 'ready',
602
+ 'backlog',
603
+ 'parked',
604
+ 'done',
605
+ ]);
606
+
607
+ const APPROVING_RE = /^approv|^lgtm$|^pass/i;
608
+
609
+ /**
610
+ * The kanban view of a folded state. PURE and clock-free: every timestamp is
611
+ * copied from an event; "how old" is a question only the HTML viewer answers,
612
+ * client-side. A ticket is in exactly one lane, decided strongest-first:
613
+ *
614
+ * done (merge) > parked/waiting-operator/blocked (override) > blocked
615
+ * (open blockage or error) > paused-limit (an open usage-limit gate AND the
616
+ * ticket would otherwise be in progress) > changes-requested > in-review >
617
+ * in-progress > ready (all deps merged; an UNKNOWN dep counts unmet — a
618
+ * typo must refuse to schedule, not schedule) > backlog.
619
+ */
620
+ export function boardOf(state) {
621
+ const lanes = new Map(LANES.map((lane) => [lane, []]));
622
+ const runningByTicket = new Map();
623
+ for (const a of state.agents) {
624
+ if (a.status === 'running' && a.ticket != null) {
625
+ runningByTicket.set(String(a.ticket), [...(runningByTicket.get(String(a.ticket)) ?? []), a.agent]);
626
+ }
627
+ }
628
+ const mergedIds = new Set(state.ticketList.filter((t) => t.merge !== null).map((t) => t.id));
629
+ const knownIds = new Set(state.ticketList.map((t) => t.id));
630
+ const pausedGate = [...state.gates.values()].find(
631
+ (g) => PAUSED_RE.test(g.kind) && !GATE_PASS.has(String(g.result ?? '').toLowerCase()),
632
+ ) ?? null;
633
+
634
+ const asks = [];
635
+ for (const g of state.openGates) {
636
+ if (WAITING_RE.test(String(g.result ?? ''))) {
637
+ asks.push({
638
+ kind: g.kind,
639
+ ticket: g.ticket ?? null,
640
+ question: g.question ?? null,
641
+ recommendation: g.recommendation ?? null,
642
+ default: g.default ?? null,
643
+ since: g.ts ?? null,
644
+ });
645
+ }
646
+ }
647
+ const askTickets = new Set(asks.filter((a) => a.ticket != null).map((a) => String(a.ticket)));
648
+ // Blockages are keyed by AGENT (one ticket can block several agents), so a
649
+ // ticket's blockage is found by scanning for its id, never by lookup.
650
+ const blockageOn = (ticketId) => {
651
+ for (const b of state.blockages.values()) if (b.ticket != null && String(b.ticket) === ticketId) return b;
652
+ return null;
653
+ };
654
+
655
+ for (const t of state.ticketList) {
656
+ const laneOf = () => {
657
+ if (t.merge) return 'done';
658
+ if (t.override?.column && LANES.includes(t.override.column)) return t.override.column;
659
+ if (askTickets.has(t.id)) return 'waiting-operator';
660
+ if (blockageOn(t.id) !== null || t.error !== null) return 'blocked';
661
+ const running = runningByTicket.get(t.id) ?? [];
662
+ if (pausedGate !== null && running.length > 0) return 'paused-limit';
663
+ if (t.review && !APPROVING_RE.test(String(t.review.verdict ?? ''))) return 'changes-requested';
664
+ if (t.review || t.report) return 'in-review';
665
+ if (running.length > 0) return 'in-progress';
666
+ const deps = Array.isArray(t.deps) ? t.deps.map(String) : [];
667
+ const unmet = deps.filter((d) => !mergedIds.has(d));
668
+ const unknown = deps.filter((d) => !knownIds.has(d));
669
+ if (deps.length === 0 || (unmet.length === 0 && unknown.length === 0)) return 'ready';
670
+ return 'backlog';
671
+ };
672
+ const lane = laneOf();
673
+ const deps = Array.isArray(t.deps) ? t.deps.map(String) : [];
674
+ const annotations = [];
675
+ if (lane === 'in-review' && t.review && APPROVING_RE.test(String(t.review.verdict ?? ''))) {
676
+ annotations.push('approved, awaiting merge');
677
+ }
678
+ if (lane === 'blocked') {
679
+ const b = blockageOn(t.id);
680
+ if (b) annotations.push(b.detail ?? 'blocked');
681
+ else if (t.error) annotations.push(`error: ${t.error.class ?? 'unknown'}`);
682
+ }
683
+ if (t.override) annotations.push(t.override.reason ?? 'set by ticket.status');
684
+ if (lane === 'backlog') {
685
+ for (const d of deps.filter((x) => !knownIds.has(x))) annotations.push(`dep ${d} (unknown)`);
686
+ }
687
+ lanes.get(lane).push({
688
+ id: t.id,
689
+ title: t.title,
690
+ agents: runningByTicket.get(t.id) ?? [],
691
+ since: t.lastTs,
692
+ annotation: annotations.length > 0 ? annotations.join(' · ') : null,
693
+ });
694
+ }
695
+
696
+ const agents = state.agents
697
+ .filter((a) => a.status === 'running')
698
+ .map((a) => {
699
+ const signal = state.progressByAgent.get(a.agent) ?? null;
700
+ return {
701
+ agent: a.agent,
702
+ role: a.role,
703
+ ticket: a.ticket,
704
+ state: signal?.state ?? 'running',
705
+ detail: signal?.detail ?? null,
706
+ next: signal?.next ?? null,
707
+ last_signal: signal?.ts ?? a.spawnTs,
708
+ };
709
+ });
710
+
711
+ return {
712
+ lanes,
713
+ asks,
714
+ agents,
715
+ paused: pausedGate === null
716
+ ? null
717
+ : { kind: pausedGate.kind, result: pausedGate.result, since: pausedGate.ts ?? null },
718
+ };
719
+ }
720
+
721
+ /** BOARD.md — the waiting queue first, then the agent strip, then the lanes. */
722
+ export function renderBoard(state, board = boardOf(state)) {
723
+ const parts = [GENERATED_HEADER, `# BOARD — ${inline(state.initiatives)}\n\n`];
724
+ parts.push(`**Progress:** ${progressLine(state)}\n`);
725
+ if (board.paused !== null) {
726
+ parts.push(`\n**PAUSED** on gate ${inline(board.paused.kind)} (${inline(board.paused.result)}) since ${inline(board.paused.since)}\n`);
727
+ }
728
+
729
+ parts.push('\n## Waiting on operator\n\n');
730
+ parts.push(
731
+ table(
732
+ ['Question', 'Recommendation', 'Default', 'Ticket', 'Gate', 'Since'],
733
+ board.asks.map((a) => [
734
+ inline(a.question ?? '(no question recorded)'),
735
+ inline(a.recommendation),
736
+ inline(a.default),
737
+ inline(a.ticket),
738
+ inline(a.kind),
739
+ inline(a.since),
740
+ ]),
741
+ ),
742
+ );
743
+
744
+ parts.push('\n## Agents\n\n');
745
+ parts.push(
746
+ table(
747
+ ['Agent', 'Role', 'Ticket', 'State', 'Detail', 'Last signal'],
748
+ sortByKey(board.agents, (a) => a.agent).map((a) => [
749
+ inline(a.agent),
750
+ inline(a.role),
751
+ inline(a.ticket),
752
+ inline(a.state),
753
+ inline(a.detail),
754
+ inline(a.last_signal),
755
+ ]),
756
+ ),
757
+ );
758
+
759
+ for (const lane of LANES) {
760
+ const cards = board.lanes.get(lane);
761
+ parts.push(`\n## ${lane} (${cards.length})\n\n`);
762
+ parts.push(
763
+ list(
764
+ cards.map(
765
+ (c) =>
766
+ `\`${inline(c.id)}\`${c.title ? ` — ${inline(c.title)}` : ''}` +
767
+ `${c.agents.length > 0 ? ` — ${inline(c.agents)}` : ''}` +
768
+ `${c.annotation ? ` _(${inline(c.annotation)})_` : ''}`,
769
+ ),
770
+ ),
771
+ );
772
+ }
773
+ return parts.join('');
774
+ }
775
+
776
+ /**
777
+ * board.json, schema 1. Deterministic: fixed key insertion order, timestamps
778
+ * verbatim from events, invisibles escaped as \uXXXX (round-trips through
779
+ * JSON.parse) — silent removal is the one thing this layer refuses to do.
780
+ */
781
+ export function boardJson(state, board = boardOf(state)) {
782
+ const payload = {
783
+ schema: 1,
784
+ initiative: state.initiatives.length === 1 ? state.initiatives[0] : state.initiatives,
785
+ progress: {
786
+ percent: state.percent,
787
+ merged: state.merged,
788
+ tickets: state.ticketList.length,
789
+ phase: state.checkpoint?.phase ?? null,
790
+ },
791
+ paused: board.paused,
792
+ asks: board.asks,
793
+ agents: sortByKey(board.agents, (a) => a.agent),
794
+ lanes: Object.fromEntries(LANES.map((lane) => [lane, board.lanes.get(lane)])),
795
+ };
796
+ return jsonEscapeInvisible(JSON.stringify(payload, null, 2)) + '\n';
797
+ }
798
+
555
799
  /** The one-line progress banner; also the H1 of PROGRESS.md. */
556
800
  export function progressLine(state) {
557
801
  const phase = state.checkpoint?.phase ?? null;
@@ -594,6 +838,9 @@ export function warnings(state) {
594
838
  for (const { ticket } of state.unknownOverrides) {
595
839
  out.push(`ticket.status for unknown ticket "${inlinePlain(ticket)}" — ignored (an override never invents a ticket)`);
596
840
  }
841
+ for (const { ticket } of state.unknownErrorTickets) {
842
+ out.push(`error names unknown ticket "${inlinePlain(ticket)}" — the error is recorded, but not bound to a ticket`);
843
+ }
597
844
  if (state.initiatives.length > 1) {
598
845
  out.push(
599
846
  `journal mixes ${state.initiatives.length} initiatives: ${state.initiatives.map((i) => inlinePlain(i)).join(', ')}`,
@@ -872,10 +1119,16 @@ function renderProgress(state) {
872
1119
  */
873
1120
  export function renderProjections(readResult) {
874
1121
  const state = fold(readResult);
1122
+ const board = boardOf(state);
875
1123
  return {
876
1124
  state,
877
1125
  warnings: warnings(state),
878
- files: { [STATE_FILE]: renderState(state), [PROGRESS_FILE]: renderProgress(state) },
1126
+ files: {
1127
+ [STATE_FILE]: renderState(state),
1128
+ [PROGRESS_FILE]: renderProgress(state),
1129
+ [BOARD_FILE]: renderBoard(state, board),
1130
+ [BOARD_JSON_FILE]: boardJson(state, board),
1131
+ },
879
1132
  };
880
1133
  }
881
1134
 
@@ -138,8 +138,11 @@ open one.
138
138
  `.tyran/state/<initiative>/journal.jsonl`:
139
139
  `node ${CLAUDE_PLUGIN_ROOT}/scripts/journal.mjs append <journal> <event>
140
140
  <initiative> --actor conductor --data '{...}'`. Regenerate the readable
141
- views with `scripts/project.mjs`; `STATE.md` and `PROGRESS.md` are
142
- GENERATED — never hand-edit them. Authored, alongside the journal:
141
+ views with `scripts/project.mjs` at every merge — `BOARD.md` and
142
+ `board.json` are part of the set — and the cross-initiative board with
143
+ `scripts/board.mjs`; every one of them is GENERATED — never hand-edit.
144
+ Moving a ticket on the board IS appending an event; there is no other way.
145
+ Authored, alongside the journal:
143
146
  `PLAN.md` (decomposition plus the **manifest of
144
147
  shared zones**) and `NOTES.md` (side observations, defaults you adopted,
145
148
  and **signals about the PROCESS itself**: what slowed the work, what the
@@ -155,9 +158,14 @@ open one.
155
158
  away from having never happened.
156
159
  - **IDs never come from memory** — omit `id` from a `decision` event's
157
160
  `--data` (or leave it empty) and `append` issues the next one itself.
161
+ `append` issues it under the same lock it writes with, so two concurrent
162
+ appends can no longer be handed one number — prefer omitting `id`
163
+ wherever you do not need the value beforehand.
158
164
  `journal.mjs next-id <file> <prefix>` exists to preview a value ahead of
159
165
  time (prefix `D` → `D-7`); it is not a required preliminary step before
160
- `append`. After a compaction, memory hands out the same number twice.
166
+ `append`, and it holds nothing — an id read there and appended later
167
+ still loses to any writer that appended in between. After a compaction,
168
+ memory hands out the same number twice.
161
169
  - **Authorizations and stops are `decision` events.** What you may do
162
170
  without asking, and the CLOSED list of situations where you halt, live
163
171
  in the journal with the date and the operator's own words. Outside that
@@ -1,5 +1,5 @@
1
1
  ---
2
- description: Where is the work right now. Regenerates STATE.md and PROGRESS.md from the journal and answers with the progress line, the agents still running, the open gates and the resume steps. Read-only. Use for /tyran:status or when asked what is going on.
2
+ description: Where is the work right now. Regenerates the projections and the kanban board from the journal and answers with the progress line, the agents still running, the open gates and the resume steps. Read-only. Use for /tyran:status or when asked what is going on.
3
3
  ---
4
4
 
5
5
  # Status
@@ -9,6 +9,7 @@ Answer from the journal, never from memory.
9
9
  ```bash
10
10
  J=$(ls -t .tyran/state/*/journal.jsonl 2>/dev/null | head -1)
11
11
  node "${CLAUDE_PLUGIN_ROOT}/scripts/project.mjs" "$J" --out-dir "$(dirname "$J")"
12
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/board.mjs" --dir .tyran
12
13
  node "${CLAUDE_PLUGIN_ROOT}/scripts/journal.mjs" tail "$J"
13
14
  node "${CLAUDE_PLUGIN_ROOT}/scripts/journal.mjs" open-spawns "$J"
14
15
  ```
@@ -28,6 +29,9 @@ Then report, in this order and no longer than a screen:
28
29
  these; they mean two agents believed they owned the same worktree.
29
30
  6. The resume steps from the last checkpoint.
30
31
 
32
+ End by pointing the operator at `.tyran/state/board.html` — the kanban view
33
+ of everything above, refreshed on every subagent stop and every merge.
34
+
31
35
  If there is no journal, say exactly that and suggest `/tyran:setup`. Do not
32
36
  reconstruct a status from the git log — a plausible status is worse than none,
33
37
  because it will be believed.