@litfamily/litgravity 0.1.11 → 0.1.12

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +15 -2
  3. package/README_ko-KR.md +15 -2
  4. package/package.json +1 -1
  5. package/plugin/hooks/lib/goal.mjs +267 -0
  6. package/plugin/hooks/lib/policy.mjs +6 -1
  7. package/plugin/hooks/lib/reentry.mjs +5 -1
  8. package/plugin/hooks/lib/rewind/collect.mjs +98 -14
  9. package/plugin/hooks/lib/rewind/verdict.mjs +250 -0
  10. package/plugin/hooks/lib/routes.mjs +84 -12
  11. package/plugin/hooks/lib/skill-plan.mjs +171 -0
  12. package/plugin/hooks/lib/workflow-stack.mjs +3 -3
  13. package/plugin/hooks/pre-invocation.mjs +65 -9
  14. package/plugin/hooks/session-start.mjs +4 -0
  15. package/plugin/hooks/stop.mjs +11 -0
  16. package/plugin/plugin.json +1 -1
  17. package/plugin/skills/autoconference/SKILL.md +1 -1
  18. package/plugin/skills/autoconference/modes/core.md +1 -1
  19. package/plugin/skills/lit-adhd/SKILL.md +96 -58
  20. package/plugin/skills/lit-adhd/references/board-and-detail.md +48 -0
  21. package/plugin/skills/lit-adhd/references/recap-view.md +59 -0
  22. package/plugin/skills/lit-comprehend/SKILL.md +2 -2
  23. package/plugin/skills/lit-handoff/SKILL.md +2 -2
  24. package/plugin/skills/lit-handoff/evals/evals.json +1 -1
  25. package/plugin/skills/lit-handoff/reference/PROVENANCE.md +1 -1
  26. package/plugin/skills/lit-handoff/scripts/verify-closure.mjs +1 -1
  27. package/plugin/skills/lit-init/SKILL.md +1 -1
  28. package/plugin/skills/lit-loop/SKILL.md +1 -1
  29. package/plugin/skills/lit-plan/SKILL.md +15 -15
  30. package/plugin/skills/lit-plan/references/goal-condition.md +78 -0
  31. package/plugin/skills/lit-plan/references/risk-and-recovery.md +1 -1
  32. package/plugin/skills/lit-plan/scripts/goal-propose.mjs +18 -0
  33. package/plugin/skills/lit-plan/templates/plan.md +4 -1
  34. package/plugin/skills/lit-team/SKILL.md +37 -21
  35. package/plugin/skills/lit-team/references/team-orchestration.md +3 -3
  36. package/plugin/skills/litgoal/SKILL.md +8 -8
  37. package/plugin/skills/litgoal/references/host-goal-binding.md +30 -22
  38. package/plugin/skills/litwork/SKILL.md +2 -2
  39. package/plugin/skills/start-work/SKILL.md +1 -1
  40. package/plugin/skills/start-work/references/admission-and-selection.md +1 -1
  41. package/plugin/skills/start-work/references/final-wave.md +1 -1
  42. package/plugin/skills/ultra-brainstorm/SKILL.md +114 -0
  43. package/plugin/skills/ultra-brainstorm/references/lenses.md +40 -0
  44. package/plugin/skills/ultra-brainstorm/references/workflow-script.md +129 -0
  45. package/plugin/skills/ultra-brainstorm/scripts/estimate.mjs +76 -0
  46. package/plugin/skills/wikify/SKILL.md +2 -2
  47. package/plugin/skills/wikify/modes/init.md +1 -1
  48. package/plugin/skills/lit-recap/SKILL.md +0 -168
  49. package/plugin/skills/lit-recap/references/recap-shapes.md +0 -166
  50. package/plugin/skills/lit-recap/references/source-reading.md +0 -105
  51. package/plugin/skills/lit-recap/references/stale-state-checks.md +0 -74
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.12 — 2026-11-18
4
+
5
+ - One prompt can start more than one skill. The router collects every skill whose words match the task, three at most, and the activation note lists them with the first as the lead; a moved skill you have not installed comes with its install line. `lit +x +y <task>` names them yourself.
6
+ - New `ultra-brainstorm` skill. It prints the quota cost, asks how many idea agents to start (100 or more), then runs them on the cheapest model tier through one `run_workflow` script, with reducers and one judge, and ends on a top list and one question. Its cost line is a range calibrated on a real 100-agent run on agy 1.5.10 (about 28k tokens per idea agent, the system and tool prompt every workflow agent carries; 3.4M for the run): 100 agents ≈ 3.0M-4.8M tokens. A picked option label such as `(Recommended) 100 (recommended minimum)` now reads as 100. Without `run_workflow` it falls back to batched subagents, and without either it reports BLOCKED and offers `lit brainstorm`.
7
+ - `lit team <goal>` makes the conversation the orchestrator: it picks subagents, `run_workflow`, herdr panes (only with `HERDR_ENV=1` and `herdr` on PATH) or per-member worktrees by itself, then briefs, watches, merges and verifies. The packet and its state files stay as they were.
8
+ - Plans get a `## Done when` check. At approval `goal-propose.mjs` compiles it, lints it, proves it false today and asks `Approve plan, start work and set goal: /goal <cond>? (yes / edit / no)`; an exact `yes` starts start-work on that plan through the hook's own start path and arms a goal LitGravity owns. A check that cannot be a goal turns the question into `Approve plan and start work? (yes / no)` with the reason; a refused start (plan gone, a start-work run already active here) arms nothing. agy's `/goal` cannot be typed by a hook, so the reply gives you the line to paste, and the Stop hook checks the condition at every turn end and says when it is met. `lit cancel` clears only an owned goal. The old "use the goal tool if available" sentences are gone.
9
+ - `lit adhd` answers with a verdict card of about six lines (Korean by default, `en` for English); `lit adhd detail` keeps the board. The `lit-recap` skill is removed: `lit adhd recap [session]` replaces it, and `lit recap`, `litrecap` and `/litgravity:lit-recap` still work with a one-line note that it moved.
10
+
3
11
  ## 0.1.11 — 2026-11-16
4
12
 
5
13
  - The handoff is saved for you. agy has no compaction event, so the Stop hook now writes `.litgravity/handoff/auto.md` at every turn end of a conversation a lit route has touched (the last request, the next plan row, the open goal criterion, the tail of the last reply; credentials redacted), and a new conversation's SessionStart carries the newest of that note and `latest.md` whole instead of only pointing at `latest.md`. It is on by default; `LITGRAVITY_AUTO_HANDOFF=0` turns both halves off and restores the pointer.
package/README.md CHANGED
@@ -28,7 +28,7 @@ What ignition looks like, captured from the real hook and status line on this Ma
28
28
  1. [Install LitGravity](#install), then open agy in a project. Type `/skills` to see the LitGravity skills and `/hooks` to see the plugin's hooks.
29
29
  2. Start a prompt with `lit`. The word after it picks the route, as the table below shows.
30
30
  3. Approve a plan, then `lit start plans/<slug>.md` builds it row by row with tests.
31
- 4. Before you stop, `lit handoff`. Next time, `lit recap` reads where you were.
31
+ 4. Before you stop, `lit handoff`. Next time, `lit adhd` tells you the one thing to do now.
32
32
 
33
33
  ```text
34
34
  you type lit plan a tiny todo app
@@ -40,7 +40,8 @@ it ends "Plan saved. Run `lit start plans/todo-app.md` when you are happy wi
40
40
  |---|---|
41
41
  | `lit` | Runs the default loop, or picks up a plan you started with `lit start` |
42
42
  | `lit` while its route is already active | A short "continues" note |
43
- | `lit plan`, `lit review`, `lit research`, `lit debug`, `lit handoff`, `lit recap`, `lit brainstorm`, `lit korean` | Picks that route |
43
+ | `lit plan`, `lit review`, `lit research`, `lit debug`, `lit handoff`, `lit adhd`, `lit brainstorm`, `lit team`, `lit korean` | Picks that route |
44
+ | `lit +x +y <task>` | Runs the skills you name, the first one leading |
44
45
  | `lit <other route>` | Switches |
45
46
  | Any skill id as that word (`lit debugging`, `lit structural-search`) | Runs that skill; `/litgravity:<skill-id>` does the same as a slash command |
46
47
  | `lit new` | Starts over |
@@ -204,6 +205,18 @@ agy gives a plugin no hook on the prompt itself, so the PreInvocation hook steer
204
205
  - **`lit review`** checks the result in five lanes.
205
206
  - **`lit handoff`** writes `.litgravity/handoff/latest.md` with what was built, how it was checked and what is left. The SessionStart hook of your next conversation points to it.
206
207
 
208
+ ### Five things a turn does for you
209
+
210
+ A single prompt often asks for more than one kind of work. `lit explain the export code and draw its data flow` needs the explainer and the diagram, so the router collects every skill whose words match, up to three, and the activation note lists them in order with the first marked as the lead. A skill that moved to wjgoarxiv-skills is listed only when you installed it; otherwise the note carries the one line that installs it. When the router guesses wrong, name the skills yourself: `lit +comprehend +diagram <task>`.
211
+
212
+ Some questions deserve more than one head. `ultra-brainstorm <topic>` first prints what the run will cost in quota and asks how many idea agents to start (100 is the floor it suggests). On your number it writes one `run_workflow` script: hundreds of small agents on agy's cheapest model tier each look at the topic through a different lens, reducers fold their ideas into clusters, and one judge scores the clusters. You get a top list and one question. On a build without `run_workflow` it says it is blocked and offers `lit brainstorm`.
213
+
214
+ `lit team <goal>` makes this conversation the team lead. It splits the goal, decides by itself whether the slices run as subagents, as one workflow, as herdr panes (only inside herdr, with `herdr` on PATH) or in separate worktrees when they touch the same files, then briefs, watches, merges, verifies and gives you one short report. Members never commit.
215
+
216
+ A plan now says when it is done in a form a machine can check: a `## Done when` block with one command such as `npm test`. At approval lit-plan compiles it into a goal sentence, refuses vague words and outward-only steps, runs the command once to prove the goal is false today, and asks `Approve plan, start work and set goal: /goal <cond>? (yes / edit / no)`. Your `yes` does both at once: the hook starts start-work on that plan and arms the goal. When the check cannot become a goal, the question shrinks to `Approve plan and start work? (yes / no)` with one line saying why. If the start is refused (the plan is gone, or this conversation already runs start-work), no goal is armed either. A hook cannot type agy's own `/goal`, so the reply gives you that line to paste, and LitGravity checks the same condition at every turn end and tells you when it is met. `lit cancel` clears a goal LitGravity armed and never one you set yourself.
217
+
218
+ `lit adhd` now answers with one card of about six lines: what changed since you last looked, the one thing to do now, the exact words to type, why, and how much of the record it read. A claimed finish never counts as done; only a commit or a fully ticked plan does. `lit adhd detail` keeps the old board, and `lit adhd recap [session]` is where `lit recap` went (that word still works and says it moved).
219
+
207
220
  ### What a planning turn may do
208
221
 
209
222
  `lit plan` turns are planning only. Most of that is asked, then checked afterwards, because agy offers no safe way to stop a write before it happens (see [the limits](#what-agy-limits-today)):
package/README_ko-KR.md CHANGED
@@ -28,7 +28,7 @@
28
28
  1. [LitGravity를 설치](#설치)한 뒤 프로젝트에서 agy를 엽니다. `/skills`로 LitGravity 스킬을, `/hooks`로 플러그인의 훅을 볼 수 있습니다.
29
29
  2. 프롬프트를 `lit`으로 시작합니다. 뒤에 오는 단어가 경로를 고르며, 아래 표에 정리했습니다.
30
30
  3. 계획을 승인한 뒤 `lit start plans/<slug>.md`를 실행하면 계획의 행을 하나씩 테스트와 함께 만들어 갑니다.
31
- 4. 멈추기 전에 `lit handoff`. 다음에는 `lit recap`이 어디까지 했는지 읽어 줍니다.
31
+ 4. 멈추기 전에 `lit handoff`. 다음에는 `lit adhd`가 지금 할 일 하나를 알려 줍니다.
32
32
 
33
33
  ```text
34
34
  입력 lit plan a tiny todo app
@@ -40,7 +40,8 @@
40
40
  |---|---|
41
41
  | `lit` | 기본 루프가 돌거나, `lit start`로 시작해 둔 계획을 이어받습니다 |
42
42
  | 경로가 이미 켜진 상태에서 다시 `lit` | 짧은 "이어 갑니다" 메모만 갑니다 |
43
- | `lit plan`, `lit review`, `lit research`, `lit debug`, `lit handoff`, `lit recap`, `lit brainstorm`, `lit korean` | 그 경로를 고릅니다 |
43
+ | `lit plan`, `lit review`, `lit research`, `lit debug`, `lit handoff`, `lit adhd`, `lit brainstorm`, `lit team`, `lit korean` | 그 경로를 고릅니다 |
44
+ | `lit +x +y <task>` | 이름을 댄 스킬을 돌리고, 첫 번째가 주 스킬입니다 |
44
45
  | `lit <다른 경로>` | 경로를 바꿉니다 |
45
46
  | 그 자리에 쓴 스킬 id(`lit debugging`, `lit structural-search`) | 그 스킬을 실행합니다. `/litgravity:<스킬-id>`는 같은 일을 슬래시 명령으로 합니다 |
46
47
  | `lit new` | 처음부터 다시 시작합니다 |
@@ -204,6 +205,18 @@ agy는 플러그인에 프롬프트 자체를 받는 훅을 주지 않으므로,
204
205
  - **`lit review`** 는 결과를 다섯 레인으로 검토합니다.
205
206
  - **`lit handoff`** 는 무엇을 만들었고 어떻게 확인했고 무엇이 남았는지 `.litgravity/handoff/latest.md`에 적습니다. 다음 대화의 SessionStart 훅이 그 메모를 가리켜 줍니다.
206
207
 
208
+ ### 한 턴이 대신 해 주는 다섯 가지
209
+
210
+ 프롬프트 하나에 일이 여러 가지 섞여 있을 때가 많습니다. `lit explain the export code and draw its data flow`에는 설명 스킬과 다이어그램 스킬이 둘 다 필요합니다. 그래서 라우터는 말이 맞는 스킬을 세 개까지 모두 모으고, 활성화 메모에 순서대로 적으며 첫 번째를 주 스킬로 표시합니다. wjgoarxiv-skills로 옮겨 간 스킬은 설치했을 때만 목록에 오르고, 설치하지 않았다면 설치하는 한 줄이 대신 붙습니다. 라우터가 잘못 고르면 직접 이름을 대면 됩니다: `lit +comprehend +diagram <task>`.
211
+
212
+ 머리 하나로는 모자란 질문도 있습니다. `ultra-brainstorm <주제>`는 먼저 이번 실행이 할당량을 얼마나 쓸지 보여 주고, 아이디어 에이전트를 몇 개 띄울지 묻습니다(권하는 최소는 100개). 숫자를 답하면 `run_workflow` 스크립트 하나를 씁니다. agy의 가장 싼 모델 등급에서 작은 에이전트 수백 개가 저마다 다른 렌즈로 주제를 보고, 정리 에이전트가 아이디어를 묶음으로 합치고, 심사 에이전트 하나가 묶음에 점수를 매깁니다. 받는 것은 상위 목록과 질문 하나입니다. `run_workflow`가 없는 빌드에서는 막혔다고 말하고 `lit brainstorm`을 권합니다.
213
+
214
+ `lit team <목표>`를 치면 이 대화가 팀장이 됩니다. 목표를 나누고, 조각을 서브에이전트로 돌릴지, 워크플로 하나로 돌릴지, herdr 창으로 돌릴지(herdr 안에서 `herdr`가 PATH에 있을 때만), 같은 파일을 만지면 작업 트리를 따로 쓸지 스스로 정합니다. 그다음 지시를 쓰고, 지켜보고, 합치고, 확인한 뒤 짧은 보고 하나를 줍니다. 팀원은 커밋하지 않습니다.
215
+
216
+ 이제 계획은 끝났는지를 기계가 확인할 수 있는 모양으로 적습니다. `## Done when` 블록에 `npm test` 같은 명령 하나를 씁니다. 승인할 때 lit-plan이 이를 목표 문장으로 바꾸고, 애매한 말과 바깥으로 내보내기만 하는 단계는 거절하고, 명령을 한 번 돌려 지금은 목표가 거짓임을 확인한 뒤 `Approve plan, start work and set goal: /goal <cond>? (yes / edit / no)`라고 묻습니다. `yes` 한 번이면 둘 다 됩니다. 훅이 그 계획으로 start-work를 시작하고 목표를 겁니다. 확인 명령을 목표로 만들 수 없으면 질문이 `Approve plan and start work? (yes / no)`로 줄고, 왜 그런지 한 줄이 붙습니다. 시작이 거절되면(계획이 없거나 이 대화가 이미 start-work를 돌리는 중) 목표도 걸리지 않습니다. 훅은 agy의 `/goal`을 대신 칠 수 없어서 답장에 붙여 넣을 한 줄을 주고, LitGravity는 턴이 끝날 때마다 같은 조건을 확인해 달성되면 알려 줍니다. `lit cancel`은 LitGravity가 건 목표만 지우고, 직접 건 목표는 건드리지 않습니다.
217
+
218
+ `lit adhd`는 이제 여섯 줄쯤 되는 카드 하나로 답합니다. 지난번 이후 바뀐 것, 지금 할 일 하나, 그대로 칠 말, 이유, 기록을 얼마나 읽었는지가 들어 있습니다. 끝났다는 말만으로는 끝난 것으로 치지 않고, 커밋이나 줄이 모두 체크된 계획만 셉니다. 예전 보드는 `lit adhd detail`에 있고, `lit recap`이 하던 일은 `lit adhd recap [세션]`으로 옮겼습니다(예전 말도 아직 통하고 옮겼다고 알려 줍니다).
219
+
207
220
  ### 계획 턴이 할 수 있는 일
208
221
 
209
222
  `lit plan` 턴은 계획만 합니다. agy에는 쓰기가 일어나기 전에 안전하게 멈출 방법이 없어서([한계](#지금-agy가-막아-두는-것) 참고), 대부분은 먼저 요청하고 나중에 확인하는 방식입니다.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litfamily/litgravity",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "description": "Installer for LitGravity: skills, hooks and agents that help Google's Antigravity CLI (agy) plan, build, check and hand off work.",
5
5
  "keywords": [
6
6
  "antigravity",
@@ -0,0 +1,267 @@
1
+ // The plan's finish line as one checkable condition. lit-plan writes a `## Done when` block with one `check:` command;
2
+ // this module compiles it into `Every row in plans/<f>.md is ticked and \`<cmd>\` exits 0 [lit:<id>]`, lints it,
3
+ // proves it is false today (the falsifier dry run) and keeps the three small records under `.litgravity/goal/`:
4
+ //
5
+ // consent.json goal-propose asked the user, with the condition, its hash and the plan (asked)
6
+ // owner.json the user typed exactly `yes` to that question; LitGravity owns this goal (armed)
7
+ // status.json the last fixed status line (set, skipped, met-and-cleared, cancelled, swept)
8
+ //
9
+ // agy 1.5.10 has its own `/goal` command in the interactive TUI, but a hook can only inject steps or decide a tool
10
+ // call; it cannot type a slash command. So the yes answer arms LitGravity's own check, and the reply hands the user the
11
+ // one line to paste for agy's goal. The check runs at every turn end through the Stop hook as an advisory: when the
12
+ // rows are ticked and the command exits 0, the owned record is cleared. A goal the user set by hand in agy is never
13
+ // touched, because nothing here can reach it.
14
+ import { spawnSync } from 'node:child_process';
15
+ import { createHash } from 'node:crypto';
16
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ import { planRows } from './continuation.mjs';
19
+ import { GOAL_NEVER } from './routes.mjs';
20
+
21
+ export const GOAL_MAX_CHARS = 500;
22
+ export const CONSENT_TTL_MS = 30 * 60 * 1000;
23
+ export const FALSIFY_TIMEOUT_MS = 120_000;
24
+ // The Stop hook has 10 s in hooks.json; the advisory check gets most of it and reports a slow check as unfinished.
25
+ export const STOP_CHECK_TIMEOUT_MS = 7_000;
26
+ export const OWNER_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
27
+ export const GOAL_DIR = join('.litgravity', 'goal');
28
+
29
+ const JUDGMENT_WORDS = [
30
+ /\bworks?\b/iu, /\bworking\b/iu, /\blooks? (?:good|fine|right|nice|great)\b/iu, /\bseems?\b/iu, /\bproperly\b/iu,
31
+ /\bcorrectly\b/iu, /\bnicely\b/iu, /\bshould (?:work|pass)\b/iu, /\bas expected\b/iu, /\bgood enough\b/iu,
32
+ /잘\s*(?:동작|작동|돌아|돼|된다|되면)/u, /괜찮/u, /깔끔/u, /제대로/u, /문제\s*없/u, /완벽/u,
33
+ ];
34
+ // A success that is only an outward action proves nothing about the work and cannot be undone.
35
+ const OUTWARD_ONLY = /^\s*(?:git\s+push|npm\s+publish|pnpm\s+publish|yarn\s+publish|gh\s+(?:release|pr\s+merge)|git\s+tag)\b/iu;
36
+ // The commands a falsifier may run: test runners and a script inside the project, nothing with a shell.
37
+ const CHECK_ALLOWLIST = [
38
+ /^npm (?:test|run [\w:.-]+)(?: --[\w-]+)*$/u,
39
+ /^node --test(?: [\w./*-]+)*$/u,
40
+ /^node [\w./-]+\.m?js(?: [\w./=-]+)*$/u,
41
+ /^(?:pnpm|yarn) (?:test|run [\w:.-]+)$/u,
42
+ /^(?:pytest|python3? -m pytest)(?: [\w./:-]+)*$/u,
43
+ /^cargo test(?: [\w-]+)*$/u,
44
+ /^go test(?: [\w./-]+)*$/u,
45
+ /^make (?:test|check|verify)$/u,
46
+ /^(?:bash|sh) scripts\/[\w./-]+\.sh$/u,
47
+ ];
48
+
49
+ export const conditionHash = (condition) => createHash('sha256').update(String(condition)).digest('hex').slice(0, 16);
50
+ export const goalId = (plan, check) => createHash('sha256').update(`${plan}\u0000${check}`).digest('hex').slice(0, 8);
51
+
52
+ /** The `## Done when` block: one `check: \`<command>\`` line. */
53
+ export const parseDoneWhen = (planText) => {
54
+ const lines = String(planText ?? '').split(/\r?\n/u);
55
+ const start = lines.findIndex((line) => /^##\s+Done when\s*$/iu.test(line));
56
+ if (start === -1) return { ok: false, reason: 'the plan has no `## Done when` block' };
57
+ for (const line of lines.slice(start + 1)) {
58
+ if (/^##\s/u.test(line)) break;
59
+ const match = /^\s*(?:[-*]\s+)?check:\s*`([^`\n]+)`\s*$/u.exec(line);
60
+ if (match) return { ok: true, check: match[1].trim() };
61
+ }
62
+ return { ok: false, reason: 'the `## Done when` block names no `check:` command' };
63
+ };
64
+
65
+ /** The condition text, or why it cannot be built. */
66
+ export const compileCondition = ({ plan, check }) => {
67
+ const id = goalId(plan, check);
68
+ const condition = `Every row in ${plan} is ticked and \`${check}\` exits 0 [lit:${id}]`;
69
+ if (condition.length > GOAL_MAX_CHARS) return { ok: false, reason: `the condition is over ${GOAL_MAX_CHARS} characters; point the check at one script` };
70
+ return { ok: true, condition, id };
71
+ };
72
+
73
+ /** Rejects judgment words, outward-only success, unlisted commands and conditions over the cap. */
74
+ export const lintCondition = (condition, check) => {
75
+ const reasons = [];
76
+ const text = String(check);
77
+ if (String(condition).length > GOAL_MAX_CHARS) reasons.push(`over ${GOAL_MAX_CHARS} characters`);
78
+ const words = JUDGMENT_WORDS.filter((re) => re.test(text)).map((re) => text.match(re)[0]);
79
+ if (words.length) reasons.push(`judgment words cannot be checked (${words.join(', ')})`);
80
+ if (OUTWARD_ONLY.test(text)) reasons.push('a push, publish or release is not a check of the work');
81
+ else if (!CHECK_ALLOWLIST.some((re) => re.test(text))) reasons.push(`\`${text}\` is not an allowlisted test command`);
82
+ return { ok: reasons.length === 0, reasons };
83
+ };
84
+
85
+ const runCheck = (cwd, check, timeoutMs, run) => {
86
+ const [cmd, ...args] = check.split(/\s+/u);
87
+ return { cmd, args, result: run(cmd, args, { cwd, encoding: 'utf8', timeout: timeoutMs, stdio: ['ignore', 'ignore', 'ignore'], shell: false }) };
88
+ };
89
+
90
+ /**
91
+ * The dry run: the condition must be false now, or the goal is met at its first check. Runs the allowlisted command
92
+ * once, time-boxed, without a shell. A check script the plan itself creates is missing until the work runs: false
93
+ * now, not broken.
94
+ */
95
+ export const falsify = ({ cwd, plan, planText, check, timeoutMs = FALSIFY_TIMEOUT_MS, run = spawnSync }) => {
96
+ const open = planRows(String(planText)).filter((row) => !row.done).length;
97
+ const { cmd, args, result } = runCheck(cwd, check, timeoutMs, run);
98
+ if (result.error?.code === 'ETIMEDOUT' || result.signal === 'SIGTERM') return { ok: false, reason: `\`${check}\` did not finish within ${Math.round(timeoutMs / 1000)} s` };
99
+ const plannedScript = ['bash', 'sh', 'node'].includes(cmd) && args.length >= 1 && String(planText).includes(args[0]) && !existsSync(join(cwd, args[0]));
100
+ if ((result.error || result.status === 127) && !plannedScript) return { ok: false, reason: `\`${check}\` cannot run here` };
101
+ if (result.status === 0 && open === 0) return { ok: false, reason: `the goal is already true (${plan} is all ticked and \`${check}\` exits 0)` };
102
+ return { ok: true, open, exit: plannedScript ? null : result.status };
103
+ };
104
+
105
+ /** `yes`, `edit` and `no` (exactly, any case) are answers; anything else is no answer at all. */
106
+ export const consentAnswer = (prompt) => {
107
+ const text = String(prompt ?? '').trim().toLowerCase();
108
+ return ['yes', 'edit', 'no'].includes(text) ? text : null;
109
+ };
110
+
111
+ /** The consent record is fresh and is the one the user is answering. */
112
+ const consentSubject = (consent) => (typeof consent?.condition === 'string' ? consent.condition
113
+ : typeof consent?.plan === 'string' && consent.condition === null ? `start ${consent.plan}` : null);
114
+ export const consentIsLive = (consent, now = Date.now()) => Boolean(consent && consentSubject(consent) !== null
115
+ && consent.hash === conditionHash(consentSubject(consent)) && Number.isFinite(Date.parse(consent.askedAt))
116
+ && now - Date.parse(consent.askedAt) <= CONSENT_TTL_MS);
117
+
118
+ // The fixed status lines. Nothing else about a goal is ever said in another wording.
119
+ export const STATUS = Object.freeze({
120
+ ask: (condition) => `Approve plan, start work and set goal: /goal ${condition}? (yes / edit / no)`,
121
+ askStart: (reason) => `No goal for this plan: ${reason}.\nApprove plan and start work? (yes / no)`,
122
+ started: (plan) => `Plan approved: start-work runs ${plan} now. No goal is set.`,
123
+ startRefused: (reason) => `Plan not started and no goal set: ${reason}.`,
124
+ set: (condition) => `Goal armed by LitGravity: ${condition}. agy's own goal is not confirmed (a hook cannot type it). Paste: /goal ${condition}`,
125
+ skipped: (reason) => `Goal skipped: ${reason}.`,
126
+ edit: (condition) => `Nothing started and no goal set. Edit the \`## Done when\` check, then answer again: /goal ${condition}? (yes / edit / no)`,
127
+ editStart: () => 'Nothing started. Edit the plan, then answer again: Approve plan and start work? (yes / no)',
128
+ declined: () => 'Nothing started and no goal set: you answered no.',
129
+ otherActive: (condition) => `A goal is already active (${condition}); LitGravity left it as it is.`,
130
+ met: (condition) => `Goal met and cleared: ${condition}. If you pasted it into agy and it still shows, type /goal clear.`,
131
+ cancelled: (condition) => `Goal cleared by lit cancel: ${condition}. If you pasted it into agy, type /goal clear.`,
132
+ swept: (condition) => `Goal record dropped (stale or its plan is gone): ${condition}.`,
133
+ });
134
+
135
+ const goalDir = (workspace) => join(workspace, GOAL_DIR);
136
+
137
+ export const readGoalRecord = (workspace, name) => {
138
+ const file = join(goalDir(workspace), `${name}.json`);
139
+ try {
140
+ if (lstatSync(file).isSymbolicLink()) return null;
141
+ const value = JSON.parse(readFileSync(file, 'utf8'));
142
+ return value && typeof value === 'object' ? value : null;
143
+ } catch {
144
+ return null;
145
+ }
146
+ };
147
+
148
+ export const writeGoalRecord = (workspace, name, value) => {
149
+ const dir = goalDir(workspace);
150
+ try {
151
+ if (lstatSync(join(workspace, '.litgravity')).isSymbolicLink()) return false;
152
+ } catch { /* created below */ }
153
+ mkdirSync(dir, { recursive: true });
154
+ if (lstatSync(dir).isSymbolicLink()) return false;
155
+ const file = join(dir, `${name}.json`);
156
+ const tmp = `${file}.tmp-${process.pid}`;
157
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`);
158
+ renameSync(tmp, file);
159
+ return true;
160
+ };
161
+
162
+ export const dropGoalRecord = (workspace, name) => {
163
+ try { unlinkSync(join(goalDir(workspace), `${name}.json`)); } catch { /* already gone */ }
164
+ };
165
+
166
+ const setStatus = (workspace, kind, line, now) => writeGoalRecord(workspace, 'status', { kind, line, at: new Date(now).toISOString() });
167
+
168
+ /**
169
+ * The prompt hook's half: a typed `yes` / `edit` / `no` while a live consent record waits. An exact `yes` bound to the
170
+ * asked hash approves the plan, starts its start-work run through `startWork(plan)` (the hook's own start path, the same
171
+ * one `lit start <plan>` takes) and, when the record carries a goal, arms it. A refused start arms nothing. Returns
172
+ * `{ line, start }` (`start` is the plan the hook started, or null) or null when the prompt answers no live question.
173
+ */
174
+ export const answerConsent = (workspace, prompt, conversationId, now = Date.now(), { startWork = () => ({ ok: false, reason: 'no start path' }) } = {}) => {
175
+ const answer = consentAnswer(prompt);
176
+ if (!answer) return null;
177
+ const consent = readGoalRecord(workspace, 'consent');
178
+ if (!consentIsLive(consent, now) || consent.route !== 'lit-plan' || GOAL_NEVER.has(consent.route)) return null;
179
+ const withGoal = typeof consent.condition === 'string';
180
+ if (answer === 'edit') return { line: withGoal ? STATUS.edit(consent.condition) : STATUS.editStart(), start: null };
181
+ dropGoalRecord(workspace, 'consent');
182
+ if (answer === 'no') {
183
+ setStatus(workspace, 'declined', STATUS.declined(), now);
184
+ return { line: STATUS.declined(), start: null };
185
+ }
186
+ const started = startWork(consent.plan);
187
+ if (!started?.ok) {
188
+ const line = STATUS.startRefused(started?.reason ?? 'the start path refused');
189
+ setStatus(workspace, 'start-refused', line, now);
190
+ return { line, start: null };
191
+ }
192
+ if (!withGoal) {
193
+ setStatus(workspace, 'started', STATUS.started(consent.plan), now);
194
+ return { line: STATUS.started(consent.plan), start: consent.plan };
195
+ }
196
+ const owner = readGoalRecord(workspace, 'owner');
197
+ if (owner && owner.hash !== consent.hash) {
198
+ setStatus(workspace, 'other-active', STATUS.otherActive(owner.condition), now);
199
+ return { line: STATUS.otherActive(owner.condition), start: consent.plan };
200
+ }
201
+ writeGoalRecord(workspace, 'owner', { condition: consent.condition, hash: consent.hash, plan: consent.plan, check: consent.check, conversationId, armedAt: new Date(now).toISOString(), native: 'paste' });
202
+ setStatus(workspace, 'set', STATUS.set(consent.condition), now);
203
+ return { line: STATUS.set(consent.condition), start: consent.plan };
204
+ };
205
+
206
+ /** `lit cancel`: clears only the goal LitGravity owns. */
207
+ export const cancelOwnedGoal = (workspace, now = Date.now()) => {
208
+ const owner = readGoalRecord(workspace, 'owner');
209
+ if (!owner || owner.hash !== conditionHash(owner.condition)) return null;
210
+ dropGoalRecord(workspace, 'owner');
211
+ setStatus(workspace, 'cancelled', STATUS.cancelled(owner.condition), now);
212
+ return STATUS.cancelled(owner.condition);
213
+ };
214
+
215
+ /**
216
+ * The Stop hook's half: the advisory check at turn end. `met` clears the owned record; anything else leaves it. A check
217
+ * slower than the hook allows is reported as unfinished, never as met.
218
+ */
219
+ export const advisoryCheck = (workspace, { run = spawnSync, now = Date.now(), timeoutMs = STOP_CHECK_TIMEOUT_MS } = {}) => {
220
+ const owner = readGoalRecord(workspace, 'owner');
221
+ if (!owner || owner.hash !== conditionHash(owner.condition) || typeof owner.plan !== 'string' || typeof owner.check !== 'string') return null;
222
+ let text;
223
+ try { text = readFileSync(join(workspace, owner.plan), 'utf8'); } catch { return { state: 'plan-missing', owner }; }
224
+ const open = planRows(text).filter((row) => !row.done).length;
225
+ if (open > 0) return { state: 'open', open, owner };
226
+ if (!lintCondition(owner.condition, owner.check).ok) return { state: 'unlisted', owner };
227
+ const { result } = runCheck(workspace, owner.check, timeoutMs, run);
228
+ if (result.error?.code === 'ETIMEDOUT' || result.signal === 'SIGTERM') return { state: 'slow', owner };
229
+ if (result.status !== 0) return { state: 'failing', exit: result.status, owner };
230
+ dropGoalRecord(workspace, 'owner');
231
+ setStatus(workspace, 'met', STATUS.met(owner.condition), now);
232
+ return { state: 'met', owner, line: STATUS.met(owner.condition) };
233
+ };
234
+
235
+ /** SessionStart: a record left by a crash (stale, or its plan is gone) is dropped and named once. */
236
+ export const sweepGoal = (workspace, now = Date.now()) => {
237
+ const owner = readGoalRecord(workspace, 'owner');
238
+ if (!owner) return null;
239
+ const age = now - Date.parse(owner.armedAt);
240
+ const planGone = typeof owner.plan !== 'string' || !existsSync(join(workspace, owner.plan));
241
+ if (!(planGone || !Number.isFinite(age) || age > OWNER_MAX_AGE_MS)) return null;
242
+ dropGoalRecord(workspace, 'owner');
243
+ setStatus(workspace, 'swept', STATUS.swept(owner.condition), now);
244
+ return STATUS.swept(owner.condition);
245
+ };
246
+
247
+ /** goal-propose: compile, lint and falsify a plan's condition; on success write the consent record. */
248
+ export const proposeGoal = ({ workspace, plan, run = spawnSync, now = Date.now(), timeoutMs = FALSIFY_TIMEOUT_MS }) => {
249
+ if (typeof plan !== 'string' || !/^plans\/[A-Za-z0-9_-][A-Za-z0-9._-]*\.md$/u.test(plan) || plan.includes('..')) return { ok: false, line: STATUS.skipped('the plan path must be plans/<name>.md') };
250
+ let planText;
251
+ try { planText = readFileSync(join(workspace, plan), 'utf8'); } catch { return { ok: false, line: STATUS.skipped(`${plan} cannot be read`) }; }
252
+ // A plan that cannot carry a goal can still be approved and started: the question drops the goal half and names why.
253
+ const startOnly = (reason) => {
254
+ writeGoalRecord(workspace, 'consent', { condition: null, hash: conditionHash(`start ${plan}`), plan, reason, route: 'lit-plan', askedAt: new Date(now).toISOString() });
255
+ return { ok: false, startOnly: true, reason, line: STATUS.askStart(reason) };
256
+ };
257
+ const done = parseDoneWhen(planText);
258
+ if (!done.ok) return startOnly(done.reason);
259
+ const built = compileCondition({ plan, check: done.check });
260
+ if (!built.ok) return startOnly(built.reason);
261
+ const lint = lintCondition(built.condition, done.check);
262
+ if (!lint.ok) return startOnly(lint.reasons.join('; '));
263
+ const dry = falsify({ cwd: workspace, plan, planText, check: done.check, timeoutMs, run });
264
+ if (!dry.ok) return startOnly(dry.reason);
265
+ writeGoalRecord(workspace, 'consent', { condition: built.condition, hash: conditionHash(built.condition), plan, check: done.check, id: built.id, route: 'lit-plan', askedAt: new Date(now).toISOString(), falsifier: { open: dry.open, exit: dry.exit } });
266
+ return { ok: true, condition: built.condition, line: STATUS.ask(built.condition) };
267
+ };
@@ -127,7 +127,12 @@ function realPath(p) {
127
127
  }
128
128
 
129
129
  function planChecker(args, pluginRoot) {
130
- if (!pluginRoot || args.length !== 3) return false;
130
+ if (!pluginRoot) return false;
131
+ // goal-propose writes only .litgravity/goal/consent.json and runs the plan's allowlisted check once.
132
+ if (args.length === 2 && realPath(args[0]) === realPath(join(pluginRoot, 'skills', 'lit-plan', 'scripts', 'goal-propose.mjs'))) {
133
+ return /^plans\/[A-Za-z0-9_-][A-Za-z0-9._-]*\.md$/u.test(args[1]);
134
+ }
135
+ if (args.length !== 3) return false;
131
136
  const [script, flag, target] = args;
132
137
  if (realPath(script) !== realPath(join(pluginRoot, 'skills', 'lit-plan', 'scripts', 'check-plan.mjs'))) return false;
133
138
  if (!['--check', '--complete', '--skeleton'].includes(flag)) return false;
@@ -92,7 +92,11 @@ export function activation(hit, conversationId, kind = 'ignite') {
92
92
  if (hit.route === 'lit-plan') lines.push(PLAN_REMINDER);
93
93
  if (MOVED_SKILLS[hit.route]) lines.push(movedNote(hit.route));
94
94
  // `go` reads the step the brief offered for this conversation, so the collector needs its id.
95
- if (hit.route === 'lit-adhd' && id) lines.push(`Run the collector for this conversation: node ${dirname(skillPath('lit-adhd'))}/scripts/rewind.mjs --brief --lang <ko|en> --session ${id}${hit.detail ? ' --detail' : ''}`);
95
+ if (hit.route === 'lit-adhd' && id) {
96
+ const mode = hit.recap ? ` --recap${hit.recapOf ? ` --of ${hit.recapOf}` : ''}${hit.recapMoved ? ' --moved' : ''}` : hit.detail ? ' --detail' : '';
97
+ lines.push(`Run the collector for this conversation: node ${dirname(skillPath('lit-adhd'))}/scripts/rewind.mjs --brief --lang ${hit.lang === 'en' ? 'en' : 'ko'} --session ${id}${mode}`);
98
+ }
99
+ if (hit.route === 'lit-adhd' && hit.recapMoved) lines.push('lit-recap moved into lit-adhd: this is its recap view (`lit adhd recap [conversation]`). The collector prints that note as the first line of the recap view; put its output right after the ignition line, unchanged, with nothing before the note.');
96
100
  if (hit.reviewMode) lines.push(`The user forced the ${hit.reviewMode} review mode.`);
97
101
  if (kind === 'confirm') {
98
102
  lines.push('The prompt has no task text after the keyword and nothing is active or resumable. After reading the skill, ask the user in one line what to run (a task for lit-loop, or a route such as plan or review) and wait for the answer before any other tool.');
@@ -3,7 +3,8 @@
3
3
  // A source that is not there reads `unknown`; nothing is inferred.
4
4
 
5
5
  import { execFileSync } from 'node:child_process';
6
- import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
6
+ import { createHash } from 'node:crypto';
7
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs';
7
8
  import { homedir } from 'node:os';
8
9
  import { basename, dirname, join, resolve, sep } from 'node:path';
9
10
 
@@ -14,6 +15,7 @@ import { renderBrief } from './brief.mjs';
14
15
  import { buildBoard, renderBoard } from './board.mjs';
15
16
  import { chooseNextStep, writeNextStep } from './next-step.mjs';
16
17
  import { makeRedactor } from './redact.mjs';
18
+ import { nextCursor, renderVerdict } from './verdict.mjs';
17
19
  import { findTranscripts, makeBudget, readTranscriptLines, sessionRecord } from './transcripts.mjs';
18
20
  import { listLive } from '../liveness.mjs';
19
21
 
@@ -167,7 +169,8 @@ const insideAny = (path, roots) => {
167
169
  };
168
170
 
169
171
  // herdr's agents that work on this repo, read only under HERDR_ENV=1: working or blocked (blocked waits on its user),
170
- // in this herdr workspace or with a cwd inside one of the roots, never this pane. Any failure reads `unknown`.
172
+ // with a cwd inside one of the roots, never this pane. Sharing the herdr workspace is not enough: herdr lists every
173
+ // agent on the machine. Any failure reads `unknown`.
171
174
  const herdrLanes = (env, roots, sessionId, exec) => {
172
175
  if (env.HERDR_ENV !== '1') return null;
173
176
  let agents;
@@ -183,8 +186,7 @@ const herdrLanes = (env, roots, sessionId, exec) => {
183
186
  && ['working', 'blocked'].includes(a.agent_status)
184
187
  && !(ownPane && a.pane_id === ownPane)
185
188
  && !(sessionId && a.agent_session?.value === sessionId)
186
- && ((typeof env.HERDR_WORKSPACE_ID === 'string' && env.HERDR_WORKSPACE_ID && a.workspace_id === env.HERDR_WORKSPACE_ID)
187
- || insideAny(a.cwd, realRoots) || insideAny(a.foreground_cwd, realRoots)))
189
+ && (insideAny(a.cwd, realRoots) || insideAny(a.foreground_cwd, realRoots)))
188
190
  .map((a) => ({
189
191
  pane: typeof a.pane_id === 'string' && PANE.test(a.pane_id) ? a.pane_id : null,
190
192
  session: typeof a.agent_session?.value === 'string' ? a.agent_session.value : null,
@@ -328,9 +330,15 @@ export const collectRewind = ({
328
330
  const geminiDir = join(home, '.gemini', 'antigravity-cli');
329
331
  const transcripts = owner.size ? findTranscripts(geminiDir, [...owner.keys()]) : { status: 'unknown', files: [] };
330
332
  const sessions = [];
331
- for (const { id, path } of transcripts.files) {
332
- if (sessions.length >= limit || budget.exhausted) break;
333
+ // What the verdict card's coverage line names: conversations left unread, by reason.
334
+ const notRead = { budget: 0, limit: 0, unreadable: 0 };
335
+ for (const [index, { id, path }] of transcripts.files.entries()) {
336
+ if (sessions.length >= limit || budget.exhausted) {
337
+ notRead[budget.exhausted ? 'budget' : 'limit'] = transcripts.files.length - index;
338
+ break;
339
+ }
333
340
  const lines = readTranscriptLines(path, budget);
341
+ if (!lines) notRead.unreadable += 1;
334
342
  const session = lines ? sessionRecord(lines, { redact, now, cwd: owner.get(id), live: liveness.get(id) ?? null, finished: finishedIn(id, owner.get(id)) }) : null;
335
343
  if (!session || (session.lastMs !== null && now - session.lastMs > sinceMs)) continue;
336
344
  session.sessionId = id;
@@ -388,6 +396,7 @@ export const collectRewind = ({
388
396
  ...(herdr ? { herdr: herdr.status } : {}),
389
397
  },
390
398
  budget: { bytesRead: budget.used, limit: budget.limit, exhausted: budget.exhausted },
399
+ coverage: { notRead },
391
400
  summary: {
392
401
  sessions: sessions.length,
393
402
  waitingOnUser: sessions.filter((s) => s.status === 'waiting-on-user').length,
@@ -406,8 +415,12 @@ export const collectRewind = ({
406
415
  },
407
416
  repo,
408
417
  workflows: (workflows ?? []).map((f) => ({ ...f, self: Boolean(sessionId) && f.sessionId === sessionId })),
409
- // A start-work run is a start-work frame on a workflow stack; agy keeps no other record of one.
410
- startWork: (workflows ?? []).filter((f) => f.skill === 'start-work').map((f) => ({ sessionId: f.sessionId, status: f.status, plan: f.ref?.plan ?? null })),
418
+ // A start-work run is a start-work frame on a workflow stack; agy keeps no other record of one. The frame outlives
419
+ // the work (nothing pops it when the last row is ticked), so a run whose plan is fully ticked is finished and left
420
+ // out. `lit start`, `go` and the approval `yes` record the plan on the frame; only an older frame without one falls
421
+ // back to the guess: finished once no plan of this folder has an open row.
422
+ startWork: (workflows ?? []).filter((f) => f.skill === 'start-work' && !runFinished(f.ref?.plan ?? null, plans))
423
+ .map((f) => ({ sessionId: f.sessionId, status: f.status, plan: f.ref?.plan ?? null })),
411
424
  handoffs,
412
425
  commits: (commits ?? []).slice(0, 20).map(({ atMs: _atMs, ...c }) => c),
413
426
  };
@@ -443,13 +456,62 @@ export const renderRewind = (data, { lang = 'en', width = 72, detail = false } =
443
456
  return tail.length ? `${board}\n*${tail.join(' ')}*\n` : board;
444
457
  };
445
458
 
446
- export const runRewindCli = (args, cwd = process.cwd(), { env = process.env, stdout = process.stdout, stderr = process.stderr } = {}) => {
447
- const options = { cwd, env, here: false, since: DEFAULT_SINCE, max: DEFAULT_MAX, sessionId: null };
459
+ // The cursor of the verdict card: when this user last looked at this folder's card, kept per workspace under the
460
+ // LitGravity state root (outside the route-state folders, so no reader mistakes it for a conversation).
461
+ export const cursorPath = (cwd, env = process.env) => {
462
+ let real;
463
+ try { real = realpathSync(cwd); } catch { real = resolve(cwd); }
464
+ return join(stateRoot(env), 'adhd', `${createHash('sha256').update(real).digest('hex').slice(0, 16)}.cursor.json`);
465
+ };
466
+ const readCursor = (path) => {
467
+ try {
468
+ const value = JSON.parse(readFileSync(path, 'utf8'));
469
+ return value && typeof value === 'object' ? value : null;
470
+ } catch {
471
+ return null;
472
+ }
473
+ };
474
+ const writeCursor = (path, value) => {
475
+ try {
476
+ mkdirSync(dirname(path), { recursive: true });
477
+ const tmp = `${path}.tmp-${process.pid}`;
478
+ writeFileSync(tmp, `${JSON.stringify(value)}\n`);
479
+ renameSync(tmp, path);
480
+ } catch { /* a card without a cursor shows "first look" next time */ }
481
+ };
482
+
483
+ // The recap view (`lit adhd recap [conversation]`, and the old `lit recap`): one conversation's own card, this one by
484
+ // default, with the plan and goal it touched. Read-only, and the cursor is left alone.
485
+ export const RECAP_MOVED_NOTE = 'lit-recap moved into lit-adhd: this is its recap view.';
486
+ const isOpen = (p) => p.progress?.total !== null && p.progress?.total !== undefined && p.progress.done < p.progress.total;
487
+ const runFinished = (plan, plans) => {
488
+ const local = (plans ?? []).filter((p) => p.local);
489
+ if (!plan) return !local.some(isOpen);
490
+ const own = local.find((p) => p.plan === plan);
491
+ return Boolean(own && own.progress?.total && !isOpen(own));
492
+ };
493
+
494
+ export const renderRecap = (data, { lang = 'ko', width = 72, of = null, moved = false } = {}) => {
495
+ // Reached by an old lit-recap name: the moved note is the view's first line, drawn here so no model can bury it.
496
+ if (moved) return `${RECAP_MOVED_NOTE}\n${renderRecap(data, { lang, width, of })}`;
497
+ const want = typeof of === 'string' && of ? of.slice(0, 8) : null;
498
+ const sessions = (data.sessions ?? []).filter((s) => (want ? s.id8 === want : s.self));
499
+ const picked = sessions.length ? sessions : (want ? [] : (data.sessions ?? []).slice(0, 1));
500
+ const head = lang === 'ko' ? '## 🧾 리캡' : '## 🧾 Recap';
501
+ if (!picked.length) return `${head}\n${lang === 'ko' ? `기록 없음${want ? `: ${want}` : ''} — \`lit adhd\`로 전체를 보세요.` : `No record${want ? ` for ${want}` : ''} — \`lit adhd\` shows every conversation.`}\n`;
502
+ return `${head}\n${renderBrief({ ...data, sessions: picked }, { lang, width: Math.max(40, Math.min(width, 100)) })}`;
503
+ };
504
+
505
+ export const runRewindCli = (args, cwd = process.cwd(), { env = process.env, stdout = process.stdout, stderr = process.stderr, now = Date.now() } = {}) => {
506
+ const options = { cwd, env, here: false, since: DEFAULT_SINCE, max: DEFAULT_MAX, sessionId: null, now };
448
507
  let json = false;
449
508
  let detail = false;
450
- let lang = 'en';
509
+ let recap = false;
510
+ let recapOf = null;
511
+ let moved = false;
512
+ let lang = 'ko';
451
513
  let width = Math.min(Number(stdout.columns) || 72, 72);
452
- const usage = 'Usage: rewind.mjs [--brief|--json] [--detail] [--lang en|ko] [--here] [--since 7d] [--max 12] [--session <id>] [--width N]';
514
+ const usage = 'Usage: rewind.mjs [--brief|--json] [--detail] [--recap [--of <conversation>] [--moved]] [--lang ko|en] [--en] [--here] [--since 7d] [--max 12] [--session <id>] [--width N]';
453
515
  if (args.some((a) => a === '--help' || a === '-h')) {
454
516
  stdout.write(`${usage}\n`);
455
517
  return 0;
@@ -459,6 +521,10 @@ export const runRewindCli = (args, cwd = process.cwd(), { env = process.env, std
459
521
  if (arg === '--json') json = true;
460
522
  else if (arg === '--brief') json = false;
461
523
  else if (arg === '--detail') detail = true;
524
+ else if (arg === '--recap') recap = true;
525
+ else if (arg === '--moved') moved = true;
526
+ else if (arg === '--of' && /^[A-Za-z0-9._:-]{1,160}$/u.test(args[i + 1] ?? '')) recapOf = args[++i];
527
+ else if (arg === '--en') lang = 'en';
462
528
  else if (arg === '--lang' && ['en', 'ko'].includes(args[i + 1])) lang = args[++i];
463
529
  else if (arg === '--here') options.here = true;
464
530
  else if (arg === '--since' && parseSince(args[i + 1])) options.since = args[++i];
@@ -471,7 +537,25 @@ export const runRewindCli = (args, cwd = process.cwd(), { env = process.env, std
471
537
  }
472
538
  }
473
539
  const data = collectRewind(options);
474
- if (json) data.boardText = renderBoard(data, { lang });
475
- stdout.write(json ? `${JSON.stringify(data, null, 2)}\n` : renderRewind(data, { lang, width, detail }));
540
+ const cursorFile = cursorPath(cwd, env);
541
+ const cursor = readCursor(cursorFile);
542
+ if (json) {
543
+ data.boardText = renderBoard(data, { lang });
544
+ data.verdict = renderVerdict(data, { lang, cursor }).verdict;
545
+ stdout.write(`${JSON.stringify(data, null, 2)}\n`);
546
+ return 0;
547
+ }
548
+ if (recap) {
549
+ stdout.write(renderRecap(data, { lang, width, of: recapOf, moved }));
550
+ return 0;
551
+ }
552
+ if (detail) {
553
+ stdout.write(renderRewind(data, { lang, width, detail: true }));
554
+ return 0;
555
+ }
556
+ // The default: the verdict card, then the cursor moves to now, so the next card counts from this look.
557
+ const card = renderVerdict(data, { lang, cursor });
558
+ writeCursor(cursorFile, nextCursor(card.verdict, now));
559
+ stdout.write(card.text);
476
560
  return 0;
477
561
  };