@litfamily/litcodex 1.0.20 โ†’ 1.0.21

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,507 @@
1
+ // src/workflow-map.ts โ€” the plain-text LIT workflow map.
2
+ //
3
+ // Codex shows a hook `systemMessage` as plain text (escape codes appear literally), so the map uses
4
+ // emoji and block cells instead of colour. It is built from saved state only: the start-work record
5
+ // and its plan checkboxes, lit-loop goals, the lit-plan activation record and the litresearch
6
+ // journal. A stage with no saved signal is left out rather than guessed. Every read fails open.
7
+ import { createHash } from "node:crypto";
8
+ import { lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
9
+ import { basename, isAbsolute, join } from "node:path";
10
+ import { LIT_LOOP_DIR, LIT_LOOP_GOALS, normalizeSessionId } from "./state-paths.js";
11
+ const STAGES = [
12
+ ["interview", "๐Ÿงญ", "INTERVIEW"],
13
+ ["plan", "๐Ÿ“", "PLAN"],
14
+ ["work", "๐Ÿ”จ", "WORK"],
15
+ ["review", "๐Ÿ”", "REVIEW"],
16
+ ["done", "๐Ÿ", "DONE"],
17
+ ];
18
+ /** Where each LIT skill sits in the main chain; `research` is its own short family. */
19
+ const MODE_STAGE = {
20
+ "deep-interview": "interview",
21
+ "lit-crucible": "interview",
22
+ "lit-plan": "plan",
23
+ litgoal: "plan",
24
+ "start-work": "work",
25
+ litwork: "work",
26
+ "lit-loop": "work",
27
+ "review-work": "review",
28
+ litresearch: "research",
29
+ };
30
+ const MAX_STATE_BYTES = 1_000_000;
31
+ const MAX_TITLE = 48;
32
+ const BAR_CELLS = 10;
33
+ const TURN_DIR = ".litcodex/workflow-map";
34
+ const RESEARCH_DIR = `${LIT_LOOP_DIR}/litresearch`;
35
+ /** An unfinished journal older than this belongs to research the user has moved on from. */
36
+ const RESEARCH_STALE_MS = 24 * 60 * 60 * 1000;
37
+ /** The start-work continuation hook stops reading a transcript past this size and stays quiet. */
38
+ const MAX_TRANSCRIPT_BYTES = 2_000_000;
39
+ const CONTEXT_ERROR_CODES = new Set(["context_length_exceeded", "context_too_large"]);
40
+ const MIN_TITLE_WORDS = 3;
41
+ const NO_SIGNALS = { work: null, goals: null, plan: null, research: null };
42
+ const NO_STOP_CONTEXT = { stopHookActive: false, transcriptPath: null };
43
+ function isRecord(value) {
44
+ return typeof value === "object" && value !== null && !Array.isArray(value);
45
+ }
46
+ /** Parse a small regular file (never a symlink); null on any failure. */
47
+ function readJson(path) {
48
+ try {
49
+ const stat = lstatSync(path);
50
+ if (!stat.isFile() || stat.size > MAX_STATE_BYTES)
51
+ return null;
52
+ return JSON.parse(readFileSync(path, "utf8"));
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ function readText(path) {
59
+ try {
60
+ const stat = lstatSync(path);
61
+ if (!stat.isFile() || stat.size > MAX_STATE_BYTES)
62
+ return null;
63
+ return readFileSync(path, "utf8");
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /**
70
+ * Checkbox rows the way start-work counts them: fenced blocks are skipped, and when the plan has a
71
+ * `## Todos` or `## Final verification wave` section only rows inside those sections count.
72
+ */
73
+ export function countPlanRows(markdown) {
74
+ const rows = planRows(markdown);
75
+ return {
76
+ done: rows.filter((row) => row.done).length,
77
+ total: rows.length,
78
+ next: rows.find((row) => !row.done)?.label ?? null,
79
+ };
80
+ }
81
+ /** The counted checkbox rows in order, as start-work reads them. */
82
+ function planRows(markdown) {
83
+ const lines = markdown.split(/\r?\n/);
84
+ const visible = [];
85
+ let fence = null;
86
+ for (const line of lines) {
87
+ if (fence !== null) {
88
+ const closing = line.match(/^ {0,3}(`+|~+)[ \t]*$/);
89
+ if (closing?.[1]?.[0] === fence.marker && closing[1].length >= fence.length)
90
+ fence = null;
91
+ continue;
92
+ }
93
+ const opening = line.match(/^ {0,3}(`{3,}|~{3,})/);
94
+ if (opening?.[1] !== undefined) {
95
+ fence = { marker: opening[1][0] ?? "`", length: opening[1].length };
96
+ continue;
97
+ }
98
+ visible.push(line);
99
+ }
100
+ const section = (line) => {
101
+ if (!line.startsWith("## ") || line.startsWith("### "))
102
+ return null;
103
+ const heading = line.slice(3).replace(/\s+/g, " ").trim().toLowerCase();
104
+ return (heading === "todos" || heading === "final verification wave" || heading.startsWith("final verification wave "));
105
+ };
106
+ const sectioned = visible.some((line) => section(line) === true);
107
+ let inside = !sectioned;
108
+ const rows = [];
109
+ for (const line of visible) {
110
+ const heading = section(line);
111
+ if (heading !== null)
112
+ inside = heading;
113
+ if (!inside)
114
+ continue;
115
+ const match = line.match(/^- \[([ xX])\] (.*)$/s);
116
+ const label = (match?.[2] ?? "").replace(/\s+/g, " ").trim();
117
+ if (match === null || label.length === 0)
118
+ continue;
119
+ rows.push({ done: match[1] !== " ", label });
120
+ }
121
+ return rows;
122
+ }
123
+ /** One cell per task, at most ten; a partly done plan never draws as full or empty. */
124
+ export function progressBar(done, total) {
125
+ const cells = Math.min(total, BAR_CELLS);
126
+ let filled = total === 0 ? 0 : Math.round((done / total) * cells);
127
+ if (done > 0 && filled === 0)
128
+ filled = 1;
129
+ if (done < total && filled === cells)
130
+ filled = cells - 1;
131
+ return "โ–ฐ".repeat(filled) + "โ–ฑ".repeat(cells - filled);
132
+ }
133
+ /** A path, code span, variable or flag: the first one ends a title, since nothing after it is shown. */
134
+ function isTechnical(word) {
135
+ return /[/\\`]/u.test(word) || /^--?[\p{L}\d]/u.test(word) || /^\$[\p{L}_{(]/u.test(word) || word.startsWith("~");
136
+ }
137
+ /**
138
+ * A task title without its row number, cut at the first code span, path, variable or flag and marked
139
+ * with `โ€ฆ`. Deleting those words mid-sentence reads oddly, so the title stops there instead; a title
140
+ * with fewer than three words left before the cut is dropped.
141
+ */
142
+ export function safeTitle(label) {
143
+ const words = label
144
+ .replace(/[\u0000-\u001f\u007f-\u009f]/gu, "")
145
+ .replace(/^(?:F?\d+\.\s+)/iu, "")
146
+ .split(/\s+/u)
147
+ .filter((word) => word.length > 0);
148
+ const cut = words.findIndex(isTechnical);
149
+ if (cut === 0)
150
+ return null;
151
+ if (cut > 0 && cut < MIN_TITLE_WORDS)
152
+ return null;
153
+ const title = (cut < 0 ? words : words.slice(0, cut)).join(" ").replace(/[\s,:;(โ€”โ€“-]+$/u, "");
154
+ if (title.length === 0)
155
+ return null;
156
+ if (title.length > MAX_TITLE)
157
+ return `${title.slice(0, MAX_TITLE - 1)}โ€ฆ`;
158
+ return cut < 0 ? title : `${title} โ€ฆ`;
159
+ }
160
+ function readWork(repoRoot, sessionId) {
161
+ const state = readJson(join(repoRoot, ".litcodex/start-work/state.json"));
162
+ if (!isRecord(state) || !isRecord(state["works"]))
163
+ return null;
164
+ const works = Object.values(state["works"]).filter(isRecord);
165
+ const activeId = state["active_work_id"];
166
+ let work = works.find((entry) => entry["work_id"] === activeId && (entry["status"] === "active" || entry["status"] === "paused"));
167
+ if (work === undefined && sessionId !== null) {
168
+ // A finished plan belongs to the session that ran it, so an old one never shows in a new session.
169
+ const mine = works.filter((entry) => entry["status"] === "completed" &&
170
+ Array.isArray(entry["session_ids"]) &&
171
+ entry["session_ids"].includes(`codex:${sessionId}`));
172
+ const at = (entry) => {
173
+ const last = entry["last_transition"];
174
+ return isRecord(last) && typeof last["at"] === "string" ? last["at"] : "";
175
+ };
176
+ work = mine.sort((a, b) => at(b).localeCompare(at(a)))[0];
177
+ }
178
+ if (work === undefined || typeof work["active_plan"] !== "string")
179
+ return null;
180
+ const file = basename(work["active_plan"]);
181
+ if (!file.endsWith(".md"))
182
+ return null;
183
+ const text = readText(join(repoRoot, ".litcodex/plans", file));
184
+ if (text === null)
185
+ return null;
186
+ const rows = countPlanRows(text);
187
+ if (rows.total === 0)
188
+ return null;
189
+ return { ...rows, status: work["status"] };
190
+ }
191
+ function goalProgress(path) {
192
+ const plan = readJson(path);
193
+ if (!isRecord(plan) || !Array.isArray(plan["goals"]))
194
+ return null;
195
+ const goals = plan["goals"].filter(isRecord);
196
+ if (goals.length === 0)
197
+ return null;
198
+ const open = goals.find((goal) => goal["status"] === "in_progress") ?? goals.find((goal) => goal["status"] === "pending");
199
+ return {
200
+ done: goals.filter((goal) => goal["status"] === "complete").length,
201
+ total: goals.length,
202
+ next: typeof open?.["title"] === "string" ? open["title"] : null,
203
+ };
204
+ }
205
+ function readGoals(repoRoot, sessionId) {
206
+ if (sessionId !== null) {
207
+ const scoped = goalProgress(join(repoRoot, LIT_LOOP_DIR, sessionId, LIT_LOOP_GOALS));
208
+ if (scoped !== null)
209
+ return scoped;
210
+ }
211
+ const shared = goalProgress(join(repoRoot, LIT_LOOP_DIR, LIT_LOOP_GOALS));
212
+ return shared !== null && shared.done < shared.total ? shared : null;
213
+ }
214
+ function readPlanRecord(repoRoot, sessionId) {
215
+ if (sessionId === null)
216
+ return null;
217
+ const record = readJson(join(repoRoot, ".litcodex/lit-plan", `${sessionId}.json`));
218
+ if (!isRecord(record) || typeof record["satisfied"] !== "boolean")
219
+ return null;
220
+ return record["satisfied"] ? "published" : "drafting";
221
+ }
222
+ /** The newest research journal by its last write, with the names of the files in it. */
223
+ function newestJournal(repoRoot) {
224
+ const root = join(repoRoot, RESEARCH_DIR);
225
+ try {
226
+ let newest = null;
227
+ for (const name of readdirSync(root)) {
228
+ if (name.startsWith("."))
229
+ continue;
230
+ const dir = join(root, name);
231
+ if (!lstatSync(dir).isDirectory())
232
+ continue;
233
+ const files = readdirSync(dir);
234
+ const mtime = Math.max(statSync(dir).mtimeMs, ...files.map((file) => lstatSync(join(dir, file)).mtimeMs));
235
+ if (newest === null || mtime > newest.mtime)
236
+ newest = { files, mtime };
237
+ }
238
+ return newest;
239
+ }
240
+ catch {
241
+ return null;
242
+ }
243
+ }
244
+ function highestWave(files) {
245
+ const waves = files.map((name) => name.match(/^wave-(\d+)-/)?.[1]).filter((wave) => wave !== undefined);
246
+ return waves.length === 0 ? null : Math.max(...waves.map(Number));
247
+ }
248
+ /**
249
+ * Progress of research still under way: the newest journal, unless it already holds `SYNTHESIS.md` or
250
+ * nothing was written to it for a day, in which case a new research starts at decomposition.
251
+ */
252
+ function readResearch(repoRoot, now) {
253
+ const journal = newestJournal(repoRoot);
254
+ if (journal === null || now - journal.mtime > RESEARCH_STALE_MS || journal.files.includes("SYNTHESIS.md")) {
255
+ return null;
256
+ }
257
+ return {
258
+ wave: highestWave(journal.files),
259
+ verifying: journal.files.some((name) => /^verify-.+\.md$/u.test(name)),
260
+ };
261
+ }
262
+ export function readWorkflowSignals(repoRoot, sessionId, now = Date.now()) {
263
+ if (typeof repoRoot !== "string" || !isAbsolute(repoRoot))
264
+ return NO_SIGNALS;
265
+ const id = normalizeSessionId(sessionId);
266
+ return {
267
+ work: readWork(repoRoot, id),
268
+ goals: readGoals(repoRoot, id),
269
+ plan: readPlanRecord(repoRoot, id),
270
+ research: readResearch(repoRoot, now),
271
+ };
272
+ }
273
+ function stageFromState(signals) {
274
+ if (signals.work?.status === "completed")
275
+ return { index: 4, active: true };
276
+ if (signals.work !== null || signals.goals !== null)
277
+ return { index: 2, active: true };
278
+ if (signals.plan === "drafting")
279
+ return { index: 1, active: true };
280
+ if (signals.plan === "published")
281
+ return { index: 2, active: false };
282
+ return null;
283
+ }
284
+ /** The research family: decompose โ€บ waves (the first, then expansion) โ€บ verify โ€บ synthesis. */
285
+ function researchMap(research) {
286
+ if (research === null || (research.wave === null && !research.verifying))
287
+ return "๐Ÿ”Ž DECOMPOSE โ€บ ๐ŸŒŠ ยท โ€บ ๐Ÿ”ฌ ยท โ€บ ๐Ÿ ยท";
288
+ const { wave } = research;
289
+ if (!research.verifying) {
290
+ return `๐Ÿ”Ž โœ“ โ€บ ๐ŸŒŠ WAVE ${wave}${wave !== null && wave > 1 ? " EXPAND" : ""} โ€บ ๐Ÿ”ฌ ยท โ€บ ๐Ÿ ยท`;
291
+ }
292
+ const waves = wave === null ? "" : ` โ€บ ๐ŸŒŠ โœ“ ${wave} wave${wave === 1 ? "" : "s"}`;
293
+ return `๐Ÿ”Ž โœ“${waves} โ€บ ๐Ÿ”ฌ VERIFY โ€บ ๐Ÿ ยท`;
294
+ }
295
+ /** One map line, or null when there is nothing true to draw. Plain text: emoji and block cells only. */
296
+ export function renderWorkflowMap(mode, signals) {
297
+ const fromMode = mode === null ? undefined : MODE_STAGE[mode];
298
+ if (fromMode === "research")
299
+ return researchMap(signals.research);
300
+ const position = fromMode === undefined
301
+ ? stageFromState(signals)
302
+ : { index: STAGES.findIndex(([stage]) => stage === fromMode), active: true };
303
+ if (position === null)
304
+ return null;
305
+ const { work } = signals;
306
+ const progress = work ?? signals.goals;
307
+ const planKnown = work !== null || signals.plan === "published";
308
+ const workFinished = work !== null && (work.status === "completed" || work.done === work.total);
309
+ const cells = [];
310
+ STAGES.forEach(([stage, icon, label], index) => {
311
+ if (index > position.index || (index === position.index && !position.active)) {
312
+ cells.push(`${icon} ยท`);
313
+ return;
314
+ }
315
+ if (index === position.index) {
316
+ const name = stage === "work" && work?.status === "paused" ? "PAUSED" : label;
317
+ const bar = stage === "work" && progress !== null
318
+ ? ` ${progressBar(progress.done, progress.total)} ${progress.done}/${progress.total}`
319
+ : "";
320
+ cells.push(`${icon} ${name}${bar}`);
321
+ return;
322
+ }
323
+ if (stage === "interview" || stage === "plan") {
324
+ if (planKnown)
325
+ cells.push(`${icon} โœ“`);
326
+ }
327
+ else if (stage === "work") {
328
+ if (workFinished)
329
+ cells.push(`${icon} โœ“`);
330
+ else if (work !== null)
331
+ cells.push(`${icon} ${progressBar(work.done, work.total)} ${work.done}/${work.total}`);
332
+ }
333
+ else if (stage === "review" && work?.status === "completed") {
334
+ cells.push(`${icon} โœ“`);
335
+ }
336
+ });
337
+ return cells.join(" โ€บ ");
338
+ }
339
+ export function workflowMapLine(repoRoot, sessionId, mode) {
340
+ return renderWorkflowMap(mode, readWorkflowSignals(repoRoot, sessionId));
341
+ }
342
+ function turnPath(repoRoot, sessionId) {
343
+ const id = normalizeSessionId(sessionId);
344
+ if (id === null || typeof repoRoot !== "string" || !isAbsolute(repoRoot))
345
+ return null;
346
+ return join(repoRoot, TURN_DIR, `${id}.json`);
347
+ }
348
+ /** Remember that this turn is a LIT activation and where its progress started. Never throws. */
349
+ export function recordWorkflowTurn(repoRoot, sessionId, turnId, mode, now = Date.now()) {
350
+ const path = turnPath(repoRoot, sessionId);
351
+ if (path === null || turnId.length === 0)
352
+ return;
353
+ const signals = readWorkflowSignals(repoRoot, sessionId);
354
+ const record = {
355
+ version: 1,
356
+ turnId,
357
+ mode,
358
+ startedAt: now,
359
+ workDone: signals.work?.done ?? null,
360
+ goalsDone: signals.goals?.done ?? null,
361
+ };
362
+ try {
363
+ mkdirSync(join(repoRoot, TURN_DIR), { recursive: true });
364
+ const tmp = `${path}.${process.pid}.tmp`;
365
+ writeFileSync(tmp, `${JSON.stringify(record)}\n`);
366
+ renameSync(tmp, path);
367
+ }
368
+ catch {
369
+ // Without the record the Stop hook simply stays quiet for this turn.
370
+ }
371
+ }
372
+ function readTurn(path) {
373
+ const record = readJson(path);
374
+ if (!isRecord(record) ||
375
+ record["version"] !== 1 ||
376
+ typeof record["turnId"] !== "string" ||
377
+ typeof record["mode"] !== "string" ||
378
+ typeof record["startedAt"] !== "number")
379
+ return null;
380
+ const count = (value) => (typeof value === "number" ? value : null);
381
+ return {
382
+ version: 1,
383
+ turnId: record["turnId"],
384
+ mode: record["mode"],
385
+ startedAt: record["startedAt"],
386
+ workDone: count(record["workDone"]),
387
+ goalsDone: count(record["goalsDone"]),
388
+ };
389
+ }
390
+ /** Highest wave number in the newest research journal written since `since`, or null. */
391
+ function researchWave(repoRoot, since) {
392
+ const journal = newestJournal(repoRoot);
393
+ return journal === null || journal.mtime < since ? null : highestWave(journal.files);
394
+ }
395
+ function isContextError(value) {
396
+ if (!isRecord(value))
397
+ return false;
398
+ const error = value["type"] === "error"
399
+ ? value["error"]
400
+ : value["type"] === "message" && isRecord(value["payload"]) && isRecord(value["payload"]["content"])
401
+ ? value["payload"]["content"]["error"]
402
+ : null;
403
+ return isRecord(error) && CONTEXT_ERROR_CODES.has(String(error["code"]));
404
+ }
405
+ /** The transcript check the continuation hook makes: a missing path is clear; oversized, unparsable or full context is not. */
406
+ function transcriptClear(path) {
407
+ if (path === null || path.length === 0)
408
+ return true;
409
+ try {
410
+ const stat = lstatSync(path);
411
+ if (!stat.isFile() || stat.size > MAX_TRANSCRIPT_BYTES)
412
+ return false;
413
+ for (const line of readFileSync(path, "utf8").split(/\r?\n/)) {
414
+ if (line.length > 0 && isContextError(JSON.parse(line)))
415
+ return false;
416
+ }
417
+ return true;
418
+ }
419
+ catch {
420
+ return false;
421
+ }
422
+ }
423
+ /**
424
+ * The plan start-work will carry on with after this Stop, or null when its continuation hook stays
425
+ * quiet. It repeats that hook's decision read-only (host continuation flag, transcript, the one active
426
+ * work this session owns with authority and open rows, and the lease that nudges each plan state once
427
+ * per turn), so the answer is the same whichever Stop hook the host runs first.
428
+ */
429
+ function continuingWork(repoRoot, sessionId, turnId, stop) {
430
+ if (stop.stopHookActive || !transcriptClear(stop.transcriptPath))
431
+ return null;
432
+ const state = readJson(join(repoRoot, ".litcodex/start-work/state.json"));
433
+ if (!isRecord(state) || !isRecord(state["works"]) || typeof state["active_work_id"] !== "string")
434
+ return null;
435
+ const owner = `codex:${sessionId}`;
436
+ const owned = Object.entries(state["works"]).filter(([id, work]) => isRecord(work) &&
437
+ work["work_id"] === id &&
438
+ work["status"] === "active" &&
439
+ Array.isArray(work["session_ids"]) &&
440
+ work["session_ids"].includes(owner));
441
+ const [entry] = owned;
442
+ if (owned.length !== 1 || entry === undefined || entry[0] !== state["active_work_id"])
443
+ return null;
444
+ const work = entry[1];
445
+ const plan = work["active_plan"];
446
+ if (!isRecord(work["authority"]) || typeof plan !== "string" || !/^\.litcodex\/plans\/[^/\\]+\.md$/u.test(plan)) {
447
+ return null;
448
+ }
449
+ const text = readText(join(repoRoot, plan));
450
+ if (text === null)
451
+ return null;
452
+ const rows = planRows(text);
453
+ const done = rows.filter((row) => row.done).length;
454
+ if (rows.length === 0 || done === rows.length)
455
+ return null;
456
+ const token = createHash("sha256")
457
+ .update(JSON.stringify(rows.map((row) => [row.done ? 1 : 0, row.label])))
458
+ .digest("hex");
459
+ const lease = work["continuation_lease"];
460
+ if (isRecord(lease) && lease["progress_token"] === token && lease["turn_id"] !== turnId)
461
+ return null;
462
+ return { done, total: rows.length, next: rows.find((row) => !row.done)?.label ?? null };
463
+ }
464
+ function counted(n, unit) {
465
+ return `${n} ${unit}${n === 1 ? "" : "s"} โœ“`;
466
+ }
467
+ /**
468
+ * The Stop line for a LIT turn, or null when this turn was not a LIT activation. At a start-work
469
+ * checkpoint the continuation hook keeps the turn going, so the line says so instead of "turn done".
470
+ * No commands or paths.
471
+ */
472
+ export function workflowStopLine(repoRoot, sessionId, turnId, stop = NO_STOP_CONTEXT) {
473
+ const path = turnPath(repoRoot, sessionId);
474
+ if (path === null)
475
+ return null;
476
+ const turn = readTurn(path);
477
+ if (turn === null || turn.turnId !== turnId)
478
+ return null;
479
+ const continuing = continuingWork(repoRoot, sessionId, turnId, stop);
480
+ if (continuing !== null) {
481
+ const next = continuing.next === null ? null : safeTitle(continuing.next);
482
+ const status = `โณ ${continuing.done}/${continuing.total} tasks โœ“ ยท continuing`;
483
+ return next === null ? status : `${status} โ–ธ ${next}`;
484
+ }
485
+ const signals = readWorkflowSignals(repoRoot, sessionId);
486
+ const parts = ["โœจ turn done"];
487
+ const progress = signals.work ?? signals.goals;
488
+ if (progress !== null) {
489
+ const unit = signals.work !== null ? "task" : "goal";
490
+ const before = signals.work !== null ? turn.workDone : turn.goalsDone;
491
+ if (before !== null && progress.done > before)
492
+ parts.push(counted(progress.done - before, unit));
493
+ if (progress.done >= progress.total)
494
+ parts.push(`all ${progress.total} ${unit}s โœ“`);
495
+ else {
496
+ const next = progress.next === null ? null : safeTitle(progress.next);
497
+ if (next !== null)
498
+ parts.push(`next โ–ธ ${next}`);
499
+ }
500
+ }
501
+ if (turn.mode === "litresearch") {
502
+ const wave = researchWave(repoRoot, turn.startedAt);
503
+ if (wave !== null)
504
+ parts.push(`๐ŸŒŠ wave ${wave}`);
505
+ }
506
+ return parts.join(" ยท ");
507
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/lit-loop",
3
- "version": "1.0.20",
3
+ "version": "1.0.21",
4
4
  "description": "LitCodex Lit-Loop runtime: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/lsp",
3
- "version": "1.0.20",
3
+ "version": "1.0.21",
4
4
  "description": "LitCodex LSP hook (inert placeholder): post-edit diagnostics + cache reset, no-op until an LSP daemon is provided.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/rules",
3
- "version": "1.0.20",
3
+ "version": "1.0.21",
4
4
  "description": "LitCodex rules: injects project rule files (AGENTS.md etc.) into model context through lifecycle hooks.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/start-work-continuation",
3
- "version": "1.0.20",
3
+ "version": "1.0.21",
4
4
  "description": "LitCodex Start-Work continuation hook: resumes in-flight start-work state on root Stop.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/telemetry",
3
- "version": "1.0.20",
3
+ "version": "1.0.21",
4
4
  "description": "LitCodex telemetry: a deliberately inert, local-only SessionStart hook (NO network, NO data collection).",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/wikify-knowledge",
3
- "version": "1.0.20",
3
+ "version": "1.0.21",
4
4
  "description": "Local review-gated knowledge records for the LitCodex Wikify surface.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -14,6 +14,7 @@ import { applyAutoHandoffRoute, clearManagedCompactionWhenOff, parseAutoHandoffR
14
14
  import { applyPreToolUseCreateGoalGuard, isLitUserPromptSubmitInput, runUserPromptSubmitHook } from "./codex-hook.js";
15
15
  import { claimJevOnBanner, formatJevHookOutput, jevSwitchState, runJevSkillHint, withJevBanner, } from "./jev-hint.js";
16
16
  import { evaluatePlanPersistence, formatStopBlockOutput, recordLitPlanActivation } from "./plan-persistence.js";
17
+ import { recordWorkflowTurn, workflowMapLine, workflowStopLine } from "./workflow-map.js";
17
18
  /** Hard cap on stdin to bound memory / ReDoS exposure inside the 5 s Codex hook budget. 8 MB. */
18
19
  export const MAX_STDIN_BYTES = 8_000_000;
19
20
  const INVALID_JSON_MESSAGE = "lit hook: stdin was not valid JSON";
@@ -105,7 +106,9 @@ export async function runUserPromptSubmitHookCli(stdin, stdout, stderr, repoRoot
105
106
  if (scope !== null)
106
107
  recordLitPlanActivation(scope.cwd, scope.sessionId);
107
108
  }
108
- const own = decision.kind === "inject" ? decision.stdout : await jevHintOutput(parsed, repoRoot, jev);
109
+ const own = decision.kind === "inject"
110
+ ? withWorkflowMap(decision.stdout, parsed, decision.mode)
111
+ : await jevHintOutput(parsed, repoRoot, jev);
109
112
  const output = withAutoHandoffReload(own, parsed, repoRoot, auto);
110
113
  if (output !== "")
111
114
  stdout.write(output);
@@ -163,6 +166,35 @@ function withReloadContext(stdout, reload) {
163
166
  return null;
164
167
  }
165
168
  }
169
+ /**
170
+ * Add the workflow map under the activation banner and remember the turn for the Stop line. Only an
171
+ * event that names its own absolute `cwd` is mapped, so the map always describes the session's repo.
172
+ */
173
+ function withWorkflowMap(stdout, parsed, mode) {
174
+ if (!isRecord(parsed) || typeof parsed["cwd"] !== "string" || !isAbsolute(parsed["cwd"]))
175
+ return stdout;
176
+ const cwd = parsed["cwd"];
177
+ const sessionId = typeof parsed["session_id"] === "string" && parsed["session_id"] !== "" ? parsed["session_id"] : null;
178
+ try {
179
+ if (sessionId !== null && typeof parsed["turn_id"] === "string") {
180
+ recordWorkflowTurn(cwd, sessionId, parsed["turn_id"], mode);
181
+ }
182
+ const map = workflowMapLine(cwd, sessionId, mode);
183
+ if (map === null)
184
+ return stdout;
185
+ const output = JSON.parse(stdout);
186
+ if (!isRecord(output) || typeof output["systemMessage"] !== "string")
187
+ return stdout;
188
+ output["systemMessage"] = `${output["systemMessage"]}\n${map}`;
189
+ return `${JSON.stringify(output)}\n`;
190
+ }
191
+ catch {
192
+ return stdout;
193
+ }
194
+ }
195
+ function isRecord(value) {
196
+ return typeof value === "object" && value !== null && !Array.isArray(value);
197
+ }
166
198
  /** Absolute `cwd` from a hook event, else the fallback root. */
167
199
  function hookCwd(parsed, repoRoot) {
168
200
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
@@ -242,8 +274,18 @@ export async function runStopPlanPersistenceHookCli(stdin, stdout, stderr, repoR
242
274
  env: auto.env ?? process.env,
243
275
  ...(auto.now === undefined ? {} : { now: auto.now }),
244
276
  });
245
- if (handoff.decision === "block")
277
+ if (handoff.decision === "block") {
246
278
  stdout.write(formatStopBlockOutput(handoff.reason));
279
+ return 0;
280
+ }
281
+ const line = typeof record["turn_id"] === "string"
282
+ ? workflowStopLine(scope.cwd, scope.sessionId, record["turn_id"], {
283
+ stopHookActive: record["stop_hook_active"] === true,
284
+ transcriptPath: typeof record["transcript_path"] === "string" ? record["transcript_path"] : null,
285
+ })
286
+ : null;
287
+ if (line !== null)
288
+ stdout.write(`${JSON.stringify({ systemMessage: line })}\n`);
247
289
  }
248
290
  return 0;
249
291
  }