@litfamily/litclaude 1.0.51 → 1.0.52

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.
@@ -23,6 +23,8 @@ import { fileURLToPath } from "node:url";
23
23
  import { SCOPE_LINE } from "./plan-scope-roots.mjs";
24
24
  import { parsePlanTaskRows } from "./plan-task-rows.mjs";
25
25
  import { requireStateDir, STATE_APPEND_FLAG, STATE_WRITE_FLAG } from "./project-state-root.mjs";
26
+ import { isGoPrompt } from "./rewind/next-step.mjs";
27
+ import { recordRunEnd } from "./shown-ledger.mjs";
26
28
  import { pathIdentity, samePathIdentity } from "./secure-path-read.mjs";
27
29
 
28
30
  const SCHEMA_VERSION = 3;
@@ -805,6 +807,7 @@ const finishWork = (root, operation, request) => withLock(root, () => {
805
807
  const response = { ok: true, operation, state: publicState(state) };
806
808
  rememberIdempotency(state, request.idempotencyKey, fingerprint, response);
807
809
  saveState(canonicalRoot, state);
810
+ recordRunEnd({ stateRoot: canonicalRoot, source: "start-work", id: work.work_id, outcome: operation === "complete" ? "sent" : "nothing" });
808
811
  return response;
809
812
  });
810
813
 
@@ -851,6 +854,7 @@ export const cancelStartWorkFromUserPrompt = (root, { sessionId, promptId }) =>
851
854
  const response = { cancelled: { workId: work.work_id, plan: work.plan_name, otherSession: owner !== sessionId, lanes } };
852
855
  rememberIdempotency(state, key, requestHash("typed-cancel", { sessionId, promptId }), response);
853
856
  saveState(canonicalRoot, state);
857
+ recordRunEnd({ stateRoot: canonicalRoot, source: "start-work", id: work.work_id, outcome: "nothing" });
854
858
  return response;
855
859
  });
856
860
  };
@@ -1068,7 +1072,7 @@ const classifyNodeScriptWords = (args, cwd) => {
1068
1072
  };
1069
1073
 
1070
1074
  const LITCLAUDE_CLI_NAMES = new Set(["litclaude-ai", "litclaude"]);
1071
- const START_WORK_SELF_MOVES = new Set(["progress", "complete", "cancel"]);
1075
+ const START_WORK_SELF_MOVES = new Set(["progress", "complete", "cancel", "lane-finalize"]);
1072
1076
 
1073
1077
  // This install's own CLI entry points: the plugin's bin/litclaude-ai that Claude Code puts on PATH,
1074
1078
  // and the package's bin/litclaude-ai.js. A command naming either by path runs code the guard
@@ -1126,6 +1130,14 @@ const classifyReadOnlyGit = (command, cwd) => {
1126
1130
  const classifyBashWords = (words, cwd) => {
1127
1131
  const [head, ...args] = words;
1128
1132
  if (head.text === "grep" || head.text === "rg") return classifySearchWords(head.text, args, cwd);
1133
+ // `date [+FORMAT]` and `tmux ls` only print; `date -s`, a bare date operand and every other tmux
1134
+ // verb (kill-server, send-keys) meet the strict checks.
1135
+ if (head.text === "date" && (args.length === 0 || (args.length === 1 && args[0].text.startsWith("+")))) {
1136
+ return canonicalBashTargets(cwd, [], "read");
1137
+ }
1138
+ if (head.text === "tmux" && args.length === 1 && (args[0].text === "ls" || args[0].text === "list-sessions")) {
1139
+ return canonicalBashTargets(cwd, [], "read");
1140
+ }
1129
1141
  let cli = null;
1130
1142
  let rest = [];
1131
1143
  let trusted = false;
@@ -1233,15 +1245,77 @@ const classifyBash = (command, cwd) => {
1233
1245
  };
1234
1246
 
1235
1247
  // `env -u NAME…` only removes variables, `2>&1` only joins the streams, and a trailing filter
1236
- // (`| tail -8`, `| grep -c ok`, `| wc -l`) only reads the output: each is peeled off before the
1237
- // command under it is classified. An assignment, a file operand or any other pipe stays put.
1248
+ // (`| tail -8`, `| grep -c 'ok '`, `| cut -d: -f1`) only reads the output: each is peeled off before
1249
+ // the command under it is classified. An assignment, a file operand or any other pipe stays put.
1238
1250
  const ENV_UNSET = /^env(?:[ \t]+-u[ \t]+[A-Za-z_][A-Za-z0-9_]*)+[ \t]+(?=\S)/u;
1239
- // Each filter takes only flags that read stdin and print: no `-f` pattern file, no `-o` output file.
1240
- const FILTER_PIPE = /[ \t]*\|[ \t]*(?:(?:tail|head)(?:[ \t]+-[nc][ \t]+\d+|[ \t]+-\d+|[ \t]+-q)*|wc(?:[ \t]+-[lwcm]+)*|sort(?:[ \t]+-[unrb]+)*|grep(?:[ \t]+-[cvinlEFwxq]+)*[ \t]+[A-Za-z0-9_.:-]+)[ \t]*$/u;
1241
1251
  const STDERR_JOIN = /[ \t]+2>&1(?=[ \t]*$)/u;
1252
+ const MAX_FILTERS = 4;
1253
+
1254
+ // The segment cut at each `|` the shell would see: one outside quotes and not escaped. A `||`, an
1255
+ // unclosed quote, a backslash outside quotes or an empty part gives null, and nothing is peeled.
1256
+ const pipeParts = (segment) => {
1257
+ const parts = [];
1258
+ let start = 0;
1259
+ let quote = null;
1260
+ for (let index = 0; index < segment.length; index += 1) {
1261
+ const ch = segment[index];
1262
+ if (quote === "'") {
1263
+ if (ch === "'") quote = null;
1264
+ } else if (quote === '"') {
1265
+ if (ch === "\\") index += 1;
1266
+ else if (ch === '"') quote = null;
1267
+ } else if (ch === "'" || ch === '"') {
1268
+ quote = ch;
1269
+ } else if (ch === "\\") {
1270
+ return null;
1271
+ } else if (ch === "|") {
1272
+ if (segment[index + 1] === "|") return null;
1273
+ parts.push(segment.slice(start, index));
1274
+ start = index + 1;
1275
+ }
1276
+ }
1277
+ if (quote) return null;
1278
+ parts.push(segment.slice(start));
1279
+ return parts.every((part) => part.trim()) ? parts : null;
1280
+ };
1281
+
1282
+ // Each filter reads stdin and prints, with no file operand: no `-f` pattern file, no `-o` output
1283
+ // file. A grep or rg pattern is one word of data, quoted or not, with no `$` or backtick in it.
1284
+ const READ_FILTER_FLAGS = Object.freeze({ wc: /^-[lwcm]+$/u, sort: /^-[unrb]+$/u, uniq: /^-c$/u, cut: /^-(?:d.|f[\d,-]+)$/su });
1285
+ const headTailArgs = (args) => {
1286
+ for (let index = 0; index < args.length; index += 1) {
1287
+ const text = args[index];
1288
+ if (text === "-n" || text === "-c") {
1289
+ index += 1;
1290
+ if (!/^\d+$/u.test(args[index] ?? "")) return false;
1291
+ } else if (!/^-(?:[nc]?\d+|q)$/u.test(text)) {
1292
+ return false;
1293
+ }
1294
+ }
1295
+ return true;
1296
+ };
1297
+ const isReadFilter = (part) => {
1298
+ if (/[$`]/u.test(part)) return false;
1299
+ const words = shellWords(part.trim())?.map(({ text }) => text);
1300
+ if (!words) return false;
1301
+ const [head, ...args] = words;
1302
+ if (head === "head" || head === "tail") return headTailArgs(args);
1303
+ if (head === "grep" || head === "rg") {
1304
+ const flags = args.slice(0, -1);
1305
+ return args.length > 0 && !args.at(-1).startsWith("-") && flags.every((text) => /^-[cvinlEFwxq]+$/u.test(text));
1306
+ }
1307
+ if (head === "cut" && !args.some((text) => text.startsWith("-f"))) return false;
1308
+ return Object.hasOwn(READ_FILTER_FLAGS, head) && args.every((text) => READ_FILTER_FLAGS[head].test(text));
1309
+ };
1310
+
1242
1311
  const peelShellNoise = (segment) => {
1243
1312
  let text = segment.replace(ENV_UNSET, "");
1244
- for (let guard = 0; guard < 4 && FILTER_PIPE.test(text); guard += 1) text = text.replace(FILTER_PIPE, "");
1313
+ const parts = pipeParts(text);
1314
+ if (parts && parts.length > 1) {
1315
+ let keep = parts.length;
1316
+ while (keep > 1 && parts.length - keep < MAX_FILTERS && isReadFilter(parts[keep - 1])) keep -= 1;
1317
+ text = parts.slice(0, keep).join("|");
1318
+ }
1245
1319
  return text.replace(STDERR_JOIN, "").trim();
1246
1320
  };
1247
1321
 
@@ -1409,8 +1483,9 @@ const isOwnRewindScript = (path, cwd) => {
1409
1483
  // A Bash shape the guard cannot verify is refused, not paused, so the refusal says what does run;
1410
1484
  // without it a session tried a script in the write-only temp folder and stopped. Forbidden actions
1411
1485
  // (push, publish, tag, reset) never get this note.
1412
- const BASH_WAY_OUT = "This start-work guard verifies one plain command per Bash call: no `;`, `||`, `$`, backticks or quoted code, redirects only as `2>&1`, at most four plain commands joined by ` && `, and an optional trailing `| tail`, `head`, `grep`, `wc` or `sort` with flags only. Split the command into separate calls. To run code, write a script inside the project and run `node <script>`, then remove it. This is not an approval prompt; `lit approve` does not apply, and the user can end the run with `lit cancel`.";
1486
+ const BASH_WAY_OUT = "This start-work guard verifies one plain command per Bash call: no `;`, `||`, `$`, backticks or quoted code, redirects only as `2>&1`, at most four plain commands joined by ` && `, and up to four trailing read filters: `| head` or `| tail` (`-n N`, `-N`, `-c N`), `| grep` or `| rg` with flags and one pattern (quotes allowed, no `$` or backtick), `| cut -d<c> -f<list>`, `| uniq [-c]`, `| wc` or `| sort` with flags only. Split the command into separate calls. To run code, write a script inside the project and run `node <script>`, then remove it. This is not an approval prompt; `lit approve` does not apply, and the user can end the run with `lit cancel`.";
1413
1487
  const bashDenial = (reason) => denial(`${reason}. ${BASH_WAY_OUT}`);
1488
+ const OUTSIDE_GRANT = "Bash target is outside the effective authority grant; a plan can name that folder on a `Scope roots: <path> (<actions>)` line";
1414
1489
 
1415
1490
  // The plugin this module ships in: reading its own skills, commands and references is never a
1416
1491
  // boundary. Writing there still is.
@@ -1471,8 +1546,9 @@ const sensitiveDenial = (classified) => {
1471
1546
  // the root session id) reads without a boundary: its spilled tool results and subagent transcripts
1472
1547
  // under `<config>/projects/<key>/<session>/`, the project's memory, the user's CLAUDE.md and skills,
1473
1548
  // the host's `tasks` and `scratchpad` folders under `<CLAUDE_CODE_TMPDIR or /tmp>/claude-<uid>/<key>/<session>/`,
1474
- // the host's bundled skills, and the run's own private temp folder. The scratchpad may also be
1475
- // written, since the host tells the session to put temp files there. The key is the folder the
1549
+ // the host's bundled skills, and the run's own private temp folder. The scratchpad and the project's
1550
+ // memory may also be written: the host tells the session to put temp files and notes there. The
1551
+ // same two are a watching session's own folders (otherSessionDecision). The key is the folder the
1476
1552
  // session started in, with every non-alphanumeric character as `-`; the transcript path names it
1477
1553
  // even when the run's root is elsewhere (a worktree lane). Another session's folders, and any other
1478
1554
  // write, stay boundaries; a symlink is judged by where it points.
@@ -1498,6 +1574,7 @@ const harnessRoots = (work, input, projectDirs) => {
1498
1574
  if (hostTmp) read.push(join(hostTmp, "bundled-skills"));
1499
1575
  for (const key of keys) {
1500
1576
  read.push(join(projects, key, sessionId, "tool-results"), join(projects, key, sessionId, "subagents"), join(projects, key, "memory"));
1577
+ write.push(join(projects, key, "memory"));
1501
1578
  if (hostTmp) {
1502
1579
  read.push(join(hostTmp, key, sessionId, "tasks"), join(hostTmp, key, sessionId, "scratchpad"));
1503
1580
  write.push(join(hostTmp, key, sessionId, "scratchpad"));
@@ -1547,7 +1624,21 @@ const parkedMessage = (boundary) => (boundary.hits >= 3
1547
1624
  // A run is stale, and another session may take it over, once its owning session has ended or the
1548
1625
  // lifecycle has not been written for two hours (plans/lit-adhd.md D8).
1549
1626
  export const START_WORK_STALE_MS = 2 * 60 * 60 * 1000;
1550
- const idleMs = (work, now) => Math.max(0, now - (Date.parse(work.updated_at) || now));
1627
+ // Activity is the later of the last ledger event and the last allowed owner tool call.
1628
+ const lastActivityMs = (work) => Math.max(Date.parse(work.updated_at) || 0, Date.parse(work.last_tool_at ?? "") || 0);
1629
+ const idleMs = (work, now) => Math.max(0, now - (lastActivityMs(work) || now));
1630
+ // A heartbeat for the owner and its lanes (they share its session id): at most one state write a
1631
+ // minute, with no ledger event, so a busy run never looks idle to another session.
1632
+ const ACTIVITY_WRITE_MS = 60_000;
1633
+ const recordToolActivity = (root, state, work, now) => {
1634
+ if (now - lastActivityMs(work) < ACTIVITY_WRITE_MS) return;
1635
+ work.last_tool_at = new Date(now).toISOString();
1636
+ try {
1637
+ saveState(root, state);
1638
+ } catch {
1639
+ // A failed heartbeat must not refuse a call the guard allowed.
1640
+ }
1641
+ };
1551
1642
  const isStale = (work, now) => Boolean(work.root_session_ended_at) || idleMs(work, now) >= START_WORK_STALE_MS;
1552
1643
  const formatAge = (ms) => {
1553
1644
  const minutes = Math.floor(ms / 60_000);
@@ -1562,10 +1653,13 @@ const planRoute = (root, work) => {
1562
1653
  };
1563
1654
 
1564
1655
  // Words and operators of a command another session sends to watch the work. Single quotes hold
1565
- // data verbatim. Outside them only path-like characters pass (`*` and `?` mark the word as a glob);
1656
+ // data verbatim. Double quotes hold data too, but the shell still expands `$`, a backtick, `\` and
1657
+ // `!` inside them, and a control character could end the line, so any of those refuses the whole
1658
+ // command. Outside quotes only path-like characters pass (`*` and `?` mark the word as a glob);
1566
1659
  // `|`, ` && ` and `2>&1` must stand alone between spaces. Anything else (`;`, `||`, `$`, a backtick,
1567
- // a double quote, a backslash, a redirect, a newline) refuses the whole command.
1660
+ // a backslash, a redirect, a newline) refuses the whole command.
1568
1661
  const OBSERVATION_CHAR = /[\p{L}\p{N}_.\/@+,:=%-]/u;
1662
+ const DOUBLE_QUOTED_UNSAFE = /[$`\\!\p{Cc}]/u;
1569
1663
  const observationTokens = (command) => {
1570
1664
  const tokens = [];
1571
1665
  const chars = [...command];
@@ -1577,11 +1671,13 @@ const observationTokens = (command) => {
1577
1671
  if (ch === " " || ch === "\t") {
1578
1672
  if (word) tokens.push(word);
1579
1673
  word = null;
1580
- } else if (ch === "'") {
1581
- const end = chars.indexOf("'", index + 1);
1674
+ } else if (ch === "'" || ch === "\"") {
1675
+ const end = chars.indexOf(ch, index + 1);
1582
1676
  if (end < 0) return null;
1677
+ const text = chars.slice(index + 1, end).join("");
1678
+ if (ch === "\"" && DOUBLE_QUOTED_UNSAFE.test(text)) return null;
1583
1679
  word ??= { text: "", quoted: false, glob: false };
1584
- word.text += chars.slice(index + 1, end).join("");
1680
+ word.text += text;
1585
1681
  word.quoted = true;
1586
1682
  index = end;
1587
1683
  } else if (standalone(index, "&&") || standalone(index, "2>&1")) {
@@ -1611,10 +1707,87 @@ const HERDR_READS = Object.freeze({ agent: ["read", "get", "list"], pane: ["read
1611
1707
  // Only the flags a read needs: a flag herdr may add later (an output file, keys to send) is refused.
1612
1708
  const HERDR_READ_FLAG = /^--(?:source|lines|workspace|tab|json)(?:=[\w.:-]+)?$/u;
1613
1709
  const HERDR_ID = /^[A-Za-z0-9][\w.:-]*$/u;
1614
- const observeHerdr = ([noun, verb, ...rest]) => plainWord(noun) && plainWord(verb)
1710
+ const observeHerdrRead = ([noun, verb, ...rest]) => plainWord(noun) && plainWord(verb)
1615
1711
  && Object.hasOwn(HERDR_READS, noun.text) && HERDR_READS[noun.text].includes(verb.text)
1616
1712
  && rest.every((word) => plainWord(word) && (HERDR_READ_FLAG.test(word.text) || HERDR_ID.test(word.text)));
1617
1713
 
1714
+ // The nudges a watcher may send: a prompt to a named agent, a new pane beside the current one, a new
1715
+ // tab. Each verb has its own closed flag set (`--flag value` or `--flag=value`); a `--cwd` must stay
1716
+ // inside the project. Closing, running, sending keys and starting agents stay refused.
1717
+ const HERDR_NUDGE_FLAGS = Object.freeze({
1718
+ "agent prompt": { "--wait": null, "--timeout": /^\d{1,7}$/u },
1719
+ "pane split": { "--current": null, "--no-focus": null, "--pane": HERDR_ID, "--direction": /^(?:right|down|left|up)$/u, "--cwd": "path" },
1720
+ "tab create": { "--no-focus": null, "--workspace": HERDR_ID, "--cwd": "path" },
1721
+ });
1722
+ const observeHerdrNudge = ([noun, verb, ...rest], cwd, root) => {
1723
+ if (!plainWord(noun) || !plainWord(verb)) return false;
1724
+ const flags = HERDR_NUDGE_FLAGS[`${noun.text} ${verb.text}`];
1725
+ if (!flags) return false;
1726
+ const positionals = [];
1727
+ for (let index = 0; index < rest.length; index += 1) {
1728
+ const word = rest[index];
1729
+ if (!flagWord(word, /^--[a-z-]+(?:=.*)?$/u)) {
1730
+ positionals.push(word);
1731
+ continue;
1732
+ }
1733
+ const [name, inline] = word.text.split(/=(.*)/su);
1734
+ if (!Object.hasOwn(flags, name)) return false;
1735
+ const rule = flags[name];
1736
+ if (rule === null) {
1737
+ if (inline !== undefined) return false;
1738
+ continue;
1739
+ }
1740
+ let value = inline;
1741
+ if (value === undefined) {
1742
+ const next = rest[index + 1];
1743
+ if (!plainWord(next)) return false;
1744
+ value = next.text;
1745
+ index += 1;
1746
+ }
1747
+ if (rule === "path") {
1748
+ if (!root || !PLAIN_PATH_WORD.test(value)) return false;
1749
+ try {
1750
+ if (!rootCovers(root, canonicalTarget(resolve(cwd, value), "herdr cwd"))) return false;
1751
+ } catch {
1752
+ return false;
1753
+ }
1754
+ } else if (!rule.test(value)) {
1755
+ return false;
1756
+ }
1757
+ }
1758
+ if (noun.text !== "agent") return positionals.length === 0;
1759
+ const [name, text] = positionals;
1760
+ return positionals.length === 2 && plainWord(name) && HERDR_ID.test(name.text) && dataWord(text) && !USER_CONTROL_TEXT.test(text.text) && !isGoPrompt(text.text);
1761
+ };
1762
+ // The prompt lands in the worker as typed text, and typed words are the user's approvals there
1763
+ // (`lit approve`, `lit cancel`, `/litclaude:start-work …`, and `go` / `진행` for a briefed plan). A
1764
+ // watcher's model may nudge, never decide for the user, so text opening with a slash command or a
1765
+ // lit control word, or a whole go prompt, is refused.
1766
+ const USER_CONTROL_TEXT = /^\s*(?:\/|lit(?:work)?(?:\s|$))/iu;
1767
+
1768
+ // `ls` lists names; `find` walks a tree, minus the actions that run, delete or write a file.
1769
+ const FIND_ACTION = /^-(?:exec|execdir|ok|okdir|delete|fprint|fprint0|fprintf|fls)$/u;
1770
+ const observeListing = (head, args, cwd) => {
1771
+ const isFind = head === "find";
1772
+ let operands = true;
1773
+ for (const word of args) {
1774
+ if (word.op || word.glob) return false;
1775
+ if (isFind && FIND_ACTION.test(word.text)) return false;
1776
+ if (word.text.startsWith("-")) {
1777
+ if (!isFind && !flagWord(word, /^-[A-Za-z1@]+$/u)) return false;
1778
+ // find's leading options (-H, -L, -P, -E, -X, -d, -s, -x) keep the search roots that follow
1779
+ // checked; BSD `-f <root>` names a root no check would see, so it is refused.
1780
+ if (isFind && word.text === "-f") return false;
1781
+ if (isFind && !(operands && /^-[HLPEXdsx]+$/u.test(word.text))) operands = false;
1782
+ continue;
1783
+ }
1784
+ if (isFind && !operands) continue;
1785
+ if (word.quoted || !PLAIN_PATH_WORD.test(word.text) || !existsSync(resolve(cwd, word.text))) return false;
1786
+ if (sensitiveReason(canonicalTarget(resolve(cwd, word.text), "listing operand"), "read")) return false;
1787
+ }
1788
+ return true;
1789
+ };
1790
+
1618
1791
  // grep or rg over existing paths: bare flags from a closed set, the include/exclude globs, one
1619
1792
  // pattern, then plain path operands. Flags that read a pattern file or run a preprocessor are absent.
1620
1793
  const observeSearch = (args, cwd) => {
@@ -1669,10 +1842,11 @@ const observeFilter = ([head, ...args]) => {
1669
1842
  };
1670
1843
 
1671
1844
  // What another session may run to watch a running work without changing it: up to four segments
1672
- // joined by ` && `, each a `cd <dir>`, a herdr read (agent read|get|list, pane read|list, tab list)
1673
- // or a grep/rg read, each followed by up to four read-only pipe filters. Only otherSessionDecision
1674
- // calls this; the owner's guard keeps classifyBash.
1675
- export const classifyObservation = (command, cwd) => {
1845
+ // joined by ` && `, each a `cd <dir>`, a herdr read (agent read|get|list, pane read|list, tab list),
1846
+ // a herdr nudge (agent prompt, pane split, tab create), a grep/rg read, or an `ls`/`find` listing,
1847
+ // each followed by up to four read-only pipe filters. `root` bounds a herdr `--cwd`. Only
1848
+ // otherSessionDecision calls this; the owner's guard keeps classifyBash.
1849
+ export const classifyObservation = (command, cwd, root = null) => {
1676
1850
  if (typeof command !== "string" || command.length === 0 || command.length > 32_768) return false;
1677
1851
  if (forbiddenShellCommand(command)) return false;
1678
1852
  const tokens = observationTokens(command.trim());
@@ -1698,9 +1872,11 @@ export const classifyObservation = (command, cwd) => {
1698
1872
  if (!moved || moved.denied) return false;
1699
1873
  here = moved.cd;
1700
1874
  } else if (head.text === "herdr") {
1701
- if (!observeHerdr(args)) return false;
1875
+ if (!observeHerdrRead(args) && !observeHerdrNudge(args, here, root)) return false;
1702
1876
  } else if (head.text === "grep" || head.text === "rg") {
1703
1877
  if (!observeSearch(args, here)) return false;
1878
+ } else if (["ls", "/bin/ls", "find"].includes(head.text)) {
1879
+ if (!observeListing(head.text, args, here)) return false;
1704
1880
  } else {
1705
1881
  return false;
1706
1882
  }
@@ -1726,6 +1902,9 @@ const otherSessionDecision = (root, work, input, now) => {
1726
1902
  if (protectedPath) return protectedPath;
1727
1903
  reads = !classified.denied && !classified.control
1728
1904
  && (classified.chain ? classified.chain.every((link) => !link.control && READ_ACTIONS.has(link.action)) : READ_ACTIONS.has(classified.action));
1905
+ // Its own scratchpad and the project's memory are this session's notes, not the work's files.
1906
+ reads ||= !classified.denied && !classified.control && !classified.chain
1907
+ && classified.action === "write" && harnessAccess(classified, work, input, [root, input.cwd]);
1729
1908
  } catch {
1730
1909
  reads = false;
1731
1910
  }
@@ -1733,19 +1912,19 @@ const otherSessionDecision = (root, work, input, now) => {
1733
1912
  if (!reads && toolName === "Bash") {
1734
1913
  try {
1735
1914
  const cwd = canonicalDirectory(typeof input.cwd === "string" ? input.cwd : root, "tool cwd");
1736
- reads = classifyObservation(input?.tool_input?.command, cwd);
1915
+ reads = classifyObservation(input?.tool_input?.command, cwd, root);
1737
1916
  } catch {
1738
1917
  reads = false;
1739
1918
  }
1740
1919
  }
1741
1920
  if (reads) {
1742
- 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.` };
1921
+ 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, nudge its worker with \`herdr agent prompt\` and write notes in your scratchpad or the shared project memory, not change project files.` };
1743
1922
  }
1744
1923
  const route = `/litclaude:start-work ${planRoute(root, work)}`;
1745
1924
  const takeover = isStale(work, now)
1746
1925
  ? `That session has ended or gone idle, so you can take the work over by typing ${route} here.`
1747
1926
  : `Once that session ends or sits idle for 2 hours, you can take it over by typing ${route} here.`;
1748
- return denial(`LitClaude start-work ${work.work_id} (${work.plan_name}) belongs to another session in this project (last activity ${age} ago), so this session may read but not change files. It frees up when that session finishes the work. ${takeover} To end it now, tell the user to type \`lit cancel\` here (no command line is needed).`);
1927
+ return denial(`LitClaude start-work ${work.work_id} (${work.plan_name}) belongs to another session in this project (last activity ${age} ago), so this session may read but not change project files. It may nudge that session's worker with \`herdr agent prompt <name> "<text>"\` and write notes in its own scratchpad or the project memory, which every session of this project shares. It frees up when that session finishes the work. ${takeover} To end it now, tell the user to type \`lit cancel\` here (no command line is needed).`);
1749
1928
  };
1750
1929
 
1751
1930
  /**
@@ -1823,78 +2002,101 @@ export const handleStartWorkPreToolUse = (root, input, { now = Date.now() } = {}
1823
2002
  if (typeof input?.session_id !== "string" || input.session_id !== work.root_session_id) {
1824
2003
  return otherSessionDecision(canonicalRoot, work, input, now);
1825
2004
  }
1826
- const executionRoot = canonicalDirectory(typeof input.cwd === "string" ? input.cwd : canonicalRoot, "tool cwd");
1827
- const classified = classifyToolAuthority(executionRoot, input);
1828
- if (classified.denied) {
1829
- return input.tool_name === "Bash" && !classified.denied.startsWith("forbidden") ? bashDenial(classified.denied) : denial(classified.denied);
1830
- }
1831
- const protectedPath = classified.control ? null : sensitiveDenial(classified);
1832
- if (protectedPath) return protectedPath;
1833
- if (classified.control) return { decision: "allow-normal", action: "control", root: executionRoot, roots: [executionRoot] };
1834
- if (pluginSelfRead(classified)) return { decision: "allow-normal", action: "read", root: PLUGIN_ROOT, roots: [PLUGIN_ROOT] };
1835
- if (!classified.chain && harnessAccess(classified, work, input, [canonicalRoot, input.cwd])) {
1836
- return { decision: "allow-normal", action: "read", root: classified.targetRoots?.[0] ?? classified.targetRoot, roots: classified.targetRoots ?? [classified.targetRoot] };
1837
- }
1838
- if (classified.chain) {
1839
- const covered = classified.chain.every((link) => link.control
1840
- || link.targetRoots.every((targetRoot) => work.authority.grants.some((grant) => grantCovers(grant, link.action, targetRoot))));
1841
- return covered ? { decision: "allow-normal", action: "chain", root: executionRoot, roots: [executionRoot] } : bashDenial("Bash target is outside the effective authority grant");
1842
- }
1843
- const targetRoots = classified.targetRoots ?? [classified.targetRoot];
1844
- const authorized = targetRoots.every((targetRoot) => work.authority.grants.some((grant) => grantCovers(grant, classified.action, targetRoot)));
1845
- if (authorized) {
1846
- return { decision: "allow-normal", action: classified.action, root: targetRoots[0], roots: targetRoots };
1847
- }
1848
- if (classified.boundaryExpansion === false) {
1849
- return bashDenial("Bash target is outside the effective authority grant");
1850
- }
1851
- const refused = (work.authority.denied_boundaries ?? []).find((denied) => denied.action === classified.action
1852
- && targetRoots.every((targetRoot) => rootCovers(denied.root, targetRoot)));
1853
- if (refused) {
1854
- return denial(`LitClaude start-work: the user denied ${refused.action} access to ${refused.root} for this work. Carry on without it, or ask the user if the task cannot be done otherwise.`);
1855
- }
1856
- const targetRoot = boundaryRoot(classified.action, targetRoots[0], canonicalRoot);
1857
- const boundaryId = `boundary-${shortHash(`${work.work_id}:${classified.action}:${targetRoot}`)}`;
1858
- const queued = work.pending_boundaries.find(({ boundary_id: id }) => id === boundaryId);
1859
- if (queued) {
1860
- // A repeat changes no revision, so a lane's progress call with the revision it holds still lands.
1861
- queued.hits = (queued.hits ?? 1) + 1;
1862
- queued.last_seen = nowIso();
1863
- saveState(canonicalRoot, state);
1864
- return denial(parkedMessage(queued));
1865
- }
1866
- if (work.pending_boundaries.length >= MAX_PARKED) {
1867
- return denial(`LitClaude start-work: ${classified.action} access to ${targetRoot} is outside this plan's scope, and ${MAX_PARKED} steps are already parked, so this call did not run. Finish what the plan allows, mark the rest \`BLOCKED: <reason>\`, and end the turn; the user decides with \`lit approve\` or \`lit cancel\`.`);
1868
- }
1869
- const validId = (value) => typeof value === "string" && /^[A-Za-z0-9._:-]{1,160}$/u.test(value);
1870
- const originPromptId = validId(input.prompt_id) ? input.prompt_id : validId(input.tool_use_id) ? `tool:${input.tool_use_id}`.slice(0, 160) : null;
1871
- if (!originPromptId) {
1872
- return denial(`LitClaude start-work: ${classified.action} access to ${targetRoot} is outside this plan's scope and the call carries no prompt identity, so it did not run. Carry on with the plan's other tasks and mark a task that needs it \`BLOCKED: <reason>\`.`);
1873
- }
1874
- const grantId = `grant-${shortHash(`${work.work_id}:${classified.action}:${targetRoot}:${originPromptId}:${input.tool_use_id ?? "unknown"}`)}`;
1875
- const requestedAt = nowIso();
1876
- const boundary = {
1877
- boundary_id: boundaryId,
1878
- action: classified.action,
1879
- root: targetRoot,
1880
- origin_session_id: input.session_id,
1881
- origin_prompt_id: originPromptId,
1882
- origin_tool_use_id: typeof input.tool_use_id === "string" ? input.tool_use_id : null,
1883
- grant_id: grantId,
1884
- requested_at: requestedAt,
1885
- last_seen: requestedAt,
1886
- hits: 1,
1887
- };
1888
- work.pending_boundaries.push(boundary);
1889
- appendEvent(state, work, "work.boundary_parked", {
1890
- boundary_id: boundaryId,
1891
- action: classified.action,
1892
- root: targetRoot,
1893
- origin_prompt_id: originPromptId,
1894
- });
2005
+ const decided = ownerToolDecision(canonicalRoot, state, work, input);
2006
+ if (decided.decision === "allow-normal") recordToolActivity(canonicalRoot, state, work, now);
2007
+ return decided;
2008
+ });
2009
+ };
2010
+
2011
+ // The owner session's verdict for one tool call, under the lock the caller holds.
2012
+ const ownerToolDecision = (canonicalRoot, state, work, input) => {
2013
+ const executionRoot = canonicalDirectory(typeof input.cwd === "string" ? input.cwd : canonicalRoot, "tool cwd");
2014
+ const classified = classifyToolAuthority(executionRoot, input);
2015
+ if (classified.denied) {
2016
+ return input.tool_name === "Bash" && !classified.denied.startsWith("forbidden") ? bashDenial(classified.denied) : denial(classified.denied);
2017
+ }
2018
+ const protectedPath = classified.control ? null : sensitiveDenial(classified);
2019
+ if (protectedPath) return protectedPath;
2020
+ if (classified.control) return { decision: "allow-normal", action: "control", root: executionRoot, roots: [executionRoot] };
2021
+ if (pluginSelfRead(classified)) return { decision: "allow-normal", action: "read", root: PLUGIN_ROOT, roots: [PLUGIN_ROOT] };
2022
+ if (!classified.chain && harnessAccess(classified, work, input, [canonicalRoot, input.cwd])) {
2023
+ return { decision: "allow-normal", action: "read", root: classified.targetRoots?.[0] ?? classified.targetRoot, roots: classified.targetRoots ?? [classified.targetRoot] };
2024
+ }
2025
+ if (classified.chain) {
2026
+ const covered = classified.chain.every((link) => link.control
2027
+ || link.targetRoots.every((targetRoot) => work.authority.grants.some((grant) => grantCovers(grant, link.action, targetRoot))));
2028
+ return covered ? { decision: "allow-normal", action: "chain", root: executionRoot, roots: [executionRoot] } : bashDenial(OUTSIDE_GRANT);
2029
+ }
2030
+ const targetRoots = classified.targetRoots ?? [classified.targetRoot];
2031
+ const authorized = targetRoots.every((targetRoot) => work.authority.grants.some((grant) => grantCovers(grant, classified.action, targetRoot)));
2032
+ if (authorized) {
2033
+ return { decision: "allow-normal", action: classified.action, root: targetRoots[0], roots: targetRoots };
2034
+ }
2035
+ if (classified.boundaryExpansion === false) {
2036
+ return bashDenial(OUTSIDE_GRANT);
2037
+ }
2038
+ const refused = (work.authority.denied_boundaries ?? []).find((denied) => denied.action === classified.action
2039
+ && targetRoots.every((targetRoot) => rootCovers(denied.root, targetRoot)));
2040
+ if (refused) {
2041
+ return denial(`LitClaude start-work: the user denied ${refused.action} access to ${refused.root} for this work. Carry on without it, or ask the user if the task cannot be done otherwise.`);
2042
+ }
2043
+ const targetRoot = boundaryRoot(classified.action, targetRoots[0], canonicalRoot);
2044
+ const boundaryId = `boundary-${shortHash(`${work.work_id}:${classified.action}:${targetRoot}`)}`;
2045
+ const queued = work.pending_boundaries.find(({ boundary_id: id }) => id === boundaryId);
2046
+ if (queued) {
2047
+ // A repeat changes no revision, so a lane's progress call with the revision it holds still lands.
2048
+ queued.hits = (queued.hits ?? 1) + 1;
2049
+ queued.last_seen = nowIso();
1895
2050
  saveState(canonicalRoot, state);
1896
- return denial(parkedMessage(boundary));
2051
+ return denial(parkedMessage(queued));
2052
+ }
2053
+ if (work.pending_boundaries.length >= MAX_PARKED) {
2054
+ return denial(`LitClaude start-work: ${classified.action} access to ${targetRoot} is outside this plan's scope, and ${MAX_PARKED} steps are already parked, so this call did not run. Finish what the plan allows, mark the rest \`BLOCKED: <reason>\`, and end the turn; the user decides with \`lit approve\` or \`lit cancel\`.`);
2055
+ }
2056
+ const validId = (value) => typeof value === "string" && /^[A-Za-z0-9._:-]{1,160}$/u.test(value);
2057
+ const originPromptId = validId(input.prompt_id) ? input.prompt_id : validId(input.tool_use_id) ? `tool:${input.tool_use_id}`.slice(0, 160) : null;
2058
+ if (!originPromptId) {
2059
+ return denial(`LitClaude start-work: ${classified.action} access to ${targetRoot} is outside this plan's scope and the call carries no prompt identity, so it did not run. Carry on with the plan's other tasks and mark a task that needs it \`BLOCKED: <reason>\`.`);
2060
+ }
2061
+ const grantId = `grant-${shortHash(`${work.work_id}:${classified.action}:${targetRoot}:${originPromptId}:${input.tool_use_id ?? "unknown"}`)}`;
2062
+ const requestedAt = nowIso();
2063
+ const boundary = {
2064
+ boundary_id: boundaryId,
2065
+ action: classified.action,
2066
+ root: targetRoot,
2067
+ origin_session_id: input.session_id,
2068
+ origin_prompt_id: originPromptId,
2069
+ origin_tool_use_id: typeof input.tool_use_id === "string" ? input.tool_use_id : null,
2070
+ grant_id: grantId,
2071
+ requested_at: requestedAt,
2072
+ last_seen: requestedAt,
2073
+ hits: 1,
2074
+ };
2075
+ work.pending_boundaries.push(boundary);
2076
+ appendEvent(state, work, "work.boundary_parked", {
2077
+ boundary_id: boundaryId,
2078
+ action: classified.action,
2079
+ root: targetRoot,
2080
+ origin_prompt_id: originPromptId,
1897
2081
  });
2082
+ saveState(canonicalRoot, state);
2083
+ // `parked` is set only here, for a step parked for the first time, so a retry never carries it.
2084
+ return { ...denial(parkedMessage(boundary)), parked: { workId: work.work_id, boundaryId, action: classified.action, root: targetRoot } };
2085
+ };
2086
+
2087
+ /** This session's running work and its parked steps (with their ids), or null. Never throws. */
2088
+ export const parkedStartWorkSteps = (root, sessionId) => {
2089
+ try {
2090
+ const state = readState(canonicalDirectory(root, "cwd root"), { optional: true });
2091
+ const work = state?.active_work_id ? state.works?.[state.active_work_id] : null;
2092
+ if (!work || work.root_session_id !== sessionId || !["active", "paused"].includes(work.status)) return null;
2093
+ return {
2094
+ workId: work.work_id,
2095
+ parked: (work.pending_boundaries ?? []).map(({ boundary_id: boundaryId, action, root: parkedRoot }) => ({ boundaryId, action, root: parkedRoot })),
2096
+ };
2097
+ } catch {
2098
+ return null;
2099
+ }
1898
2100
  };
1899
2101
 
1900
2102
  const activeRootWork = (state, sessionId) => {
@@ -1962,6 +2164,57 @@ export const recordStartWorkSubagentStop = (root, input) => {
1962
2164
  });
1963
2165
  };
1964
2166
 
2167
+ const STUCK_LANE_MS = 30 * 60 * 1000;
2168
+
2169
+ /**
2170
+ * The owner closes a lane that never sent its stop (a helper that crashed or was killed), so the run
2171
+ * can complete. Only the session that owns the active work may do it; the lane is marked
2172
+ * `finalized: abandoned` and the ledger records it.
2173
+ */
2174
+ export const finalizeStartWorkLane = (root, request) => withLock(root, () => {
2175
+ const canonicalRoot = canonicalDirectory(root, "cwd root");
2176
+ const state = readState(canonicalRoot);
2177
+ const work = state.works[request.workId];
2178
+ if (!work || state.active_work_id !== request.workId || !["active", "paused"].includes(work.status)) {
2179
+ throw new StartWorkLifecycleError("requested work is not the active work");
2180
+ }
2181
+ if (work.root_session_id !== request.sessionId) throw new StartWorkLifecycleError("session does not own the active work", 77);
2182
+ const lane = work.lanes?.[request.lane];
2183
+ if (!lane || lane.status !== "active") throw new StartWorkLifecycleError("lane is not active", 409);
2184
+ if (Date.now() - (Date.parse(lane.started_at) || Date.now()) < STUCK_LANE_MS) {
2185
+ throw new StartWorkLifecycleError("lane has run under 30 minutes and may still be working; wait for its stop", 409);
2186
+ }
2187
+ lane.status = "finalized";
2188
+ lane.finalized = "abandoned";
2189
+ lane.finalized_at = nowIso();
2190
+ if (work.worktrees[lane.worktree_path]) {
2191
+ work.worktrees[lane.worktree_path].status = "host-removal-expected";
2192
+ work.worktrees[lane.worktree_path].finalized_at = lane.finalized_at;
2193
+ }
2194
+ appendEvent(state, work, "lane.abandoned", { agent_id: request.lane, by_session_id: request.sessionId });
2195
+ saveState(canonicalRoot, state);
2196
+ return { ok: true, operation: "lane-finalize", lane: clone(lane), state: publicState(state) };
2197
+ });
2198
+
2199
+ /**
2200
+ * The folder whose lifecycle recorded this session's active lane `agent_id`, found by walking up from
2201
+ * `cwd`. A stop from a nested checkout with its own git root resolves to that checkout, not the run
2202
+ * the lane started in. Reads only; null when no folder holds such a lane.
2203
+ */
2204
+ export const laneRootFor = (cwd, input) => {
2205
+ const agentId = typeof input?.agent_id === "string" ? input.agent_id : input?.subagent_id;
2206
+ if (typeof agentId !== "string" || agentId.length === 0) return null;
2207
+ for (let current = resolve(cwd); ; current = dirname(current)) {
2208
+ try {
2209
+ const state = readState(current, { optional: true });
2210
+ if (activeRootWork(state, input?.session_id)?.lanes?.[agentId]?.status === "active") return current;
2211
+ } catch {
2212
+ // An unreadable record is not this lane's.
2213
+ }
2214
+ if (dirname(current) === current) return null;
2215
+ }
2216
+ };
2217
+
1965
2218
  export const recordStartWorkSessionEnd = (root, input) => {
1966
2219
  const canonicalRoot = canonicalDirectory(root, "cwd root");
1967
2220
  if (!existsSync(startWorkStatePath(canonicalRoot))) return false;
@@ -1999,8 +2252,13 @@ export const handleStartWorkStop = (root, input) => {
1999
2252
  const progress = readPlanProgress(work.active_plan);
2000
2253
  // Parked steps join the fingerprint, so a newly parked step earns one more continuation.
2001
2254
  const parked = work.pending_boundaries ?? [];
2002
- const fingerprint = parked.length
2003
- ? `${progress.fingerprint}:${shortHash(parked.map(({ boundary_id: id }) => id).join(","))}`
2255
+ // A lane active for 30 min with no stop joins the fingerprint too, so it is named once.
2256
+ const nowMs = Date.now();
2257
+ const stuck = Object.values(work.lanes ?? {}).filter(({ status, started_at: startedAt }) => status === "active"
2258
+ && nowMs - (Date.parse(startedAt) || nowMs) >= STUCK_LANE_MS);
2259
+ const flagged = [...parked.map(({ boundary_id: id }) => id), ...stuck.map(({ agent_id: id }) => `lane:${id}`)];
2260
+ const fingerprint = flagged.length
2261
+ ? `${progress.fingerprint}:${shortHash(flagged.join(","))}`
2004
2262
  : progress.fingerprint;
2005
2263
  if (fingerprint === work.continuation.last_emitted_progress_fingerprint) {
2006
2264
  return { handled: false, output: null };
@@ -2018,9 +2276,12 @@ export const handleStartWorkStop = (root, input) => {
2018
2276
  const parkedNote = parked.length
2019
2277
  ? ` Parked, not run: ${parkedList}. Mark a task that cannot be done without one with a \`BLOCKED: <reason>\` line under its row and carry on with the others.`
2020
2278
  : "";
2279
+ const stuckNote = stuck.length
2280
+ ? ` ${stuck.slice(0, 5).map(({ agent_id: id, agent_type: type }) => `Lane ${clipText(id)} (${clipText(type)}) has run 30+ min with no stop; if it is finished or gone, close it with \`litclaude-ai start-work lane-finalize --work-id ${work.work_id} --lane ${clipText(id)} --session-id ${input.session_id}\`.`).join(" ")}`
2281
+ : "";
2021
2282
  const next = progress.next_task
2022
- ? `Continue work ${work.work_id} with next top-level task: ${progress.next_task}.${parkedNote}`
2023
- : `Work ${work.work_id} has all top-level tasks checked; run final verification and cleanup, then complete it with \`litclaude-ai start-work complete --work-id ${work.work_id} --session-id ${input.session_id} --expected-revision ${work.revision} --idempotency-key complete-${work.work_id}-${work.revision}\`.`;
2283
+ ? `Continue work ${work.work_id} with next top-level task: ${progress.next_task}.${parkedNote}${stuckNote}`
2284
+ : `Work ${work.work_id} has all top-level tasks checked; run final verification and cleanup, then complete it with \`litclaude-ai start-work complete --work-id ${work.work_id} --session-id ${input.session_id} --expected-revision ${work.revision} --idempotency-key complete-${work.work_id}-${work.revision}\`.${stuckNote}`;
2024
2285
  // Every open task waits on the user (BLOCKED:): say so once and let the session stop. The
2025
2286
  // fingerprint below keeps the next Stop silent until the plan changes.
2026
2287
  const waiting = !progress.next_task && progress.unchecked > 0;
@@ -2044,6 +2305,7 @@ export const handleStartWorkStop = (root, input) => {
2044
2305
  payload: clone(output),
2045
2306
  };
2046
2307
  saveState(canonicalRoot, state);
2308
+ if (waiting) recordRunEnd({ stateRoot: canonicalRoot, source: "start-work", id: `${work.work_id}:${output.continuation_id}`, outcome: "waiting" });
2047
2309
  return { handled: true, output };
2048
2310
  });
2049
2311
  };