@litfamily/litgravity 0.1.10 → 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 (56) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +17 -3
  3. package/README_ko-KR.md +17 -3
  4. package/package.json +1 -1
  5. package/plugin/hooks/lib/auto-handoff.mjs +107 -0
  6. package/plugin/hooks/lib/common.mjs +1 -1
  7. package/plugin/hooks/lib/goal.mjs +267 -0
  8. package/plugin/hooks/lib/policy.mjs +6 -1
  9. package/plugin/hooks/lib/reentry.mjs +5 -1
  10. package/plugin/hooks/lib/rewind/collect.mjs +98 -14
  11. package/plugin/hooks/lib/rewind/verdict.mjs +250 -0
  12. package/plugin/hooks/lib/routes.mjs +84 -12
  13. package/plugin/hooks/lib/shown.mjs +65 -0
  14. package/plugin/hooks/lib/skill-plan.mjs +171 -0
  15. package/plugin/hooks/lib/transcript.mjs +20 -0
  16. package/plugin/hooks/lib/workflow-stack.mjs +3 -3
  17. package/plugin/hooks/pre-invocation.mjs +65 -9
  18. package/plugin/hooks/session-start.mjs +28 -13
  19. package/plugin/hooks/stop.mjs +16 -0
  20. package/plugin/plugin.json +1 -1
  21. package/plugin/rules/AGENTS.md +1 -1
  22. package/plugin/skills/autoconference/SKILL.md +1 -1
  23. package/plugin/skills/autoconference/modes/core.md +1 -1
  24. package/plugin/skills/lit-adhd/SKILL.md +96 -58
  25. package/plugin/skills/lit-adhd/references/board-and-detail.md +48 -0
  26. package/plugin/skills/lit-adhd/references/recap-view.md +59 -0
  27. package/plugin/skills/lit-comprehend/SKILL.md +2 -2
  28. package/plugin/skills/lit-handoff/SKILL.md +2 -2
  29. package/plugin/skills/lit-handoff/evals/evals.json +1 -1
  30. package/plugin/skills/lit-handoff/reference/PROVENANCE.md +1 -1
  31. package/plugin/skills/lit-handoff/scripts/verify-closure.mjs +1 -1
  32. package/plugin/skills/lit-init/SKILL.md +1 -1
  33. package/plugin/skills/lit-loop/SKILL.md +1 -1
  34. package/plugin/skills/lit-plan/SKILL.md +15 -15
  35. package/plugin/skills/lit-plan/references/goal-condition.md +78 -0
  36. package/plugin/skills/lit-plan/references/risk-and-recovery.md +1 -1
  37. package/plugin/skills/lit-plan/scripts/goal-propose.mjs +18 -0
  38. package/plugin/skills/lit-plan/templates/plan.md +4 -1
  39. package/plugin/skills/lit-team/SKILL.md +37 -21
  40. package/plugin/skills/lit-team/references/team-orchestration.md +3 -3
  41. package/plugin/skills/litgoal/SKILL.md +8 -8
  42. package/plugin/skills/litgoal/references/host-goal-binding.md +30 -22
  43. package/plugin/skills/litwork/SKILL.md +2 -2
  44. package/plugin/skills/start-work/SKILL.md +1 -1
  45. package/plugin/skills/start-work/references/admission-and-selection.md +1 -1
  46. package/plugin/skills/start-work/references/final-wave.md +1 -1
  47. package/plugin/skills/ultra-brainstorm/SKILL.md +114 -0
  48. package/plugin/skills/ultra-brainstorm/references/lenses.md +40 -0
  49. package/plugin/skills/ultra-brainstorm/references/workflow-script.md +129 -0
  50. package/plugin/skills/ultra-brainstorm/scripts/estimate.mjs +76 -0
  51. package/plugin/skills/wikify/SKILL.md +2 -2
  52. package/plugin/skills/wikify/modes/init.md +1 -1
  53. package/plugin/skills/lit-recap/SKILL.md +0 -168
  54. package/plugin/skills/lit-recap/references/recap-shapes.md +0 -166
  55. package/plugin/skills/lit-recap/references/source-reading.md +0 -105
  56. package/plugin/skills/lit-recap/references/stale-state-checks.md +0 -74
@@ -0,0 +1,65 @@
1
+ import { appendFileSync, lstatSync, mkdirSync, readFileSync } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ import { join } from 'node:path';
4
+ import { realStateDir, safeId, workspaceOf } from './common.mjs';
5
+ import { WORK_ROUTES, activePlan, openGoal, planRows } from './continuation.mjs';
6
+
7
+ // An append-only record in `.litgravity/shown/notices.jsonl` of what the hooks already told the user in this project:
8
+ // one line per notice (`kind`, `hash` of its normalised text, `ts`) and one per run end (`outcome`). A missing, corrupt
9
+ // or unwritable record changes nothing: the notice is shown as before. Only text the hooks print themselves is
10
+ // recorded; the model's own prose is never intercepted.
11
+ const RUN_END_FILE_CAP = 1_000_000;
12
+
13
+ const hashOf = (text) => createHash('sha256').update(String(text).replace(/\s+/g, ' ').trim().toLowerCase()).digest('hex').slice(0, 16);
14
+
15
+ function recordFile(payload) {
16
+ if (!safeId(payload.conversationId)) return null;
17
+ const dir = realStateDir(payload, 'shown');
18
+ return dir ? join(dir, 'notices.jsonl') : null;
19
+ }
20
+
21
+ function append(file, entry, { cap = Infinity } = {}) {
22
+ try {
23
+ mkdirSync(join(file, '..'), { recursive: true });
24
+ try {
25
+ const st = lstatSync(file);
26
+ if (st.isSymbolicLink() || st.size > cap) return;
27
+ } catch { /* absent: created by the append */ }
28
+ appendFileSync(file, `${JSON.stringify({ ts: new Date().toISOString(), ...entry })}\n`);
29
+ } catch { /* the record never blocks a hook */ }
30
+ }
31
+
32
+ function seen(file, hash) {
33
+ try {
34
+ return readFileSync(file, 'utf8').split('\n').some((line) => {
35
+ try { return JSON.parse(line).hash === hash; } catch { return false; }
36
+ });
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ /** True when `text` should be shown now: it was not recorded before. A fresh notice is recorded as shown. */
43
+ export function noticeOnce(payload, kind, text) {
44
+ const file = recordFile(payload);
45
+ if (!file) return true;
46
+ const hash = hashOf(text);
47
+ if (seen(file, hash)) return false;
48
+ append(file, { kind, hash });
49
+ return true;
50
+ }
51
+
52
+ /** How a work run's turn ended: `waiting` on the user, `nothing` (open work left, nobody asked), or `sent` (nothing left open). */
53
+ export function recordRunEnd(payload, state, waiting) {
54
+ try {
55
+ const file = recordFile(payload);
56
+ if (!file || !WORK_ROUTES.has(state.route)) return;
57
+ const cwd = workspaceOf(payload);
58
+ let open = Boolean(openGoal(payload, state, cwd));
59
+ if (!open) {
60
+ const plan = activePlan(payload, cwd);
61
+ open = plan ? planRows(readFileSync(join(cwd, plan), 'utf8')).some((r) => !r.done) : false;
62
+ }
63
+ append(file, { kind: 'run-end', outcome: waiting ? 'waiting' : open ? 'nothing' : 'sent', route: state.route, conversation: payload.conversationId }, { cap: RUN_END_FILE_CAP });
64
+ } catch { /* the record never blocks a hook */ }
65
+ }
@@ -0,0 +1,171 @@
1
+ // The skill plan of a `lit <task>` prompt. The router still picks one primary route, exactly as before; this module
2
+ // adds the companions: the other intent routes the same task matched, in the router's priority order, without
3
+ // duplicates and capped, plus lit-crucible when the ask is a large or risky design. agy has no skill-loading tool, so
4
+ // the model reads each companion's SKILL.md with read_file when its part of the work starts. `lit +viz +ui <task>`
5
+ // names the plan outright.
6
+ //
7
+ // A moved skill (MOVED_SKILLS) is offered only when its standalone copy is installed for agy, in
8
+ // ~/.gemini/config/skills/<id>/ or the workspace's .agents/skills/<id>/; otherwise the plan names it once with the
9
+ // install command. A read-only primary (lit-adhd, review-work, litresearch, the brainstorms) never gains a companion
10
+ // that writes.
11
+ import { existsSync } from 'node:fs';
12
+ import { homedir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import { PLUGIN_ROOT } from './common.mjs';
15
+ import { MOVED_SKILLS, SKILL_IDS, SKILL_ROUTES, companionIntents, extensionCommand } from './routes.mjs';
16
+
17
+ export const PLAN_CAP = 3;
18
+
19
+ // `lit +<alias>` names: short words a user can type without looking anything up. Any skill id works too.
20
+ export const PLAN_ALIASES = Object.freeze({
21
+ viz: 'lit-scientific-visualization',
22
+ plot: 'lit-scientific-visualization',
23
+ figure: 'lit-scientific-visualization',
24
+ ui: 'frontend-ui-ux',
25
+ design: 'frontend-ui-ux',
26
+ qa: 'visual-qa',
27
+ crucible: 'lit-crucible',
28
+ plan: 'lit-plan',
29
+ research: 'litresearch',
30
+ review: 'review-work',
31
+ debug: 'debugging',
32
+ deck: 'lit-pptx',
33
+ slides: 'lit-pptx',
34
+ pptx: 'lit-pptx',
35
+ doc: 'lit-docx',
36
+ docx: 'lit-docx',
37
+ diagram: 'lit-diagram-drawer',
38
+ schematic: 'lit-schematic',
39
+ motion: 'lit-typographic-motion',
40
+ video: 'lit-typographic-motion',
41
+ readme: 'readme-studio',
42
+ ast: 'structural-search',
43
+ refactor: 'refactor',
44
+ brainstorm: 'lit-brainstorm',
45
+ ultra: 'ultra-brainstorm',
46
+ humanize: 'lit-humanizer',
47
+ commit: 'lit-commit',
48
+ });
49
+
50
+ // Routes that only read. A plan led by one of these keeps only companions from this set.
51
+ export const READ_ONLY_SKILLS = Object.freeze(new Set(['lit-adhd', 'review-work', 'litresearch', 'lit-brainstorm', 'ultra-brainstorm', 'lit-crucible', 'lit-comprehend']));
52
+ const READ_ONLY_PRIMARIES = new Set(['lit-adhd', 'review-work', 'litresearch', 'lit-brainstorm', 'ultra-brainstorm']);
53
+
54
+ // The skills the catalog may offer, each with its route-table purpose. Moved ones appear only when installed.
55
+ const CATALOG_IDS = ['lit-plan', 'lit-crucible', 'lit-brainstorm', 'ultra-brainstorm', 'litresearch', 'review-work', 'debugging', 'refactor',
56
+ 'structural-search', 'lit-humanizer', 'lit-commit', 'browser-drive', ...Object.keys(MOVED_SKILLS)];
57
+ const WHEN = new Map(SKILL_ROUTES.map((r) => [r.id, r.when.replace(/ \(moved\)$/u, '')]));
58
+
59
+ // Large or risky design asks: lit-crucible joins as the first companion. A request to explain or describe stays out.
60
+ const RISKY_DESIGN = /\b(?:redesign(?:ing)?|re-?architect(?:ure|ing)?|architecture|migrat(?:e|ion|ing)|overhaul(?:ing)?)\b|재설계|설계|아키텍처|마이그레이션|전면\s?개편/iu;
61
+ const EXPLAIN = /\b(?:explain|describe|summari[sz]e|what\s+is)\b|설명|요약/iu;
62
+ const DELIVERABLES = new Set(['lit-pptx', 'lit-docx', 'frontend-ui-ux', 'lit-scientific-visualization', 'lit-diagram-drawer', 'lit-schematic', 'lit-typographic-motion', 'readme-studio']);
63
+
64
+ export const wantsCrucible = (task, ids) => {
65
+ if (EXPLAIN.test(task)) return false;
66
+ return RISKY_DESIGN.test(task) || ids.filter((id) => DELIVERABLES.has(id)).length >= 3;
67
+ };
68
+
69
+ /** Text that only quotes something (a fence, inline code, a quoted span) routes nothing. */
70
+ export const inertStripped = (text) => String(text ?? '')
71
+ .replace(/```[\s\S]*?(?:```|$)/gu, ' ')
72
+ .replace(/`[^`\n]*`/gu, ' ')
73
+ .replace(/"[^"\n]*"|“[^”\n]*”|'[^'\n]{3,}'|「[^」\n]*」/gu, ' ');
74
+
75
+ /** Where agy would load an installed standalone copy of a moved skill from, or null. */
76
+ export const installedCopy = (id, { env = process.env, workspace = null } = {}) => {
77
+ const home = env.HOME || homedir();
78
+ const candidates = [
79
+ ...(workspace ? [join(workspace, '.agents', 'skills', id, 'SKILL.md')] : []),
80
+ join(home, '.gemini', 'config', 'skills', id, 'SKILL.md'),
81
+ ];
82
+ return candidates.find((path) => existsSync(path)) ?? null;
83
+ };
84
+
85
+ /** `+viz +ui` → skill ids in the user's order, plus the names nothing knows. */
86
+ export const resolveForced = (names) => {
87
+ const skills = [];
88
+ const unknown = [];
89
+ for (const name of names ?? []) {
90
+ const id = PLAN_ALIASES[name] ?? (SKILL_IDS.has(name) ? name : null);
91
+ if (!id) unknown.push(name);
92
+ else if (!skills.includes(id)) skills.push(id);
93
+ }
94
+ return { skills, unknown };
95
+ };
96
+
97
+ /**
98
+ * The ordered plan for a routed hit, or null when the plan is the primary alone (an ordinary prompt's activation
99
+ * stays exactly as it was). `hit.task` is the task text, `hit.forced` the `+name` words.
100
+ */
101
+ export const buildSkillPlan = (hit, { env = process.env, workspace = null } = {}) => {
102
+ const primary = hit?.route;
103
+ if (typeof primary !== 'string' || !primary) return null;
104
+ const forced = Array.isArray(hit.forced) ? resolveForced(hit.forced) : null;
105
+ const task = inertStripped(hit.task ?? '');
106
+ const readOnly = READ_ONLY_PRIMARIES.has(primary);
107
+ const dropped = [];
108
+ let picked;
109
+ if (forced) {
110
+ picked = forced.skills.filter((id) => id !== primary);
111
+ } else {
112
+ picked = companionIntents(task).filter((id) => id !== primary);
113
+ if (!readOnly && primary !== 'lit-crucible' && wantsCrucible(`${hit.keyword ?? ''} ${task}`, [primary, ...picked])) picked.unshift('lit-crucible');
114
+ }
115
+ picked = [...new Set(picked)].filter((id) => {
116
+ if (readOnly && !READ_ONLY_SKILLS.has(id)) {
117
+ dropped.push({ id, why: `${primary} is read-only` });
118
+ return false;
119
+ }
120
+ return true;
121
+ });
122
+ for (const id of picked.slice(PLAN_CAP - 1)) dropped.push({ id, why: 'over the cap of 3' });
123
+ picked = picked.slice(0, PLAN_CAP - 1);
124
+ if (picked.length === 0 && !forced) return null;
125
+ const entries = [primary, ...picked].map((id) => {
126
+ const moved = Boolean(MOVED_SKILLS[id]);
127
+ const copy = moved ? installedCopy(id, { env, workspace }) : null;
128
+ return { id, moved, family: MOVED_SKILLS[id] ?? null, path: moved ? copy : join(PLUGIN_ROOT, 'skills', id, 'SKILL.md'), installed: moved ? Boolean(copy) : true };
129
+ });
130
+ return { entries, dropped, forced: Boolean(forced), unknown: forced?.unknown ?? [], readOnly };
131
+ };
132
+
133
+ const label = (entry, index) => {
134
+ const lead = index === 0 ? ' (primary)' : '';
135
+ if (!entry.moved) return `${entry.id}${lead}`;
136
+ if (entry.installed) return `${entry.id}${lead} (${entry.family} extension)`;
137
+ return `${entry.id}${lead} (not installed: ${extensionCommand(entry.id)})`;
138
+ };
139
+
140
+ /** `Skill plan: 1 lit-loop (primary) → 2 lit-scientific-visualization (figures extension) → 3 …` */
141
+ export const skillPlanLine = (plan) => `Skill plan: ${plan.entries.map((entry, index) => `${index + 1} ${label(entry, index)}`).join(' → ')}`;
142
+
143
+ const catalogLines = (plan, env, workspace) => {
144
+ const inPlan = new Set(plan.entries.map(({ id }) => id));
145
+ return CATALOG_IDS
146
+ .filter((id) => !inPlan.has(id))
147
+ .filter((id) => !plan.readOnly || READ_ONLY_SKILLS.has(id))
148
+ .filter((id) => !MOVED_SKILLS[id] || installedCopy(id, { env, workspace }))
149
+ .map((id) => `${id} — ${WHEN.get(id)}`);
150
+ };
151
+
152
+ /** The model-facing block: fixed text around the plan. Nothing from the prompt is echoed. */
153
+ export const skillPlanContext = (plan, { env = process.env, workspace = null } = {}) => {
154
+ const lines = [skillPlanLine(plan)];
155
+ if (plan.forced) {
156
+ lines.push('The user named this plan with `lit +…`: keep it exactly, add nothing and drop nothing.');
157
+ if (plan.unknown.length) lines.push(`Ignored unknown plan names: ${plan.unknown.map((name) => `+${name}`).join(' ')}.`);
158
+ } else {
159
+ lines.push('The companions after the primary are candidates the router matched, not orders: confirm or drop each one for this request, and add at most one skill from the catalog below when the work clearly needs it.');
160
+ }
161
+ for (const { id, why } of plan.dropped) lines.push(`Left out: ${id} (${why}).`);
162
+ lines.push('State the final plan on the line right after the ignition line, in the same `Skill plan: 1 … → 2 …` form. The primary is the skill named above; read each companion\'s SKILL.md with read_file only when its part of the work starts, never all up front. A skill marked not installed is not read: give its install command once and carry on without it.');
163
+ const paths = plan.entries.slice(1).filter((entry) => entry.installed).map((entry) => `${entry.id}: ${entry.path}`);
164
+ if (paths.length) lines.push(`Companion files: ${paths.join('; ')}.`);
165
+ const catalog = plan.forced ? [] : catalogLines(plan, env, workspace);
166
+ if (catalog.length) lines.push(`Catalog (installed here): ${catalog.join('; ')}.`);
167
+ return lines.join('\n');
168
+ };
169
+
170
+ /** The plan's skill ids, for the ledger line. */
171
+ export const skillPlanIds = (plan) => (plan ? plan.entries.map(({ id }) => id) : []);
@@ -25,6 +25,26 @@ export function extractRequest(content) {
25
25
  return (m ? m[1] : content).trim();
26
26
  }
27
27
 
28
+ // The text of the newest model reply that has any, or null.
29
+ export function lastModelText(transcriptPath) {
30
+ if (typeof transcriptPath !== 'string' || !transcriptPath) return null;
31
+ let text;
32
+ try {
33
+ text = tailText(transcriptPath);
34
+ } catch {
35
+ return null;
36
+ }
37
+ const lines = text.split('\n');
38
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
39
+ if (!lines[i].includes('"PLANNER_RESPONSE"')) continue;
40
+ try {
41
+ const rec = JSON.parse(lines[i]);
42
+ if (rec?.type === 'PLANNER_RESPONSE' && typeof rec.content === 'string' && rec.content.trim()) return rec.content.trim();
43
+ } catch { /* partial line */ }
44
+ }
45
+ return null;
46
+ }
47
+
28
48
  // {text, stepIndex} of the newest user prompt, or null when the transcript is absent or has none.
29
49
  export function lastUserRequest(transcriptPath) {
30
50
  if (typeof transcriptPath !== 'string' || !transcriptPath) return null;
@@ -16,16 +16,16 @@ export const MAX_FRAMES = 3;
16
16
  export const MAX_HISTORY = 20;
17
17
  export const MAX_STACK_BYTES = 64 * 1024;
18
18
  export const STACK_DROP_MS = 24 * 60 * 60 * 1000;
19
- export const READ_ONLY_DISCIPLINES = Object.freeze(['lit-recap', 'lit-comprehend', 'lit-handoff', 'lit-adhd', 'lit-rewind']);
19
+ export const READ_ONLY_DISCIPLINES = Object.freeze(['lit-comprehend', 'lit-handoff', 'lit-adhd', 'lit-rewind']);
20
20
 
21
21
  // The main-chain stage families and entry points; a newcomer of a higher rank succeeds the frame below.
22
22
  const CHAIN_RANK = Object.freeze({
23
- 'deep-interview': 0, 'lit-brainstorm': 0, 'lit-crucible': 1, 'lit-plan': 1,
23
+ 'deep-interview': 0, 'lit-brainstorm': 0, 'ultra-brainstorm': 0, 'lit-crucible': 1, 'lit-plan': 1,
24
24
  'start-work': 2, litwork: 2, litgoal: 2, autoresearch: 2, 'lit-loop': 2, 'review-work': 3,
25
25
  });
26
26
 
27
27
  const DISCIPLINE_FAMILY = {
28
- 'deep-interview': 'main', 'lit-brainstorm': 'main', 'lit-crucible': 'main', 'lit-plan': 'main',
28
+ 'deep-interview': 'main', 'lit-brainstorm': 'main', 'ultra-brainstorm': 'main', 'lit-crucible': 'main', 'lit-plan': 'main',
29
29
  'start-work': 'main', litwork: 'main', litgoal: 'main', autoresearch: 'main', 'review-work': 'main',
30
30
  litresearch: 'research', 'lit-loop': 'loop',
31
31
  };
@@ -1,4 +1,4 @@
1
- import { readFileSync } from 'node:fs';
1
+ import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
 
4
4
  import { run, inject, readSession, writeSession, appendLedger, workspaceOf, safeId, stateRoot } from './lib/common.mjs';
@@ -9,23 +9,36 @@ import { PAUSE_WORD, planRows } from './lib/continuation.mjs';
9
9
  import { saveSnapshot } from './lib/boundary.mjs';
10
10
  import { applyStackEvent, readStack, writeStack } from './lib/workflow-stack.mjs';
11
11
  import { isGoPrompt, takeNextStep } from './lib/rewind/next-step.mjs';
12
+ import { buildSkillPlan, skillPlanContext, skillPlanIds } from './lib/skill-plan.mjs';
13
+ import { answerConsent, cancelOwnedGoal } from './lib/goal.mjs';
12
14
 
13
15
  // agy has no UserPromptSubmit event. PreInvocation fires before every model call; invocationNum 0 is the first call of a
14
16
  // user turn, and its transcript already holds the prompt. The router reads that prompt, applies the D1 re-entry rule
15
17
  // and injects one ephemeral step, so a `lit` prompt is steered before the model has answered anything.
16
18
 
17
- function textFor(decision, hit, payload) {
19
+ function textFor(decision, hit, payload, plan = null) {
18
20
  switch (decision.kind) {
19
21
  case 'continue': return continueNote(decision.route);
20
22
  case 'resume': return resumeNote(decision.plan);
21
- default: return activation(hit, payload.conversationId, decision.kind);
23
+ default: {
24
+ const text = activation(hit, payload.conversationId, decision.kind);
25
+ return plan ? `${text}\n${skillPlanContext(plan, { workspace: workspaceOf(payload) })}` : text;
26
+ }
22
27
  }
23
28
  }
24
29
 
25
- function stackEvent(decision, hit) {
30
+ // `lit start plans/<x>.md` names its plan; the frame keeps it so a finished plan reads finished (lit-adhd).
31
+ const namedPlan = (decision, hit, workspace) => {
32
+ if (decision.route !== 'start-work') return null;
33
+ const plan = String(hit?.task ?? '').split(/\s+/u).find((w) => /^plans\/[^/\\]+\.md$/u.test(w));
34
+ return plan && existsSync(join(workspace, plan)) ? plan : null;
35
+ };
36
+
37
+ function stackEvent(decision, hit, workspace) {
26
38
  if (decision.kind === 'continue' && decision.route) return { type: 'continue' };
27
39
  if (decision.kind === 'ignite' || decision.kind === 'switch' || decision.kind === 'confirm') {
28
- return { type: 'start', skill: decision.route, restart: hit?.restart === true };
40
+ const plan = namedPlan(decision, hit, workspace);
41
+ return { type: 'start', skill: decision.route, restart: hit?.restart === true, ...(plan ? { ref: { plan } } : {}) };
29
42
  }
30
43
  return null;
31
44
  }
@@ -69,6 +82,24 @@ function stillHolds(step, workspace, conversationId) {
69
82
  }
70
83
  }
71
84
 
85
+ // The `yes` to lit-plan's approval question starts the plan here, by the same writes `go` and `lit start` make: route
86
+ // start-work, a fresh boundary snapshot, a start-work frame on this conversation's stack. A missing plan, a plan with
87
+ // no open row, or a start-work run this conversation already holds refuses the start, and then no goal is armed.
88
+ function startPlanRun(payload, workspace, turnId, plan) {
89
+ if (typeof plan !== 'string' || !/^plans\/[^/\\]+\.md$/u.test(plan)) return { ok: false, reason: 'the plan path is not plans/<name>.md' };
90
+ let rows;
91
+ try { rows = planRows(readFileSync(join(workspace, plan), 'utf8')); } catch { return { ok: false, reason: `${plan} was not found` }; }
92
+ if (!rows.some((r) => !r.done)) return { ok: false, reason: `${plan} has no open row` };
93
+ const stack = readStack(workspace, payload.conversationId);
94
+ if (stack.frames.some((f) => f.skill === 'start-work' && f.status === 'active')) return { ok: false, reason: 'a start-work run is already active in this conversation' };
95
+ writeSession(payload, { route: 'start-work', turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested: false, lastKind: 'ignite' });
96
+ saveSnapshot(payload);
97
+ const { stack: next } = applyStackEvent(stack, { type: 'start', skill: 'start-work', ref: { plan } });
98
+ writeStack(workspace, payload.conversationId, next);
99
+ appendLedger(payload, { kind: 'route', route: 'start-work', how: 'consent', plan });
100
+ return { ok: true };
101
+ }
102
+
72
103
  function staleGoText(step) {
73
104
  const what = step.kind === 'start-plan' ? `start ${step.target?.plan ?? 'the plan'}`
74
105
  : step.kind === 'continue-work' ? 'continue this conversation\'s start-work run'
@@ -113,7 +144,7 @@ run((payload) => {
113
144
  writeSession(payload, { route: 'start-work', turnId, activatedAt: Date.now(), stopHeldFor: null, pauseRequested: false, lastKind: 'ignite' });
114
145
  saveSnapshot(payload);
115
146
  const stack = readStack(workspace, payload.conversationId);
116
- const { stack: next } = applyStackEvent(stack, { type: 'start', skill: 'start-work' });
147
+ const { stack: next } = applyStackEvent(stack, { type: 'start', skill: 'start-work', ...(step.target?.plan ? { ref: { plan: step.target.plan } } : {}) });
117
148
  writeStack(workspace, payload.conversationId, next);
118
149
  appendLedger(payload, { kind: 'route', route: 'start-work', how: 'go', plan: step.target?.plan ?? null });
119
150
  } else {
@@ -125,6 +156,27 @@ run((payload) => {
125
156
  return {};
126
157
  }
127
158
 
159
+ // The approval question lit-plan asked: an exact `yes` to a live consent record starts the plan and arms its goal;
160
+ // `edit` asks again; `no` does nothing. Any other prompt is not an answer and falls through.
161
+ const answered = answerConsent(workspace, request.text, safeId(payload.conversationId), Date.now(), {
162
+ startWork: (plan) => startPlanRun(payload, workspace, turnId, plan),
163
+ });
164
+ if (answered) {
165
+ appendLedger(payload, { kind: 'decision', decision: 'goal', answer: request.text.trim().toLowerCase(), started: answered.start });
166
+ const note = `LitGravity goal: tell the user this line once, verbatim, and nothing else about the goal:\n${answered.line}`;
167
+ if (!answered.start) return inject(`${note}\nStart nothing.`);
168
+ const start = activation({ route: 'start-work', keyword: 'start', bare: false, resume: false, restart: false, direct: false, empty: false }, payload.conversationId, 'ignite');
169
+ return inject(`${start}\nThe user approved ${answered.start} with \`yes\`: this is the typed approval for start-work, and the plan to execute is ${answered.start}.\n${note}`);
170
+ }
171
+ // `lit cancel` clears a goal LitGravity owns; a goal set by hand in agy is out of reach and stays.
172
+ if (/^lit\s+cancel\s*$/u.test(request.text.trim())) {
173
+ const cleared = cancelOwnedGoal(workspace);
174
+ if (cleared) {
175
+ appendLedger(payload, { kind: 'decision', decision: 'goal-cancel' });
176
+ return inject(`LitGravity goal: tell the user this line once, verbatim, then stop the work:\n${cleared}`);
177
+ }
178
+ }
179
+
128
180
  const hit = detectRoute(request.text);
129
181
  const previous = readSession(payload);
130
182
 
@@ -160,7 +212,8 @@ run((payload) => {
160
212
  const again = previous.lastKind === 'resume'
161
213
  ? { kind: 'resume', route: 'start-work', plan: resumablePlan(workspace) }
162
214
  : { kind: previous.lastKind, route: previous.route };
163
- return inject(textFor(again, { ...hit, route: previous.route }, payload));
215
+ const againPlan = ['ignite', 'switch', 'confirm'].includes(again.kind) && previous.route === hit.route ? buildSkillPlan(hit, { workspace }) : null;
216
+ return inject(textFor(again, { ...hit, route: previous.route }, payload, againPlan));
164
217
  }
165
218
 
166
219
  const plan = !hit.restart && (hit.bare || hit.resume) ? resumablePlan(workspace) : null;
@@ -174,16 +227,19 @@ run((payload) => {
174
227
  saveSnapshot(payload);
175
228
 
176
229
  // Update the workflow stack on every route change.
177
- const event = stackEvent(decision, hit);
230
+ const event = stackEvent(decision, hit, workspace);
178
231
  if (event) {
179
232
  const stack = readStack(workspace, payload.conversationId);
180
233
  const { stack: next } = applyStackEvent(stack, event);
181
234
  writeStack(workspace, payload.conversationId, next);
182
235
  }
183
236
 
237
+ // The skill plan rides only on a fresh activation of the routed skill; a continue or a resume keeps its own text.
238
+ const skillPlan = ['ignite', 'switch', 'confirm'].includes(decision.kind) && decision.route === hit.route ? buildSkillPlan(hit, { workspace }) : null;
184
239
  appendLedger(payload, {
185
240
  kind: 'route', route: decision.route, how: decision.kind, keyword: hit.keyword ?? null,
186
241
  ...(decision.plan ? { path: decision.plan.file } : {}),
242
+ ...(skillPlan ? { plan: skillPlanIds(skillPlan) } : {}),
187
243
  });
188
- return inject(textFor(decision, hit, payload));
244
+ return inject(textFor(decision, hit, payload, skillPlan));
189
245
  });
@@ -3,8 +3,10 @@ import { join } from 'node:path';
3
3
  import { run, injectSystem, workspaceOf, pluginVersion, cachedLatest, newerThan, sessionPath } from './lib/common.mjs';
4
4
  import { SKILL_ROUTES } from './lib/routes.mjs';
5
5
  import { extensionNotice, litgravityData, takeExtensionNotice } from './lib/extensions.mjs';
6
+ import { HANDOFF_MAX_AGE_MS, autoHandoffOn, handoffContext } from './lib/auto-handoff.mjs';
7
+ import { noticeOnce } from './lib/shown.mjs';
8
+ import { sweepGoal } from './lib/goal.mjs';
6
9
 
7
- const HANDOFF_MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000;
8
10
  const RECENT_SESSION_MS = 7 * 24 * 60 * 60 * 1000;
9
11
 
10
12
  function hasRecentLitSessions(workspace, env) {
@@ -35,28 +37,41 @@ run((payload) => {
35
37
  `LitGravity routes (skill id: use when)\n${routes}`,
36
38
  ];
37
39
  const latest = cachedLatest();
38
- if (latest && newerThan(latest, version)) {
39
- parts.push(`Update: LitGravity ${latest} is available (installed ${version}). Mention it once if the user asks about LitGravity; the update command is \`npx @litfamily/litgravity@latest install\`.`);
40
- }
40
+ const update = latest && newerThan(latest, version)
41
+ ? `Update: LitGravity ${latest} is available (installed ${version}). Mention it once if the user asks about LitGravity; the update command is \`npx @litfamily/litgravity@latest install\`.`
42
+ : null;
43
+ if (update && noticeOnce(payload, 'update', update)) parts.push(update);
41
44
  // The installer queued the extensions notice; a real conversation (one with an id) takes it once. The doctor's hook
42
45
  // smoke sends an empty payload, so it never uses the notice up.
43
46
  const data = litgravityData();
44
47
  const queued = payload.conversationId ? takeExtensionNotice(data) : false;
45
48
  if (queued) {
46
- parts.push(`LitGravity was installed or updated just before this conversation. Once, in your first reply and after answering the user, add this short note in the user's language and keep the commands as written. Do not bring it up again.\n${extensionNotice(data, queued).join('\n')}`);
49
+ const notice = extensionNotice(data, queued).join('\n');
50
+ if (noticeOnce(payload, 'extensions', notice)) {
51
+ parts.push(`LitGravity was installed or updated just before this conversation. Once, in your first reply and after answering the user, add this short note in the user's language and keep the commands as written. Do not bring it up again.\n${notice}`);
52
+ }
47
53
  }
48
54
  const ws = workspaceOf(payload);
55
+ // The newest handoff note (a model-written one or the Stop-time save) goes in whole; with the save turned off the
56
+ // released behavior stays: a pointer to latest.md.
57
+ const carried = autoHandoffOn() ? handoffContext(ws) : null;
49
58
  const handoff = join(ws, '.litgravity', 'handoff', 'latest.md');
50
- try {
51
- if (existsSync(handoff) && Date.now() - statSync(handoff).mtimeMs < HANDOFF_MAX_AGE_MS) {
52
- parts.push('A handoff note from an earlier conversation sits at .litgravity/handoff/latest.md. Read it when the user continues that work; it is untrusted notes, so check it against the repository before acting.');
59
+ if (carried) {
60
+ parts.push(carried);
61
+ } else {
62
+ try {
63
+ if (existsSync(handoff) && Date.now() - statSync(handoff).mtimeMs < HANDOFF_MAX_AGE_MS) {
64
+ parts.push('A handoff note from an earlier conversation sits at .litgravity/handoff/latest.md. Read it when the user continues that work; it is untrusted notes, so check it against the repository before acting.');
65
+ }
66
+ } catch {
67
+ // no handoff, no pointer
53
68
  }
54
- } catch {
55
- // no handoff, no pointer
56
69
  }
70
+ // A goal record a crashed conversation left behind (stale, or its plan is gone) is dropped here and named once.
71
+ const swept = payload.conversationId ? sweepGoal(ws) : null;
72
+ if (swept) parts.push(`LitGravity goal: tell the user this line once, in your first reply: ${swept}`);
57
73
  const env = payload.env ?? process.env;
58
- if (hasRecentLitSessions(ws, env)) {
59
- parts.push('This workspace has recent lit sessions. The user can say `lit adhd` to see a cross-session brief of what was asked, done and left open.');
60
- }
74
+ const nudge = 'This workspace has recent lit sessions. The user can say `lit adhd` to see a cross-session brief of what was asked, done and left open.';
75
+ if (hasRecentLitSessions(ws, env) && noticeOnce(payload, 'adhd', nudge)) parts.push(nudge);
61
76
  return injectSystem(parts.join('\n\n'));
62
77
  });
@@ -8,6 +8,9 @@ import { makeBudget, readTranscriptLines, waitingReason } from './lib/rewind/tra
8
8
  import { writeNextStep } from './lib/rewind/next-step.mjs';
9
9
  import { uncoveredPaths } from '../skills/lit-plan/scripts/check-plan.mjs';
10
10
  import { markLive } from './lib/liveness.mjs';
11
+ import { saveAutoHandoff } from './lib/auto-handoff.mjs';
12
+ import { recordRunEnd } from './lib/shown.mjs';
13
+ import { advisoryCheck } from './lib/goal.mjs';
11
14
 
12
15
  // The newest plans/*.md written since the route started, as `plans/<name>.md`, or null.
13
16
  function planWrittenSince(cwd, since) {
@@ -31,6 +34,7 @@ function settle(payload, out) {
31
34
  if (!state || state.corrupt || !state.route) return out;
32
35
  const lines = readTranscriptLines(payload.transcriptPath, makeBudget(WAIT_READ_BYTES), { head: 0, tail: WAIT_READ_BYTES });
33
36
  const reason = waitingReason(lines);
37
+ recordRunEnd(payload, state, Boolean(reason));
34
38
  if (reason || state.waiting) writeSession(payload, { ...state, waiting: reason ? { reason, at: Date.now() } : null });
35
39
  return out;
36
40
  }
@@ -40,6 +44,8 @@ function settle(payload, out) {
40
44
  // holds are bounded by continuation.mjs. Only a normal end of turn is held: errors, cancellations and limits end.
41
45
  run((payload) => {
42
46
  const finish = (r) => {
47
+ // agy has no compaction hook, so the note a fresh conversation resumes from is saved at every turn end, held or not.
48
+ saveAutoHandoff(payload);
43
49
  // A held turn goes on; any other end leaves the conversation idle until the next tool call.
44
50
  if (r?.decision !== 'continue') {
45
51
  try { markLive(workspaceOf(payload), payload.conversationId, 'idle'); } catch { /* liveness never blocks */ }
@@ -49,7 +55,17 @@ run((payload) => {
49
55
  return finish(decide(payload));
50
56
  });
51
57
 
58
+ // A goal LitGravity armed is checked at every normal turn end (advisory: agy's own /goal is not reachable from a hook).
59
+ // When it is met the record is cleared and the turn is held once, so the user hears the fixed status line.
60
+ function goalAtTurnEnd(payload) {
61
+ if (payload.terminationReason && payload.terminationReason !== 'NO_TOOL_CALL') return null;
62
+ const result = advisoryCheck(workspaceOf(payload));
63
+ return result?.state === 'met' ? holdStop(`LitGravity goal: tell the user this line once, verbatim, then end the turn:\n${result.line}`) : null;
64
+ }
65
+
52
66
  function decide(payload) {
67
+ const goal = goalAtTurnEnd(payload);
68
+ if (goal) return goal;
53
69
  if (payload.terminationReason && payload.terminationReason !== 'NO_TOOL_CALL') return {};
54
70
  const state = activeRoute(payload);
55
71
  if (!state) return {};
@@ -2,6 +2,6 @@
2
2
  "$schema": "https://antigravity.google/schemas/v1/plugin.json",
3
3
  "name": "litgravity",
4
4
  "description": "LitFamily workflows for the Antigravity CLI: bare lit activation, planning, evidence-bound execution, review, research, handoff and Korean prose care.",
5
- "version": "0.1.10",
5
+ "version": "0.1.12",
6
6
  "logo": "assets/logo.svg"
7
7
  }
@@ -18,7 +18,7 @@ LitGravity agents are started with `invoke_subagent` by their type name: lit-pla
18
18
  ## Workspace state
19
19
 
20
20
  - Plans: `plans/<slug>.md`, task rows at column zero as `- [ ] N. <title>`. A lit-plan turn is planning only: product files stay untouched and the turn ends once the plan file exists.
21
- - Everything else is under `.litgravity/`: goals `goals/<slug>.json`, the ledger `ledger/<conversation>.jsonl` (the hooks append tool events while a route is active; add your own note, evidence and decision lines), evidence `evidence/<slug>/`, handoffs `handoff/latest.md`, wiki `wiki/`.
21
+ - Everything else is under `.litgravity/`: goals `goals/<slug>.json`, the ledger `ledger/<conversation>.jsonl` (the hooks append tool events while a route is active; add your own note, evidence and decision lines), evidence `evidence/<slug>/`, handoffs `handoff/latest.md` (yours) and `handoff/auto.md` (saved by a hook when a turn ends), the list of notices already shown `shown/notices.jsonl` (hook-owned), wiki `wiki/`.
22
22
  - Route state belongs to the hooks and lives outside the workspace; tools cannot write it.
23
23
 
24
24
  ## Reader-facing replies
@@ -74,7 +74,7 @@ If reports do not arrive after the turn ends (a headless run that exits, a close
74
74
  5. **Run the round loop** exactly as `modes/core.md` defines it. Phase 1: dispatch every researcher in one turn, each with its own namespace and the least-authority `TypeName` from the map below; record crashes, silence and refusals as `failed` rows. Phase 2: a read-only Session Chair child returns the poster session as text and the Chair saves it. Phase 3: a read-only reviewer child challenges every claim and assigns `validated`, `challenged` or `overturned`; for metric claims a `qa-runner` child re-runs the evaluator first and the Chair hands its receipt to the reviewer. Phase 4: only `validated` findings enter Shared Knowledge, written by the Chair.
75
75
  6. **Check the budget, then convergence**, after every phase dispatch and every round (`references/convergence-guide.md`, `references/conference-protocol.md`). Before each `invoke_subagent` or follow-up, compare the counters with the approved budget; a dispatch that would exceed any counter does not happen, and the conference goes to synthesis with `BUDGET STOP` (the synthesizer's own dispatch is reserved inside the budget at the start gate). Convergence: best metric unchanged for two rounds, every reviewer score at 8 or above for two rounds, a counter or `time_budget` reached, or every researcher stalled at level two or worse. Announce ENDGAME in the briefs of the last round. Honor `pause_every` between rounds with `ask_question`.
76
76
  7. **Synthesize.** A read-only synthesizer child receives the paths to every poster session, review, log and TSV, combines complementary validated findings (more than naming a winner), and returns the text of `synthesis.md` and `final_report.md`. The Chair saves both, offers the worktree choices (merge, keep, delete) through `ask_question` with no default, appends `conference.completed`, and reports.
77
- 8. **Review and hand off.** Run `review-work` over changed files and conference worktrees. Offer `lit-recap` or `lit-handoff` for continuity. `ship` mode writes local draft files only.
77
+ 8. **Review and hand off.** Run `review-work` over changed files and conference worktrees. Offer `lit adhd recap` or `lit-handoff` for continuity. `ship` mode writes local draft files only.
78
78
  9. **Cancel or interruption.** Append one Chair checkpoint (`conference.cancelled` or `conference.paused` with the outstanding `report_id`s), tell every running child to stop with `send_message`, record which ones acknowledged, and stop. Resume goes through `modes/resume.md`: it validates the event order, TSV row counts, inbox contents, worktree state, staleness and the consumed budget, never replays a completed round, and moves partial artifacts to `interrupted/`.
79
79
 
80
80
  ### Persistence inside the budget
@@ -117,7 +117,7 @@ On any verdict, go to SYNTHESIS. When the next round is the last, put the ENDGAM
117
117
 
118
118
  **12. Worktree disposition** (worktree mode). Ask with `ask_question`, no default: merge `conference/best` into the original branch (the Chair prints the exact command; the user decides and nothing is pushed), keep the worktrees for inspection, or delete the worktrees and branches this conference created (listed first). Headless runs keep them and say so.
119
119
 
120
- **13. Completion.** Append `conference.completed` with links to the synthesis and the report, run `review-work` over changed files and worktrees, then report rounds run, iterations, children and model calls used, best validated result, dissent and the synthesis path. Offer `lit-recap` or `lit-handoff`.
120
+ **13. Completion.** Append `conference.completed` with links to the synthesis and the report, run `review-work` over changed files and worktrees, then report rounds run, iterations, children and model calls used, best validated result, dissent and the synthesis path. Offer `lit adhd recap` or `lit-handoff`.
121
121
 
122
122
  ## Turns, pauses and silence
123
123