@litfamily/litmuse 0.1.21 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,110 @@
1
+ // Suggestions for a prompt without `lit`: gated rules offer the skills that may fit plus "none", and the model
2
+ // decides. A rule ships only after it passes the gate on the sealed held-out half of test/fixtures/routing-eval
3
+ // (recall >= 0.85, near-miss false positives <= 0.10); scripts/routing-eval.mjs scores it. Nothing loads by itself.
4
+
5
+ const KNOWLEDGE = /^\s*(?:what(?:'s| is| are| does)|explain|why (?:is|are|do|does)|how does|define|difference between|tell me about)\b|(?:뭐야|뭔가요|무엇인가요|설명해|란\s?무엇|차이(?:가|점)|알려\s?줘\s*$)/i;
6
+
7
+ // Each rule: every `all` pattern must match and no `none` pattern may. Korean stems are bare substrings.
8
+ export const SUGGEST_RULES = [
9
+ {
10
+ id: 'lit-scientific-visualization',
11
+ all: [
12
+ /\b(?:plot|plots|chart|charts|graph|graphs|histogram|scatter ?plot|heat ?map|box ?plot|bar chart|line chart|error bars?|figure)\b|그래프|플롯|차트|시각화|히스토그램|산점도|히트맵/i,
13
+ /\b(?:plot|draw|make|create|render|visuali[sz]e|generate|produce|turn|show)\b|\.csv\b|\bcsv\b|\bdata(?:set)?\b|\bresults?\b|\bmeasurements?\b|그려|만들|시각화|보여|데이터|결과|측정/i,
14
+ ],
15
+ none: [/\b(?:dashboard|web ?page|website|landing|html|react|component|diagram|flowchart|architecture|sequence diagram)\b|다이어그램|도식|순서도|웹페이지|대시보드/i,
16
+ /\bplot (?:twist|hole|line)s?\b|\b(?:story|novel|movie|film|book)\b|줄거리|스토리/i,
17
+ /\b(?:graph ?ql|graph database|knowledge graph|dependency graph|call graph|graph algorithm|graph theory|shortest path)\b|\bchart (?:a|the|our) (?:course|path|roadmap)\b/i],
18
+ },
19
+ {
20
+ id: 'lit-diagram-drawer',
21
+ all: [
22
+ /\b(?:diagram|flowchart|flow chart|sequence diagram|architecture (?:diagram|drawing|overview picture)|swimlane|timeline graphic|mind ?map|org chart|block diagram)\b|다이어그램|도식|개념도|개요도|순서도|흐름도|구성도|아키텍처\s?그림/i,
23
+ /\b(?:draw|make|create|sketch|design|render|produce|build|generate|need|want)\b|그려|만들|작성|그림으로|필요/i,
24
+ ],
25
+ none: [/\b(?:p&id|pid diagram|piping and instrumentation|apparatus|isometric cutaway|process flow diagram|pfd)\b|계장도|공정도|장치도/i],
26
+ },
27
+ {
28
+ id: 'lit-pptx',
29
+ all: [
30
+ /\b(?:slides?|slide deck|deck|presentation|pptx|power ?point|keynote)\b|발표\s?자료|슬라이드|피피티|\bppt\b/i,
31
+ /\b(?:make|create|build|prepare|turn|draft|design|put together|generate|need)\b|만들|만들어|준비|작성|정리/i,
32
+ ],
33
+ none: [/\bpresentation (?:layer|logic|component)s?\b|\bdeck(?:ing)? (?:of cards|builder)\b|\bslide(?:r| out| in| animation)\b|\b(?:google slides api|reveal\.js plugin)\b/i],
34
+ },
35
+ {
36
+ id: 'lit-docx',
37
+ all: [
38
+ /\b(?:docx|word (?:document|doc|file|report)|ms word|\.docx)\b|워드\s?(?:문서|파일)?|보고서|기획서|제안서|\bhwp\b/i,
39
+ /\b(?:make|create|write|draft|build|produce|export|convert|turn|prepare|generate)\b|만들|작성|써\s?줘|정리|변환|뽑아/i,
40
+ ],
41
+ none: [/\bword (?:count|cloud|wrap|list|boundary|embedding|frequency)\b|\bin (?:a|one|other) word\b/i],
42
+ },
43
+ {
44
+ id: 'debugging',
45
+ all: [
46
+ /\b(?:bug|bugs|failing|fails|failed|failure|error|errors|exception|crash(?:es|ed|ing)?|stack ?trace|traceback|segfault|hangs?|hanging|broken|regression|flaky)\b|에러|오류|버그|실패|안\s?돼|안\s?됨|멈춰|죽어|튕겨/i,
47
+ /\b(?:fix|debug|why|investigate|figure out|track down|diagnose|repro(?:duce)?|keeps|after|since|when i)\b|고쳐|왜|원인|해결|디버그|나요|나는데|납니다/i,
48
+ ],
49
+ none: [/\b(?:add|write|implement|improve) (?:error|exception) handling\b|\berror (?:message|messages) (?:copy|text|wording)\b|\b(?:bug report template|bug bounty)\b|에러\s?처리\s?(?:추가|코드)/i],
50
+ },
51
+ {
52
+ id: 'review-work',
53
+ all: [
54
+ /\b(?:review|audit|look over|check)\b|리뷰|검토/i,
55
+ /\b(?:diff|pr|pull request|branch|patch|changes|changeset|commit|commits|merge request|mr)\b|변경(?:사항|점)?|브랜치|커밋|패치|\bPR\b/i,
56
+ ],
57
+ none: [/\b(?:literature|paper|book|movie|film|restaurant|product|performance) review\b|\breview (?:the |this )?(?:paper|literature|book|essay|article|manuscript)\b|\bcode review (?:checklist|guidelines|best practices)\b|논문\s?리뷰|문헌/i,
58
+ /\b(?:write|draft|create|make|squash|amend|revert|cherry-pick|rebase)\b[^.?!]*\bcommit/i],
59
+ },
60
+ {
61
+ id: 'lit-commit',
62
+ all: [
63
+ /\b(?:commit|commits|rebase|squash|fixup|cherry-pick|bisect|git blame|reflog|amend|interactive rebase|split (?:this|the) commit)\b|커밋|리베이스|스쿼시|체리픽/i,
64
+ /^\s*(?:please\s+)?(?:commit|squash|rebase)\b|\b(?:make|create|write|split|squash|rebase|fix|find|which|who|when|undo|clean up|reword|stage|amend)\b|만들|나눠|정리|찾아|누가|언제|되돌|해\s?줘/i,
65
+ ],
66
+ none: [/\bcommit (?:to|ourselves|myself)\b|\bcommitted to\b|\bcommitment\b|\bcommit message (?:format|convention) (?:docs|documentation)\b/i,
67
+ /\breview\b|리뷰|검토/i],
68
+ },
69
+ ];
70
+
71
+ // The compact line a plain prompt carries when no rule fires: about fifteen common skills, cheap on every turn.
72
+ export const CATALOG_SKILLS = ['lit-loop', 'lit-plan', 'start-work', 'deep-interview', 'lit-brainstorm', 'debugging', 'review-work',
73
+ 'lit-commit', 'litresearch', 'frontend-ui-ux', 'lit-docx', 'lit-pptx', 'lit-scientific-visualization', 'lit-diagram-drawer',
74
+ 'lit-humanizer'];
75
+
76
+ /** The user's own request: code fences, inline code and host notification blocks are stripped first. */
77
+ export function requestText(prompt) {
78
+ return String(prompt ?? '')
79
+ .replace(/```[\s\S]*?```/g, ' ')
80
+ .replace(/~~~[\s\S]*?~~~/g, ' ')
81
+ .replace(/`[^`\n]*`/g, ' ')
82
+ .replace(/<(system-reminder|task-notification|notification|system-notification)>[\s\S]*?<\/\1>/gi, ' ');
83
+ }
84
+
85
+ /** The ids of every rule a prompt fires, in table order. A knowledge question fires none. */
86
+ export function firedRules(prompt) {
87
+ const text = requestText(prompt);
88
+ if (!text.trim() || KNOWLEDGE.test(text)) return [];
89
+ return SUGGEST_RULES.filter((r) => r.all.every((re) => re.test(text)) && !r.none.some((re) => re.test(text))).map((r) => r.id);
90
+ }
91
+
92
+ export function catalogLine() {
93
+ return `LitMuse skills, if one fits (read_skill \`plugin:litmuse:<id>\`; none is fine): ${CATALOG_SKILLS.join(', ')}.`;
94
+ }
95
+
96
+ /** A slash command anywhere in the prompt is the user's own route: no suggestion rides on it. */
97
+ export const hasSlash = (prompt) => /(?:^|\s)\/[A-Za-z][\w:-]*(?=\s|$)/.test(requestText(prompt));
98
+
99
+ /** The context a plain prompt gets: the fired rules with their route lines and "none", else the catalog line. */
100
+ export function suggestionNote(prompt, routes) {
101
+ const fired = firedRules(prompt);
102
+ if (!fired.length) return catalogLine();
103
+ const when = new Map(routes.map((r) => [r.id, r.when]));
104
+ return [
105
+ 'LitMuse suggestion, not an instruction: this prompt may fit',
106
+ ...fired.map((id) => `- ${id}: ${when.get(id) ?? ''}`),
107
+ '- none of these',
108
+ 'Decide yes or no for each from the request itself. Load only the ones that fit with read_skill `plugin:litmuse:<id>`; otherwise carry on without one.',
109
+ ].join('\n');
110
+ }
@@ -1,11 +1,13 @@
1
1
  import { existsSync, readFileSync, realpathSync } from 'node:fs';
2
2
  import { resolve, dirname, sep, basename } from 'node:path';
3
- import { run, block, activeRoute, toolName, toolInput, workspaceOf } from './lib/common.mjs';
3
+ import { run, block, readSession, unreadPayload, toolName, toolInput, workspaceOf } from './lib/common.mjs';
4
4
  import { addedHedgeCluster, HEDGE_MESSAGE } from './lib/hedge.mjs';
5
5
  import { LIT_PLAN_READ_ONLY_TOOLS, FILE_TOOLS, SHELL_TOOLS, READ_ONLY_AGENTS, shellReadOnly } from './lib/policy.mjs';
6
6
  import { LIT_TAG, objectiveOf, readGoalRecord } from './lib/goal.mjs';
7
7
  import { resolveProjectStateRoot } from './lib/workflow-stack.mjs';
8
8
  import { PLUGIN_ROOT } from './lib/common.mjs';
9
+ import { GOAL_SELF_END, guardShell, guardWrite, park, runOwner } from './lib/autopilot.mjs';
10
+ import { classifyCommand, protectedBelow, protectedReason } from './lib/shell-verdict.mjs';
9
11
 
10
12
  const PROSE_FILE = /\.(md|mdx|markdown|txt)$/i;
11
13
  const EN_PLEDGE = /\b(never|do not|don't|does not|doesn't|cannot|can't|will not|won't|must not|should not|shouldn't)\b/i;
@@ -54,9 +56,13 @@ function inside(cwd, p, dirs) {
54
56
  let root;
55
57
  try { root = realpathSync(cwd); } catch { root = resolve(cwd); }
56
58
  const target = realTarget(cwd, p);
59
+ // Case-folded on every OS, so `.LitMuse/Sessions` is the same folder as `.litmuse/sessions` on a case-folding disk
60
+ // and is refused as a precaution on a case-sensitive one.
61
+ const fold = (x) => x.toLowerCase();
57
62
  return dirs.some((d) => {
58
- const base = resolve(root, d);
59
- return target === base || target.startsWith(base + sep);
63
+ const base = fold(resolve(root, d));
64
+ const t = fold(target);
65
+ return t === base || t.startsWith(base + sep);
60
66
  });
61
67
  }
62
68
 
@@ -116,6 +122,77 @@ function proseWrites(tool, input, cwd) {
116
122
 
117
123
  const PLAN_HINT = 'Write the plan under plans/ with write_file; implementation waits for /start-work.';
118
124
 
125
+ const READ_PATH_TOOLS = new Set(['read_file', 'search']);
126
+ // Tools a run may call without parking: reads, the run's own goal and todo bookkeeping, and child agents (a child
127
+ // is bound to the run's guard at SubagentStart).
128
+ const RUN_KNOWN_TOOLS = new Set([...READ_ONLY_TOOLS, 'subagent_spawn', 'update_goal', 'write_todos', 'write_memory']);
129
+
130
+ // During a start-work run (a child lane uses its parent's run): steps that need the user's word are parked for the
131
+ // one wrap-up answer, secrets and host homes are refused, and a native goal is armed only on a `goal: native` plan.
132
+ // Why a read tool may not read where it points, or null. `search` walks its folder, so a folder that holds a protected
133
+ // place (the home folder, `/`) is refused as a recursive reader would be.
134
+ function readPathReason(tool, input, cwd) {
135
+ for (const key of ['path', 'file_path', 'directory']) {
136
+ if (typeof input[key] !== 'string') continue;
137
+ const abs = resolve(cwd, input[key]);
138
+ const reason = protectedReason(abs) ?? (tool === 'search' ? protectedBelow(abs, process.env) : null);
139
+ if (reason) return reason;
140
+ }
141
+ return null;
142
+ }
143
+
144
+ function startWorkGuard(payload, state, tool, input, cwd) {
145
+ const owner = runOwner(payload, state);
146
+ if (!owner) return;
147
+ if (tool === 'bash_input') {
148
+ block(park(owner.payload, owner.state, { command: `bash_input: ${String(input.input ?? input.text ?? input.chars ?? '')}`, cwd, tier: 'X', held: 'input to a running shell cannot be checked', reason: 'input to a running shell' }));
149
+ } else if (SHELL_TOOLS.has(tool)) {
150
+ let command = input.command ?? input.cmd ?? input.script;
151
+ if (Array.isArray(command)) command = command.join(' ');
152
+ const dir = [input.workdir, input.cwd, input.working_directory].find((d) => typeof d === 'string' && d);
153
+ const verdict = guardShell(owner.payload, owner.state, typeof command === 'string' ? command : JSON.stringify(command ?? null), dir);
154
+ if (verdict) block(verdict.message);
155
+ } else if (FILE_TOOLS.has(tool)) {
156
+ for (const t of targetPaths(tool, input)) {
157
+ const verdict = guardWrite(owner.payload, owner.state, resolve(cwd, t));
158
+ if (verdict) block(verdict.message);
159
+ }
160
+ } else if (READ_PATH_TOOLS.has(tool)) {
161
+ const reason = readPathReason(tool, input, cwd);
162
+ if (reason) block(`LitMuse start-work refused this read and did not store it: ${reason}. Leave it out and continue with the next row.`);
163
+ } else if (tool === 'subagent_spawn' && !READ_ONLY_AGENTS.has(input.subagent_type)) {
164
+ // BLOCKED host fact: Muse is not known to name the child session in SubagentStart, so a working child could act
165
+ // outside the run guard. Only read-only litmuse/* agents start during a run.
166
+ block(park(owner.payload, owner.state, { command: `subagent_spawn: ${JSON.stringify(input ?? {}).slice(0, 1500)}`, cwd, tier: 'X', held: 'a working child agent runs outside the run guard', reason: `a ${input.subagent_type ?? 'general-purpose'} child agent` }));
167
+ } else if (!RUN_KNOWN_TOOLS.has(tool) && tool !== 'create_goal') {
168
+ // Any other tool (cron, MCP servers, tools a later Muse adds) may run code or reach outside where the guard cannot
169
+ // look, so it is held for the user's own decision and never replayed.
170
+ block(park(owner.payload, owner.state, { command: `${tool}: ${JSON.stringify(input ?? {}).slice(0, 1500)}`, cwd, tier: 'X', held: `the ${tool} tool may run code the run guard cannot check`, reason: `the ${tool} tool` }));
171
+ } else if (tool === 'create_goal') {
172
+ if (!owner.state.run.goalNative) block('LitMuse start-work: this plan has no `goal: native` line, so the start-work hooks drive the run and no native goal is armed. Carry on with the next row.');
173
+ if (!objectiveOf(input).replace(LIT_TAG, '').trimEnd().endsWith(GOAL_SELF_END.slice(2))) {
174
+ block(`LitMuse start-work: a native goal always ends itself. End the objective with "${GOAL_SELF_END}", then create it again.`);
175
+ }
176
+ }
177
+ }
178
+
179
+ // A state file that does not parse may have held a run: the planning limits apply, and reads of protected places
180
+ // (secrets, real-home key folders, run state) stay refused, as the run guard would refuse them.
181
+ function damagedReadGuard(tool, input, cwd) {
182
+ const refuse = (reason) => block(`LitMuse could not read this session's state, so it keeps the run guard's refusals: ${reason}. Leave it out and continue.`);
183
+ if (READ_PATH_TOOLS.has(tool)) {
184
+ const reason = readPathReason(tool, input, cwd);
185
+ if (reason) refuse(reason);
186
+ } else if (SHELL_TOOLS.has(tool)) {
187
+ let command = input.command ?? input.cmd ?? input.script;
188
+ if (Array.isArray(command)) command = command.join(' ');
189
+ const dir = [input.workdir, input.cwd, input.working_directory].find((d) => typeof d === 'string' && d);
190
+ const here = dir ? resolve(cwd, dir) : cwd;
191
+ const v = classifyCommand(typeof command === 'string' ? command : '', { cwd: here, root: cwd, roots: [], grants: [], charter: [], check: null, denied: { commands: [], paths: [] }, env: process.env });
192
+ if (v.action === 'refuse') refuse(v.reason);
193
+ }
194
+ }
195
+
119
196
  // The one non-read-only command a planning turn may run: this plugin's own goal-propose script on a plan under plans/.
120
197
  const GOAL_PROPOSE = resolve(PLUGIN_ROOT, 'skills', 'lit-plan', 'scripts', 'goal-propose.mjs');
121
198
  function isGoalPropose(command) {
@@ -141,7 +218,31 @@ function litGoalRefusal(payload, input) {
141
218
  return 'LitMuse sets a [lit:…] goal only after the user typed yes to a LitMuse goal question (plan approval or a lit-loop), with that exact objective. Ask the question again (run goal-propose) instead of creating it.';
142
219
  }
143
220
 
221
+ // The run guard fails closed: a call it could not read or check during an active run is denied. Outside a run a
222
+ // broken hook still lets the call through, as every LitMuse hook does.
223
+ function runActive(payload) {
224
+ try {
225
+ const s = readSession(payload);
226
+ return Boolean(s && (s.run?.status === 'active' || s.parentSession));
227
+ } catch {
228
+ return true;
229
+ }
230
+ }
231
+
144
232
  run((payload) => {
233
+ const unread = !Object.keys(payload).length && unreadPayload();
234
+ if (unread) {
235
+ if (runActive(unread)) block('LitMuse start-work could not read this call (too large or malformed), so it is refused during the run and nothing was stored. Make the call smaller and continue with the next row.');
236
+ return;
237
+ }
238
+ try {
239
+ guardCall(payload);
240
+ } catch (err) {
241
+ if (runActive(payload)) block(`LitMuse start-work could not check this call (${String(err?.message ?? err).slice(0, 200)}), so it is refused during the run. Continue with the next row.`);
242
+ }
243
+ });
244
+
245
+ function guardCall(payload) {
145
246
  const tool = toolName(payload);
146
247
  const input = toolInput(payload);
147
248
  const cwd = workspaceOf(payload);
@@ -157,7 +258,12 @@ run((payload) => {
157
258
  if (refusal) block(refusal);
158
259
  }
159
260
 
160
- const state = activeRoute(payload);
261
+ // The run guard follows an active run, whatever route a later plain prompt left behind.
262
+ const session = readSession(payload);
263
+ if (session?.corrupt) damagedReadGuard(tool, input, cwd);
264
+ if (session && (session.route === 'start-work' || session.run?.status === 'active')) startWorkGuard(payload, session, tool, input, cwd);
265
+
266
+ const state = session?.route ? session : null;
161
267
  if (!state) return;
162
268
 
163
269
  if (state.route === 'lit-plan') {
@@ -194,4 +300,4 @@ run((payload) => {
194
300
  block(`LitMuse write guard: this write adds stacked hedges to a deliverable ("${hedge.snippet}..."). The limit is one hedge per sentence and under four per paragraph. ${HEDGE_MESSAGE} If the user dictated this wording, run the edit on the lit-humanizer route (lit korean / lit humanize), which keeps the writer's claims as given.`);
195
301
  }
196
302
  }
197
- });
303
+ }
@@ -1,9 +1,20 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { run, emitContext, PLUGIN_ROOT } from './lib/common.mjs';
3
+ import { run, emitContext, PLUGIN_ROOT, readSession, safeId, writeSession } from './lib/common.mjs';
4
4
  import { recordLaneStart } from './lib/stage.mjs';
5
5
 
6
+ // A child spawned during a start-work run meets the run's guard: its own route state points at the parent, whose
7
+ // state holds the parked queue. Only a child session id the payload names binds; nothing is guessed.
8
+ function bindChild(payload) {
9
+ const parent = readSession(payload);
10
+ if (parent?.route !== 'start-work' || parent.run?.status !== 'active') return;
11
+ const child = ['child_session_id', 'subagent_session_id', 'agent_session_id'].map((k) => safeId(payload[k])).find(Boolean);
12
+ if (!child || child === payload.session_id) return;
13
+ writeSession({ ...payload, session_id: child }, { route: 'start-work', parentSession: payload.session_id, activatedAt: Date.now() });
14
+ }
15
+
6
16
  run((payload) => {
7
17
  recordLaneStart(payload);
18
+ try { bindChild(payload); } catch { /* binding is best effort; the lane still starts */ }
8
19
  emitContext('SubagentStart', readFileSync(join(PLUGIN_ROOT, 'context', 'child.md'), 'utf8').trim());
9
20
  });
@@ -8,9 +8,23 @@ import { isGoPrompt, takeNextStep } from './lib/next-step.mjs';
8
8
  import { ROUTE_INTENTS } from './lib/routes.mjs';
9
9
  import { buildSkillPlan, matchedSkills, parseSkillHatch, skillPlanContext, skillPlanIds } from './lib/skill-plan.mjs';
10
10
  import { GOAL_STATUS, buildLoopConsent, consentAnswer, consentIsLive, detectCheck, dropGoalRecord, normalizeLoopObjective, readGoalRecord, writeGoalRecord } from './lib/goal.mjs';
11
+ import { answerPrompt, startNote, startRun } from './lib/autopilot.mjs';
12
+ import { hasSlash, suggestionNote } from './lib/suggest.mjs';
13
+ import { SKILL_ROUTES } from './lib/routes.mjs';
11
14
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'node:fs';
12
15
  import { resolve, join, dirname } from 'node:path';
13
16
 
17
+ // The run record a start-work start carries. A start that names its plan (the user's `yes`, a typed plan path, `go`
18
+ // on a briefed plan) approves it as it stands; an active run on the same plan keeps its parked queue.
19
+ function runFor(payload, previous, plan, options = {}) {
20
+ try {
21
+ return startRun(payload, previous && !previous.corrupt ? previous : null, plan, options);
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+ const withRun = (text, run, short = false) => [text, run ? startNote(run, short) : ''].filter(Boolean).join('\n');
27
+
14
28
  // The banner leads every context this hook sends: Muse shows no hook message of its own, so the model's first line is
15
29
  // the only place the user can see the route ignite, and a model that narrates first ("Loading the loop route") hides it.
16
30
  const banner = (word, route) => [
@@ -269,10 +283,11 @@ function goalAnswer(payload) {
269
283
  if (withGoal) writeGoalRecord(root, 'intent', { version: 1, condition: consent.condition, hash: consent.hash, id: consent.id, plan: consent.plan, check: consent.check, sessionId: payload.session_id ?? null, armedAt: now });
270
284
  const turnId = payload.turn_id ?? null;
271
285
  const pauseRequested = false;
272
- writeSession(payload, { route: 'start-work', turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested });
286
+ const run = runFor(payload, readSession(payload), consent.plan, { approved: true, consentHash: consent.charterHash ?? null });
287
+ writeSession(payload, { route: 'start-work', turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested, ...(run ? { run } : {}) });
273
288
  stackStart(payload, 'start-work', { plan: consent.plan }, false);
274
289
  recordRoute(payload, { route: 'start-work', keyword: 'yes', kind: 'ignite', plan: consent.plan, activatedAt: Date.now() });
275
- const lines = [activation({ route: 'start-work', keyword: 'yes', bare: false, resume: false, restart: false, trailing: false }, payload)];
290
+ const lines = [withRun(activation({ route: 'start-work', keyword: 'yes', bare: false, resume: false, restart: false, trailing: false }, payload), run)];
276
291
  if (withGoal) {
277
292
  lines.push(
278
293
  `Plan: ${consent.plan}. The user's yes approves the plan, starts the work and sets its goal: the work starts now; work through its open rows in order.`,
@@ -339,6 +354,19 @@ function loopGoalNote(hit, payload) {
339
354
  }
340
355
  }
341
356
 
357
+ // `lit cancel` ends this session's start-work run, a damaged state file included: the run record is closed (or the
358
+ // unreadable file replaced), its parked steps are dropped, and the run guard stops.
359
+ const CANCEL = /^\s*\/?(?:litmuse:)?lit\s+(?:cancel|취소)\s*$/iu;
360
+ function cancelRun(payload, owned) {
361
+ const run = owned.corrupt ? null : { ...owned.run, status: 'cancelled', parked: [], paths: [], snapshot: null };
362
+ writeSession(payload, { route: null, turnId: payload.turn_id ?? null, activatedAt: Date.now(), stopHeldFor: null, pauseRequested: false, ...(run ? { run } : {}) });
363
+ const goal = cancelOwnedGoal(payload);
364
+ emitContext('UserPromptSubmit', [...banner('LIT CONTINUES', 'start-work'),
365
+ `The user typed \`lit cancel\`. The run is cancelled${owned.corrupt ? ' (its state file could not be read and was replaced)' : ''}: its parked steps were dropped and the run guard is off.`,
366
+ ...(goal ? [goal] : []),
367
+ 'Stop the run\'s work at the next safe point and say which rows are left.'].join('\n'));
368
+ }
369
+
342
370
  // `lit cancel` while this session owns an open LitMuse goal: close that goal only, never a goal the user set.
343
371
  function cancelOwnedGoal(payload) {
344
372
  if (!/^\s*\/?(?:litmuse:)?lit\s+cancel\s*$/iu.test(String(payload.prompt ?? ''))) return null;
@@ -355,6 +383,20 @@ run((payload) => {
355
383
  try {
356
384
  if (goalAnswer(payload)) return;
357
385
  } catch { /* an unwritable goal record leaves the prompt as ordinary text */ }
386
+ // Approval words count only here, from the prompt the user typed in the session that owns the run.
387
+ const owned = readSession(payload);
388
+ if (CANCEL.test(String(payload.prompt ?? '')) && (owned?.corrupt || owned?.run?.status === 'active')) {
389
+ cancelRun(payload, owned);
390
+ return;
391
+ }
392
+ if (owned?.run && !owned.corrupt) {
393
+ const answer = answerPrompt(payload, { ...owned, route: 'start-work', turnId: payload.turn_id ?? null, pauseRequested: false });
394
+ if (answer) {
395
+ recordRoute(payload, { route: 'start-work', keyword: null, kind: 'continue' });
396
+ emitContext('UserPromptSubmit', [...banner('LIT CONTINUES', 'start-work'), answer].join('\n'));
397
+ return;
398
+ }
399
+ }
358
400
  const cancelNote = cancelOwnedGoal(payload);
359
401
  if (cancelNote) {
360
402
  emitContext('UserPromptSubmit', [...banner('LIT CONTINUES', 'litgoal'), cancelNote, 'Then stop the current work at the next safe point and say what is left.'].join('\n'));
@@ -389,7 +431,7 @@ run((payload) => {
389
431
  if (step.kind === 'resume-frame') {
390
432
  const frame = stackContinue(payload);
391
433
  const skill = frame?.skill ?? step.target?.skill ?? 'lit-loop';
392
- writeSession(payload, { route: skill, turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested });
434
+ writeSession(payload, { route: skill, turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested, ...(owned?.run && !owned.corrupt ? { run: owned.run } : {}) });
393
435
  recordRoute(payload, { route: skill, keyword: 'go', kind: 'continue', activatedAt: Date.now() });
394
436
  emitContext('UserPromptSubmit', [
395
437
  ...banner('LIT CONTINUES', skill),
@@ -399,9 +441,10 @@ run((payload) => {
399
441
  }
400
442
  if (step.kind === 'continue-work') {
401
443
  const plan = resumablePlan(workspaceOf(payload));
402
- writeSession(payload, { route: 'start-work', turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested });
444
+ const run = plan ? runFor(payload, owned, plan.file) : null;
445
+ writeSession(payload, { route: 'start-work', turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested, ...(run ? { run } : {}) });
403
446
  recordRoute(payload, { route: 'start-work', keyword: 'go', kind: 'resume', plan: plan?.file ?? null, activatedAt: Date.now() });
404
- emitContext('UserPromptSubmit', resumeNote(plan, true, payload));
447
+ emitContext('UserPromptSubmit', withRun(resumeNote(plan, true, payload), run, true));
405
448
  return;
406
449
  }
407
450
  if (step.kind === 'start-plan') {
@@ -410,13 +453,14 @@ run((payload) => {
410
453
  emitContext('UserPromptSubmit', goHint('its plan has no open row'));
411
454
  return;
412
455
  }
413
- writeSession(payload, { route: 'start-work', turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested });
456
+ const run = runFor(payload, owned, plan, { approved: true });
457
+ writeSession(payload, { route: 'start-work', turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested, ...(run ? { run } : {}) });
414
458
  stackStart(payload, 'start-work', { plan }, false);
415
459
  recordRoute(payload, { route: 'start-work', keyword: 'go', kind: 'ignite', plan, activatedAt: Date.now() });
416
- emitContext('UserPromptSubmit', [
460
+ emitContext('UserPromptSubmit', withRun([
417
461
  activation({ route: 'start-work', keyword: 'go', bare: false, resume: false, restart: false, trailing: false }, payload),
418
462
  `Plan: ${plan}. The typed go is the approval: the work starts without a separate approval turn; work through its open rows in order.`,
419
- ].join('\n'));
463
+ ].join('\n'), run));
420
464
  return;
421
465
  }
422
466
  emitContext('UserPromptSubmit', goHint('an unreadable next step'));
@@ -427,13 +471,19 @@ run((payload) => {
427
471
  const hit = detectRoute(hatch ? hatch.rest : payload.prompt);
428
472
  const previous = readSession(payload);
429
473
  if (!hit) {
474
+ // A prompt without `lit` carries one suggestion note (fired rules plus "none", else the compact catalog line);
475
+ // a slash command is the user's own route and gets none.
476
+ const text = String(payload.prompt ?? '');
477
+ const suggestion = text.trim() && !hasSlash(text) ? suggestionNote(text, SKILL_ROUTES) : null;
430
478
  if (previous && previous.route) {
431
479
  writeSession(payload, { ...previous, route: null, turnId: payload.turn_id ?? null, pauseRequested });
432
480
  recordRoute(payload, { route: null, kind: 'clear' });
481
+ if (suggestion) emitContext('UserPromptSubmit', suggestion);
433
482
  return;
434
483
  }
435
484
  const wayBackIn = suggestAdhdOnce(payload);
436
- if (wayBackIn) emitContext('UserPromptSubmit', wayBackIn);
485
+ const note = [wayBackIn, suggestion].filter(Boolean).join('\n');
486
+ if (note) emitContext('UserPromptSubmit', note);
437
487
  return;
438
488
  }
439
489
  const turnId = payload.turn_id ?? null;
@@ -447,16 +497,17 @@ run((payload) => {
447
497
  writeSession(payload, { ...previous, route, turnId, pauseRequested });
448
498
  recordRoute(payload, { route, keyword: hit.keyword ?? null, kind: 'continue' });
449
499
  emitContext('UserPromptSubmit', route === 'start-work'
450
- ? resumeNote(resumablePlan(workspaceOf(payload)), true, payload)
500
+ ? withRun(resumeNote(resumablePlan(workspaceOf(payload)), true, payload), previous?.run, true)
451
501
  : continueNote(route) + (frame && frame.skill !== active ? ` Resumed the paused ${frame.skill}${frame.stage ? ` at ${frame.stage}` : ''}${stackCount(frame)}; the interjected work is closed.` : ''));
452
502
  return;
453
503
  }
454
504
  const plan = !hit.restart && (hit.bare || hit.resume) ? resumablePlan(workspaceOf(payload)) : null;
455
505
  if (plan) {
456
- writeSession(payload, { route: 'start-work', turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested });
506
+ const run = runFor(payload, previous, plan.file);
507
+ writeSession(payload, { route: 'start-work', turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested, ...(run ? { run } : {}) });
457
508
  stackStart(payload, 'start-work', { plan: plan.file }, false);
458
509
  recordRoute(payload, { route: 'start-work', keyword: hit.keyword ?? null, kind: 'resume', plan: plan.file, activatedAt: Date.now() });
459
- emitContext('UserPromptSubmit', resumeNote(plan, false, payload));
510
+ emitContext('UserPromptSubmit', withRun(resumeNote(plan, false, payload), run, true));
460
511
  return;
461
512
  }
462
513
  const named = hit.route === 'start-work' ? typedPlan(payload.prompt) : null;
@@ -464,13 +515,18 @@ run((payload) => {
464
515
  // the one open plan start-work would pick. The context's approval line stays for a typed plan only.
465
516
  const runPlan = hit.route === 'start-work' ? named ?? soleOpenPlan(workspaceOf(payload)) : null;
466
517
  const skillPlan = skillPlanFor(hit, hatch);
467
- writeSession(payload, { route: hit.route, turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested });
518
+ // A start-work start gets a run record; any other route keeps a run this session already has, so a side route
519
+ // (a review, a debug) does not drop the parked queue.
520
+ const run = hit.route === 'start-work' && runPlan ? runFor(payload, previous, runPlan, { approved: Boolean(named) }) : null;
521
+ const keepRun = run ? { run } : previous?.run && !previous.corrupt ? { run: previous.run } : {};
522
+ writeSession(payload, { route: hit.route, turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested, ...keepRun });
468
523
  stackStart(payload, hit.route, runPlan ? { plan: runPlan } : undefined, hit.restart);
469
524
  recordRoute(payload, { route: hit.route, keyword: hit.keyword ?? null, kind: 'ignite', plan: runPlan, activatedAt: Date.now(), skills: skillPlanIds(skillPlan) });
470
525
  const loopGoal = loopGoalNote(hit, payload);
471
526
  emitContext('UserPromptSubmit', activation(hit, payload)
472
527
  + (loopGoal ? `\n${loopGoal}` : '')
473
528
  + (named ? `\nPlan: ${named}. The typed command is the approval: the work starts without a separate approval turn; work through its open rows in order.` : '')
529
+ + (run ? `\n${startNote(run)}` : '')
474
530
  + (skillPlan ? `\n${skillPlanContext(skillPlan)}` : ''));
475
531
  });
476
532
 
@@ -115,7 +115,7 @@ If the question cannot be asked in this turn but a human is present, write the p
115
115
 
116
116
  The plan carries a `Goal` block (one outcome sentence and two to six criteria, each naming the command or surface that proves it) and a machine-readable `## Done when` block with exactly one line `- check: \`<command>\``: the one allowlisted test command whose exit 0, together with every row ticked, means the plan is done (`npm test`, `npm run <script>`, `node --test …`, `pytest …`, `cargo test`, `go test …`, `make test|check|verify`, or `bash scripts/<name>.sh` for a long plan that needs a check script). Judgment words ("works", "looks good", "잘 동작") and outward actions (push, publish, release) are not checks. A plan that should never become a goal says `goal: never` on its own line instead.
117
117
 
118
- After the plan file exists, run `node <skill-dir>/scripts/goal-propose.mjs plans/<slug>.md` once (the planning guard allows exactly this command). It compiles the block into one Muse goal objective, `Every row in plans/<slug>.md is ticked and \`<check>\` exits 0 [lit:<id>]` (at most 500 characters), lints it, runs the check once to prove the objective is false right now, and prints the closing approval question: `Approve plan, start work and set goal: /goal <objective>? (yes / edit / no)`. When no goal is possible (no Done when block, `goal: never`, a refused check, an objective that is already true), it prints `Approve plan and start work? (yes / no)` and under it the one `No goal set: <reason>` line. After a blank line it prints the answer guide, a Markdown block quote with one row per accepted answer (`yes`, `edit`, `no`, or `yes`, `no` for start only) saying what each one does, closed by `Type the word alone.` End the reply with what it printed: the question line exactly as printed, then the answer guide under it, its title and descriptions in the user's language and the answer words in English, because the prompt hook matches only the exact English word. Do not drop the guide: it is how a first-time user learns what to type.
118
+ After the plan file exists, run `node <skill-dir>/scripts/goal-propose.mjs plans/<slug>.md` once (the planning guard allows exactly this command). It compiles the block into one Muse goal objective, `Every row in plans/<slug>.md is ticked and \`<check>\` exits 0, or the latest reply starts with WAITING-ON-USER:, or after 30 turns [lit:<id>]` (at most 500 characters; only for a plan with a `goal: native` line), lints it, runs the check once to prove the objective is false right now, and prints the closing approval question: `Approve plan, start work and set goal: /goal <objective>? (yes / edit / no)`. When no goal is possible (no `goal: native` line, no Done when block, `goal: never`, a refused check, an objective that is already true), it prints `Approve plan and start work? (yes / no)` and under it the one `No goal set: <reason>` line. After a blank line it prints the answer guide, a Markdown block quote with one row per accepted answer (`yes`, `edit`, `no`, or `yes`, `no` for start only) saying what each one does, closed by `Type the word alone.` End the reply with what it printed: the question line exactly as printed, then the answer guide under it, its title and descriptions in the user's language and the answer words in English, because the prompt hook matches only the exact English word. Do not drop the guide: it is how a first-time user learns what to type.
119
119
 
120
120
  The planning turn itself sets nothing: `create_goal` and `update_goal` are refused here. Only the session that was asked can answer: PostToolUse stamps this session on the question when goal-propose runs, and a `yes` typed in any other session, or on a question no session was stamped on, starts nothing and shows `Approval not recorded for this session. Run: lit start plans/<slug>.md`. In `muse exec` or another one-shot run nobody can answer in that session, so the question is printed and the user starts the plan later with `lit start plans/<slug>.md`, or types `yes` after resuming that same session (`muse resume`). The user's exact `yes` on the next prompt of this session does it all in one step: the LitMuse prompt hook approves the plan, starts `start-work` on it (the same start as a typed `lit start plans/<slug>.md`, with the same grants) and arms the goal, telling the model to call `create_goal` with that exact objective (PreToolUse admits a `[lit:…]` objective only then). When the start is refused (another live session already runs start-work on the plan, or the plan has no open row), nothing starts, no goal is armed, and the hook shows `Work not started and no goal set: <reason>`. `edit` re-opens the plan and asks again, `no` starts nothing and sets no goal, and anything else leaves the question open for 30 minutes. `get_goal` is allowed here: call it once, and when another goal is active, say so in the plan's Bootstrap section, because a session holds one goal and LitMuse never replaces the user's own.
121
121
 
@@ -182,7 +182,17 @@ Scope roots: /abs/path/to/folder (read)
182
182
  Scope roots: /abs/path/to/scratch (read, write, execute)
183
183
  ```
184
184
 
185
- Grant the narrowest existing folder and only the actions the todos need. Paths inside the project need no line. A command quoted in a fence or an inline code span (it holds a space) is data and needs no line; a code span that is one bare path counts. Before saving, search the Todos for `/` paths and add the missing lines. `start-work` runs `node scripts/check-plan.mjs --check plans/<slug>.md`, which fails on an uncovered folder and prints the exact line to add; a filesystem-root, top-level or home folder is never suggested, so name a narrower one.
185
+ Grant the narrowest existing folder and only the actions the todos need. Paths inside the project need no line. A command quoted in a fence or an inline code span (it holds a space) is data and needs no line; a code span that is one bare path counts. Before saving, search the Todos for `/` paths and add the missing lines. `start-work` runs `node scripts/check-plan.mjs --check plans/<slug>.md`, which fails on an uncovered folder and prints the exact line to add; a filesystem-root, top-level or home folder is never suggested, so name a narrower one. During the run, a new file or folder made in a `(read)` root is parked as tier B for the user's `lit approve`; a `write` grant lets it run.
186
+
187
+ ### Optional autopilot lines
188
+
189
+ Three more lines, each on its own line outside any code fence, shape how the run finishes on its own:
190
+
191
+ - `Run charter: commit on <branch> in <repo>` (for example `Run charter: commit on feat/qa in .`) lets the run make plain commits on that branch in that repo. Write it only when the user asked for commits; push, tag and publish are never covered.
192
+ - `goal: native` arms Muse's native goal for the run; the goal always ends itself on a `WAITING-ON-USER:` reply or after 30 turns. Without it the start-work hooks drive the run alone, which is the default.
193
+ - The `## Done when` block with its `- check:` line is what lets the run close itself: every row ticked plus that check exiting 0.
194
+
195
+ The user's `yes` binds the charter and Scope roots lines as they read when the question was asked; an edit after that grants nothing new.
186
196
 
187
197
  A task that builds or changes a user-facing web interface names `frontend-ui-ux` in its verification (the interface probe across the responsive matrix, with no HIGH finding left) and hands the acceptance verdict to `visual-qa`. A CLI, library or backend-only task names neither.
188
198
 
@@ -15,6 +15,7 @@ import { isAbsolute, relative, resolve } from 'node:path';
15
15
  import { pathToFileURL } from 'node:url';
16
16
  import { GOAL_STATUS, answerGuide, buildLoopConsent, compileCondition, conditionHash, consentKey, falsify, lintCondition, parseDoneWhen, writeGoalRecord } from '../../../hooks/lib/goal.mjs';
17
17
  import { resolveProjectStateRoot } from '../../../hooks/lib/workflow-stack.mjs';
18
+ import { parsePlan } from '../../../hooks/lib/autopilot.mjs';
18
19
 
19
20
  export function proposeGoal({ cwd, planArg, now = Date.now(), timeoutMs, run, sessionId = null } = {}) {
20
21
  const planPath = resolve(cwd, String(planArg ?? ''));
@@ -27,9 +28,13 @@ export function proposeGoal({ cwd, planArg, now = Date.now(), timeoutMs, run, se
27
28
  return { line: GOAL_STATUS.skipped(`${plan} cannot be read`) };
28
29
  }
29
30
  const askedAt = new Date(now).toISOString();
31
+ // The question binds the plan's `Run charter:` and `Scope roots:` lines as they read now; a plan edited before
32
+ // the `yes` starts with project grants only.
33
+ const parsed = parsePlan(planText);
34
+ const charterHash = parsed.consentHash;
30
35
  // No goal is possible: the question still approves the plan and starts the work, and names why there is no goal.
31
36
  const startOnly = (reason) => {
32
- const consent = { version: 1, goal: false, plan, reason, sessionId, askedAt };
37
+ const consent = { version: 1, goal: false, plan, reason, sessionId, askedAt, charterHash };
33
38
  consent.hash = conditionHash(consentKey(consent));
34
39
  writeGoalRecord(resolveProjectStateRoot(cwd), 'consent', consent);
35
40
  return { line: `${GOAL_STATUS.askedStart}\n${GOAL_STATUS.skipped(reason)}`, guide: answerGuide('start'), consent };
@@ -37,13 +42,15 @@ export function proposeGoal({ cwd, planArg, now = Date.now(), timeoutMs, run, se
37
42
  if (/^goal:\s*never\s*$/mu.test(planText)) return startOnly('this plan is marked goal: never');
38
43
  const done = parseDoneWhen(planText);
39
44
  if (!done.ok) return startOnly(done.reason);
45
+ // A start-work run is driven by its own hooks; Muse's native goal is armed only when the plan opts in.
46
+ if (!parsed.goalNative) return startOnly('the plan has no `goal: native` line, so the start-work hooks drive the run');
40
47
  const built = compileCondition({ plan, check: done.check });
41
48
  if (!built.ok) return startOnly(built.reason);
42
49
  const lint = lintCondition(built.condition, done.check);
43
50
  if (!lint.ok) return startOnly(lint.reasons.join('; '));
44
51
  const dry = falsify({ cwd, plan, planText, check: done.check, ...(timeoutMs ? { timeoutMs } : {}), ...(run ? { run } : {}) });
45
52
  if (!dry.ok) return startOnly(dry.reason);
46
- const consent = { version: 1, goal: true, condition: built.condition, hash: conditionHash(built.condition), id: built.id, plan, check: done.check, sessionId, askedAt };
53
+ const consent = { version: 1, goal: true, condition: built.condition, hash: conditionHash(built.condition), id: built.id, plan, check: done.check, sessionId, askedAt, charterHash };
47
54
  writeGoalRecord(resolveProjectStateRoot(cwd), 'consent', consent);
48
55
  return { line: GOAL_STATUS.asked(built.condition), guide: answerGuide('plan', built.condition), consent };
49
56
  }