@litfamily/litmuse 0.1.14 → 0.1.16

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 (49) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +8 -7
  3. package/README_ko-KR.md +8 -7
  4. package/bin/litmuse.mjs +1 -1
  5. package/lib/stage-card.mjs +4 -12
  6. package/package.json +1 -1
  7. package/plugin/.muse-plugin/plugin.json +16 -16
  8. package/plugin/commands/lit-status.md +1 -1
  9. package/plugin/commands/lit.md +6 -5
  10. package/plugin/hooks/lib/goal.mjs +224 -0
  11. package/plugin/hooks/lib/routes.mjs +27 -10
  12. package/plugin/hooks/lib/skill-plan.mjs +199 -0
  13. package/plugin/hooks/lib/stage.mjs +4 -1
  14. package/plugin/hooks/lib/workflow-stack.mjs +1 -1
  15. package/plugin/hooks/post-tool-use.mjs +39 -0
  16. package/plugin/hooks/pre-tool-use.mjs +34 -1
  17. package/plugin/hooks/session-start.mjs +4 -0
  18. package/plugin/hooks/stop.mjs +53 -3
  19. package/plugin/hooks/user-prompt-submit.mjs +217 -9
  20. package/plugin/lib/rewind/collect.mjs +93 -15
  21. package/plugin/lib/rewind/rainbow.mjs +13 -0
  22. package/plugin/lib/rewind/verdict.mjs +258 -0
  23. package/plugin/skills/autoconference/SKILL.md +1 -1
  24. package/plugin/skills/autoconference/modes/core.md +1 -1
  25. package/plugin/skills/browser-drive/scripts/capability-probe.mjs +25 -11
  26. package/plugin/skills/lit-adhd/SKILL.md +56 -32
  27. package/plugin/skills/lit-brainstorm/SKILL.md +1 -0
  28. package/plugin/skills/lit-comprehend/SKILL.md +4 -3
  29. package/plugin/skills/lit-crucible/SKILL.md +1 -0
  30. package/plugin/skills/lit-handoff/SKILL.md +3 -2
  31. package/plugin/skills/lit-init/SKILL.md +1 -1
  32. package/plugin/skills/lit-loop/SKILL.md +6 -0
  33. package/plugin/skills/lit-plan/SKILL.md +8 -4
  34. package/plugin/skills/lit-plan/scripts/goal-propose.mjs +63 -0
  35. package/plugin/skills/lit-plan/templates/plan.md +4 -0
  36. package/plugin/skills/lit-team/SKILL.md +97 -64
  37. package/plugin/skills/lit-team/references/team-orchestration.md +6 -4
  38. package/plugin/skills/litgoal/SKILL.md +3 -1
  39. package/plugin/skills/litresearch/SKILL.md +1 -0
  40. package/plugin/skills/litwork/SKILL.md +6 -6
  41. package/plugin/skills/review-work/SKILL.md +1 -0
  42. package/plugin/skills/start-work/SKILL.md +1 -1
  43. package/plugin/skills/ultra-brainstorm/SKILL.md +107 -0
  44. package/plugin/skills/ultra-brainstorm/references/lenses.md +38 -0
  45. package/plugin/skills/ultra-brainstorm/references/workflow-script.md +169 -0
  46. package/plugin/skills/ultra-brainstorm/scripts/estimate.mjs +57 -0
  47. package/plugin/skills/wikify/SKILL.md +2 -2
  48. package/plugin/skills/wikify/modes/init.md +1 -1
  49. package/plugin/skills/lit-recap/SKILL.md +0 -232
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.16 — 2026-11-21
4
+
5
+ - A lit-loop or litwork run with no plan can now get a Muse goal too, asked once. When the project has a test command (`npm test`, `pytest`, `cargo test` or `go test ./...`) and the prompt names an objective, the prompt hook records one question at the run's first activation and tells the model to end its first reply with `Set goal for this lit-loop: /goal <check> exits 0 and this is done: <objective>? (yes / no)`. Muse shows no hook text, so that is the model's job and cannot be forced. An exact `yes` arms the goal, and the model sets it with `create_goal` the way a plan's goal is set, but starts no start-work; `no`, `edit` or any other prompt drops the question. With no test command the model asks after its failing check through `goal-propose.mjs --loop --check "<check>" <objective>`, which runs the check once and prints `No goal set: <reason>` when it already passes, cannot run or is not an allowlisted test command. A repeat of `lit`, `lit goal`, a plan, and a session that already holds an open goal or a pending question ask nothing.
6
+ - The hook code changed, so Muse asks you to approve the LitMuse hooks again after the update.
7
+
8
+ ## 0.1.15 — 2026-11-18
9
+
10
+ - `lit-adhd` now answers "so what do I do now?" with a verdict card of about six lines: what changed since your last look in this project, the one thing to do with the exact text to type, why and what skipping it costs, what else waits on you, and what was not read. A versioned rule table picks the action from proven records only (a ticked plan, a finished start-work run, a commit), a push is always a question for you, and a card whose action rested on records that moved says the old action is withdrawn. `lit adhd detail` opens the KPI board and the per-session brief; `litmuse rewind --json` carries the card under `verdict`.
11
+ - lit-recap moved into lit-adhd as its recap view, `lit adhd recap [session]`. `lit recap`, `litrecap`, `/litmuse:lit-recap` and `lit status` keep working, and the view they print starts with one line saying where it moved.
12
+ - A start-work run whose plan has every row ticked now always reads finished in lit-adhd, even while another plan is open, so the card never offers to continue it. Every start (`yes` at approval, `lit start`, `/start-work`, `go`) records the exact plan on the run record, using the one open plan when none is typed; only an old record without a plan falls back to "no open plan in the folder".
13
+ - `lit adhd` is Korean by default, also for an English-looking prompt. The hook picks the language in code and passes the exact `--lang` flag; English only for `--en`, `--lang en`, "in English" or 영어로.
14
+ - `lit adhd` now runs the collector shipped with the plugin instead of the `litmuse` bin on PATH, which can be an older package that prints the old board.
15
+ - ultra-brainstorm reads the count from a picked option's whole label as well as from a typed number, so `(Recommended) 100 (recommended minimum)` or `300명 (Recommended)` launches; an answer with two different numbers, such as `100 or 300?`, asks again. The reply reaches the reader only as quoted heredoc data on stdin, so shell syntax in it never runs.
16
+ - ultra-brainstorm's cost line is now a measured range: 100 agents read `≈ 3.8M–9.2M tokens` instead of `≈ 0.39M`. Each child carries about 33k tokens of host prompt before its task and makes at least two calls, which the old per-agent average left out.
17
+ - ultra-brainstorm's Workflow script now uses the Workflow API V1 that live Muse 1.4.23 sessions advertise (`host.parallel`, `host.agent`), and merges same-name clusters from different reducers before the judge scores them.
18
+ - The "other work here" count in lit-adhd now includes only herdr agents whose working folder is inside this repo; an agent of another repo in the same herdr workspace no longer holds `go` back.
19
+ - New `ultra-brainstorm` skill: asks how many idea agents first (100 or 300, with a token estimate), runs them at minimal effort through a Muse Workflow, folds the ideas with reducers and one judge, and hands you a scored top list to pick from. `lit ultra <topic>` and `/ultra-brainstorm` start it, and a plain `no` to the count question ends it at once.
20
+ - Only the session that was asked can answer the plan-approval question: a `yes` typed in another session starts nothing and shows one line saying the approval was not recorded and which `lit start` command to run. After a one-shot `muse exec` run, start the plan with `lit start plans/<f>.md`, or resume that session and type `yes`.
21
+ - One `yes` at plan approval starts the work and sets a Muse goal. A plan with a `## Done when` check gets the question `Approve plan, start work and set goal: /goal …? (yes / edit / no)`, and a plan that cannot carry a goal gets `Approve plan and start work? (yes / no)` with the one reason. An exact `yes` starts start-work on the plan (the same start as `lit start plans/<f>.md`) and arms the goal; a refused start (another live run on the plan, no open row) arms nothing and says why, PreToolUse refuses any other LitMuse-tagged goal, a goal of your own is left alone, and the Stop hook asks for the check once every row is ticked. Read-only skills carry `goal: never`. See `docs/reference.md`.
22
+ - `lit +viz`, `+research`, `+ast` and other `+` words put companion skills beside a route, and LitMuse adds an obvious one itself, three skills at most.
23
+ - `lit-team` now makes this session the orchestrator: it splits the work, picks subagents, a Workflow, herdr panes or isolated worktrees, merges and re-verifies, and reports once.
24
+ - The hook code changed, so Muse asks you to approve the LitMuse hooks again after the update.
25
+
3
26
  ## 0.1.14 — 2026-11-16
4
27
 
5
28
  - `install` now prints the LitFamily extensions notice (and the fixed "Muse refuses a folder that is already there" line after it) once per text. Each printed text leaves a hash and a time as one line in `~/.local/share/litmuse/shown.jsonl`; a later install whose notice would be the same leaves it out, while the live "N things need a look" line and the status line still print. A new text (for example the leftover-engines line after an upgrade) is printed and appended. A missing, corrupt or symlinked record prints the notice as before. No hook, context or manifest file changed, so the hook digests stay the ones 0.1.13 shipped and Muse does not ask you to approve the hooks again.
package/README.md CHANGED
@@ -37,7 +37,8 @@ You need Node.js 20 or newer and Muse Code, signed in once.
37
37
  2. `doctor` ends with `LitMuse doctor: PASS` when everything is in place.
38
38
  3. Open Muse in a project with `muse`. `/skills` shows the LitMuse skills and `/plugins` the plugin.
39
39
  4. Start a prompt with `lit`. Plain `lit` runs lit-loop; a word after it picks the route: `lit plan`, `lit review`, `lit research`, `lit debug`, `lit handoff`, `lit recap`, `lit korean`.
40
- 5. Approve a plan, then type `/start-work` to build it row by row with tests. Before you stop, `lit handoff`; next time, `lit recap` reads where you were.
40
+ 5. Approve a plan, then type `/start-work` to build it row by row with tests. When the plan names its test command, the approval question also offers a Muse goal (`Approve plan, start work and set goal: /goal …? (yes / edit / no)`): one `yes` starts the work and sets that goal, which closes once every row is ticked and the command exits 0. A plan with no test command gets `Approve plan and start work? (yes / no)` instead. Before you stop, `lit handoff`; next time, `lit adhd` tells you what to do now.
41
+ 6. Add `+viz`, `+research` or another `+` word after `lit` (`lit +viz plot the results`) to put a companion skill beside the route; LitMuse also adds one on its own when the task clearly asks for it, at most three in all.
41
42
 
42
43
  Run from any folder:
43
44
 
@@ -64,7 +65,7 @@ Four real outputs rendered on a Mac during the quality parity round, each opened
64
65
 
65
66
  <p align="center"><img src="./docs/assets/parity/lit-adhd-brief.png" width="960" alt="Terminal card of litmuse rewind, the lit-adhd brief: a rainbow headline with 2 sessions and 0 waiting on you, a table of the two ended sessions in todo-app, the roadmap gauge for plans/todo-app.md at 1/2, and a boxed recommended next step to start the plan." /></p>
66
67
 
67
- `lit-adhd` opens with a KPI board: the one thing to do now and the exact text to type, done / in progress / waiting on you / left counts with an overall bar, and milestone rows with ten-cell bars. It also lists what you finished lately, what is still to do, and reminders such as uncommitted changes or a plan untouched for a week. `lit adhd detail` adds the per-session brief pictured above: session cards with status badges, an ended table and a boxed recommended step, in colour on a TTY with no internal field names leaking.
68
+ `lit-adhd` answers "so what do I do now?" in about six lines. It says what changed since you last looked, gives the one thing to do with the exact text to type, says why and what it costs to skip it, lists what else waits on you, and owns up to what it could not read. A fixed rule table picks that one action from records it can prove (a ticked plan row, a finished run, a commit), so a session that only claims to be done does not count, and a push always comes back as a question for you. `lit adhd detail` opens the KPI board with bars, milestones and reminders, plus the per-session brief pictured above. `lit adhd recap` is the per-session view that lit-recap used to give; the old `lit recap` keeps working and says where it moved.
68
69
 
69
70
  <p align="center"><img src="./docs/assets/parity/lit-pptx-deck.png" width="960" alt="A lit-pptx status deck: KPI row and a column chart of suite growth per wave." /></p>
70
71
 
@@ -86,7 +87,7 @@ Muse still runs the session and picks the model; LitMuse adds the way of working
86
87
  | --- | --- |
87
88
  | Takes a line and gets to work | Pins the goal and writes the failing test first |
88
89
  | Fills its context over a long session | Writes the handoff before compaction, reads it back after |
89
- | Opens the next session blank | `lit recap` reads the handoff and names the next step |
90
+ | Opens the next session blank | `lit adhd` reads every recent session and names the one next step |
90
91
  | Calls it done when the model says so | Checks the plan with tests and real-surface proof |
91
92
 
92
93
  **33 skills** load on demand, each a dense Muse skill with the references and scripts it needs inside its own folder. The catalog holds only their short descriptions, so they keep their place even next to a large personal skill collection. Nine short stubs stand in for the skills that became LitFamily extensions (see [Extensions](#extensions)).
@@ -95,12 +96,12 @@ Muse still runs the session and picks the model; LitMuse adds the way of working
95
96
  | --- | --- | --- |
96
97
  | Work loop | lit-loop, litgoal, litwork | Goal pinned, failing test first, record left |
97
98
  | Plan and build | lit-plan, start-work, lit-code, debugging, refactor, lit-commit, lsp, lsp-setup | Written plan, then row-by-row build |
98
- | Ideas first | lit-brainstorm, deep-interview, lit-crucible | Diverge, clarify, pressure-test |
99
+ | Ideas first | lit-brainstorm, ultra-brainstorm, deep-interview, lit-crucible | Diverge, go very wide, clarify, pressure-test |
99
100
  | Review and cleanup | review-work, comment-checker, lit-burnoff, lit-burnoff-file | Second look, then residue stripped |
100
101
  | Research | litresearch, autoresearch, autoconference, wikify, lit-comprehend | Parallel searchers, traced claims |
101
- | Teams | lit-team | Child agents behind one packet |
102
+ | Teams | lit-team | This session splits, distributes, merges and verifies |
102
103
  | Prose | lit-humanizer | Korean and English cleanup, facts kept |
103
- | Continuity | lit-recap, lit-handoff, lit-init, rules | Handoffs, recaps, orientation |
104
+ | Continuity | lit-adhd, lit-handoff, lit-init, rules | Handoffs, recaps, orientation |
104
105
  | Tools | structural-search, browser-drive | Syntax-shaped search, live pages |
105
106
 
106
107
  The skills call programs already on your machine: Python 3.10 to 3.14 for autoresearch (a newer `python3` is passed over for the newest `python3.X` in that range), Chrome or Chromium for browser-drive, ast-grep and the language checkers the `lsp` skill drives. `doctor` lists what is missing and the command that installs it; LitMuse installs nothing globally.
@@ -185,7 +186,7 @@ The card reads the hook-kept state under `~/.local/state/litmuse/`, outside the
185
186
 
186
187
  ### Automatic handoff
187
188
 
188
- A long session fills the model's context, and when Muse compacts it, detail drops out of the summary. So the PreCompact hook writes a handoff file before the compaction, and SessionStart reads the fresh file back into the conversation after it. Type `lit handoff` before you stop and `lit recap` when you return; the packet names what was built, how it was checked, and what is left.
189
+ A long session fills the model's context, and when Muse compacts it, detail drops out of the summary. So the PreCompact hook writes a handoff file before the compaction, and SessionStart reads the fresh file back into the conversation after it. Type `lit handoff` before you stop and `lit adhd recap` when you return; the packet names what was built, how it was checked, and what is left.
189
190
 
190
191
  The hook answers with one recorded line:
191
192
 
package/README_ko-KR.md CHANGED
@@ -37,7 +37,8 @@ Node.js 20 이상과, 한 번 로그인해 둔 Muse Code가 필요합니다.
37
37
  2. 모두 갖춰지면 `doctor`의 마지막 줄이 `LitMuse doctor: PASS`입니다.
38
38
  3. 프로젝트에서 `muse`로 Muse를 엽니다. `/skills`로 LitMuse 스킬을, `/plugins`로 플러그인을 확인합니다.
39
39
  4. 프롬프트를 `lit`으로 시작합니다. `lit`만 쓰면 lit-loop가 돌고, 뒤에 붙는 낱말이 경로를 고릅니다: `lit plan`, `lit review`, `lit research`, `lit debug`, `lit handoff`, `lit recap`, `lit korean`.
40
- 5. 계획이 마음에 들면 `/start-work`로 한 줄씩 테스트와 함께 구현합니다. 끝내기 전에 `lit handoff`, 다음에는 `lit recap`이 어디까지 왔는지 읽어 줍니다.
40
+ 5. 계획이 마음에 들면 `/start-work`로 한 줄씩 테스트와 함께 구현합니다. 계획이 테스트 명령을 적어 두면 승인 질문이 Muse 목표도 함께 묻습니다(`Approve plan, start work and set goal: /goal …? (yes / edit / no)`). `yes` 한 번에 작업이 시작되고 그 목표가 걸리며, 모든 행이 체크되고 그 명령이 0으로 끝나면 목표가 닫힙니다. 테스트 명령이 없는 계획은 `Approve plan and start work? (yes / no)`로 묻습니다. 끝내기 전에 `lit handoff`, 다음에는 `lit adhd`가 지금 할 일을 알려 줍니다.
41
+ 6. `lit` 뒤에 `+viz`, `+research` 같은 `+` 낱말을 붙이면(`lit +viz 결과 그려 줘`) 경로 옆에 도우미 스킬이 붙습니다. 일이 분명히 그걸 원할 때는 LitMuse가 알아서 붙이고, 모두 합쳐 셋까지입니다.
41
42
 
42
43
  아무 폴더에서 실행합니다.
43
44
 
@@ -64,7 +65,7 @@ npx @litfamily/litmuse doctor
64
65
 
65
66
  <p align="center"><img src="./docs/assets/parity/lit-adhd-brief.png" width="960" alt="litmuse rewind로 출력한 lit-adhd 브리프의 터미널 카드. 세션 2개와 대기 0개를 알리는 무지개 헤드라인, todo-app에서 끝난 두 세션의 표, plans/todo-app.md의 1/2 로드맵 게이지, 계획 시작을 권하는 박스형 다음 단계." /></p>
66
67
 
67
- `lit-adhd`는 KPI 보드부터 보여 줍니다. 지금 할 일 하나와 그대로 입력할 말, 끝남·진행 중·나를 기다림·남음 개수와 전체 진행 막대, 10칸 막대가 붙은 마일스톤 표, 최근 끝낸 일과 남은 일, 커밋 안 된 변경이나 일주일째 멈춘 계획 같은 잊지 말 것이 한 화면에 담깁니다. `lit adhd 자세히`라고 하면 위 그림의 세션별 브리프가 붙습니다. 상태 뱃지가 달린 세션 카드와 종료 표, 박스형 권장 다음 단계가 터미널 색상 그대로 나오고, 내부 필드 이름은 새지 않습니다.
68
+ `lit-adhd`는 "그래서 지금 뭘 하지?"에 여섯 줄쯤으로 답합니다. 마지막으로 본 뒤 무엇이 바뀌었는지 말하고, 할 일 하나와 그대로 입력할 말, 이유와 안 했을 때 생기는 일, 그 밖에 나를 기다리는 것, 읽지 못한 기록까지 밝힙니다. 할 일은 정해진 규칙표가 증명할 수 있는 기록(체크된 계획 행, 끝난 실행, 커밋)만 보고 고릅니다. 그래서 끝났다고 말만 한 세션은 끝난 것으로 치지 않고, push는 언제나 내가 답할 질문으로 남습니다. `lit adhd 자세히`라고 하면 막대와 마일스톤, 잊지 말 것이 담긴 KPI 보드와 위 그림의 세션별 브리프가 열립니다. `lit adhd recap`은 예전 lit-recap이 보여 주던 세션별 보기이고, 예전 이름 `lit recap`도 그대로 통하며 어디로 옮겼는지 한 줄 알려 줍니다.
68
69
 
69
70
  <p align="center"><img src="./docs/assets/parity/lit-pptx-deck.png" width="960" alt="lit-pptx 상태 덱. KPI 행과 웨이브별 스위트 증가 막대 차트." /></p>
70
71
 
@@ -86,7 +87,7 @@ npx @litfamily/litmuse doctor
86
87
  | --- | --- |
87
88
  | 한 줄을 받고 바로 일을 시작합니다 | 목표를 고정하고 떨어지는 테스트를 먼저 씁니다 |
88
89
  | 긴 세션에서 컨텍스트가 찹니다 | 컴팩션 전에 인계를 쓰고 뒤에 다시 읽습니다 |
89
- | 다음 세션은 빈자리에서 시작합니다 | `lit recap`이 인계를 읽고 다음 일을 가리킵니다 |
90
+ | 다음 세션은 빈자리에서 시작합니다 | `lit adhd`가 최근 세션을 모두 읽고 다음 일 하나를 가리킵니다 |
90
91
  | 모델이 끝났다고 하면 끝납니다 | 계획에 맞춰 테스트와 실제 확인으로 검증합니다 |
91
92
 
92
93
  **스킬 33개**는 필요할 때 불러오는 밀도 높은 Muse 스킬이며, 각 스킬에 필요한 참고 문서와 스크립트가 그 스킬 폴더 안에 함께 들어 있습니다. 카탈로그에는 짧은 설명만 올라가므로 개인 스킬이 많은 환경에서도 자리를 지킵니다. 여기에 LitFamily 확장이 된 스킬의 짧은 스텁 아홉 개가 더해집니다([확장](#확장) 참고).
@@ -95,12 +96,12 @@ npx @litfamily/litmuse doctor
95
96
  | --- | --- | --- |
96
97
  | 작업 고리 | lit-loop, litgoal, litwork | 목표 고정, 떨어지는 테스트 먼저, 기록 남기기 |
97
98
  | 계획과 구현 | lit-plan, start-work, lit-code, debugging, refactor, lit-commit, lsp, lsp-setup | 계획서 작성, 행별 구현 |
98
- | 아이디어 다지기 | lit-brainstorm, deep-interview, lit-crucible | 넓히기, 묻기, 압박 테스트 |
99
+ | 아이디어 다지기 | lit-brainstorm, ultra-brainstorm, deep-interview, lit-crucible | 넓히기, 아주 넓히기, 묻기, 압박 테스트 |
99
100
  | 검토와 정리 | review-work, comment-checker, lit-burnoff, lit-burnoff-file | 다시 보기, 잔재 지우기 |
100
101
  | 조사 | litresearch, autoresearch, autoconference, wikify, lit-comprehend | 병렬 탐색, 근거 추적 |
101
- | 팀 | lit-team | 하나의 패킷 뒤 자식 에이전트 |
102
+ | 팀 | lit-team | 이 세션이 나누고, 맡기고, 합치고, 확인 |
102
103
  | 글 | lit-humanizer | 한국어와 영어 다듬기, 사실 유지 |
103
- | 이어 가기 | lit-recap, lit-handoff, lit-init, rules | 인계, 회고, 길잡이 |
104
+ | 이어 가기 | lit-adhd, lit-handoff, lit-init, rules | 인계, 회고, 길잡이 |
104
105
  | 도구 | structural-search, browser-drive | 코드 모양 검색, 살아 있는 페이지 |
105
106
 
106
107
  스킬들은 내 컴퓨터에 이미 있는 프로그램을 씁니다: autoresearch에는 Python 3.10~3.14(더 새로운 `python3`는 건너뛰고 이 범위에서 가장 새로운 `python3.X`를 씀), browser-drive에는 Chrome 또는 Chromium, 그리고 ast-grep과 `lsp` 스킬이 부르는 언어 검사 도구. 빠진 것과 설치 명령은 `doctor`가 알려 주며, LitMuse가 전역으로 무언가를 설치하는 일은 없습니다.
@@ -185,7 +186,7 @@ Muse의 `/hud`는 켜고 끄는 고정 항목 목록이라서 플러그인 글
185
186
 
186
187
  ### 자동 핸드오프
187
188
 
188
- 긴 세션은 모델 컨텍스트를 채우고, Muse가 컴팩션하면 요약에서 세부 사항이 떨어져 나갑니다. 그래서 컴팩션 전에 PreCompact 훅이 인계 파일을 쓰고, 컴팩션 뒤에 SessionStart가 새 파일을 대화로 다시 읽어들입니다. 멈추기 전에 `lit handoff`, 돌아오면 `lit recap`을 쓰면 되고, 패킷에는 만든 것, 확인한 방법, 남은 일이 들어갑니다.
189
+ 긴 세션은 모델 컨텍스트를 채우고, Muse가 컴팩션하면 요약에서 세부 사항이 떨어져 나갑니다. 그래서 컴팩션 전에 PreCompact 훅이 인계 파일을 쓰고, 컴팩션 뒤에 SessionStart가 새 파일을 대화로 다시 읽어들입니다. 멈추기 전에 `lit handoff`, 돌아오면 `lit adhd recap`을 쓰면 되고, 패킷에는 만든 것, 확인한 방법, 남은 일이 들어갑니다.
189
190
 
190
191
  훅은 기록 한 줄로 답합니다.
191
192
 
package/bin/litmuse.mjs CHANGED
@@ -28,7 +28,7 @@ Commands
28
28
  hud Show the recommended /hud and /theme preset
29
29
  config agentFile on|off: the short LitFamily block in Muse's user rules file (acts at once)
30
30
  style eli5 | asd-ste100 | off | status: the answer style LitMuse adds to every session
31
- rewind Cross-session KPI board [--lang ko|en] [--detail] [--json] [--here] [--since 7d] [--max 12] [--session <id>]
31
+ rewind What to do now (verdict card) [--lang ko|en] [--detail | --recap [id]] [--json] [--here] [--since 7d] [--max 12] [--session <id>]
32
32
  extensions list | check | install | update | remove | prune-backups: the nine LitFamily extensions as Muse
33
33
  user skills (litmuse extensions help; writes only with --yes)
34
34
  uninstall Remove the plugin from Muse and the staged bundle
@@ -5,6 +5,10 @@ import { newerThan } from '../plugin/hooks/lib/common.mjs';
5
5
  import { readManifest } from './bundle.mjs';
6
6
  import { paths } from './paths.mjs';
7
7
  import { gauge } from '../plugin/lib/rewind/gauge.mjs';
8
+ // One rainbow-tinted line at most (a static ANSI gradient, flash-safe); it marks the adhd turn.
9
+ import { rainbowLine } from '../plugin/lib/rewind/rainbow.mjs';
10
+
11
+ export { rainbowLine };
8
12
  import { REVIEW_LANES, projectKey, resolveProjectStateRoot } from '../plugin/hooks/lib/workflow-stack.mjs';
9
13
 
10
14
  // The hooks write `.litmuse` at the project state root, which may sit above the card's cwd.
@@ -83,18 +87,6 @@ export function loadStage({ cwd, session, env = process.env }) {
83
87
  return entry && entry.session ? readStage(stageFile(cwd, entry.session, env)) : null;
84
88
  }
85
89
 
86
- // One rainbow-tinted line at most: a static ANSI gradient, no animation, no blinking, no
87
- // full-field luminance swing, so it stays flash-safe on any terminal. It marks the adhd turn.
88
- const RAINBOW = [196, 208, 226, 46, 51, 21, 201];
89
- export function rainbowLine(text) {
90
- let color = 0;
91
- let out = '';
92
- for (const ch of String(text)) {
93
- out += ch === ' ' ? ch : `\u001b[38;5;${RAINBOW[color++ % RAINBOW.length]}m${ch}`;
94
- }
95
- return `${out}\u001b[0m`;
96
- }
97
-
98
90
  // Fresh workflow stacks mean recent sessions worth briefing: any stack file touched in 24 h.
99
91
  export function freshStacks(cwd, now = Date.now()) {
100
92
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litfamily/litmuse",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "description": "Installer for LitMuse: skills, hooks and agents that help Meta's Muse Code plan, build, check and hand off work.",
5
5
  "keywords": [
6
6
  "muse",
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "name": "litmuse",
4
4
  "displayName": "LitMuse",
5
- "version": "0.1.14",
5
+ "version": "0.1.16",
6
6
  "description": "LitFamily workflows for Muse Code: bare lit activation, planning, evidence-bound execution, review, research, handoff and Korean prose care.",
7
7
  "compat": {
8
8
  "source": "native",
@@ -105,11 +105,6 @@
105
105
  "path": "skills/lit-humanizer/SKILL.md",
106
106
  "enabledDefault": true
107
107
  },
108
- {
109
- "id": "lit-recap",
110
- "path": "skills/lit-recap/SKILL.md",
111
- "enabledDefault": true
112
- },
113
108
  {
114
109
  "id": "lit-handoff",
115
110
  "path": "skills/lit-handoff/SKILL.md",
@@ -190,6 +185,11 @@
190
185
  "path": "skills/lit-brainstorm/SKILL.md",
191
186
  "enabledDefault": true
192
187
  },
188
+ {
189
+ "id": "ultra-brainstorm",
190
+ "path": "skills/ultra-brainstorm/SKILL.md",
191
+ "enabledDefault": true
192
+ },
193
193
  {
194
194
  "id": "lit-burnoff-file",
195
195
  "path": "skills/lit-burnoff-file/SKILL.md",
@@ -251,7 +251,7 @@
251
251
  "node",
252
252
  "hooks/session-start.mjs",
253
253
  "--digest",
254
- "783e805fb4c86f73"
254
+ "a4a3defb933793e6"
255
255
  ],
256
256
  "timeoutMs": 5000
257
257
  },
@@ -262,7 +262,7 @@
262
262
  "node",
263
263
  "hooks/user-prompt-submit.mjs",
264
264
  "--digest",
265
- "6e99e1297993c089"
265
+ "02f7f133ee18fa8f"
266
266
  ],
267
267
  "timeoutMs": 5000,
268
268
  "statusMessage": "LitMuse route check"
@@ -274,7 +274,7 @@
274
274
  "node",
275
275
  "hooks/pre-tool-use.mjs",
276
276
  "--digest",
277
- "3812c6ffa6e3d051"
277
+ "61284066a83e7bf9"
278
278
  ],
279
279
  "timeoutMs": 5000
280
280
  },
@@ -285,7 +285,7 @@
285
285
  "node",
286
286
  "hooks/post-tool-use.mjs",
287
287
  "--digest",
288
- "e4842aa51b5ec3b7"
288
+ "c6a96dd6cbac119d"
289
289
  ],
290
290
  "timeoutMs": 5000
291
291
  },
@@ -296,7 +296,7 @@
296
296
  "node",
297
297
  "hooks/post-tool-use-failure.mjs",
298
298
  "--digest",
299
- "45bdb35ffeabee4f"
299
+ "f4d021c9a022292c"
300
300
  ],
301
301
  "timeoutMs": 5000
302
302
  },
@@ -307,7 +307,7 @@
307
307
  "node",
308
308
  "hooks/stop.mjs",
309
309
  "--digest",
310
- "6669bed30efabf95"
310
+ "60f1b3268eb85120"
311
311
  ],
312
312
  "timeoutMs": 5000
313
313
  },
@@ -318,7 +318,7 @@
318
318
  "node",
319
319
  "hooks/subagent-start.mjs",
320
320
  "--digest",
321
- "b0c6e445a1fa594f"
321
+ "d8b88f8c7d564788"
322
322
  ],
323
323
  "timeoutMs": 5000
324
324
  },
@@ -329,7 +329,7 @@
329
329
  "node",
330
330
  "hooks/subagent-stop.mjs",
331
331
  "--digest",
332
- "b57bf22ea5228b2e"
332
+ "99aa8e23fc29a0a2"
333
333
  ],
334
334
  "timeoutMs": 5000
335
335
  },
@@ -340,7 +340,7 @@
340
340
  "node",
341
341
  "hooks/session-end.mjs",
342
342
  "--digest",
343
- "2056c29d36a3ba1d"
343
+ "0a3ad8b835c39886"
344
344
  ],
345
345
  "timeoutMs": 5000
346
346
  },
@@ -351,7 +351,7 @@
351
351
  "node",
352
352
  "hooks/pre-compact.mjs",
353
353
  "--digest",
354
- "a89a944c105d54bc"
354
+ "1b0c8c166a3ae681"
355
355
  ],
356
356
  "timeoutMs": 5000
357
357
  }
@@ -14,4 +14,4 @@ Print the LitMuse status card for this workspace. Scope: $ARGUMENTS (empty means
14
14
  - Goal: each `.litmuse/goals/*.json` whose status is `active`, with its objective and the criteria that are not `pass`.
15
15
  3. Add the first lines of `.litmuse/handoff/latest.md` if present, and the count of tool events and failures in the newest ledger.
16
16
 
17
- Answer with the card, then one line naming the next action. If the record is missing or older than the ledger, say the card may be stale rather than guessing. For a fuller recap, load `plugin:litmuse:lit-recap`.
17
+ Answer with the card, then one line naming the next action. If the record is missing or older than the ledger, say the card may be stale rather than guessing. For a fuller recap, run `lit adhd recap` (the per-session view of `plugin:litmuse:lit-adhd`).
@@ -1,12 +1,13 @@
1
1
  ---
2
2
  description: "Run a request as a LitMuse lit route (plan, loop, review, research and more)"
3
- argument-hint: "[plan|loop|work|review|research|handoff|recap|...] <task>"
3
+ argument-hint: "[plan|loop|work|review|research|handoff|adhd|...] [+viz +ui ...] <task>"
4
4
  ---
5
5
  LitMuse route request: $ARGUMENTS
6
6
 
7
7
  Treat the line above as a LitMuse request; the prompt hook has already recorded its route.
8
8
 
9
- 1. The first word picks the route: loop → lit-loop, plan → lit-plan, work → litwork, goal → litgoal, research → litresearch, review → review-work, start → start-work, recap → lit-recap, status → lit-recap, handoff → lit-handoff, init → lit-init, debug → debugging, interview → deep-interview, crucible → lit-crucible, commit → lit-commit, refactor → refactor, burnoff → lit-burnoff, burnoff-file → lit-burnoff-file, brainstorm → lit-brainstorm, brainstorming → lit-brainstorm, ideation → lit-brainstorm, ideate → lit-brainstorm, idea → lit-brainstorm, ideas → lit-brainstorm, hijack → lit-hijack, hijacking → lit-hijack, 하이재킹 → lit-hijack, 하이잭 → lit-hijack, adhd → lit-adhd, rewind → lit-adhd, approve → start-work, deny → start-work, team → lit-team, conference → autoconference, rules → rules, lsp → lsp, diagnostics → lsp, lsp-setup → lsp-setup, motion → lit-typographic-motion, film → lit-typographic-motion, video → lit-typographic-motion, 영상 → lit-typographic-motion, explain → lit-comprehend, humanize → lit-humanizer, korean → lit-humanizer, 다듬어 → lit-humanizer, 윤문 → lit-humanizer. Any other first word means lit-loop, except a task that asks to make a film (a film compound such as kinetic type, lyric video, title sequence, cover loop, 모션그래픽, 가사 영상, or a bare video noun with a making verb), which goes to lit-typographic-motion. Skills without a keyword (frontend-ui-ux, readme-studio, visual-qa, comment-checker, wikify, autoresearch, structural-search, browser-drive, lit-code) are reached through lit-loop or their own `/<skill>` command.
10
- 2. Load that skill with read_skill using the id `plugin:litmuse:<route>` before any other tool, and follow it. When the hook context says the route is already active or resuming, skip steps 2 and 3: keep the criteria, plan and ledger you have.
11
- 3. Your first output, before any tool call or other text, is the line `🔥 **LIT IGNITED · <route>** 🔥` on its own line, once. When the hook context says the route continues, the line is `🔥 **LIT CONTINUES · <route>** 🔥` instead.
12
- 4. Report in reader mode: the result, any material risk, and the action the user must take.
9
+ 1. The first word picks the route: loop → lit-loop, plan → lit-plan, work → litwork, goal → litgoal, research → litresearch, review → review-work, start → start-work, recap → lit-adhd (recap view; lit-recap moved there), status → lit-adhd (recap view), handoff → lit-handoff, init → lit-init, debug → debugging, interview → deep-interview, crucible → lit-crucible, commit → lit-commit, refactor → refactor, burnoff → lit-burnoff, burnoff-file → lit-burnoff-file, brainstorm → lit-brainstorm, brainstorming → lit-brainstorm, ideation → lit-brainstorm, ideate → lit-brainstorm, idea → lit-brainstorm, ideas → lit-brainstorm, ultra-brainstorm → ultra-brainstorm, ultra → ultra-brainstorm, hijack → lit-hijack, hijacking → lit-hijack, 하이재킹 → lit-hijack, 하이잭 → lit-hijack, adhd → lit-adhd, rewind → lit-adhd, approve → start-work, deny → start-work, team → lit-team, conference → autoconference, rules → rules, lsp → lsp, diagnostics → lsp, lsp-setup → lsp-setup, motion → lit-typographic-motion, film → lit-typographic-motion, video → lit-typographic-motion, 영상 → lit-typographic-motion, explain → lit-comprehend, humanize → lit-humanizer, korean → lit-humanizer, 다듬어 → lit-humanizer, 윤문 → lit-humanizer. Any other first word means lit-loop, except a task that asks to make a film (a film compound such as kinetic type, lyric video, title sequence, cover loop, 모션그래픽, 가사 영상, or a bare video noun with a making verb), which goes to lit-typographic-motion. Skills without a keyword (frontend-ui-ux, readme-studio, visual-qa, comment-checker, wikify, autoresearch, structural-search, browser-drive, lit-code) are reached through lit-loop or their own `/<skill>` command.
10
+ 2. `+` words right after `lit` (`lit +viz +ui <task>`) name the skill plan outright; the hook context lists it as `Skill plan: 1 … → 2 …`, and companions load only when their part starts.
11
+ 3. Load that skill with read_skill using the id `plugin:litmuse:<route>` before any other tool, and follow it. When the hook context says the route is already active or resuming, skip steps 3 and 4: keep the criteria, plan and ledger you have.
12
+ 4. Your first output, before any tool call or other text, is the line `🔥 **LIT IGNITED · <route>** 🔥` on its own line, once. When the hook context says the route continues, the line is `🔥 **LIT CONTINUES · <route>** 🔥` instead.
13
+ 5. Report in reader mode: the result, any material risk, and the action the user must take.
@@ -0,0 +1,224 @@
1
+ // The native-goal pipeline. A plan's `## Done when` block becomes one checkable Muse goal objective, asked for once at
2
+ // plan approval together with starting the work; the user's exact `yes` starts start-work on the plan and arms the goal
3
+ // in one step (a plan that cannot carry a goal is asked "start work?" alone). Muse 1.4.23 has a native goal: the model's `create_goal`
4
+ // tool sets the session's one goal (it fails while another goal is unfinished) and `update_goal` marks it `complete`
5
+ // or `blocked`; the user's `/goal clear` ends it by hand. Hooks cannot call tools and run under a 5 s timeout, so the
6
+ // hooks steer, guard and record, and the model makes the two tool calls. The records live in
7
+ // `<project state root>/.litmuse/goal/`:
8
+ //
9
+ // consent.json written by goal-propose.mjs: the objective (or none), its hash and the plan (asked)
10
+ // A lit-loop run with no plan asks one too (kind "loop", plan null, condition = its check exits 0 and the
11
+ // objective is done); its `yes` arms the goal and starts no start-work.
12
+ // intent.json written by the prompt hook when `yes` started the work and a goal is due (armed)
13
+ // owner.json written by PostToolUse after `create_goal` set that exact objective (set by LitMuse)
14
+ //
15
+ // PreToolUse refuses a `create_goal` whose objective carries a `[lit:<id>]` tag without a matching armed intent, so
16
+ // no LitMuse-tagged goal exists without the user's yes. LitMuse only ever closes a goal it owns; a goal the user set
17
+ // by hand is reported and left alone.
18
+ import { spawnSync } from 'node:child_process';
19
+ import { createHash } from 'node:crypto';
20
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
21
+ import { join } from 'node:path';
22
+ import { clip } from './redact.mjs';
23
+
24
+ export const GOAL_DIR = join('.litmuse', 'goal');
25
+ export const GOAL_MAX_CHARS = 500;
26
+ export const CONSENT_TTL_MS = 30 * 60 * 1000;
27
+ export const FALSIFY_TIMEOUT_MS = 120_000;
28
+ export const LIT_TAG = /\[lit:([0-9a-f]{8})\]\s*$/u;
29
+
30
+ // Fixed status lines, one per outcome. Hooks and the propose script print these and nothing else.
31
+ export const GOAL_STATUS = Object.freeze({
32
+ asked: (cond) => `Approve plan, start work and set goal: /goal ${cond}? (yes / edit / no)`,
33
+ askedStart: 'Approve plan and start work? (yes / no)',
34
+ declined: 'Nothing started and no goal set: you said no',
35
+ notStarted: (why) => `Work not started and no goal set: ${why}`,
36
+ notRecorded: (plan) => `Approval not recorded for this session. Run: lit start ${plan}`,
37
+ loopAsked: (cond) => `Set goal for this lit-loop: /goal ${cond}? (yes / no)`,
38
+ skipped: (reason) => `No goal set: ${reason}`,
39
+ set: (id) => `LitMuse goal set [lit:${id}]`,
40
+ yours: 'Your own goal is active; LitMuse left it alone.',
41
+ notConfirmed: (cond) => `Goal not confirmed. Paste: /goal ${cond}`,
42
+ met: (id) => `Goal met and closed [lit:${id}]`,
43
+ cleared: (id, why) => `LitMuse goal closed (${why}) [lit:${id}]`,
44
+ });
45
+
46
+ const JUDGMENT_WORDS = [
47
+ /\bworks?\b/iu, /\bworking\b/iu, /\blooks? (?:good|fine|right|nice|great)\b/iu, /\bseems?\b/iu, /\bproperly\b/iu,
48
+ /\bcorrectly\b/iu, /\bclean(?:ly)?\b/iu, /\bnicely\b/iu, /\bshould (?:work|pass)\b/iu, /\bas expected\b/iu, /\bgood enough\b/iu,
49
+ /잘\s*(?:동작|작동|돌아|돼|된다|되면)/u, /괜찮/u, /깔끔/u, /제대로/u, /문제\s*없/u, /완벽/u,
50
+ ];
51
+ // A success that is only an outward action proves nothing about the work and cannot be undone.
52
+ 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;
53
+ // Check commands the dry run may run. Anything else is refused before it runs.
54
+ const CHECK_ALLOWLIST = [
55
+ /^npm (?:test|run [\w:.-]+)(?: --[\w-]+)*$/u,
56
+ /^node --test(?: [\w./*-]+)*$/u,
57
+ /^node [\w./-]+\.m?js(?: [\w./=-]+)*$/u,
58
+ /^(?:pnpm|yarn) (?:test|run [\w:.-]+)$/u,
59
+ /^(?:pytest|python3? -m pytest)(?: [\w./:-]+)*$/u,
60
+ /^cargo test(?: [\w-]+)*$/u,
61
+ /^go test(?: [\w./-]+)*$/u,
62
+ /^make (?:test|check|verify)$/u,
63
+ /^(?:bash|sh) scripts\/[\w./-]+\.sh$/u,
64
+ ];
65
+
66
+ export const conditionHash = (condition) => createHash('sha256').update(String(condition)).digest('hex').slice(0, 16);
67
+ export const goalId = (plan, check) => createHash('sha256').update(`${plan}\u0000${check}`).digest('hex').slice(0, 8);
68
+
69
+ /** The `## Done when` block: one `check: \`<command>\`` line. A plan marked `goal: never` has none on purpose. */
70
+ export function parseDoneWhen(planText) {
71
+ const lines = String(planText ?? '').split(/\r?\n/u);
72
+ const start = lines.findIndex((line) => /^##\s+Done when\s*$/iu.test(line));
73
+ if (start === -1) return { ok: false, reason: 'the plan has no `## Done when` block' };
74
+ for (const line of lines.slice(start + 1)) {
75
+ if (/^##\s/u.test(line)) break;
76
+ const match = /^\s*(?:[-*]\s+)?check:\s*`([^`\n]+)`\s*$/u.exec(line);
77
+ if (match) return { ok: true, check: match[1].trim() };
78
+ }
79
+ return { ok: false, reason: 'the `## Done when` block names no `check:` command' };
80
+ }
81
+
82
+ /** `Every row in plans/<f>.md is ticked and \`<cmd>\` exits 0 [lit:<id>]`, or why it cannot be built. */
83
+ export function compileCondition({ plan, check }) {
84
+ const id = goalId(plan, check);
85
+ const condition = `Every row in ${plan} is ticked and \`${check}\` exits 0 [lit:${id}]`;
86
+ if (condition.length > GOAL_MAX_CHARS) return { ok: false, reason: `the condition is over ${GOAL_MAX_CHARS} characters; point the check at one script` };
87
+ return { ok: true, condition, id };
88
+ }
89
+
90
+ /** Rejects judgment words, outward-only success, unlisted commands and conditions over the cap. */
91
+ export function lintCondition(condition, check) {
92
+ const reasons = [];
93
+ if (String(condition).length > GOAL_MAX_CHARS) reasons.push(`over ${GOAL_MAX_CHARS} characters`);
94
+ const words = JUDGMENT_WORDS.filter((pattern) => pattern.test(String(check))).map((pattern) => String(check).match(pattern)[0]);
95
+ if (words.length) reasons.push(`judgment words cannot be checked (${words.join(', ')})`);
96
+ if (OUTWARD_ONLY.test(String(check))) reasons.push('a push, publish or release is not a check of the work');
97
+ if (!CHECK_ALLOWLIST.some((pattern) => pattern.test(String(check)))) reasons.push(`\`${check}\` is not an allowlisted test command`);
98
+ return { ok: reasons.length === 0, reasons };
99
+ }
100
+
101
+ /** A lit-loop has no plan rows: its condition is the check exiting 0 together with the objective being done. */
102
+ export function compileLoopCondition({ objective, check }) {
103
+ const id = goalId(`loop\u0000${objective}`, check);
104
+ const condition = `\`${check}\` exits 0 and this is done: ${objective} [lit:${id}]`;
105
+ if (condition.length > GOAL_MAX_CHARS) return { ok: false, reason: `the condition is over ${GOAL_MAX_CHARS} characters; shorten the objective` };
106
+ return { ok: true, condition, id };
107
+ }
108
+
109
+ /** The objective text of a run prompt as a goal may carry it: no slash lines, no credential, no backtick or `[lit:` tag, one line, 200 characters. */
110
+ export function normalizeLoopObjective(value) {
111
+ if (typeof value !== 'string') return '';
112
+ const lines = value.split(/\r?\n/u).filter((line) => !line.trimStart().startsWith('/')).join(' ');
113
+ return clip(lines.replace(/\[lit:[^\]]*\]/giu, ' ').replace(/`/gu, "'"), 200);
114
+ }
115
+
116
+ /** The project's own test command, for the question the prompt hook asks; null when there is none. */
117
+ export function detectCheck(cwd) {
118
+ try {
119
+ if (typeof JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8'))?.scripts?.test === 'string') return 'npm test';
120
+ } catch { /* no readable package.json */ }
121
+ for (const [file, check] of [['pytest.ini', 'pytest'], ['pyproject.toml', 'pytest'], ['Cargo.toml', 'cargo test'], ['go.mod', 'go test ./...']]) {
122
+ if (existsSync(join(cwd, file))) return check;
123
+ }
124
+ return null;
125
+ }
126
+
127
+ /** A lit-loop has no unticked rows to keep its goal false, so its check must fail right now. */
128
+ export function falsifyLoop({ cwd, check, timeoutMs = FALSIFY_TIMEOUT_MS, run = spawnSync }) {
129
+ const [cmd, ...args] = check.split(/\s+/u);
130
+ const result = run(cmd, args, { cwd, encoding: 'utf8', timeout: timeoutMs, stdio: ['ignore', 'ignore', 'ignore'], shell: false });
131
+ if (result.error?.code === 'ETIMEDOUT' || result.signal === 'SIGTERM') return { ok: false, reason: `\`${check}\` did not finish within ${Math.round(timeoutMs / 1000)} s` };
132
+ if (result.error || result.status === 127) return { ok: false, reason: `\`${check}\` cannot run here` };
133
+ if (result.status === 0) return { ok: false, reason: `\`${check}\` already passes, so the goal would be met at once; write the failing test first` };
134
+ return { ok: true, exit: result.status };
135
+ }
136
+
137
+ /**
138
+ * The lit-loop question and its consent record (kind "loop", no plan), or the one `No goal set: <reason>` line.
139
+ * Pure: the caller writes the record. falsifyNow: false skips the dry run (the prompt hook cannot wait on a test run);
140
+ * the objective clause still keeps such a goal false until the work is done.
141
+ */
142
+ export function buildLoopConsent({ cwd, check, objective, now = Date.now(), timeoutMs, run, falsifyNow = true, sessionId = null } = {}) {
143
+ const goal = normalizeLoopObjective(String(objective ?? ''));
144
+ const command = String(check ?? '').trim();
145
+ if (!goal) return { line: GOAL_STATUS.skipped('name what the loop should finish') };
146
+ const built = compileLoopCondition({ objective: goal, check: command });
147
+ if (!built.ok) return { line: GOAL_STATUS.skipped(built.reason) };
148
+ const lint = lintCondition(built.condition, command);
149
+ if (!lint.ok) return { line: GOAL_STATUS.skipped(lint.reasons.join('; ')) };
150
+ const dry = falsifyNow ? falsifyLoop({ cwd, check: command, ...(timeoutMs ? { timeoutMs } : {}), ...(run ? { run } : {}) }) : { ok: true };
151
+ if (!dry.ok) return { line: GOAL_STATUS.skipped(dry.reason) };
152
+ const consent = { version: 1, kind: 'loop', goal: true, condition: built.condition, hash: conditionHash(built.condition), id: built.id, plan: null, check: command, objective: goal, sessionId, askedAt: new Date(now).toISOString() };
153
+ return { line: GOAL_STATUS.loopAsked(built.condition), consent };
154
+ }
155
+
156
+ const openRows = (planText) => String(planText ?? '').split('\n').filter((line) => /^- \[ \] (?:\d+|F\d+)\. /u.test(line)).length;
157
+
158
+ /**
159
+ * The dry run: the condition must be false now, or the goal would be met at once. Runs the allowlisted check once,
160
+ * time-boxed, without a shell. Open rows already make it false, but the check still runs so an unrunnable or hanging
161
+ * command is caught before it becomes a goal.
162
+ */
163
+ export function falsify({ cwd, plan, planText, check, timeoutMs = FALSIFY_TIMEOUT_MS, run = spawnSync }) {
164
+ const open = openRows(planText);
165
+ const [cmd, ...args] = check.split(/\s+/u);
166
+ const result = run(cmd, args, { cwd, encoding: 'utf8', timeout: timeoutMs, stdio: ['ignore', 'ignore', 'ignore'], shell: false });
167
+ if (result.error?.code === 'ETIMEDOUT' || result.signal === 'SIGTERM') return { ok: false, reason: `\`${check}\` did not finish within ${Math.round(timeoutMs / 1000)} s` };
168
+ // A check script the plan itself creates is missing until the work runs: that is false now, not broken.
169
+ const plannedScript = ['bash', 'sh', 'node'].includes(cmd) && args.length >= 1 && String(planText).includes(args[0]);
170
+ if (result.error || (result.status === 127 && !plannedScript)) return { ok: false, reason: `\`${check}\` cannot run here` };
171
+ if (result.status === 0 && open === 0) return { ok: false, reason: `the goal is already true (${plan} is all ticked and \`${check}\` exits 0)` };
172
+ return { ok: true, open, exit: result.status };
173
+ }
174
+
175
+ /** `yes` (exactly, any case) arms; `edit` and `no` are answers too; anything else is no answer. */
176
+ export function consentAnswer(prompt) {
177
+ const text = String(prompt ?? '').trim().toLowerCase();
178
+ return ['yes', 'edit', 'no'].includes(text) ? text : null;
179
+ }
180
+
181
+ /** What the consent hash covers: the objective, or the plan path for a start-only question. */
182
+ export const consentKey = (consent) => (typeof consent?.condition === 'string' ? consent.condition : `start:${consent?.plan ?? ''}`);
183
+
184
+ /** The consent record is fresh, unanswered and the one the user is answering. */
185
+ export const consentIsLive = (consent, now = Date.now()) => Boolean(consent && typeof consent === 'object'
186
+ && (typeof consent.condition === 'string' || (consent.goal === false && typeof consent.plan === 'string'))
187
+ && consent.hash === conditionHash(consentKey(consent)) && !consent.answeredAt && Number.isFinite(Date.parse(consent.askedAt))
188
+ && now - Date.parse(consent.askedAt) <= CONSENT_TTL_MS);
189
+
190
+ export const goalFile = (root, name) => join(root, GOAL_DIR, `${name}.json`);
191
+
192
+ /** A goal record, or null when it is missing, unreadable, a link or not an object. */
193
+ export function readGoalRecord(root, name) {
194
+ const file = goalFile(root, name);
195
+ try {
196
+ if (lstatSync(file).isSymbolicLink()) return null;
197
+ const value = JSON.parse(readFileSync(file, 'utf8'));
198
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
199
+ } catch {
200
+ return null;
201
+ }
202
+ }
203
+
204
+ /** Whole-file write through a temporary file. */
205
+ export function writeGoalRecord(root, name, value) {
206
+ const file = goalFile(root, name);
207
+ mkdirSync(join(root, GOAL_DIR), { recursive: true });
208
+ const staging = `${file}.${process.pid}.tmp`;
209
+ writeFileSync(staging, `${JSON.stringify(value)}\n`);
210
+ renameSync(staging, file);
211
+ }
212
+
213
+ export const dropGoalRecord = (root, name) => rmSync(goalFile(root, name), { force: true });
214
+
215
+ /** The objective string of a `create_goal` / `update_goal` call, however the host names the field. */
216
+ export const objectiveOf = (input) => String(input?.objective ?? input?.goal ?? input?.text ?? '');
217
+
218
+ /** SessionStart sweep: an unanswered consent or an unused intent past its time is a leftover, never a live question. */
219
+ export function sweepGoalState(root, now = Date.now()) {
220
+ const consent = readGoalRecord(root, 'consent');
221
+ if (consent && !consentIsLive(consent, now) && !consent.answeredAt) dropGoalRecord(root, 'consent');
222
+ const intent = readGoalRecord(root, 'intent');
223
+ if (intent && !intent.consumedAt && now - Date.parse(intent.armedAt ?? 0) > CONSENT_TTL_MS) dropGoalRecord(root, 'intent');
224
+ }