@litfamily/litgravity 0.1.3 → 0.1.5

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.5 — 2026-10-31
4
+
5
+ - The plugin now carries the official LitFamily ignition icon (`plugin/assets/logo.svg`, wired as the manifest `logo`), so `agy plugin validate --json --strict` reports zero findings instead of the no-logo note.
6
+ - lit-adhd no longer tells this session to `lit continue` or `go` while other lanes work: the next-step chooser counts lanes first, so a held paused frame or a held own run offers no resume and no continue, and the session's own card shows the hold instead of the resume command. Answering a lane that waits on the user is still offered through the hold.
7
+ - User-scope installs now leave one owned rule file at `~/.gemini/config/rules/litgravity.md`, because agy reads that folder at every session start and a shared `GEMINI.md` block is refused on symlinked files. The rule stays short: the lit activation word, where plans and handoffs live, and the release freeze. An interactive install asks first and a No stores the rule off; `--yes` adds it, `--no-agent-file` skips one run, and `config agentFile off` removes it at any time. `doctor` reports it as `agent file`, and `uninstall` takes back exactly the file it wrote. `agent-file project --dir <path>` writes the matching project block into a repo's `AGENTS.md`.
8
+ - A `ci.yml` workflow runs the repo's gates on push and pull request to `main`: tests, version lockstep, legacy-token scan, plugin validation, fixture pinning, pack dry run, route listing and the no-release-command guard. The runner has no agy, so host-dependent tests skip with a reason and validation reports SKIP.
9
+ - lit-adhd no longer offers `go` to start a plan while other lanes work: another conversation of the workspace that is running or waits on you, or, under `HERDR_ENV=1`, a working or blocked herdr agent on this repo. The box says to answer the waiting lane or wait for them, and the last line says not to type `go` yet. When `go` arrives the hook re-checks the step and starts nothing if the run finished or is not this conversation's. The HANDOFF step now comes from the newest HANDOFF file, skips Next items already marked done, and ranks above an ended conversation.
10
+
11
+ ## 0.1.4 — 2026-10-28
12
+
13
+ - The interface check now starts its headless Chrome with a stand-in keychain, so macOS no longer pops up "keychain not found" while it runs.
14
+ - Releases are now built and published from GitHub Actions with npm provenance. The npm page shows a green check that links each version to this repository and the commit it was built from, so a copy published under another name cannot claim to be this one.
15
+
3
16
  ## 0.1.3 — 2026-10-28
4
17
 
5
18
  Plans:
package/README.md CHANGED
@@ -66,11 +66,13 @@ The installer shows every destination first. By default it copies the plugin to
66
66
  npx @litfamily/litgravity doctor
67
67
  ```
68
68
 
69
- `doctor` lists the installed copy, the validation result, the six hook events and a smoke run of each hook script, every skill and agent, every engine with its pre-warm command, the host programs the skills call, and the Python the engines will use. It ends with `LitGravity: ready` when nothing is broken.
69
+ `doctor` lists the installed copy, the validation result, the six hook events and a smoke run of each hook script, the global rule file, every skill and agent, every engine with its pre-warm command, the host programs the skills call, and the Python the engines will use. It ends with `LitGravity: ready` when nothing is broken.
70
+
71
+ Every user-scope install also leaves one owned rule file at `~/.gemini/config/rules/litgravity.md`, because agy reads that folder at every session start. The rule stays short on purpose: the lit activation word, where plans and handoffs live, and the release freeze, so the ground rules hold before any skill loads. An interactive install asks first and a No stores the rule off; `--yes` adds it, `--no-agent-file` skips it for one run, and `npx @litfamily/litgravity config agentFile off` removes it at any time. A repo gets the matching project conventions with `npx @litfamily/litgravity agent-file project --dir <path>`, which writes only the marked block into its `AGENTS.md`.
70
72
 
71
73
  <p align="center"><img src="./docs/assets/litgravity/install-doctor.webp" width="960" alt="Terminal capture. The install command ends with Status: Ready, and the doctor command ends with LitGravity: ready after thirty passing checks." /></p>
72
74
 
73
- Useful switches: `--dry-run` previews and writes nothing; `--yes` lets an agent or CI shell install (a shell without a terminal otherwise only previews); `--status-line` adds the optional LitGravity status line to agy's user settings (never on by default).
75
+ Useful switches: `--dry-run` previews and writes nothing; `--yes` lets an agent or CI shell install (a shell without a terminal otherwise only previews); `--no-agent-file` skips the global rule file for one run; `--status-line` adds the optional LitGravity status line to agy's user settings (never on by default).
74
76
 
75
77
  The status line is one row under the prompt, drawn in the LitFamily status-line style: the `[🔥LIT v…]` mark, then every segment in LitGravity's flame orange. It reads `model [effort] │ ctx [█▎░] 42%/1049k │ quota [▌░]28% ↻ 2h5m`, then the active lit route as a pink `🔥 LIT` chip with its clock, then where the route stands on its map (PIN, RED, GREEN, VERIFY, REVIEW, RECORD for the open criterion of litwork and lit-loop, read from its evidence files; interview, plan, work, review, done for planning and start-work, with the plan's rows), the lanes of a lit-team, and whatever agy also reports: cost, background tasks, the branch and the title. The context and quota gauges turn yellow at 70% and red at 90%. On a narrow terminal the extras go first and the route and the context gauge stay. `NO_COLOR` turns colour off and `LITGRAVITY_HUD_ASCII=1` keeps every glyph ASCII. If agy already shows another status line, the installer refuses to touch it; `install --status-line --replace-status-line` swaps it after saving the old value, and `uninstall` puts that value back.
76
78
 
@@ -170,7 +172,7 @@ While a route is active, every tool call lands in `.litgravity/ledger/<conversat
170
172
 
171
173
  ## Safety and uninstall
172
174
 
173
- - The installer writes only its own plugin folder, its data directory (`$XDG_DATA_HOME/litgravity`) and, when you ask, the status line key in agy's user settings, after a backup. It never reads agy's credential files.
175
+ - The installer writes only its own plugin folder, its data directory (`$XDG_DATA_HOME/litgravity`), the owned rule file in agy's global rules folder, and, when you ask, the status line key in agy's user settings, after a backup. It never reads agy's credential files. A rule file it did not write stops the install before the first write instead of being merged into.
174
176
  - A symlinked, foreign or edited destination stops the install before the first write, with the command to move it aside. `--dry-run` never mutates.
175
177
  - Hooks fail open: if one breaks, your conversation continues.
176
178
  - Engine caches live under `~/.local/share/litgravity/runtime/`. `uninstall` keeps them, so delete that folder to free the space.
@@ -181,6 +183,8 @@ Three commands cover the lifecycle, and every one previews with `--dry-run`:
181
183
  |---|---|
182
184
  | Install | `npx @litfamily/litgravity install` |
183
185
  | Update | `npx @litfamily/litgravity install` (validates, replaces in place) |
186
+ | Global rule off or back on | `npx @litfamily/litgravity config agentFile off` (or `on`) |
187
+ | Project block | `npx @litfamily/litgravity agent-file project --dir <path>` |
184
188
  | Refresh engines | `npx @litfamily/litgravity runtime install all` |
185
189
  | Check | `npx @litfamily/litgravity doctor` |
186
190
  | Remove | `npx @litfamily/litgravity uninstall --yes` |
package/README_ko-KR.md CHANGED
@@ -66,11 +66,13 @@ npx @litfamily/litgravity install
66
66
  npx @litfamily/litgravity doctor
67
67
  ```
68
68
 
69
- `doctor`는 설치된 사본, 검증 결과, 훅 이벤트 6개와 각 훅 스크립트의 실행 확인, 스킬과 에이전트 전체, 각 엔진과 그 사전 설치 명령, 스킬이 부르는 호스트 프로그램, 엔진이 쓸 Python을 보여 줍니다. 깨진 곳이 없으면 마지막 줄이 `LitGravity: ready`입니다.
69
+ `doctor`는 설치된 사본, 검증 결과, 훅 이벤트 6개와 각 훅 스크립트의 실행 확인, 전역 규칙 파일, 스킬과 에이전트 전체, 각 엔진과 그 사전 설치 명령, 스킬이 부르는 호스트 프로그램, 엔진이 쓸 Python을 보여 줍니다. 깨진 곳이 없으면 마지막 줄이 `LitGravity: ready`입니다.
70
+
71
+ 사용자 범위 설치는 `~/.gemini/config/rules/litgravity.md`에 LitGravity 전용 규칙 파일 하나를 남깁니다. agy가 매 세션 시작에 그 폴더를 읽기 때문입니다. 규칙은 일부러 짧습니다. lit 호출어, 계획과 핸드오프의 위치, 릴리스 동결만 담아서 어떤 스킬이 뜨기 전에 기본 규칙이 서도록 합니다. 대화형 설치는 먼저 묻고, No라고 답하면 규칙을 끈 채로 저장합니다. `--yes`는 규칙을 더하고, `--no-agent-file`은 한 번만 건너뛰고, `npx @litfamily/litgravity config agentFile off`는 언제든 규칙을 지웁니다. 저장소에는 `npx @litfamily/litgravity agent-file project --dir <경로>`로 맞는 프로젝트 관례를 넣습니다. `AGENTS.md`에 표시된 블록만 씁니다.
70
72
 
71
73
  <p align="center"><img src="./docs/assets/litgravity/install-doctor.webp" width="960" alt="터미널 갈무리. 설치 명령은 Status: Ready로 끝나고, doctor 명령은 서른 개의 통과 확인 뒤에 LitGravity: ready로 끝납니다." /></p>
72
74
 
73
- 자주 쓰는 옵션: `--dry-run`은 미리 보기만 하고 아무것도 쓰지 않습니다. `--yes`는 터미널이 붙지 않은 에이전트나 CI 셸에서 설치를 허용합니다(그런 셸에서는 기본으로 미리 보기만 합니다). `--status-line`은 agy 사용자 설정에 선택형 LitGravity 상태 표시줄을 추가합니다(기본값은 꺼짐).
75
+ 자주 쓰는 옵션: `--dry-run`은 미리 보기만 하고 아무것도 쓰지 않습니다. `--yes`는 터미널이 붙지 않은 에이전트나 CI 셸에서 설치를 허용합니다(그런 셸에서는 기본으로 미리 보기만 합니다). `--no-agent-file`은 전역 규칙 파일을 한 번만 건너뜁니다. `--status-line`은 agy 사용자 설정에 선택형 LitGravity 상태 표시줄을 추가합니다(기본값은 꺼짐).
74
76
 
75
77
  상태 표시줄은 프롬프트 아래 한 줄이고, LitFamily 상태 표시줄 모양을 따릅니다. `[🔥LIT v…]` 표시 뒤의 모든 칸은 LitGravity의 불꽃 주황 한 가지 색입니다. 순서는 `model [effort] │ ctx [█▎░] 42%/1049k │ quota [▌░]28% ↻ 2h5m`이고, 그 뒤에 지금 도는 lit 경로를 분홍 `🔥 LIT` 칩과 시계로, 그 경로가 지도에서 어디쯤인지를 보여 줍니다. litwork와 lit-loop는 열린 기준의 증거 파일을 읽어 PIN, RED, GREEN, VERIFY, REVIEW, RECORD 중 하나를, 계획과 start-work는 interview, plan, work, review, done 중 하나를 계획 행 수와 함께 보여 줍니다. lit-team은 레인을 보여 주고, agy가 함께 넘겨주는 비용, 백그라운드 작업, 브랜치, 제목이 이어집니다. 컨텍스트와 쿼터 게이지는 70%에서 노랑, 90%에서 빨강이 됩니다. 터미널이 좁으면 덧붙인 정보부터 빠지고 경로와 컨텍스트 게이지는 남습니다. `NO_COLOR`는 색을 끄고, `LITGRAVITY_HUD_ASCII=1`은 모든 기호를 ASCII로 바꿉니다. agy에 이미 다른 상태 표시줄이 있으면 설치기는 손대지 않습니다. `install --status-line --replace-status-line`을 쓰면 원래 값을 저장한 뒤 바꾸고, `uninstall`이 그 값을 되돌려 놓습니다.
76
78
 
@@ -170,7 +172,7 @@ Google Antigravity CLI용 LitFamily 플러그인인 LitGravity를 설치해 줘.
170
172
 
171
173
  ## 안전과 제거
172
174
 
173
- - 설치기는 자기 플러그인 폴더, 데이터 디렉터리(`$XDG_DATA_HOME/litgravity`), 그리고 요청했을 때 agy 사용자 설정의 상태 표시줄 키만 씁니다. 설정 파일은 먼저 백업합니다. agy의 인증 파일은 읽지 않습니다.
175
+ - 설치기는 자기 플러그인 폴더, 데이터 디렉터리(`$XDG_DATA_HOME/litgravity`), agy 전역 규칙 폴더의 전용 규칙 파일, 그리고 요청했을 때 agy 사용자 설정의 상태 표시줄 키만 씁니다. 설정 파일은 먼저 백업합니다. agy의 인증 파일은 읽지 않습니다. 설치기가 쓰지 않은 규칙 파일은 합치지 않고 첫 쓰기 전에 설치를 멈춥니다.
174
176
  - 심볼릭 링크이거나, 남의 파일이거나, 설치 뒤 수정된 대상은 첫 쓰기 전에 설치를 멈추고, 옮기는 명령을 알려 줍니다. `--dry-run`은 아무것도 바꾸지 않습니다.
175
177
  - 훅이 하나 깨져도 대화는 계속됩니다.
176
178
  - 엔진 캐시는 `~/.local/share/litgravity/runtime/`에 있습니다. `uninstall`은 캐시를 남기므로, 공간이 필요하면 그 폴더를 지우세요.
@@ -181,6 +183,8 @@ Google Antigravity CLI용 LitFamily 플러그인인 LitGravity를 설치해 줘.
181
183
  |---|---|
182
184
  | 설치 | `npx @litfamily/litgravity install` |
183
185
  | 업데이트 | `npx @litfamily/litgravity install` (검증하고 그 자리에서 교체) |
186
+ | 전역 규칙 끄기/켜기 | `npx @litfamily/litgravity config agentFile off` (또는 `on`) |
187
+ | 프로젝트 블록 | `npx @litfamily/litgravity agent-file project --dir <경로>` |
184
188
  | 엔진 새로 받기 | `npx @litfamily/litgravity runtime install all` |
185
189
  | 확인 | `npx @litfamily/litgravity doctor` |
186
190
  | 제거 | `npx @litfamily/litgravity uninstall --yes` |
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createInterface } from 'node:readline/promises';
3
3
  import { install } from '../lib/install.mjs';
4
+ import { runAgentFileConfig, runAgentFileProject } from '../lib/agent-file.mjs';
4
5
  import { uninstall } from '../lib/uninstall.mjs';
5
6
  import { doctor } from '../lib/doctor.mjs';
6
7
  import { models } from '../lib/models.mjs';
@@ -21,12 +22,15 @@ Commands
21
22
  status Short version of doctor plus an update check
22
23
  models List the models and efforts your agy offers
23
24
  list Every skill with the words that reach it, its purpose and its engine (--json for tools)
25
+ config config agentFile on|off: keep or remove the LitGravity rule in agy's global rules folder
26
+ agent-file agent-file project [--dir <path>]: write the LitGravity block into a repo's AGENTS.md
24
27
  runtime status [name] | install <name|all>: the pinned engine runtimes, cached under the LitGravity data dir
25
28
  uninstall Remove the copies this installer wrote (both scopes unless --scope is given)
26
29
  help This text
27
30
 
28
31
  Options
29
32
  --dry-run Show every destination and command; write nothing
33
+ --no-agent-file install: skip the global rule file for this run (stored setting untouched)
30
34
  --yes, -y Allow writes from a shell without a terminal (agents, CI)
31
35
  --scope <s> user (default): ~/.gemini/config/plugins/litgravity, or project: ./.agents/plugins/litgravity
32
36
  --status-line install: also set the LitGravity status line in agy's user settings (opt-in, user scope only)
@@ -42,6 +46,7 @@ function parse(argv) {
42
46
  for (let i = 0; i < argv.length; i += 1) {
43
47
  const a = argv[i];
44
48
  if (a === '--dry-run') flags.dryRun = true;
49
+ else if (a === '--no-agent-file') flags.noAgentFile = true;
45
50
  else if (a === '--yes' || a === '-y') flags.yes = true;
46
51
  else if (a === '--json') flags.json = true;
47
52
  else if (a === '--offline') flags.offline = true;
@@ -95,6 +100,10 @@ async function main() {
95
100
  return models({ env, flags, print });
96
101
  case 'list':
97
102
  return list({ flags, print });
103
+ case 'config':
104
+ return runAgentFileConfig({ env, args, cwd, print });
105
+ case 'agent-file':
106
+ return runAgentFileProject({ env, args, cwd, flags, print });
98
107
  case 'runtime':
99
108
  return runtime({ env, flags, args, print });
100
109
  case 'status': {
@@ -0,0 +1,450 @@
1
+ // The LitFamily ground rule for the Antigravity CLI: one owned file in agy's
2
+ // global rules folder (`~/.gemini/config/rules/litgravity.md`), which agy's own
3
+ // changelog says the agent reads, plus a marker block for a project's AGENTS.md.
4
+ // A shared GEMINI.md block is not offered: on this machine it is a symlink, and
5
+ // a symlinked file is always refused. Only the bytes between a block's markers
6
+ // are ever written; the rest of the user's file stays byte for byte.
7
+ import { createHash } from 'node:crypto';
8
+ import { lstatSync, readFileSync, rmSync } from 'node:fs';
9
+ import { dirname, join, resolve } from 'node:path';
10
+ import { packageVersion } from './bundle.mjs';
11
+ import { assertSafeWritePath } from './guard.mjs';
12
+ import { paths } from './paths.mjs';
13
+ import { writeFileAtomic } from './safe-write.mjs';
14
+
15
+ export const AGENT_FILE_ID = 'litgravity';
16
+ export const AGENT_FILE_MODES = Object.freeze(['on', 'off']);
17
+ // The global rule file loads on every turn of every session, so it stays small.
18
+ export const AGENT_FILE_MAX_BYTES = 1200;
19
+
20
+ const GLOBAL_BODY = `---
21
+ trigger: model_decision
22
+ description: "LitGravity ground rules for the Antigravity CLI: lit activation, plans, handoffs and release safety."
23
+ ---
24
+
25
+ # LitGravity ground rules
26
+
27
+ These rules apply in an Antigravity CLI session that uses LitGravity's lit workflows
28
+ (lit-plan, start-work, lit-loop, review-work, lit-adhd, litresearch).
29
+
30
+ - 'lit' at the start of a prompt is LitGravity's activation word.
31
+ - Plans live in 'plans/', the session handoff in 'HANDOFF.md', run state in '.litgravity/'. Read them before resuming work in a repo.
32
+ - Never push, publish, tag or bump a version without the user's explicit yes for that action.
33
+ - Call work done only after its tests pass and the changed surface was checked for real.
34
+ - In a new repo, 'lit init' maps the repo and leaves short 'AGENTS.md' files with these conventions.
35
+ - Turn this rule off with 'npx @litfamily/litgravity config agentFile off'.
36
+ `;
37
+
38
+ const PROJECT_BODY = `## LitGravity project conventions
39
+
40
+ This repo is worked with LitGravity's lit workflows (lit-plan, start-work, lit-loop, review-work).
41
+
42
+ - Plans live in 'plans/', the session handoff in 'HANDOFF.md', run state in '.litgravity/' (keep it out of commits). Read the handoff and the active plan before resuming.
43
+ - Never push, publish, tag or bump a version without the user's explicit yes for that action.
44
+ - Pair every behaviour change with a test that failed first, and check the changed surface for real before calling it done.
45
+ `;
46
+
47
+ /** The shipped text: `global` for the rules-folder file, `project` for a repo's AGENTS.md. */
48
+ export function agentFileBody(kind = 'global') {
49
+ if (kind === 'global') return GLOBAL_BODY;
50
+ if (kind === 'project') return PROJECT_BODY;
51
+ throw new Error(`unknown agent file kind: ${kind}`);
52
+ }
53
+
54
+ export const ruleFileMarker = (fileVersion) => `<!-- litfamily:litgravity:rule v=${fileVersion} -->`;
55
+
56
+ /** The full owned-file text: our marker line, then the global body. */
57
+ export const ruleFileText = (fileVersion) => `${ruleFileMarker(fileVersion)}\n${agentFileBody('global')}`;
58
+
59
+ export class RuleBlockError extends Error {}
60
+
61
+ const startPrefix = (id) => `<!-- litfamily:${id}:start`;
62
+ const endMarker = (id) => `<!-- litfamily:${id}:end -->`;
63
+ const eolOf = (text) => (text.includes('\r\n') ? '\r\n' : '\n');
64
+ const START_LINE = /^<!-- litfamily:[^:\s]+:start v=(\S+)((?: [a-z]+=[0-9a-f]*)*) -->/u;
65
+
66
+ const occurrences = (text, needle) => {
67
+ const found = [];
68
+ for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + needle.length)) found.push(at);
69
+ return found;
70
+ };
71
+
72
+ // The block's span `[start, end)`, end just past the end marker, and its recorded attributes; or null.
73
+ const locate = (text, id) => {
74
+ const starts = occurrences(text, startPrefix(id));
75
+ const ends = occurrences(text, endMarker(id));
76
+ if (starts.length === 0 && ends.length === 0) return null;
77
+ if (starts.length !== 1 || ends.length !== 1 || ends[0] < starts[0]) {
78
+ throw new RuleBlockError(`malformed LitFamily ${id} block: expected one start and one end marker`);
79
+ }
80
+ const head = START_LINE.exec(text.slice(starts[0]));
81
+ if (!head) throw new RuleBlockError(`malformed LitFamily ${id} block: unreadable start marker`);
82
+ const attrs = Object.fromEntries(head[2].trim().split(' ').filter(Boolean).map((pair) => pair.split('=')));
83
+ return {
84
+ start: starts[0],
85
+ end: ends[0] + endMarker(id).length,
86
+ version: head[1],
87
+ pre: attrs.pre ? Buffer.from(attrs.pre, 'hex').toString('utf8') : '',
88
+ created: attrs.new === '1',
89
+ };
90
+ };
91
+
92
+ const render = ({ id, version: blockVersion, body }, eol, { pre, created }) => [
93
+ `${startPrefix(id)} v=${blockVersion}${pre ? ` pre=${Buffer.from(pre, 'utf8').toString('hex')}` : ''}${created ? ' new=1' : ''} -->`,
94
+ ...String(body).replace(/\r?\n$/u, '').split(/\r?\n/u),
95
+ endMarker(id),
96
+ ].join(eol);
97
+
98
+ /** `{state: "absent" | "present" | "malformed", version, created}` for block `id` in `text`. */
99
+ export function inspectRuleBlock(text, id) {
100
+ let span;
101
+ try {
102
+ span = locate(text, id);
103
+ } catch {
104
+ return { state: 'malformed', version: null, created: false };
105
+ }
106
+ return span ? { state: 'present', version: span.version, created: span.created } : { state: 'absent', version: null, created: false };
107
+ }
108
+
109
+ /** Adds or replaces block `id`; `created` marks a file made for the block. Returns `{text, changed}`. */
110
+ export function upsertRuleBlock(text, block, { created = false } = {}) {
111
+ const eol = eolOf(text);
112
+ const span = locate(text, block.id);
113
+ if (span) {
114
+ const rendered = render(block, eol, span);
115
+ const next = `${text.slice(0, span.start)}${rendered}${text.slice(span.end)}`;
116
+ return { text: next, changed: next !== text };
117
+ }
118
+ const pre = text === '' ? '' : `${text.endsWith('\n') ? '' : eol}${eol}`;
119
+ return { text: `${text}${pre}${render(block, eol, { pre, created })}${eol}`, changed: true };
120
+ }
121
+
122
+ /** Removes block `id`, the line ending after it and what was added before it. */
123
+ export function removeRuleBlock(text, id) {
124
+ const span = locate(text, id);
125
+ if (!span) return { text, changed: false, created: false };
126
+ let before = text.slice(0, span.start);
127
+ let after = text.slice(span.end);
128
+ const eol = after.startsWith('\r\n') ? '\r\n' : after.startsWith('\n') ? '\n' : '';
129
+ after = after.slice(eol.length);
130
+ if (span.pre && before.endsWith(span.pre)) before = before.slice(0, -span.pre.length);
131
+ return { text: `${before}${after}`, changed: true, created: span.created };
132
+ }
133
+
134
+ // "missing", "file", "symlink" or "other", without following a link.
135
+ function entryKind(path) {
136
+ try {
137
+ const stats = lstatSync(path);
138
+ return stats.isSymbolicLink() ? 'symlink' : stats.isFile() ? 'file' : 'other';
139
+ } catch (error) {
140
+ if (error.code === 'ENOENT') return 'missing';
141
+ throw error;
142
+ }
143
+ }
144
+
145
+ // The file's text, or null when it is not UTF-8 (a UTF-16 file from Notepad, Latin-1): rewriting
146
+ // those would corrupt the user's bytes outside our marker.
147
+ function readUtf8(path) {
148
+ const bytes = readFileSync(path);
149
+ if (bytes.includes(0) || (bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff)) return null;
150
+ try {
151
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
152
+ } catch {
153
+ return null;
154
+ }
155
+ }
156
+
157
+ const sha256 = (text) => createHash('sha256').update(text, 'utf8').digest('hex');
158
+
159
+ const hasRuleMarker = (text) => /^<!-- litfamily:litgravity:rule v=\S+ -->$/.test(text.split('\n', 1)[0].replace(/\r$/, ''));
160
+
161
+ /**
162
+ * `present v=<x>` (current), `stale v=<x>` (an older install's file), `absent`, `malformed`,
163
+ * or `symlink` / `not-file` / `not-utf8` for a file LitGravity will not write.
164
+ */
165
+ export function ruleFileState({ path, version: fileVersion }) {
166
+ const kind = entryKind(path);
167
+ if (kind === 'missing') return 'absent';
168
+ if (kind === 'symlink') return 'symlink';
169
+ if (kind === 'other') return 'not-file';
170
+ const text = readUtf8(path);
171
+ if (text === null) return 'not-utf8';
172
+ if (!hasRuleMarker(text)) return 'malformed';
173
+ const held = /^<!-- litfamily:litgravity:rule v=(\S+) -->$/.exec(text.split('\n', 1)[0].replace(/\r$/, ''))[1];
174
+ return `${held === fileVersion ? 'present' : 'stale'} v=${held}`;
175
+ }
176
+
177
+ /** The stored on/off setting, beside any other keys in our data-dir config. `LITGRAVITY_AGENT_FILE` wins. */
178
+ export function readAgentFileMode({ env = process.env, configFile } = {}) {
179
+ const override = String(env.LITGRAVITY_AGENT_FILE ?? '').trim().toLowerCase();
180
+ if (AGENT_FILE_MODES.includes(override)) return override;
181
+ try {
182
+ const parsed = JSON.parse(readFileSync(configFile, 'utf8'));
183
+ const stored = parsed && typeof parsed === 'object' ? parsed.agentFile : undefined;
184
+ return AGENT_FILE_MODES.includes(stored) ? stored : 'on';
185
+ } catch {
186
+ return 'on';
187
+ }
188
+ }
189
+
190
+ export function writeAgentFileMode(configFile, mode) {
191
+ if (!AGENT_FILE_MODES.includes(mode)) throw new Error(`agentFile takes one of: ${AGENT_FILE_MODES.join(', ')}`);
192
+ let current = {};
193
+ try {
194
+ current = JSON.parse(readFileSync(configFile, 'utf8'));
195
+ } catch (error) {
196
+ if (error.code !== 'ENOENT') throw new Error(`${configFile} is not valid JSON (${error.message}); refusing to overwrite config.json`);
197
+ }
198
+ if (!current || typeof current !== 'object' || Array.isArray(current)) {
199
+ throw new Error(`${configFile} is not a JSON object; refusing to overwrite config.json`);
200
+ }
201
+ writeFileAtomic(configFile, `${JSON.stringify({ ...current, agentFile: mode })}\n`);
202
+ return mode;
203
+ }
204
+
205
+ // The record of the rule file we wrote: path, content hash and version. Uninstall removes the file
206
+ // only while it still matches this record, so a hand-edited file is kept.
207
+ function readRecord(p) {
208
+ try {
209
+ const rec = JSON.parse(readFileSync(p.agentFileRecord, 'utf8'));
210
+ if (rec && rec.path === p.geminiRulesFile && typeof rec.sha256 === 'string') return rec;
211
+ return null;
212
+ } catch {
213
+ return null;
214
+ }
215
+ }
216
+
217
+ function writeRecord(p, content, fileVersion) {
218
+ writeFileAtomic(p.agentFileRecord, `${JSON.stringify({ path: p.geminiRulesFile, sha256: sha256(content), version: fileVersion, updatedAt: new Date().toISOString() })}\n`);
219
+ }
220
+
221
+ function clearRecord(p) {
222
+ rmSync(p.agentFileRecord, { force: true });
223
+ }
224
+
225
+ const moveAsideHint = (target) => {
226
+ const saved = `${target}.saved-${new Date().toISOString().slice(0, 10)}`;
227
+ return `move it aside: mv "${target}" "${saved}" — then run install again`;
228
+ };
229
+
230
+ /**
231
+ * Decides before any write what the install should do about the global rule file:
232
+ * `create` / `update` / `unchanged` / `off` (stored off: our file goes) / `skip`
233
+ * (project scope or a per-run skip: left alone) / `refuse` (foreign, edited or
234
+ * unreadable: fail closed with the way through in `detail`).
235
+ */
236
+ export function planRuleFile({ p, version: fileVersion, env = process.env, flags = {}, scope = 'user' }) {
237
+ if (scope !== 'user') return { action: 'skip', detail: 'skipped: project scope installs only the plugin; the global rule belongs to a user-scope install' };
238
+ if (flags.noAgentFile) return { action: 'skip', detail: 'skipped (--no-agent-file)' };
239
+ if (readAgentFileMode({ env, configFile: p.litgravityConfig }) === 'off') {
240
+ return { action: 'off', detail: `off (turn it back on with \`npx @litfamily/litgravity config agentFile on\`)` };
241
+ }
242
+ const target = p.geminiRulesFile;
243
+ const kind = entryKind(target);
244
+ if (kind === 'symlink') return { action: 'refuse', state: 'symlinked', detail: `${target} is a symbolic link; LitGravity never writes through it. Remove the link itself and run install again` };
245
+ if (kind === 'other') return { action: 'refuse', state: 'not-file', detail: `${target} is not a regular file; ${moveAsideHint(target)}` };
246
+ if (kind === 'missing') return { action: 'create', detail: `create ${target}` };
247
+ const text = readUtf8(target);
248
+ if (text === null) return { action: 'refuse', state: 'not-utf8', detail: `${target} is not UTF-8; ${moveAsideHint(target)}` };
249
+ if (text === ruleFileText(fileVersion)) return { action: 'unchanged', detail: `unchanged ${target}` };
250
+ const record = readRecord(p);
251
+ if (record && record.sha256 === sha256(text)) return { action: 'update', detail: `update ${target} (stale v=${record.version ?? '?'})` };
252
+ if (hasRuleMarker(text)) return { action: 'refuse', state: 'modified', detail: `${target} changed since install; ${moveAsideHint(target)}` };
253
+ return { action: 'refuse', state: 'foreign', detail: `${target} holds text LitGravity did not write; ${moveAsideHint(target)}` };
254
+ }
255
+
256
+ /** Runs a `create` / `update` / `off` plan from `planRuleFile`. Returns `{status, path, ...}`. */
257
+ export function applyRuleFile({ p, version: fileVersion, action, env = process.env, flags = {}, scope = 'user' }) {
258
+ const target = p.geminiRulesFile;
259
+ if (target !== p.geminiRulesFile) throw new Error(`refused: agent file target is not the rules folder file (${target})`);
260
+ if (action === 'skip' || action === 'unchanged') return { status: action === 'skip' ? 'skipped' : 'unchanged', path: target };
261
+ if (action === 'off') {
262
+ const removed = removeRuleFile({ p });
263
+ return { status: removed.status === 'removed' ? 'removed' : 'absent', path: target };
264
+ }
265
+ if (action !== 'create' && action !== 'update') throw new Error(`unknown agent file action: ${action}`);
266
+ // Re-check under the write: a foreign file that landed after the plan still fails closed.
267
+ const fresh = planRuleFile({ p, version: fileVersion, env, flags, scope });
268
+ if (fresh.action !== action) return { status: `refused-${fresh.state ?? 'changed'}`, path: target, detail: fresh.detail };
269
+ assertSafeWritePath(target);
270
+ const text = ruleFileText(fileVersion);
271
+ writeFileAtomic(target, text);
272
+ writeRecord(p, text, fileVersion);
273
+ return { status: action === 'create' ? 'created' : 'updated', path: target };
274
+ }
275
+
276
+ /** True when an uninstall would remove the rule file (it still matches our install record). */
277
+ export function willRemoveRuleFile(p) {
278
+ if (entryKind(p.geminiRulesFile) === 'missing') return false;
279
+ try {
280
+ const text = readUtf8(p.geminiRulesFile);
281
+ const record = readRecord(p);
282
+ return text !== null && record !== null && record.sha256 === sha256(text);
283
+ } catch {
284
+ return false;
285
+ }
286
+ }
287
+
288
+ /**
289
+ * Removes the rule file when it still matches our install record. An edited or foreign file
290
+ * stays, unless `discardModified` says otherwise for a file carrying our marker.
291
+ */
292
+ export function removeRuleFile({ p, discardModified = false }) {
293
+ const target = p.geminiRulesFile;
294
+ if (entryKind(target) === 'missing') {
295
+ clearRecord(p);
296
+ return { status: 'absent', path: target };
297
+ }
298
+ let text = null;
299
+ try {
300
+ text = readUtf8(target);
301
+ } catch {
302
+ return { status: 'kept', path: target, detail: `${target} cannot be read; left alone` };
303
+ }
304
+ const record = readRecord(p);
305
+ if (text !== null && record && record.sha256 === sha256(text)) {
306
+ rmSync(assertSafeWritePath(target), { force: true });
307
+ clearRecord(p);
308
+ return { status: 'removed', path: target };
309
+ }
310
+ if (text !== null && hasRuleMarker(text) && discardModified) {
311
+ rmSync(assertSafeWritePath(target), { force: true });
312
+ clearRecord(p);
313
+ return { status: 'removed', path: target, discarded: true };
314
+ }
315
+ if (text !== null && hasRuleMarker(text)) {
316
+ return { status: 'kept', path: target, detail: `${target} changed since install; add --discard-modified to remove it anyway` };
317
+ }
318
+ return { status: 'kept', path: target, detail: `${target} holds text LitGravity did not write; left alone` };
319
+ }
320
+
321
+ /**
322
+ * `present v=<x>` (current), `stale v=<x>`, `absent`, `malformed`, or `symlink` /
323
+ * `not-file` / `not-utf8` for a project file LitGravity will not write.
324
+ */
325
+ export function projectBlockState({ path, id = AGENT_FILE_ID, version: fileVersion }) {
326
+ const kind = entryKind(path);
327
+ if (kind === 'missing') return 'absent';
328
+ if (kind === 'symlink') return 'symlink';
329
+ if (kind === 'other') return 'not-file';
330
+ const text = readUtf8(path);
331
+ if (text === null) return 'not-utf8';
332
+ const found = inspectRuleBlock(text, id);
333
+ if (found.state !== 'present') return found.state;
334
+ return `${found.version === fileVersion ? 'present' : 'stale'} v=${found.version}`;
335
+ }
336
+
337
+ /**
338
+ * Installs or removes the project block in `path`. Returns `{status, path, preview?}` with status
339
+ * created | updated | unchanged | removed | absent | dry-run | refused-symlink | refused-not-file |
340
+ * refused-not-utf8 | refused-malformed | refused-no-dir | refused-io. No backup copy is left
341
+ * beside the tracked file, and a missing folder is never created.
342
+ */
343
+ export function applyProjectBlock({ path, id = AGENT_FILE_ID, version: fileVersion, body, action = 'install', dryRun = false }) {
344
+ try {
345
+ const kind = entryKind(path);
346
+ if (kind === 'symlink') return { status: 'refused-symlink', path };
347
+ if (kind === 'other') return { status: 'refused-not-file', path };
348
+ if (kind === 'missing') {
349
+ let parentOk = false;
350
+ try {
351
+ parentOk = lstatSync(dirname(path)).isDirectory();
352
+ } catch {
353
+ parentOk = false;
354
+ }
355
+ if (!parentOk) return { status: 'refused-no-dir', path };
356
+ }
357
+ const text = kind === 'file' ? readUtf8(path) : '';
358
+ if (text === null) return { status: 'refused-not-utf8', path };
359
+ let next;
360
+ try {
361
+ next = action === 'uninstall'
362
+ ? removeRuleBlock(text, id)
363
+ : upsertRuleBlock(text, { id, version: fileVersion, body }, { created: kind === 'missing' });
364
+ } catch (error) {
365
+ if (error instanceof RuleBlockError) return { status: 'refused-malformed', path };
366
+ throw error;
367
+ }
368
+ if (!next.changed) return { status: action === 'uninstall' ? 'absent' : 'unchanged', path };
369
+ if (dryRun) return { status: 'dry-run', path, preview: next.text };
370
+ assertSafeWritePath(path);
371
+ writeFileAtomic(path, next.text);
372
+ return { status: kind === 'file' ? (action === 'uninstall' ? 'removed' : 'updated') : (action === 'uninstall' ? 'removed' : 'created'), path };
373
+ } catch (error) {
374
+ return { status: 'refused-io', path, error: error?.code ?? error?.message };
375
+ }
376
+ }
377
+
378
+ export const agentFileLine = (result) => `AGENT_FILE: ${result.status} ${result.path}`;
379
+
380
+ /** `litgravity config agentFile on|off`: stores the mode; off removes our file, on writes it back. */
381
+ export async function runAgentFileConfig({ env = process.env, args = [], cwd = process.cwd(), print = console.log }) {
382
+ const [key, value] = args;
383
+ if (key !== 'agentFile' || (value !== 'on' && value !== 'off')) {
384
+ print('Usage: litgravity config agentFile on|off');
385
+ return 64;
386
+ }
387
+ const p = paths(env, cwd);
388
+ if (value === 'off') {
389
+ const removed = removeRuleFile({ p });
390
+ writeAgentFileMode(p.litgravityConfig, 'off');
391
+ print(`AGENT_FILE: ${removed.status} ${removed.path}${removed.detail ? ` (${removed.detail})` : ''}`);
392
+ return 0;
393
+ }
394
+ writeAgentFileMode(p.litgravityConfig, 'on');
395
+ const plan = planRuleFile({ p, version: packageVersion(), env, flags: {}, scope: 'user' });
396
+ if (plan.action === 'refuse') {
397
+ print(`FAIL agent file ${plan.state}: ${plan.detail}`);
398
+ return 1;
399
+ }
400
+ const applied = applyRuleFile({ p, version: packageVersion(), action: plan.action, env, flags: {}, scope: 'user' });
401
+ print(agentFileLine(applied));
402
+ return applied.status.startsWith('refused') ? 1 : 0;
403
+ }
404
+
405
+ /**
406
+ * `litgravity agent-file project [--dir <path>]`: the project block into the repo's AGENTS.md.
407
+ * An existing file is kept byte for byte outside the markers; a missing folder is never created.
408
+ */
409
+ export async function runAgentFileProject({ env = process.env, args = [], cwd = process.cwd(), flags = {}, print = console.log }) {
410
+ const [sub, ...rest] = args;
411
+ if (sub === '--help' || sub === '-h') {
412
+ print('Usage: litgravity agent-file project [--dir <path>]');
413
+ return 0;
414
+ }
415
+ if (sub !== 'project') {
416
+ print('Usage: litgravity agent-file project [--dir <path>]');
417
+ return 64;
418
+ }
419
+ let dir = cwd;
420
+ for (let i = 0; i < rest.length; i += 1) {
421
+ if (rest[i] === '--dir' && rest[i + 1]) {
422
+ dir = resolve(cwd, rest[i + 1]);
423
+ i += 1;
424
+ continue;
425
+ }
426
+ print(`Unknown agent-file option: ${rest[i]}`);
427
+ return 64;
428
+ }
429
+ let isDirectory = false;
430
+ try {
431
+ isDirectory = lstatSync(dir).isDirectory();
432
+ } catch {
433
+ // Missing: reported below, never created.
434
+ }
435
+ if (!isDirectory) {
436
+ print(`agent-file: ${dir} is not an existing folder`);
437
+ return 64;
438
+ }
439
+ const fileVersion = packageVersion();
440
+ const result = applyProjectBlock({
441
+ path: join(dir, 'AGENTS.md'),
442
+ id: AGENT_FILE_ID,
443
+ version: fileVersion,
444
+ body: agentFileBody('project'),
445
+ action: 'install',
446
+ dryRun: flags.dryRun === true,
447
+ });
448
+ print(agentFileLine(result));
449
+ return result.status.startsWith('refused') ? 1 : 0;
450
+ }
package/lib/doctor.mjs CHANGED
@@ -9,6 +9,7 @@ import { pickPython } from '../plugin/lib/python-pick.mjs';
9
9
  import { describeSpawn, firstLine } from '../plugin/lib/host-exec.mjs';
10
10
  import { HOST_TOOLS, hostToolOk } from './host-tools.mjs';
11
11
  import { isOurs, replacedStatusLine, stripBom } from './statusline.mjs';
12
+ import { readAgentFileMode, ruleFileState } from './agent-file.mjs';
12
13
  import { checkUpdate } from './update-check.mjs';
13
14
  import { SKILL_ROUTES } from '../plugin/hooks/lib/routes.mjs';
14
15
 
@@ -120,6 +121,17 @@ export async function doctor({ env = process.env, flags = {}, cwd = process.cwd(
120
121
  add(existsSync(join(dest, 'rules', 'AGENTS.md')) ? 'PASS' : 'FAIL', 'rules', existsSync(join(dest, 'rules', 'AGENTS.md')) ? 'rules/AGENTS.md present' : 'rules/AGENTS.md is missing');
121
122
  break;
122
123
  }
124
+ const agentMode = readAgentFileMode({ env, configFile: p.litgravityConfig });
125
+ if (agentMode === 'off') {
126
+ add('INFO', 'agent file', 'off (turn it back on with `npx @litfamily/litgravity config agentFile on`)');
127
+ } else {
128
+ const agentState = ruleFileState({ path: p.geminiRulesFile, version });
129
+ if (agentState.startsWith('present')) add('PASS', 'agent file', `${agentState} (${p.geminiRulesFile})`);
130
+ else if (agentState.startsWith('stale')) add('WARN', 'agent file', `${agentState}; this package is ${version}`, 'npx @litfamily/litgravity install --yes');
131
+ else if (agentState === 'absent') {
132
+ add(found.length ? 'WARN' : 'INFO', 'agent file', `not set (a user-scope install adds ${p.geminiRulesFile})`, found.length ? 'npx @litfamily/litgravity install --yes' : undefined);
133
+ } else add('WARN', 'agent file', `${agentState}: ${p.geminiRulesFile} holds text LitGravity did not write`, 'move it aside, then run: npx @litfamily/litgravity install --yes');
134
+ }
123
135
  add(orphans.length ? 'FAIL' : 'PASS', 'routes', orphans.length ? `skills with no route: ${orphans.join(', ')}` : `every shipped skill has a route (${routeIds.size} routes)`);
124
136
  if (pending.length) add('INFO', 'pending skills', `${pending.length} routed skills are not shipped yet: ${pending.join(', ')}`);
125
137
 
package/lib/install.mjs CHANGED
@@ -3,6 +3,7 @@ import { writeFileAtomic, realExistingAncestor } from './safe-write.mjs';
3
3
  import { agyVersion, validatePlugin } from './agy.mjs';
4
4
  import { destState, stageTo, packageVersion, PLUGIN_DIR, readManifest } from './bundle.mjs';
5
5
  import { assertSafeWritePath } from './guard.mjs';
6
+ import { applyRuleFile, planRuleFile, writeAgentFileMode } from './agent-file.mjs';
6
7
  import { planStatusLine, applyStatusLine } from './statusline.mjs';
7
8
  import { firstLine } from '../plugin/lib/host-exec.mjs';
8
9
 
@@ -63,12 +64,14 @@ export async function install({ env = process.env, flags = {}, interactive = fal
63
64
  }
64
65
  }
65
66
 
67
+ let agentPlan = planRuleFile({ p, version, env, flags, scope });
66
68
  const other = destination(p, scope === 'user' ? 'project' : 'user');
67
69
  const otherState = destState(other);
68
70
  print('');
69
71
  print('Plan');
70
72
  print(` scope ${scope}${scope === 'project' ? ` (${cwd})` : ' (every project on this machine)'}`);
71
73
  print(` plugin ${dest}${st.state === 'owned' ? ` (replaces LitGravity ${st.version})` : ''}`);
74
+ print(` agent file ${agentPlan.detail}`);
72
75
  print(` receipt ${p.receipt}`);
73
76
  print(` validate agy plugin validate on the packaged plugin, then on the installed copy`);
74
77
  if (hud) print(` status line ${hud.action === 'already' ? 'already set' : `${hud.detail} (backup in ${p.backups})`}`);
@@ -87,10 +90,22 @@ export async function install({ env = process.env, flags = {}, interactive = fal
87
90
  print('No files written: this shell has no terminal. Rerun with --yes to install.');
88
91
  return 0;
89
92
  }
93
+ if (agentPlan.action === 'refuse') {
94
+ print(`FAIL agent file ${agentPlan.state}: ${agentPlan.detail}`);
95
+ print('No files written.');
96
+ return 1;
97
+ }
90
98
  if (interactive && !flags.yes && ask && !(await ask(`Install LitGravity ${version} at ${scope} scope? [y/N] `))) {
91
99
  print('Nothing installed.');
92
100
  return 0;
93
101
  }
102
+ if (interactive && !flags.yes && ask && (agentPlan.action === 'create' || agentPlan.action === 'update')) {
103
+ if (!(await ask(`Add the LitGravity global rule for the Antigravity CLI at ${p.geminiRulesFile}? [y/N] `))) {
104
+ writeAgentFileMode(p.litgravityConfig, 'off');
105
+ agentPlan = { action: 'off', detail: 'off (declined; stored, so later installs skip it)' };
106
+ print('Agent file off: stored `off`, so later installs skip the rule file.');
107
+ }
108
+ }
94
109
 
95
110
  const source = validatePlugin(env, PLUGIN_DIR);
96
111
  if (!source.ok) {
@@ -113,6 +128,16 @@ export async function install({ env = process.env, flags = {}, interactive = fal
113
128
  return 1;
114
129
  }
115
130
  if (hud && ['add', 'replace'].includes(hud.action)) written.push(...applyStatusLine(p, dest, stamp()));
131
+ if (agentPlan.action === 'create' || agentPlan.action === 'update' || agentPlan.action === 'off') {
132
+ const applied = applyRuleFile({ p, version, action: agentPlan.action, env, flags, scope });
133
+ if (applied.status.startsWith('refused')) {
134
+ print(`FAIL agent file ${applied.status}: ${applied.detail}`);
135
+ print('The plugin copy above was left in place; move the rule file aside and run install again.');
136
+ return 1;
137
+ }
138
+ print(`agent file: ${applied.status} ${applied.path}`);
139
+ if (applied.status === 'created' || applied.status === 'updated') written.push(applied.path);
140
+ }
116
141
 
117
142
  writeFileAtomic(p.receipt, `${JSON.stringify({
118
143
  product: 'litgravity', version, scope, installedAt: new Date().toISOString(), host: `agy ${host}`, files: count, written,
package/lib/paths.mjs CHANGED
@@ -18,6 +18,12 @@ export function paths(env = process.env, cwd = process.cwd(), { platform = proce
18
18
  // user scope is the global customization root.
19
19
  userPlugin: join(home, '.gemini', 'config', 'plugins', 'litgravity'),
20
20
  projectPlugin: join(cwd, '.agents', 'plugins', 'litgravity'),
21
+ // The owned LitGravity rule file, read from agy's global rules folder. The rules folder is the
22
+ // cleaner route over a block in the shared GEMINI.md; the installer writes only this one file.
23
+ geminiRulesFile: join(home, '.gemini', 'config', 'rules', 'litgravity.md'),
24
+ // Install records for the rule file, and our own on/off setting.
25
+ agentFileRecord: join(data, 'agent-file.json'),
26
+ litgravityConfig: join(data, 'config.json'),
21
27
  // The status line is configured only here, at user level.
22
28
  agySettings: join(home, '.gemini', 'antigravity-cli', 'settings.json'),
23
29
  };
package/lib/uninstall.mjs CHANGED
@@ -2,6 +2,7 @@ import { rmSync, existsSync, readFileSync } from 'node:fs';
2
2
  import { paths, destination } from './paths.mjs';
3
3
  import { destState } from './bundle.mjs';
4
4
  import { assertSafeWritePath } from './guard.mjs';
5
+ import { removeRuleFile, willRemoveRuleFile } from './agent-file.mjs';
5
6
  import { removeStatusLine, isOurs, replacedStatusLine, stripBom } from './statusline.mjs';
6
7
 
7
8
  function ourStatusLine(p) {
@@ -34,6 +35,7 @@ export async function uninstall({ env = process.env, flags = {}, interactive = f
34
35
  }
35
36
  const hud = scopes.includes('user') && ourStatusLine(p);
36
37
  const previous = hud ? replacedStatusLine(p) : null;
38
+ if (scopes.includes('user')) print(` agent file remove the LitGravity rule file ${p.geminiRulesFile} when it is still the one we wrote`);
37
39
  if (hud) print(` status line ${previous ? `put back the status line LitGravity replaced (${String(previous.command ?? 'custom').slice(0, 60)})` : 'remove the LitGravity entry'} in ${p.agySettings}`);
38
40
  print(` kept ${p.backups} and ${p.receipt}`);
39
41
  if (flags.dryRun) {
@@ -44,7 +46,8 @@ export async function uninstall({ env = process.env, flags = {}, interactive = f
44
46
  print('Nothing removed: this shell has no terminal. Rerun with --yes.');
45
47
  return 0;
46
48
  }
47
- if (interactive && !flags.yes && ask && (plan.some((y) => y.remove) || hud) && !(await ask('Remove these LitGravity files? [y/N] '))) {
49
+ const agentRemove = scopes.includes('user') && willRemoveRuleFile(p);
50
+ if (interactive && !flags.yes && ask && (plan.some((y) => y.remove) || hud || agentRemove) && !(await ask('Remove these LitGravity files? [y/N] '))) {
48
51
  print('Nothing removed.');
49
52
  return 0;
50
53
  }
@@ -52,6 +55,11 @@ export async function uninstall({ env = process.env, flags = {}, interactive = f
52
55
  rmSync(assertSafeWritePath(x.dest), { recursive: true, force: true });
53
56
  print(`Removed ${x.dest}.`);
54
57
  }
58
+ if (scopes.includes('user')) {
59
+ const rule = removeRuleFile({ p, discardModified: flags.discardModified === true });
60
+ if (rule.status === 'removed') print(`agent file: removed ${rule.path}${rule.discarded ? ' (discarding edits)' : ''}.`);
61
+ else if (rule.status === 'kept') print(`agent file: kept ${rule.path} (${rule.detail}).`);
62
+ }
55
63
  const removed = hud ? removeStatusLine(p) : false;
56
64
  if (removed === 'restored') print('Restored the previous status line.');
57
65
  else if (removed) print('Removed the LitGravity status line.');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litfamily/litgravity",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Installer for LitGravity: skills, hooks and agents that help Google's Antigravity CLI (agy) plan, build, check and hand off work.",
5
5
  "keywords": [
6
6
  "antigravity",
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="512" height="512"
2
+ viewBox="0 0 512 512" role="img" aria-labelledby="title description">
3
+ <title id="title">LITFAMILY — Ignition icon</title>
4
+ <desc id="description">Original geometric LitFamily ignition symbol, bespoke angular lettering, and ordered vector halftone. Ember orange, signal lime, warm white, and carbon navy. All lettering is outlined; no raster images or external resources.</desc>
5
+ <rect x="0" y="0" width="512" height="512" fill="#080D14" /><g transform="translate(44 36) scale(.69)"><g id="family-symbol" transform="translate(20 30) scale(1)"><path d="M0 42H76V438H195L151 510H0Z" fill="#FF6337" /><path d="M133 220V142L271 0H311V77Z" fill="#F2EFDF" /><path d="M101 323L247 180V270L101 413Z" fill="#F2EFDF" /><path d="M270 99H571V121L527 165H204Z" fill="#FF6337" /><rect x="518" y="119" width="17" height="17" fill="#080D14" /><circle cx="417" cy="30" r="49" fill="#D7F75B" /><rect x="263" y="190" width="65" height="71" fill="#D7F75B" /><rect x="334" y="190" width="190" height="71" fill="#F2EFDF" /><rect x="334" y="295" width="72" height="215" fill="#F2EFDF" /><path d="M479 293L529 335H494L479 351Z" fill="#F2EFDF" /><rect x="-11" y="145" width="98" height="4" fill="#080D14" /><rect x="-17" y="145" width="10" height="4" fill="#D7F75B" /><rect x="94" y="145" width="17" height="4" fill="#D7F75B" /><rect x="114" y="145" width="10" height="4" fill="#D7F75B" /><rect x="353" y="460" width="72" height="3" fill="#080D14" /><rect x="413" y="460" width="41" height="3" fill="#FF6337" /><rect x="458" y="460" width="9" height="3" fill="#FF6337" /></g></g><path d="M52 448L460 448" fill="none" stroke="#354139" stroke-width="1" /><g aria-label="LF"><path d="M130 0V730H220V82H550V0Z" fill="#D7F75B" transform="translate(52.000 483) scale(0.020000 -0.020000)"/><path d="M95 0V730H525V648H183V406H499V324H185V0Z" fill="#D7F75B" transform="translate(66.000 483) scale(0.020000 -0.020000)"/></g><rect x="437" y="466" width="23" height="6" fill="#FF6337" /></svg>
@@ -64,6 +64,12 @@ const WORDS = {
64
64
  handoff: ({ file, next }) => `From ${file}: ${next}`,
65
65
  start: () => 'No conversation or plan in this window: say what to start',
66
66
  },
67
+ hold: {
68
+ wait: ({ lanes, plan }) => `Wait for ${lanes} ${lanes === 1 ? 'lane' : 'lanes'} to finish, then start ${plan}`,
69
+ waitLanes: ({ lanes }) => `Wait for ${lanes} ${lanes === 1 ? 'lane' : 'lanes'} to finish`,
70
+ answerPane: ({ pane }) => `Answer the lane waiting on you in pane ${pane}`,
71
+ },
72
+ holdGo: 'Do not type `go` until they finish.',
67
73
  goLine: (say) => `Type **\`${say}\`** to continue.`,
68
74
  noGo: 'Nothing runs on its own here: open that conversation, or say what to do.',
69
75
  unknownSources: (list) => `Not read: ${list}.`,
@@ -125,6 +131,12 @@ const WORDS = {
125
131
  handoff: ({ file, next }) => `${file}에서: ${next}`,
126
132
  start: () => '이 기간에 대화·계획이 없습니다. 시작할 일을 말해 주세요',
127
133
  },
134
+ hold: {
135
+ wait: ({ lanes, plan }) => `작업 중인 레인 ${lanes}개가 끝나면 ${plan} 시작`,
136
+ waitLanes: ({ lanes }) => `작업 중인 레인 ${lanes}개가 끝날 때까지 기다리기`,
137
+ answerPane: ({ pane }) => `${pane} 창에서 나를 기다리는 레인에 답하기`,
138
+ },
139
+ holdGo: '지금은 `go`는 입력하지 마세요.',
128
140
  goLine: (say) => `**\`${say}\`** 라고 입력하면 이어갑니다.`,
129
141
  noGo: '저절로 실행되는 단계는 아닙니다. 그 대화를 열거나 할 일을 말해 주세요.',
130
142
  unknownSources: (list) => `읽지 못함: ${list}.`,
@@ -198,6 +210,9 @@ const doneLine = (session, w) => {
198
210
  const nextOf = (session, data, w) => {
199
211
  if (session.status === 'waiting-on-user') {
200
212
  const paused = framesOf(session, data).find((f) => f.status === 'paused');
213
+ // This session's own card never offers its resume command while lanes work: the hold answers
214
+ // a lane that waits on the user, else waits for them.
215
+ if (paused && session.self && data.next?.held) return holdStep(data, data.next.held, w);
201
216
  if (paused) return w.resume(plain(paused.skill), plain(paused.stage));
202
217
  return w.answer(lastQuestion(session.result));
203
218
  }
@@ -243,7 +258,8 @@ const endedTable = (sessions, now, w) => {
243
258
 
244
259
  // When nothing can run on `go`, the box still recommends one step from what was read: a conversation
245
260
  // that waits on the user, a paused route, an open plan item (a live conversation's folder first), the
246
- // newest other active conversation, the newest ended one. It is shown, never recorded for `go`.
261
+ // newest other active conversation, the newest HANDOFF's open Next item, the newest ended one. It is
262
+ // shown, never recorded for `go`.
247
263
  const suggestion = (data, w) => {
248
264
  const sessions = data.sessions ?? [];
249
265
  const where = (session) => bare(placeOf(session));
@@ -261,13 +277,24 @@ const suggestion = (data, w) => {
261
277
  if (plan) return w.suggest.plan({ plan: plan.local ? plan.plan : `${basename(String(plan.worktree))}/${plan.plan}`, item: clipToWidth(bare(plan.current), 60) });
262
278
  const active = sessions.find((s) => s.status === 'active' && !s.self);
263
279
  if (active) return w.suggest.check({ id8: active.id8, goal: goal(active), where: where(active), doing: actionOf(active, bare) });
264
- const ended = sessions.find((s) => s.status === 'ended' && !s.self);
265
- if (ended) return w.suggest.pickUp({ id8: ended.id8, goal: goal(ended), where: where(ended) });
280
+ // The newest handoff's first open Next item: below every live signal, above an ended conversation.
266
281
  const handoff = (data.handoffs ?? []).find((h) => h.local && h.next);
267
282
  if (handoff) return w.suggest.handoff({ file: bare(handoff.file), next: bare(handoff.next) });
283
+ const ended = sessions.find((s) => s.status === 'ended' && !s.self);
284
+ if (ended) return w.suggest.pickUp({ id8: ended.id8, goal: goal(ended), where: where(ended) });
268
285
  return w.suggest.start();
269
286
  };
270
287
 
288
+ // A step held while other lanes work: answer the one waiting on the user, else wait for them.
289
+ // A held plan names the plan to start after; a held resume or continue only waits.
290
+ const holdStep = (data, held, w) => {
291
+ const waiting = (data.sessions ?? []).find((s) => s.status === 'waiting-on-user' && !s.self);
292
+ if (waiting) return suggestion(data, w);
293
+ if (data.lanes?.waitingPane) return w.hold.answerPane({ pane: data.lanes.waitingPane });
294
+ if (held.plan) return w.hold.wait({ lanes: held.lanes, plan: bare(held.plan) });
295
+ return w.hold.waitLanes({ lanes: held.lanes });
296
+ };
297
+
271
298
  const ROADMAP_COMMITS = 5;
272
299
  const roadmapLines = (data, w) => {
273
300
  const lines = [];
@@ -328,7 +355,10 @@ export const renderBrief = (data, { lang = 'en', width = 72, now = Date.parse(da
328
355
  const sessions = data.sessions ?? [];
329
356
  const summary = data.summary ?? { sessions: sessions.length, waitingOnUser: 0, active: 0 };
330
357
  const runs = data.next?.kind && data.next.kind !== 'none';
331
- const step = runs ? w.step[data.next.kind](Object.fromEntries(Object.entries(data.next.target ?? {}).map(([k, v]) => [k, bare(v)]))) : bare(suggestion(data, w));
358
+ const held = !runs && data.next?.held ? data.next.held : null;
359
+ const step = runs
360
+ ? w.step[data.next.kind](Object.fromEntries(Object.entries(data.next.target ?? {}).map(([k, v]) => [k, bare(v)])))
361
+ : bare(held ? holdStep(data, held, w) : suggestion(data, w));
332
362
  const out = [`## 🧭 ${[w.sessions(summary.sessions), w.waiting(summary.waitingOnUser), w.active(summary.active)].join(' · ')}`];
333
363
  out.push(...opener(data, step, w));
334
364
  out.push(`*${w.window(data.scope?.since ?? '7d', (data.scope?.worktrees ?? []).length || 1)}*`);
@@ -355,7 +385,7 @@ export const renderBrief = (data, { lang = 'en', width = 72, now = Date.parse(da
355
385
  if (runs && data.next.command) body.push(clipToWidth(data.next.command, width - 4));
356
386
  if (runs && data.next.say) body.push(`${w.type}: ${data.next.say}`);
357
387
  out.push('', box(w.recommended, body));
358
- out.push('', runs && data.next.say ? w.goLine(data.next.say) : w.noGo);
388
+ out.push('', held ? w.holdGo : runs && data.next.say ? w.goLine(data.next.say) : w.noGo);
359
389
 
360
390
  const unread = Object.entries(data.sources ?? {}).filter(([, v]) => v === 'unknown').map(([k]) => k);
361
391
  const tail = [unread.length ? w.unknownSources(unread.join(', ')) : null, data.roadmap?.plansSkipped ? w.plansSkipped(data.roadmap.plansSkipped) : null, data.budget?.exhausted ? w.older : null].filter(Boolean);
@@ -3,9 +3,9 @@
3
3
  // A source that is not there reads `unknown`; nothing is inferred.
4
4
 
5
5
  import { execFileSync } from 'node:child_process';
6
- import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdirSync, statSync } from 'node:fs';
6
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
7
7
  import { homedir } from 'node:os';
8
- import { basename, dirname, join, resolve } from 'node:path';
8
+ import { basename, dirname, join, resolve, sep } from 'node:path';
9
9
 
10
10
  import { planRows } from '../continuation.mjs';
11
11
  import { sessionPath, stateRoot } from '../common.mjs';
@@ -22,6 +22,8 @@ const DEFAULT_SINCE = '7d';
22
22
  const DEFAULT_MAX = 12;
23
23
  const NAME_MAX = 90;
24
24
  const PLAN_LIMIT = 8;
25
+ const HERDR_TIMEOUT_MS = 2000;
26
+ const PANE = /^[A-Za-z0-9._:-]{1,64}$/u;
25
27
 
26
28
  export const parseSince = (text) => {
27
29
  const match = /^(\d{1,4})([dhm])$/u.exec(String(text ?? ''));
@@ -116,28 +118,101 @@ const litgoalOf = (root, budget, redact) => {
116
118
  };
117
119
  };
118
120
 
119
- // The first item under a handoff's `## Next` heading, without its list marker, or null.
121
+ // An item already finished: ticked, struck through, marked ✅ or ✓, or carrying the word DONE or SHIPPED.
122
+ const isDoneItem = (item) => /^\[[xX]\]|^~~/u.test(item) || /[✅✓]/u.test(item) || /\b(?:DONE|SHIPPED)\b/u.test(item);
123
+
124
+ // The first open item under a handoff's `## Next` heading, without its list marker, or null.
120
125
  const nextOfHandoff = (text) => {
121
126
  const lines = text.split('\n');
122
127
  const at = lines.findIndex((l) => /^#{2,3}\s+Next\b/iu.test(l));
123
128
  if (at === -1) return null;
124
129
  for (const line of lines.slice(at + 1)) {
125
130
  if (/^#{1,6} /u.test(line)) return null;
126
- const item = line.replace(/^\s*(?:[-*+]|\d+[.)])\s+/u, '').replace(/^\s*-\s*\[[ xX]\]\s*/u, '').trim();
127
- if (item) return item;
131
+ const item = line.replace(/^\s*(?:[-*+]|\d+[.)])\s+/u, '').trim();
132
+ if (!item || isDoneItem(item)) continue;
133
+ return item.replace(/^\[ \]\s*/u, '').trim() || null;
128
134
  }
129
135
  return null;
130
136
  };
131
137
 
138
+ // Newest file first, so a dated handoff written today wins over an old root HANDOFF.md.
132
139
  const handoffsOf = (root, budget, redact, local) => (entries(root) ?? [])
133
140
  .filter((e) => e.isFile() && /^HANDOFF.*\.md$/u.test(e.name))
134
141
  .map((e) => {
142
+ let mtime = 0;
143
+ try { mtime = statSync(join(root, e.name)).mtimeMs; } catch { /* unreadable: oldest */ }
144
+ return { e, mtime };
145
+ })
146
+ .sort((a, b) => b.mtime - a.mtime || a.e.name.localeCompare(b.e.name))
147
+ .map(({ e }) => {
135
148
  const text = readSmallFile(join(root, e.name), budget) ?? '';
136
149
  const headings = text.split('\n').slice(0, 40).filter((l) => /^#{1,3} /u.test(l)).map((l) => clipToWidth(redact(l), 100));
137
150
  const next = nextOfHandoff(text);
138
151
  return { worktree: redact(root), file: e.name, headings, local, next: next ? clipToWidth(redact(next), 100) : null };
139
152
  });
140
153
 
154
+ const realOf = (path) => {
155
+ try { return realpathSync(path); } catch { return resolve(path); }
156
+ };
157
+ // Compares both spellings, so a herdr cwd under /var matches a root under /private/var, even for a path not yet made.
158
+ const insideAny = (path, roots) => {
159
+ if (typeof path !== 'string' || !path) return false;
160
+ const forms = new Set([resolve(path), realOf(path)]);
161
+ return roots.some((r) => [...forms].some((p) => p === r || p.startsWith(r.endsWith(sep) ? r : `${r}${sep}`)));
162
+ };
163
+
164
+ // herdr's agents that work on this repo, read only under HERDR_ENV=1: working or blocked (blocked waits on its user),
165
+ // in this herdr workspace or with a cwd inside one of the roots, never this pane. Any failure reads `unknown`.
166
+ const herdrLanes = (env, roots, sessionId, exec) => {
167
+ if (env.HERDR_ENV !== '1') return null;
168
+ let agents;
169
+ try {
170
+ agents = JSON.parse(exec('herdr', ['agent', 'list'], { timeout: HERDR_TIMEOUT_MS }))?.result?.agents;
171
+ } catch {
172
+ return { status: 'unknown', agents: [] };
173
+ }
174
+ if (!Array.isArray(agents)) return { status: 'unknown', agents: [] };
175
+ const realRoots = [...new Set(roots.flatMap((r) => [resolve(r), realOf(r)]))];
176
+ const ownPane = typeof env.HERDR_PANE_ID === 'string' ? env.HERDR_PANE_ID : null;
177
+ const list = agents.filter((a) => a && typeof a === 'object'
178
+ && ['working', 'blocked'].includes(a.agent_status)
179
+ && !(ownPane && a.pane_id === ownPane)
180
+ && !(sessionId && a.agent_session?.value === sessionId)
181
+ && ((typeof env.HERDR_WORKSPACE_ID === 'string' && env.HERDR_WORKSPACE_ID && a.workspace_id === env.HERDR_WORKSPACE_ID)
182
+ || insideAny(a.cwd, realRoots) || insideAny(a.foreground_cwd, realRoots)))
183
+ .map((a) => ({
184
+ pane: typeof a.pane_id === 'string' && PANE.test(a.pane_id) ? a.pane_id : null,
185
+ session: typeof a.agent_session?.value === 'string' ? a.agent_session.value : null,
186
+ waiting: a.agent_status === 'blocked',
187
+ }));
188
+ return { status: 'ok', agents: list };
189
+ };
190
+
191
+ // Other conversations of this workspace that work or wait on the user, plus herdr agents on this repo; one lane seen
192
+ // both ways (same conversation id or same pane) counts once.
193
+ const lanesOf = (sessions, liveRecords, herdr, sessionId) => {
194
+ const lanes = new Map();
195
+ for (const s of sessions) {
196
+ if (s.sessionId === sessionId || !['active', 'waiting-on-user'].includes(s.status)) continue;
197
+ lanes.set(s.sessionId, { pane: null, waiting: s.status === 'waiting-on-user' });
198
+ }
199
+ for (const r of liveRecords) {
200
+ if (r.id === sessionId) continue;
201
+ const known = lanes.get(r.id);
202
+ if (known) known.pane = known.pane ?? r.pane ?? null;
203
+ else if (r.state === 'alive') lanes.set(r.id, { pane: r.pane ?? null, waiting: false });
204
+ }
205
+ const panes = new Set([...lanes.values()].map((l) => l.pane).filter(Boolean));
206
+ let waitingPane = null;
207
+ for (const a of herdr?.agents ?? []) {
208
+ if ((a.session && lanes.has(a.session)) || (a.pane && panes.has(a.pane))) continue;
209
+ lanes.set(`herdr:${a.pane ?? lanes.size}`, { pane: a.pane, waiting: a.waiting });
210
+ if (a.waiting && a.pane && !waitingPane) waitingPane = a.pane;
211
+ }
212
+ const all = [...lanes.values()];
213
+ return { count: all.length, waiting: all.filter((l) => l.waiting).length, waitingPane };
214
+ };
215
+
141
216
  const branchOf = (root, exec) => {
142
217
  try {
143
218
  return exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: root, timeout: GIT_TIMEOUT_MS }).trim() || null;
@@ -228,7 +303,8 @@ export const collectRewind = ({
228
303
  const handoffs = roots.flatMap((r) => handoffsOf(r, budget, redact, resolve(r) === start));
229
304
  const stackLists = stateDirs.map(({ dir }) => stacksOf(dir, budget, redact));
230
305
  const workflows = stackLists.every((v) => v === null) ? null : stackLists.flatMap((v) => v ?? []);
231
- const liveness = new Map(stateDirs.flatMap(({ dir }) => listLive(dir, now).map((r) => [r.id, r.state])));
306
+ const liveRecords = stateDirs.flatMap(({ dir }) => listLive(dir, now));
307
+ const liveness = new Map(liveRecords.map((r) => [r.id, r.state]));
232
308
  // A conversation whose start-work frame names a plan with every row ticked is done.
233
309
  const finishedPlans = new Set((plans ?? []).filter((p) => p.finished).map((p) => `${p.worktree}\u0000${p.plan}`));
234
310
  const finishedIn = (id, root) => (workflows ?? []).some((f) => f.sessionId === id && f.ref?.plan && finishedPlans.has(`${redact(root)}\u0000${f.ref.plan}`));
@@ -274,6 +350,8 @@ export const collectRewind = ({
274
350
  const orderedPlans = (plans ?? []).filter(recent).sort((a, b) => Number(b.local) - Number(a.local) || (b.mtime ?? 0) - (a.mtime ?? 0));
275
351
  const shownPlans = orderedPlans.slice(0, PLAN_LIMIT);
276
352
  const localGoals = (litgoal ?? []).filter((g) => g.local);
353
+ const herdr = herdrLanes(env, roots, sessionId, exec);
354
+ const lanes = lanesOf(sessions, liveRecords, herdr, sessionId);
277
355
  const roadmapItems = [...orderedPlans.filter((p) => p.local).map((p) => p.progress), ...localGoals.map((g) => g.progress)];
278
356
  const data = {
279
357
  version: 1,
@@ -286,6 +364,7 @@ export const collectRewind = ({
286
364
  handoffs: handoffs.length ? 'ok' : 'unknown',
287
365
  git: known(commits),
288
366
  workflowStack: known(workflows),
367
+ ...(herdr ? { herdr: herdr.status } : {}),
289
368
  },
290
369
  budget: { bytesRead: budget.used, limit: budget.limit, exhausted: budget.exhausted },
291
370
  summary: {
@@ -293,6 +372,7 @@ export const collectRewind = ({
293
372
  waitingOnUser: sessions.filter((s) => s.status === 'waiting-on-user').length,
294
373
  active: sessions.filter((s) => s.status === 'active').length,
295
374
  },
375
+ lanes,
296
376
  sessions: sessions.map(({ cwd: _cwd, lastMs: _lastMs, root: _root, sessionId: id, ...rest }) => ({ ...rest, self: Boolean(sessionId) && id === sessionId })),
297
377
  roadmap: {
298
378
  plans: shownPlans,
@@ -1,29 +1,35 @@
1
1
  // The one next step a lit-adhd brief offers, chosen by fixed priority over the collected records,
2
2
  // and the small record `go` later reads back within 30 minutes:
3
- // 1. this session's paused spine frame -> resume-frame (`lit continue`)
4
- // 2. this session's active start-work -> continue-work
5
- // 3. a single open plan with no work -> start-plan (`lit start plans/<plan>.md`)
6
- // 4. otherwise -> none
7
- // A start-work approval is typed as `lit approve` when the run asks for it; agy keeps no record of a
8
- // pending one for a brief to offer.
3
+ // 1. this session's paused spine frame -> resume-frame (`lit continue`, never while lanes work)
4
+ // 2. this session's active start-work -> continue-work (`go`, never while lanes work)
5
+ // 3. a single open plan with no work -> start-plan (held with the plan while lanes work)
6
+ // 4. lanes work here -> none, held (answer who waits, else wait for them)
7
+ // 5. otherwise -> none
8
+ // While another lane works, neither this session's paused frame nor its own run is offered: answering
9
+ // a lane that waits on the user is still offered, through the hold. Another conversation's run is
10
+ // never offered. PreInvocation re-checks the recorded step when `go` arrives. A start-work approval
11
+ // is typed as `lit approve` when the run asks for it; agy keeps no record of a pending one for a
12
+ // brief to offer.
9
13
 
10
14
  import { closeSync, constants, fstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
11
15
  import { dirname, join } from 'node:path';
12
16
  import { safeId } from '../common.mjs';
13
17
 
14
18
  export const chooseNextStep = (data, sessionId) => {
19
+ const lanes = data.lanes?.count ?? 0;
15
20
  const ownStack = data.workflows.find((f) => f.sessionId === sessionId && f.role === 'spine' && f.status === 'paused');
16
- if (sessionId && ownStack) {
21
+ if (sessionId && ownStack && !lanes) {
17
22
  return { kind: 'resume-frame', target: { skill: ownStack.skill, stage: ownStack.stage, progress: ownStack.progress.gauge ?? `${ownStack.progress.done ?? 0} done` }, say: 'lit continue' };
18
23
  }
19
24
  const own = data.startWork.find((w) => w.status === 'active' && sessionId && w.sessionId === sessionId);
20
- if (own) return { kind: 'continue-work', target: { plan: own.plan }, say: 'go' };
25
+ if (own && !lanes) return { kind: 'continue-work', target: { plan: own.plan }, say: 'go' };
21
26
  const running = data.startWork.some((w) => ['active', 'paused'].includes(w.status));
22
27
  const open = data.roadmap.plans.filter((p) => p.local && p.progress.total !== null && p.progress.done < p.progress.total);
23
28
  if (!running && open.length === 1) {
29
+ if (lanes > 0) return { kind: 'none', target: null, held: { lanes, plan: open[0].plan } };
24
30
  return { kind: 'start-plan', target: { plan: open[0].plan }, say: 'go', command: `lit start ${open[0].plan}` };
25
31
  }
26
- return { kind: 'none', target: null };
32
+ return lanes > 0 ? { kind: 'none', target: null, held: { lanes } } : { kind: 'none', target: null };
27
33
  };
28
34
 
29
35
  export const nextStepPath = (root, conversationId) => {
@@ -1,8 +1,11 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
1
4
  import { run, inject, readSession, writeSession, appendLedger, workspaceOf, safeId, stateRoot } from './lib/common.mjs';
2
5
  import { detectRoute } from './lib/routes.mjs';
3
6
  import { decide, resumablePlan, activation, continueNote, resumeNote } from './lib/reentry.mjs';
4
7
  import { lastUserRequest } from './lib/transcript.mjs';
5
- import { PAUSE_WORD } from './lib/continuation.mjs';
8
+ import { PAUSE_WORD, planRows } from './lib/continuation.mjs';
6
9
  import { saveSnapshot } from './lib/boundary.mjs';
7
10
  import { MOTION_ROUTE, armMotionTurn } from './lib/motion.mjs';
8
11
  import { applyStackEvent, readStack, writeStack } from './lib/workflow-stack.mjs';
@@ -43,6 +46,37 @@ function goActivation(step, conversationId) {
43
46
  }
44
47
  }
45
48
 
49
+ // The brief may be up to 30 minutes old: `go` acts only when its step still holds for this conversation. The stack
50
+ // file is this conversation's own, so a run found there is one it owns.
51
+ function stillHolds(step, workspace, conversationId) {
52
+ const frames = readStack(workspace, conversationId).frames;
53
+ switch (step.kind) {
54
+ case 'resume-frame':
55
+ return frames.some((f) => f.role === 'spine' && f.status === 'paused' && (!step.target?.skill || f.skill === step.target.skill));
56
+ case 'continue-work':
57
+ return frames.some((f) => f.skill === 'start-work' && f.status === 'active' && (!step.target?.plan || f.ref?.plan === step.target.plan));
58
+ case 'start-plan': {
59
+ const plan = step.target?.plan;
60
+ if (typeof plan !== 'string' || !/^plans\/[^/\\]+\.md$/u.test(plan)) return false;
61
+ if (frames.some((f) => f.skill === 'start-work')) return false;
62
+ try {
63
+ return planRows(readFileSync(join(workspace, plan), 'utf8')).some((r) => !r.done);
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+ default:
69
+ return false;
70
+ }
71
+ }
72
+
73
+ function staleGoText(step) {
74
+ const what = step.kind === 'start-plan' ? `start ${step.target?.plan ?? 'the plan'}`
75
+ : step.kind === 'continue-work' ? 'continue this conversation\'s start-work run'
76
+ : `resume the paused ${step.target?.skill ?? 'route'}`;
77
+ return `LitGravity: the user typed \`go\`, but the step the brief offered (${what}) no longer holds: the run finished, moved on or is not this conversation's. Start nothing. Say so in one line and suggest \`lit adhd\` for a fresh brief.`;
78
+ }
79
+
46
80
  function approveText(word) {
47
81
  if (word === 'approve') return 'LitGravity: the user typed `lit approve`. This is the typed approval for start-work. Proceed with the work.';
48
82
  return 'LitGravity: the user typed `lit deny`. This is a denial. Stop the work and explain what was denied.';
@@ -64,6 +98,10 @@ run((payload) => {
64
98
  // `go` / `ㄱㄱ` / `진행`: consume the next-step record the collector wrote within 30 minutes.
65
99
  if (isGoPrompt(request.text)) {
66
100
  const step = takeNextStep(root, safeId(payload.conversationId));
101
+ if (step && step.kind !== 'none' && !stillHolds(step, workspace, payload.conversationId)) {
102
+ appendLedger(payload, { kind: 'route', route: null, how: 'go-stale', step: step.kind });
103
+ return inject(staleGoText(step));
104
+ }
67
105
  if (step) {
68
106
  const text = goActivation(step, payload.conversationId);
69
107
  if (text) {
@@ -2,5 +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.3"
5
+ "version": "0.1.5",
6
+ "logo": "assets/logo.svg"
6
7
  }
@@ -166,7 +166,8 @@ export class ChromeSession {
166
166
  const args = [
167
167
  "--headless=new", "--remote-debugging-port=0", `--user-data-dir=${this.profile}`,
168
168
  "--no-first-run", "--no-default-browser-check", "--disable-gpu", "--hide-scrollbars",
169
- "--disable-extensions", "--disable-background-networking", "--mute-audio", "about:blank",
169
+ "--disable-extensions", "--disable-background-networking", "--mute-audio", "--use-mock-keychain",
170
+ "--password-store=basic", "about:blank",
170
171
  ];
171
172
  if (process.env.LITGRAVITY_CHROME_NO_SANDBOX === "1") args.unshift("--no-sandbox");
172
173
  this.child = spawn(this.command, args, { stdio: ["ignore", "ignore", "pipe"] });
@@ -53,7 +53,7 @@ The collector draws the brief in Markdown (`plugin/hooks/lib/rewind/brief.mjs`),
53
53
  2. **Live cards, grouped by folder and branch.** Conversations that wait on the user, are active, idle or done get a `### 🌿 branch · folder` heading per group and one quoted card each: a status badge (🟠 waiting on you, 🟢 active, 💤 idle, ✅ done; see `references/status-taxonomy.md`) with why it waits, its `id8`, its route, how long ago it moved and `this conversation` / `이 대화`; the goal in bold; a real gauge with the next items, or the known facts after ⏳ (how long it ran, its last ask); ✅ what was written and committed, or before any write the tools it used most; ▶ what is next for it (answer its question, resume its paused route, its route stage, or its last tool call by base name, never a command line).
54
54
  3. **Ended conversations, one table row each** (`### ⚪ Ended · N`: id, where, goal, ago, done), at most eight and a count of the rest. Each row fits on one line at 120 columns: the age is its largest unit and done is a commit count or a file count.
55
55
  4. **Roadmap timeline** (`### 🗺️`, with this folder's gauge): ✓ commits with their dates and branch, ▶ the current item of each open plan changed inside the window, here or in another folder (with its folder name), ○ the items after it, then litgoal objectives. Plans are held to the window here too. Unfilled plan scaffolds and files without task rows are skipped and counted on the last line; another folder's finished plans and objectives are left out.
56
- 5. **One recommended next step** in a box (an untagged code fence), then one line. A step that runs on `go` shows its command and the word to type, and the line says "Type `go` to continue." When nothing runs on `go`, the box still recommends a real step from the records, in this order: a conversation waiting on the user, a paused route, an open plan item (a live conversation's folder first), the newest other active conversation, the newest ended one, the first item under `## Next` in this folder's `HANDOFF*.md`; the line then says nothing runs on its own.
56
+ 5. **One recommended next step** in a box (an untagged code fence), then one line. A step that runs on `go` shows its command and the word to type, and the line says "Type `go` to continue." When nothing runs on `go`, the box still recommends a real step from the records, in this order: a conversation waiting on the user, a paused route, an open plan item (a live conversation's folder first), the newest other active conversation, the first open item under `## Next` in this folder's newest `HANDOFF*.md` (items marked ✅, ✓, `[x]`, ~~struck~~, DONE or SHIPPED are skipped), the newest ended one; the line then says nothing runs on its own. When other lanes work, a plan start is held: the box says to answer the lane waiting on you or to wait for the N lanes, and the line says "Do not type `go` until they finish." (Korean: "지금은 `go`는 입력하지 마세요.").
57
57
 
58
58
  **Progress gauges (D9).** A gauge appears only when the collector provides both done and total as real integers: `[▉▉▉░░] 3/5`. When the total is unknown, the card shows known facts in words instead (`⏳ 2h 19m of work · last ask: …`). Never show `?/?`, `[???]`, `k/?` or any question-mark placeholder. The gauge is the progress; do not compute progress from prose like "about halfway".
59
59
 
@@ -124,12 +124,14 @@ Sessions waiting on the user come first, then active, idle, done and ended ones,
124
124
  1. This session's own paused spine frame: resume it. Say `lit continue`.
125
125
  2. A start-work paused at a boundary: show what it wants to reach. Say `lit approve` or `lit deny`. This is never automatic.
126
126
  3. This session's own active start-work: keep going. Say `go`.
127
- 4. Exactly one open plan in this worktree and no work running: start it. Say `go`, which runs `lit start plans/<plan>.md`.
127
+ 4. Exactly one open plan in this worktree and no work running: start it. Say `go`, which runs `lit start plans/<plan>.md`. When other lanes work (another conversation of this workspace that is running or waits on the user, or, under `HERDR_ENV=1`, a working or blocked herdr agent in this herdr workspace or this repo, read from `herdr agent list` with a 2 s limit and counted once), the step is `none` with `held`, and nothing runs on `go`.
128
128
  5. Otherwise `none`: say so.
129
129
 
130
+ Another conversation's run is never offered as `go`.
131
+
130
132
  ## Continuing with go
131
133
 
132
- After a brief, the user's `go` (also `lit go`, `ㄱㄱ`, `고`, `진행`, as the whole prompt) continues the step the brief offered, in the same session, within 30 minutes. The hook reads the next-step record the collector wrote for this session and acts on it: a paused frame resumes, an active work continues, a single open plan starts through the same typed-start path. A boundary approval still needs `lit approve`. Anything else typed after the brief is an ordinary prompt.
134
+ After a brief, the user's `go` (also `lit go`, `ㄱㄱ`, `고`, `진행`, as the whole prompt) continues the step the brief offered, in the same session, within 30 minutes. The hook reads the next-step record the collector wrote for this session and first re-checks it: the paused frame must still be paused, the start-work run still active on this conversation's stack, the plan still open with no run started. When the step no longer holds, `go` says so and starts nothing. Otherwise a paused frame resumes, an active work continues, a single open plan starts through the same typed-start path. A boundary approval still needs `lit approve`. Anything else typed after the brief is an ordinary prompt.
133
135
 
134
136
  ## Typed start-work approval
135
137