@litfamily/litclaude 1.0.41 โ†’ 1.0.42

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.
@@ -89,24 +89,30 @@ const mtimeOf = (path) => {
89
89
  }
90
90
  };
91
91
 
92
- const plansIn = (root, budget, redact, local) => {
92
+ // A plan met after the read budget ran out is counted in `skipped.count`, so the brief can say so.
93
+ const plansIn = (root, budget, redact, local, skipped = { count: 0 }) => {
93
94
  const list = entries(join(root, "plans"));
94
95
  if (!list) return null;
95
96
  return list.filter((entry) => entry.isFile() && entry.name.endsWith(".md")).sort((a, b) => a.name.localeCompare(b.name)).flatMap((entry) => {
97
+ if (budget.used >= budget.limit) {
98
+ skipped.count += 1;
99
+ return [];
100
+ }
96
101
  const text = readSmallFile(join(root, "plans", entry.name), budget);
97
102
  if (text === null) return [];
98
103
  const rows = parsePlanTaskRows(text);
99
104
  if (!rows.length || isTemplate(rows)) return [];
100
105
  const open = rows.filter((row) => !row.checked);
101
- if (!open.length) return [];
102
106
  const done = rows.length - open.length;
107
+ // A plan with every row ticked is kept, marked complete: it is finished work, not roadmap.
103
108
  return [{
104
109
  worktree: redact(root),
105
110
  plan: `plans/${entry.name}`,
106
111
  local,
112
+ complete: open.length === 0,
107
113
  changedMs: mtimeOf(join(root, "plans", entry.name)),
108
114
  rows: rows.map((row) => ({ checked: row.checked, title: clipToWidth(redact(row.text), NAME_MAX) })),
109
- current: clipToWidth(redact(open[0].text), NAME_MAX),
115
+ current: open.length ? clipToWidth(redact(open[0].text), NAME_MAX) : null,
110
116
  progress: progressOf(done, rows.length, open.map((row) => clipToWidth(redact(row.text), NAME_MAX))),
111
117
  }];
112
118
  });
@@ -125,12 +131,27 @@ const litgoalOf = (root, budget, redact) => {
125
131
  };
126
132
  };
127
133
 
128
- const handoffsOf = (root, budget, redact) => (entries(root) ?? [])
134
+ // The first list item or line of text under a `## Next` or `## Next Steps` heading, without its marker.
135
+ const handoffNext = (text) => {
136
+ const lines = text.split("\n");
137
+ const start = lines.findIndex((line) => /^#{1,6}\s+Next(?:\s+Steps)?\s*$/iu.test(line.trim()));
138
+ if (start < 0) return null;
139
+ for (const line of lines.slice(start + 1)) {
140
+ if (/^#{1,6}\s/u.test(line.trim())) return null;
141
+ const item = line.trim().replace(/^(?:[-*+]|\d+[.)])\s+/u, "");
142
+ if (item) return item;
143
+ }
144
+ return null;
145
+ };
146
+
147
+ // Only this worktree's own HANDOFF files give a next step (`next`); another worktree's never does.
148
+ const handoffsOf = (root, budget, redact, local = false) => (entries(root) ?? [])
129
149
  .filter((entry) => entry.isFile() && /^HANDOFF.*\.md$/u.test(entry.name))
130
150
  .map((entry) => {
131
151
  const text = readSmallFile(join(root, entry.name), budget) ?? "";
132
152
  const headings = text.split("\n").slice(0, 40).filter((line) => /^#{1,3} /u.test(line)).map((line) => clipToWidth(redact(line), 100));
133
- return { worktree: redact(root), file: entry.name, headings };
153
+ const next = local ? handoffNext(text) : null;
154
+ return { worktree: redact(root), file: entry.name, headings, local, next: next ? clipToWidth(redact(next), 120) : null };
134
155
  });
135
156
 
136
157
  const commitsOf = (root, sinceMs, now, exec, redact) => {
@@ -192,6 +213,37 @@ const startWorkOf = (root, budget, redact) => {
192
213
  }];
193
214
  };
194
215
 
216
+ // start-work runs this lifecycle completed, from its history: which plan, which session, and when.
217
+ const completedRunsOf = (root, budget, redact) => {
218
+ const state = readJson(join(root, ".litclaude", "boulder.json"), budget);
219
+ if (!state || !Array.isArray(state.history)) return null;
220
+ return state.history.filter((entry) => entry?.status === "completed" && typeof entry.plan === "string").map((entry) => ({
221
+ worktree: redact(root),
222
+ plan: `plans/${basename(entry.plan)}`,
223
+ sessionId: state.works?.[entry.work_id]?.root_session_id ?? null,
224
+ atMs: Date.parse(entry.terminal_at),
225
+ })).filter((run) => Number.isFinite(run.atMs));
226
+ };
227
+
228
+ // Each session's last hook event (session-liveness.mjs): `alive`, `idle` or `ended`, newest first.
229
+ const LIVENESS_FILES = 24;
230
+ const livenessOf = (root, budget) => {
231
+ const directory = join(root, ".litclaude", "liveness");
232
+ const list = entries(directory);
233
+ if (!list) return null;
234
+ return list.filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
235
+ .map((entry) => ({ entry, at: mtimeOf(join(directory, entry.name)) ?? 0 }))
236
+ .sort((a, b) => b.at - a.at)
237
+ .slice(0, LIVENESS_FILES)
238
+ .flatMap(({ entry }) => {
239
+ const record = readJson(join(directory, entry.name), budget);
240
+ const atMs = Date.parse(record?.at);
241
+ return typeof record?.sessionId === "string" && ["alive", "idle", "ended"].includes(record.state) && Number.isFinite(atMs)
242
+ ? [{ sessionId: record.sessionId, state: record.state, atMs }]
243
+ : [];
244
+ });
245
+ };
246
+
195
247
  const herdrOf = (env, exec, redact) => {
196
248
  if (env.HERDR_ENV !== "1") return { status: "unknown", agents: [] };
197
249
  try {
@@ -203,7 +255,10 @@ const herdrOf = (env, exec, redact) => {
203
255
  };
204
256
 
205
257
  const known = (list) => (list === null ? "unknown" : "ok");
206
- const statusRank = { "waiting-on-user": 0, active: 1, ended: 2, unknown: 3 };
258
+ const statusRank = { "waiting-on-user": 0, active: 1, idle: 2, done: 2, ended: 3, unknown: 4 };
259
+ // The Stop hook writes `idle` just after the turn's last transcript line, so a record this much older
260
+ // than that line still describes it; anything older predates a newer prompt.
261
+ const LIVENESS_SLACK_MS = 5000;
207
262
 
208
263
  /**
209
264
  * Collects the brief. Options: `cwd`, `here` (cwd only), `since` (`7d`), `max` (12), `sessionId`
@@ -230,6 +285,24 @@ export const collectRewind = ({
230
285
  const listed = here ? null : worktreesOf(start, exec);
231
286
  const roots = [...new Set([start, ...(here ? [] : listed ?? [stateRoot])])];
232
287
 
288
+ // The small records first: plans, litgoal, handoffs and stacks cost little, and the transcripts
289
+ // after them may use up the read budget.
290
+ const collectEach = (read) => {
291
+ const results = roots.map(read);
292
+ return results.every((value) => value === null) ? null : results.flatMap((value) => value ?? []);
293
+ };
294
+ const plansSkipped = { count: 0 };
295
+ const plans = collectEach((root) => plansIn(root, budget, redact, resolve(root) === stateRoot || resolve(root) === start, plansSkipped));
296
+ const litgoal = collectEach((root) => {
297
+ const goal = litgoalOf(root, budget, redact);
298
+ return goal ? [{ ...goal, local: resolve(root) === stateRoot || resolve(root) === start }] : null;
299
+ });
300
+ const handoffs = roots.flatMap((root) => handoffsOf(root, budget, redact, resolve(root) === start));
301
+ const workflows = collectEach((root) => stacksOf(root, budget, redact));
302
+ const startWork = collectEach((root) => startWorkOf(root, budget, redact));
303
+ const runs = collectEach((root) => completedRunsOf(root, budget, redact));
304
+ const liveness = collectEach((root) => livenessOf(root, budget));
305
+
233
306
  const rootSet = new Set(roots.map((root) => resolve(root).normalize("NFC")));
234
307
  const transcripts = findTranscripts(env.CLAUDE_CONFIG_DIR || join(home, ".claude"), roots);
235
308
  const sessions = [];
@@ -245,19 +318,7 @@ export const collectRewind = ({
245
318
  sessions.push(session);
246
319
  }
247
320
 
248
- const collectEach = (read) => {
249
- const results = roots.map(read);
250
- return results.every((value) => value === null) ? null : results.flatMap((value) => value ?? []);
251
- };
252
- const plans = collectEach((root) => plansIn(root, budget, redact, resolve(root) === stateRoot || resolve(root) === start));
253
- const litgoal = collectEach((root) => {
254
- const goal = litgoalOf(root, budget, redact);
255
- return goal ? [{ ...goal, local: resolve(root) === stateRoot || resolve(root) === start }] : null;
256
- });
257
- const handoffs = roots.flatMap((root) => handoffsOf(root, budget, redact));
258
321
  const commits = collectEach((root) => commitsOf(root, sinceMs, now, exec, redact));
259
- const workflows = collectEach((root) => stacksOf(root, budget, redact));
260
- const startWork = collectEach((root) => startWorkOf(root, budget, redact));
261
322
  const herdr = herdrOf(env, exec, redact);
262
323
 
263
324
  // A session waits on the user when it asked something, or holds a paused frame or boundary.
@@ -280,14 +341,33 @@ export const collectRewind = ({
280
341
  .slice(0, 5)
281
342
  .map(({ hash, subject }) => ({ hash, subject }));
282
343
  }
344
+ // A transcript only says when a session last moved. Its own hook record and its start-work run say
345
+ // more: a run it completed (and did not move past) makes it done; an idle or ended record at least
346
+ // as new as its last transcript line makes it idle or ended. This session is running the brief,
347
+ // whatever its last Stop wrote, and a session that asked the user something still waits.
348
+ const newestLiveness = new Map();
349
+ for (const record of liveness ?? []) {
350
+ if ((newestLiveness.get(record.sessionId)?.atMs ?? -Infinity) < record.atMs) newestLiveness.set(record.sessionId, record);
351
+ }
352
+ const recentRuns = (runs ?? []).filter((run) => now - run.atMs <= sinceMs).sort((a, b) => b.atMs - a.atMs);
353
+ for (const session of sessions) {
354
+ if ((sessionId && session.sessionId === sessionId) || session.status === "waiting-on-user") continue;
355
+ const live = newestLiveness.get(session.sessionId);
356
+ const run = recentRuns.find((item) => item.sessionId === session.sessionId);
357
+ if (run && !(live?.state === "alive" && live.atMs > run.atMs)) {
358
+ session.status = "done";
359
+ session.finishedPlan = run.plan;
360
+ } else if (live && live.state !== "alive" && live.atMs >= (session.lastMs ?? 0) - LIVENESS_SLACK_MS) {
361
+ session.status = live.state === "ended" ? "ended" : "idle";
362
+ }
363
+ }
283
364
  sessions.sort((a, b) => statusRank[a.status] - statusRank[b.status] || (b.lastMs ?? 0) - (a.lastMs ?? 0));
284
365
 
285
- // This worktree's open plans and the ones another worktree touched inside the window are listed,
286
- // this one's first, then the most recently changed, up to a short cap; a stale plan elsewhere is
287
- // left out entirely. The roadmap gauge counts this worktree only, since a sum over unrelated
288
- // branches measures nothing.
289
- const recent = (plan) => plan.local || (plan.changedMs !== null && now - plan.changedMs <= sinceMs);
290
- const orderedPlans = (plans ?? []).filter(recent).sort((a, b) => Number(b.local) - Number(a.local) || (b.changedMs ?? 0) - (a.changedMs ?? 0));
366
+ // Open plans changed inside the window are listed, this worktree's first, then the most recently
367
+ // changed, up to a short cap; a stale plan is left out, here or elsewhere. The roadmap gauge
368
+ // counts this worktree only, since a sum over unrelated branches measures nothing.
369
+ const recent = (plan) => plan.changedMs !== null && now - plan.changedMs <= sinceMs;
370
+ const orderedPlans = (plans ?? []).filter((plan) => !plan.complete && recent(plan)).sort((a, b) => Number(b.local) - Number(a.local) || (b.changedMs ?? 0) - (a.changedMs ?? 0));
291
371
  const shownPlans = orderedPlans.slice(0, PLAN_LIMIT);
292
372
  const localGoals = (litgoal ?? []).filter((goal) => goal.local);
293
373
  const roadmapItems = [...orderedPlans.filter((plan) => plan.local).map((plan) => plan.progress), ...localGoals.map((goal) => goal.progress)];
@@ -315,10 +395,16 @@ export const collectRewind = ({
315
395
  roadmap: {
316
396
  plans: shownPlans,
317
397
  plansOmitted: orderedPlans.length - shownPlans.length,
398
+ plansSkipped: plansSkipped.count,
318
399
  // Another worktree's finished objective is history, not roadmap.
319
400
  litgoal: (litgoal ?? []).filter((goal) => goal.local || goal.status !== "complete"),
320
401
  progress: roadmapItems.length ? aggregateProgress(roadmapItems) : progressOf(null, null),
321
402
  },
403
+ // Finished inside the window: completed start-work runs and plans with every row ticked.
404
+ finished: {
405
+ runs: recentRuns.map(({ worktree, plan, atMs }) => ({ worktree, plan, at: new Date(atMs).toISOString() })),
406
+ plans: (plans ?? []).filter((plan) => plan.complete && recent(plan)).map(({ worktree, plan, local, progress }) => ({ worktree, plan, local, gauge: progress.gauge })),
407
+ },
322
408
  workflows: (workflows ?? []).map((frame) => ({ ...frame, self: Boolean(sessionId) && frame.sessionId === sessionId })),
323
409
  startWork: startWork ?? [],
324
410
  handoffs,
@@ -337,7 +423,10 @@ export const collectRewind = ({
337
423
  }
338
424
  }
339
425
  for (const frame of data.workflows) delete frame.sessionId;
340
- for (const work of data.startWork) delete work.sessionId;
426
+ for (const work of data.startWork) {
427
+ work.self = Boolean(sessionId) && work.sessionId === sessionId;
428
+ delete work.sessionId;
429
+ }
341
430
  return data;
342
431
  };
343
432
 
@@ -0,0 +1,36 @@
1
+ // Each session's last hook event as one small record, `.litclaude/liveness/<session>.json`:
2
+ // PostToolUse and PostToolUseFailure say `alive`, Stop says `idle`, SessionEnd says `ended`. The LIT
3
+ // card reads it to tell running, idle and ended sessions apart, and to find herdr lanes of this
4
+ // project by the pane id the hooks ran under. A repeat of the same state is written at most every
5
+ // 30 s, so a busy session costs one small write per half minute.
6
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+
9
+ import { ignitionFileName } from "./mod/state.mjs";
10
+ import { requireStateDir, resolveProjectStateRoot, STATE_WRITE_FLAG } from "./project-state-root.mjs";
11
+
12
+ export const LIVENESS_STATES = Object.freeze(["alive", "idle", "ended"]);
13
+ const SAME_STATE_MS = 30_000;
14
+ const HERDR_PANE = /^[A-Za-z0-9:_-]{1,32}$/u;
15
+
16
+ export const livenessPath = (stateRoot, sessionId) => join(stateRoot, ".litclaude", "liveness", ignitionFileName(sessionId));
17
+
18
+ export const markLiveness = (cwd, sessionId, state, { now = Date.now(), env = process.env } = {}) => {
19
+ if (typeof sessionId !== "string" || !sessionId.trim() || !LIVENESS_STATES.includes(state)) return null;
20
+ const stateRoot = resolveProjectStateRoot(cwd);
21
+ // Only a project that already keeps LitClaude state gets the record; a plain repository stays untouched.
22
+ if (!existsSync(join(stateRoot, ".litclaude"))) return null;
23
+ const path = livenessPath(stateRoot, sessionId);
24
+ try {
25
+ const previous = JSON.parse(readFileSync(path, "utf8"));
26
+ if (previous?.state === state && now - Date.parse(previous.at) < SAME_STATE_MS) return null;
27
+ } catch {
28
+ // No record yet, or an unreadable one: write a fresh record.
29
+ }
30
+ const pane = typeof env.HERDR_PANE_ID === "string" && HERDR_PANE.test(env.HERDR_PANE_ID) ? env.HERDR_PANE_ID : null;
31
+ requireStateDir(join(stateRoot, ".litclaude", "liveness"));
32
+ const staging = `${path}.${process.pid}.tmp`;
33
+ writeFileSync(staging, `${JSON.stringify({ version: 1, sessionId, state, at: new Date(now).toISOString(), herdrPane: pane })}\n`, { flag: STATE_WRITE_FLAG });
34
+ renameSync(staging, path);
35
+ return path;
36
+ };
@@ -20,6 +20,7 @@ import {
20
20
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
22
 
23
+ import { SCOPE_LINE } from "./plan-scope-roots.mjs";
23
24
  import { parsePlanTaskRows } from "./plan-task-rows.mjs";
24
25
  import { requireStateDir, STATE_APPEND_FLAG, STATE_WRITE_FLAG } from "./project-state-root.mjs";
25
26
  import { pathIdentity, samePathIdentity } from "./secure-path-read.mjs";
@@ -1378,9 +1379,156 @@ const planRoute = (root, work) => {
1378
1379
  return path.startsWith("..") || isAbsolute(path) ? work.active_plan : path;
1379
1380
  };
1380
1381
 
1382
+ // Words and operators of a command another session sends to watch the work. Single quotes hold
1383
+ // data verbatim. Outside them only path-like characters pass (`*` and `?` mark the word as a glob);
1384
+ // `|`, ` && ` and `2>&1` must stand alone between spaces. Anything else (`;`, `||`, `$`, a backtick,
1385
+ // a double quote, a backslash, a redirect, a newline) refuses the whole command.
1386
+ const OBSERVATION_CHAR = /[\p{L}\p{N}_.\/@+,:=%-]/u;
1387
+ const observationTokens = (command) => {
1388
+ const tokens = [];
1389
+ const chars = [...command];
1390
+ let word = null;
1391
+ const standalone = (index, text) => word === null && chars.slice(index, index + text.length).join("") === text
1392
+ && (index + text.length === chars.length || /[ \t]/u.test(chars[index + text.length]));
1393
+ for (let index = 0; index < chars.length; index += 1) {
1394
+ const ch = chars[index];
1395
+ if (ch === " " || ch === "\t") {
1396
+ if (word) tokens.push(word);
1397
+ word = null;
1398
+ } else if (ch === "'") {
1399
+ const end = chars.indexOf("'", index + 1);
1400
+ if (end < 0) return null;
1401
+ word ??= { text: "", quoted: false, glob: false };
1402
+ word.text += chars.slice(index + 1, end).join("");
1403
+ word.quoted = true;
1404
+ index = end;
1405
+ } else if (standalone(index, "&&") || standalone(index, "2>&1")) {
1406
+ const op = standalone(index, "&&") ? "&&" : "2>&1";
1407
+ tokens.push({ op });
1408
+ index += op.length - 1;
1409
+ } else if (standalone(index, "|")) {
1410
+ tokens.push({ op: "|" });
1411
+ } else if (OBSERVATION_CHAR.test(ch) || ch === "*" || ch === "?") {
1412
+ word ??= { text: "", quoted: false, glob: false };
1413
+ word.text += ch;
1414
+ if (ch === "*" || ch === "?") word.glob = true;
1415
+ } else {
1416
+ return null;
1417
+ }
1418
+ }
1419
+ if (word) tokens.push(word);
1420
+ return tokens;
1421
+ };
1422
+
1423
+ const plainWord = (word) => Boolean(word) && !word.op && !word.quoted && !word.glob;
1424
+ // A word starting with `-` is a flag only when bare; quoted, the tool would still read it as one.
1425
+ const flagWord = (word, pattern) => plainWord(word) && pattern.test(word.text);
1426
+ const dataWord = (word) => Boolean(word) && !word.op && !word.glob && !word.text.startsWith("-");
1427
+
1428
+ const HERDR_READS = Object.freeze({ agent: ["read", "get", "list"], pane: ["read", "list"], tab: ["list"] });
1429
+ // Only the flags a read needs: a flag herdr may add later (an output file, keys to send) is refused.
1430
+ const HERDR_READ_FLAG = /^--(?:source|lines|workspace|tab|json)(?:=[\w.:-]+)?$/u;
1431
+ const HERDR_ID = /^[A-Za-z0-9][\w.:-]*$/u;
1432
+ const observeHerdr = ([noun, verb, ...rest]) => plainWord(noun) && plainWord(verb)
1433
+ && Object.hasOwn(HERDR_READS, noun.text) && HERDR_READS[noun.text].includes(verb.text)
1434
+ && rest.every((word) => plainWord(word) && (HERDR_READ_FLAG.test(word.text) || HERDR_ID.test(word.text)));
1435
+
1436
+ // grep or rg over existing paths: bare flags from a closed set, the include/exclude globs, one
1437
+ // pattern, then plain path operands. Flags that read a pattern file or run a preprocessor are absent.
1438
+ const observeSearch = (args, cwd) => {
1439
+ let pattern = false;
1440
+ for (const word of args) {
1441
+ if (word.op) return false;
1442
+ if (word.text.startsWith("-")) {
1443
+ if (flagWord(word, /^-[rRlLnicvwxoEFHhsqZ]+$/u)) continue;
1444
+ if (!word.quoted && /^--(?:include|exclude|exclude-dir)=[\w.*?-]+$/u.test(word.text)) continue;
1445
+ return false;
1446
+ }
1447
+ if (word.glob) return false;
1448
+ if (!pattern) pattern = true;
1449
+ else if (word.quoted || !PLAIN_PATH_WORD.test(word.text) || !existsSync(resolve(cwd, word.text))) return false;
1450
+ }
1451
+ return pattern;
1452
+ };
1453
+
1454
+ const LIST_WORD = /^[\d,-]+$/u;
1455
+ const observeFilter = ([head, ...args]) => {
1456
+ if (!plainWord(head)) return false;
1457
+ switch (head.text) {
1458
+ case "grep":
1459
+ case "rg":
1460
+ return args.every((word) => flagWord(word, /^-[vinEFcwxoh]+$/u) || dataWord(word))
1461
+ && args.filter((word) => !word.text.startsWith("-")).length === 1;
1462
+ case "head":
1463
+ case "tail":
1464
+ for (let index = 0; index < args.length; index += 1) {
1465
+ if (flagWord(args[index], /^-n$/u) && flagWord(args[index + 1], /^\d+$/u)) index += 1;
1466
+ else if (!flagWord(args[index], /^-(?:\d+|q)$/u)) return false;
1467
+ }
1468
+ return true;
1469
+ case "cut":
1470
+ for (let index = 0; index < args.length; index += 1) {
1471
+ if (flagWord(args[index], /^-c[\d,-]+$/u)) continue;
1472
+ if (flagWord(args[index], /^-[cf]$/u) && flagWord(args[index + 1], LIST_WORD)) index += 1;
1473
+ else if (flagWord(args[index], /^-d$/u) && args[index + 1] && !args[index + 1].op && !args[index + 1].glob && [...args[index + 1].text].length === 1) index += 1;
1474
+ else return false;
1475
+ }
1476
+ return true;
1477
+ case "wc":
1478
+ return args.every((word) => flagWord(word, /^-[lwcm]+$/u));
1479
+ case "sort":
1480
+ return args.every((word) => flagWord(word, /^-[unrbf]+$/u));
1481
+ case "uniq":
1482
+ return args.every((word) => flagWord(word, /^-[cdu]+$/u));
1483
+ default:
1484
+ return false;
1485
+ }
1486
+ };
1487
+
1488
+ // What another session may run to watch a running work without changing it: up to four segments
1489
+ // joined by ` && `, each a `cd <dir>`, a herdr read (agent read|get|list, pane read|list, tab list)
1490
+ // or a grep/rg read, each followed by up to four read-only pipe filters. Only otherSessionDecision
1491
+ // calls this; the owner's guard keeps classifyBash.
1492
+ export const classifyObservation = (command, cwd) => {
1493
+ if (typeof command !== "string" || command.length === 0 || command.length > 32_768) return false;
1494
+ if (forbiddenShellPattern.test(command)) return false;
1495
+ const tokens = observationTokens(command.trim());
1496
+ if (!tokens?.length) return false;
1497
+ const segments = [[]];
1498
+ for (const token of tokens) {
1499
+ if (token.op === "&&") segments.push([]);
1500
+ else if (token.op !== "2>&1") segments.at(-1).push(token);
1501
+ }
1502
+ if (segments.length > MAX_CHAIN_SEGMENTS) return false;
1503
+ let here = cwd;
1504
+ for (const segment of segments) {
1505
+ const parts = [[]];
1506
+ for (const token of segment) {
1507
+ if (token.op === "|") parts.push([]);
1508
+ else parts.at(-1).push(token);
1509
+ }
1510
+ const [[head, ...args], ...filters] = parts;
1511
+ if (!plainWord(head) || filters.length > 4 || filters.some((filter) => !observeFilter(filter))) return false;
1512
+ if (head.text === "cd") {
1513
+ if (filters.length || args.length !== 1 || !plainWord(args[0])) return false;
1514
+ const moved = classifyCd(`cd ${args[0].text}`, here);
1515
+ if (!moved || moved.denied) return false;
1516
+ here = moved.cd;
1517
+ } else if (head.text === "herdr") {
1518
+ if (!observeHerdr(args)) return false;
1519
+ } else if (head.text === "grep" || head.text === "rg") {
1520
+ if (!observeSearch(args, here)) return false;
1521
+ } else {
1522
+ return false;
1523
+ }
1524
+ }
1525
+ return true;
1526
+ };
1527
+
1381
1528
  // Another session in the project of a running work: reading, searching, read-only shell, loading a
1382
- // skill, a read-type agent and the status call pass with a note; anything that changes files is
1383
- // refused with the work, its age and the ways out. The owner's work never pauses for it.
1529
+ // skill, a read-type agent, the status call and an observation command pass with a note; anything
1530
+ // that changes files is refused with the work, its age and the ways out. The owner's work never
1531
+ // pauses for it.
1384
1532
  const STATUS_CALL = /^(?:litclaude-ai|litclaude)[ \t]+start-work[ \t]+status(?:[ \t]+--json)?$/u;
1385
1533
  const READ_ACTIONS = new Set(["read", "vcs-read"]);
1386
1534
  const otherSessionDecision = (root, work, input, now) => {
@@ -1397,6 +1545,14 @@ const otherSessionDecision = (root, work, input, now) => {
1397
1545
  reads = false;
1398
1546
  }
1399
1547
  }
1548
+ if (!reads && toolName === "Bash") {
1549
+ try {
1550
+ const cwd = canonicalDirectory(typeof input.cwd === "string" ? input.cwd : root, "tool cwd");
1551
+ reads = classifyObservation(input?.tool_input?.command, cwd);
1552
+ } catch {
1553
+ reads = false;
1554
+ }
1555
+ }
1400
1556
  if (reads) {
1401
1557
  return { decision: "allow-normal", action: "read", root, roots: [root], context: `Another session is running start-work ${work.work_id} here (last activity ${age} ago); you may read, not change files.` };
1402
1558
  }
@@ -1683,9 +1839,6 @@ export const openPlans = (root) => {
1683
1839
  }).map((name) => `plans/${name}`);
1684
1840
  };
1685
1841
 
1686
- // `Scope roots: <path> (<action>, <action>)` lines in the plan widen the grants it starts with.
1687
- const SCOPE_LINE = /^Scope roots?:[ \t]*(\S+)[ \t]*\(([a-z, -]+)\)[ \t]*$/gmu;
1688
-
1689
1842
  const derivedGrants = (root, plan, workId) => {
1690
1843
  const grants = ["read", "write", "execute", "test", "package", "vcs-read"].map((action) => ({ action, root, issuedBy: "user-invocation" }));
1691
1844
  if (!rootCovers(root, dirname(plan))) grants.push({ action: "read", root: dirname(plan), issuedBy: "user-invocation" });
@@ -29,6 +29,7 @@ import { realpathSync } from "node:fs";
29
29
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
30
30
  import { fileURLToPath } from "node:url";
31
31
 
32
+ import { describeScopePath, uncoveredScopePaths } from "../lib/plan-scope-roots.mjs";
32
33
  import { parsePlanTaskRows, planLinesOutsideFences } from "../lib/plan-task-rows.mjs";
33
34
  import { ensureStateDirIgnored, resolveProjectStateRoot } from "../lib/project-state-root.mjs";
34
35
  import { readRegularStable, samePathIdentity } from "../lib/secure-path-read.mjs";
@@ -950,7 +951,7 @@ export async function scaffold(cwd, { slug, intent, reset = false, force = false
950
951
  * UNCHECKED at this point. `scripts/audit-plan-checkboxes.mjs` is the different,
951
952
  * post-completion audit that requires them checked.
952
953
  */
953
- export function checkPlanStructure(text) {
954
+ export function checkPlanStructure(text, projectRoot = null) {
954
955
  const problems = [];
955
956
  const lines = text.split(/\r?\n/u);
956
957
  const visibleLines = planLinesOutsideFences(text);
@@ -1008,6 +1009,11 @@ export function checkPlanStructure(text) {
1008
1009
  problems.push("unfilled <fill ...> placeholders remain โ€” the plan is not decision-complete");
1009
1010
  }
1010
1011
 
1012
+ // A folder outside the project that a todo names is granted up front, never asked for mid-run.
1013
+ if (projectRoot) {
1014
+ for (const entry of uncoveredScopePaths(text, projectRoot)) problems.push(describeScopePath(entry));
1015
+ }
1016
+
1011
1017
  return { ok: problems.length === 0, problems };
1012
1018
  }
1013
1019
 
@@ -1019,7 +1025,7 @@ async function runCheck(checkPath, cwd) {
1019
1025
  throw new Error(`refused: --check cannot safely read ${checkPath}: ${read.failure}`);
1020
1026
  }
1021
1027
  const text = read.bytes.toString("utf8");
1022
- const { ok, problems } = checkPlanStructure(text);
1028
+ const { ok, problems } = checkPlanStructure(text, cwd);
1023
1029
  if (ok) {
1024
1030
  process.stdout.write(`PLAN_STRUCTURE_PASS: ${checkPath}\n`);
1025
1031
  return 0;
@@ -46,18 +46,19 @@ verdicts: [PASS, FAIL, BLOCKED]
46
46
 
47
47
  ## #contract.outputs
48
48
 
49
- The collector draws the brief in Markdown (`lib/rewind/brief.mjs`), so its shape is the same every time and a tired reader finds each part where it was last time. It has five parts, in this order:
49
+ The collector draws the brief in Markdown (`lib/rewind/brief.mjs`), so its shape is the same every time and a tired reader finds each part where it was last time. It opens with three lines, then has five parts, in this order:
50
50
 
51
+ 0. **Three opening lines**, from records only: `Done so far:` this worktree's newest commits in the window (two at most), then its completed start-work runs (`<plan> (start-work complete)`) and its plans with every row ticked (`<plan> [โ–‰โ–‰] 2/2`), three items at most, else its finished litgoal objective, else "nothing finished in this window"; `Doing now:` this session's top workflow frame (skill, stage, gauge), else its running start-work plan, else the newest active session's title, else "nothing running"; `Next:` the recommended step with the word to type in brackets (`(type go)`). In Korean: `์ง€๊ธˆ๊นŒ์ง€:`, `์ง€๊ธˆ:`, `๋‹ค์Œ: โ€ฆ (go ์ž…๋ ฅ)`.
51
52
  1. **Headline.** One `## ๐Ÿงญ` line: sessions found, how many wait on the user, how many are active, and the next step in plain words: `์„ธ์…˜ 7๊ฐœ ยท ๋‚˜๋ฅผ ๊ธฐ๋‹ค๋ฆฌ๋Š” ๊ฒƒ 1 ยท ์ง„ํ–‰ ์ค‘ 4 ยท ๋‹ค์Œ: ๋ฉˆ์ถ˜ lit-loop(verify) ์ด์–ด๊ฐ€๊ธฐ` / `7 sessions ยท 1 waits on you ยท 4 active ยท next: Resume the paused lit-loop at verify`. A dim line under it gives the window and how many worktrees were read.
52
53
  2. **Live session cards, grouped by worktree and branch.** Sessions that wait on the user or are active come first: a `### ๐ŸŒฟ branch ยท worktree` heading per group, then one quoted card per session:
53
- - a coloured status badge (๐ŸŸ  waiting on you, ๐ŸŸข active, โšช ended, โšซ unknown; see `references/status-taxonomy.md`) with the reason it waits, its `id8`, how long ago it last moved, and `this session` / `์ด ์„ธ์…˜` for the current one;
54
+ - a coloured status badge (๐ŸŸ  waiting on you, ๐ŸŸข active, ๐Ÿ’ค idle, โœ… done, โšช ended, โšซ unknown; see `references/status-taxonomy.md`) with the reason it waits, its `id8`, how long ago it last moved, and `this session` / `์ด ์„ธ์…˜` for the current one;
54
55
  - the goal in bold, from the session's title, else its first ask;
55
56
  - its progress: a gauge with the next remaining items when both numbers are recorded, otherwise the known facts after โณ (how long it ran and its last ask);
56
57
  - โœ… what was done: edited files and commits, or, before any edit, the tools it used most;
57
- - โ–ถ what is next for that session: answer the question it asked, resume its paused frame, approve its boundary, its plan's current item, or what it is doing now (its last tool call: `Bash โ€œRun the gatesโ€`).
58
+ - โ–ถ what is next for that session: answer the question it asked, resume its paused frame, approve its boundary, its plan's current item, or what it is doing now (its last tool call: `Bash โ€œRun the gatesโ€`, for an active session only). A done session names the plan its run finished; an idle or done session's last tool call is never offered as its next step.
58
59
  3. **Ended sessions, one table row each.** A `### โšช Ended ยท N` table (id, where, goal, ended, done), at most 8 rows and a count of the rest.
59
60
  4. **Roadmap timeline.** A `### ๐Ÿ—บ๏ธ` heading with this worktree's roadmap gauge, then โœ“ finished commits with their dates and branch, โ–ถ the current item of each open plan of this worktree and of plans another worktree changed inside the window (with its worktree name) with its gauge, โ—‹ the items after it, then litgoal objectives. Stale plans elsewhere, unfilled plan scaffolds and another worktree's finished objectives are left out.
60
- 5. **One recommended next step** in a box, from `next`, with the word to type (`go`, `lit continue` or `lit approve`), then one line: "Type `go` to continue." When nothing can run on `go`, the box still recommends a real step from the records (a session waiting on the user, a paused workflow, an open plan item, the latest active session, the latest ended one) and says that nothing runs on its own.
61
+ 5. **One recommended next step** in a box, from `next`, with the word to type (`go`, `lit continue` or `lit approve`), then one line: "Type `go` to continue." When nothing can run on `go`, the box still recommends a real step from the records: first the first item under `## Next` or `## Next Steps` in this worktree's own `HANDOFF*.md`, then a session waiting on the user, a paused workflow, an open plan item, the latest active session, then the newest listed session that is not running (review what a done one finished, or pick up an idle or ended one). Only a window with no session and no plan says there is nothing to start. It says that nothing runs on its own, and a HANDOFF step never carries a word to type.
61
62
 
62
63
  **Progress gauges (D9), required.** A gauge appears only when both numbers are real, in the form `[โ–‰โ–‰โ–‰โ–‘โ–‘] 3/5` (filled `โ–‰` done, light `โ–‘` remaining, then done/total). An unknown total has no gauge: the card states what is known in words instead. Never a question-mark gauge, never a guess, never an estimate, never a gauge of your own.
63
64
 
@@ -102,24 +103,27 @@ The collector (`plugins/litclaude/lib/rewind/collect.mjs`, served as `litclaude-
102
103
  | Source | What it gives | Missing reads |
103
104
  | --- | --- | --- |
104
105
  | Claude Code transcripts, `<config>/projects/<slug>/*.jsonl` | per session: title (custom, then AI, then first prompt), first and last ask, tools used, files changed, last assistant text, status | `transcripts: unknown` |
105
- | `plans/*.md` checkbox rows | open plans, current item, done/total, remaining names | `plans: unknown` |
106
+ | `plans/*.md` checkbox rows | open plans changed inside the window (this worktree's too), current item, done/total, remaining names | `plans: unknown` |
106
107
  | `.litclaude/litgoal/goals.json` | objective and passed/total criteria | `litgoal: unknown` |
107
- | `HANDOFF*.md` | headings from the first 40 lines only | `handoffs: unknown` |
108
+ | `HANDOFF*.md` | headings from the first 40 lines; for this worktree's own file only, the first item under `## Next` / `## Next Steps` | `handoffs: unknown` |
108
109
  | `git log --since` | commits in the window, matched to sessions by time and branch | `git: unknown` |
109
110
  | `.litclaude/workflow-stack/*.json` | running and paused disciplines with stage and k/n | `workflowStack: unknown` |
110
- | `.litclaude/boulder.json` | active start-work, its plan progress and any boundary waiting for approval | `startWork: unknown` |
111
+ | `.litclaude/boulder.json` | active start-work, its plan progress and any boundary waiting for approval; completed runs from its history | `startWork: unknown` |
112
+ | `.litclaude/liveness/*.json` | each session's last hook event (`alive`, `idle`, `ended`), written by PostToolUse, Stop and SessionEnd | the transcript time alone decides |
111
113
  | `herdr agent list` (only when `HERDR_ENV=1`) | agent panes | `herdr: unknown` |
112
114
 
113
- Transcripts are read head (64 KiB) and tail (256 KiB) only, under one 8 MiB budget for the whole run, through descriptors opened without following links; subagent transcripts and sidechain lines are skipped. The slug is the session's absolute cwd with every character outside `[A-Za-z0-9]` turned into `-`; a folder whose slug is missing is found by the `cwd` its newest transcript records. Every string is redacted before it leaves the collector: credential shapes, `NAME=value` with a secret-like name, URI userinfo, any current environment value of eight or more characters, and the home directory (shown as `~`).
115
+ Plans, litgoal, handoffs, workflow stacks and start-work are read first, then transcripts, so a busy transcript folder never crowds out the plans; a plan met after the budget ran out is counted and the brief says how many were not read. Transcripts are read head (64 KiB) and tail (256 KiB) only, under one 8 MiB budget for the whole run, through descriptors opened without following links; subagent transcripts and sidechain lines are skipped. The slug is the session's absolute cwd with every character outside `[A-Za-z0-9]` turned into `-`; a folder whose slug is missing is found by the `cwd` its newest transcript records. Every string is redacted before it leaves the collector: credential shapes, `NAME=value` with a secret-like name, URI userinfo, any current environment value of eight or more characters, and the home directory (shown as `~`).
114
116
 
115
117
  ## Status taxonomy
116
118
 
117
119
  - `waiting-on-user`: the session's last word was the assistant asking something, or it holds a paused workflow frame or a start-work boundary awaiting `lit approve`.
118
120
  - `active`: written to within the last 15 minutes and not waiting.
119
- - `ended`: quiet for longer than that.
121
+ - `done`: its start-work run completed in the window and it has not moved since.
122
+ - `idle`: its last hook event was a Stop at least as new as its last transcript line (another session's only; this session is always active while it runs the brief).
123
+ - `ended`: quiet for longer than 15 minutes, or its last hook event was SessionEnd.
120
124
  - `unknown`: the transcript held no timestamp.
121
125
 
122
- Sessions waiting on the user come first, then active ones, newest first.
126
+ Sessions waiting on the user come first, then active ones, then idle and done ones, newest first.
123
127
 
124
128
  ## The next step
125
129
 
@@ -163,6 +167,9 @@ The colours move by hue at a steady lightness, so the card never flashes: at mos
163
167
  | The brief says no session records were found | No `projects/` folder under the Claude config dir | Print it as drawn; plans and goals still show |
164
168
  | The brief says older sessions were not read | The 8 MiB budget ran out | Print it as drawn |
165
169
  | A card shows โณ facts and no gauge | No stack, plan or start-work records a total for that session | Print it as drawn; do not estimate |
166
- | The box recommends a step with no word to type | `next.kind: none`; the step is drawn from the records | Print it as drawn; do not run it or invent another |
170
+ | The box recommends a step with no word to type | `next.kind: none`; the step is drawn from the records (this worktree's HANDOFF.md Next item first) | Print it as drawn; do not run it or invent another |
171
+ | The brief says N plans were not read | The read budget ran out before those plan files | Print it as drawn |
172
+ | A plan you expected is missing | It was last changed before the window (`--since`, 7 days by default) | Print it as drawn; a wider `--since` lists it |
173
+ | `Doing now: nothing running` | No frame, start-work or active session is on record | Print it as drawn |
167
174
 
168
175
  See `references/card-examples.md` for complete briefs in English and Korean and `references/status-taxonomy.md` for the status wording in both languages.
@@ -57,7 +57,7 @@ with the language.
57
57
  - โ—‹ later ยท 12. go continues
58
58
  - โ—‹ later ยท 13. card
59
59
 
60
- ```text
60
+ ```
61
61
  โ•ญโ”€ RECOMMENDED NEXT STEP โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
62
62
  โ”‚ Resume the paused lit-loop at verify โ”‚
63
63
  โ”‚ type: lit continue โ”‚
@@ -104,7 +104,7 @@ Type **`lit continue`** to continue.
104
104
  - โ—‹ ์ดํ›„ ยท 12. go continues
105
105
  - โ—‹ ์ดํ›„ ยท 13. card
106
106
 
107
- ```text
107
+ ```
108
108
  โ•ญโ”€ ์ถ”์ฒœํ•˜๋Š” ๋‹ค์Œ ๋‹จ๊ณ„ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
109
109
  โ”‚ ๋ฉˆ์ถ˜ lit-loop(verify) ์ด์–ด๊ฐ€๊ธฐ โ”‚
110
110
  โ”‚ ์ž…๋ ฅ: lit continue โ”‚
@@ -1,20 +1,25 @@
1
1
  # lit-adhd status taxonomy
2
2
 
3
3
  The collector assigns every session exactly one status. The brief renders it in the user's language
4
- with the words below and never invents a fifth.
4
+ with the words below and never invents another.
5
5
 
6
6
  | Status | Set when | English | ํ•œ๊ตญ์–ด |
7
7
  | --- | --- | --- | --- |
8
8
  | `waiting-on-user` | The last transcript entry is the assistant asking something (a closing `?`, `lit approve`, `ํ™•์ธํ•ด ์ฃผ์„ธ์š”`, `ํ• ๊นŒ์š”`โ€ฆ), or the session holds a paused workflow frame or a start-work boundary | waiting on you | ๋‚˜๋ฅผ ๊ธฐ๋‹ค๋ฆผ |
9
9
  | `active` | A transcript write within the last 15 minutes and not waiting | active | ์ง„ํ–‰ ์ค‘ |
10
- | `ended` | Quiet for longer than 15 minutes | ended | ๋๋‚จ |
10
+ | `done` | Its start-work run completed inside the window (boulder history) and its liveness record shows no activity after that | done | ์™„๋ฃŒ |
11
+ | `idle` | Another session whose newest liveness record is `idle`, at least as new as its last transcript line | idle | ์‰ฌ๋Š” ์ค‘ |
12
+ | `ended` | Quiet for longer than 15 minutes, or its newest liveness record is `ended` | ended | ๋๋‚จ |
11
13
  | `unknown` | The transcript held no timestamp | unknown | ๋ชจ๋ฆ„ |
12
14
 
15
+ The session running the brief is always `active`, and a `waiting-on-user` session keeps that status
16
+ whatever its liveness record says.
17
+
13
18
  `waitingReason` says why a session waits: `asked the user`, `paused workflow` or
14
19
  `start-work boundary`. Name it in the card's status cell when present: `waiting on you (paused
15
20
  workflow)` / `๋‚˜๋ฅผ ๊ธฐ๋‹ค๋ฆผ (๋ฉˆ์ถ˜ ์›Œํฌํ”Œ๋กœ)`.
16
21
 
17
- Order in the brief: waiting sessions first, then active, ended and unknown; newest first inside each group.
22
+ Order in the brief: waiting sessions first, then active, then idle and done, then ended and unknown; newest first inside each group.
18
23
 
19
24
  ## Sources
20
25
 
@@ -89,11 +89,18 @@ fresh Claude Code session execute without re-solving the architecture.
89
89
  This skill is **planning-only**. You must not implement, must not edit files for
90
90
  product changes, and must not run mutating commands. Do not call any start-work
91
91
  tool from inside planning mode. Close the saved plan with one step: tell the
92
- user to type `/litclaude:start-work plans/<slug>.md`; typing it approves this plan and runs it,
93
- so no second confirm reply and no `/goal` line is needed. The hook starts the work
92
+ user to type `go` within 30 minutes, or `/litclaude:start-work plans/<slug>.md`;
93
+ typing it approves this plan and runs it, so no second confirm reply and no `/goal` line is needed. The
94
+ Stop hook saves the plan as this session's next step once the plan file is written, which is
95
+ what lets the one word `go` start it. The hook starts the work
94
96
  with grants derived from the project; a plan that needs more names it on a line
95
97
  such as `Scope roots: <path> (read)`, and anything else outside the
96
- project pauses until the user answers `lit approve` or `lit deny`.
98
+ project pauses until the user answers `lit approve` or `lit deny`. Every absolute
99
+ path a todo names outside the project must sit under such a line: `scaffold-plan.mjs
100
+ --check` and the Stop hook list each uncovered one with the exact line to paste
101
+ (`Scope roots: <existing folder> (read)`), and the Stop hook blocks until it is there.
102
+ Widen `(read)` by hand when a lane must write in that folder. A command quoted in
103
+ backticks is data and is not read for paths.
97
104
 
98
105
  ## Planning Contract
99
106