@litfamily/litgravity 0.1.4 → 0.1.6
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 +12 -0
- package/README.md +7 -3
- package/README_ko-KR.md +7 -3
- package/bin/litgravity.mjs +9 -0
- package/lib/agent-file.mjs +450 -0
- package/lib/doctor.mjs +12 -0
- package/lib/install.mjs +25 -0
- package/lib/paths.mjs +6 -0
- package/lib/uninstall.mjs +9 -1
- package/package.json +1 -1
- package/plugin/assets/logo.svg +5 -0
- package/plugin/hooks/lib/rewind/brief.mjs +35 -5
- package/plugin/hooks/lib/rewind/collect.mjs +86 -6
- package/plugin/hooks/lib/rewind/next-step.mjs +15 -9
- package/plugin/hooks/pre-invocation.mjs +39 -1
- package/plugin/plugin.json +2 -1
- package/plugin/skills/lit-adhd/SKILL.md +5 -3
- package/plugin/skills/lit-typographic-motion/SKILL.md +1 -1
- package/plugin/skills/lit-typographic-motion/engine/node/cover.mjs +1 -1
- package/plugin/skills/lit-typographic-motion/engine/node/stage-gate.mjs +1 -0
- package/plugin/skills/lit-typographic-motion/engine/node/stage-serve.mjs +126 -4
- package/plugin/skills/lit-typographic-motion/engine/node/stage.mjs +1 -0
- package/plugin/skills/lit-typographic-motion/engine/stage/stage-kit.js +40 -1
- package/plugin/skills/lit-typographic-motion/references/stage.md +44 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.6 — 2026-11-01
|
|
4
|
+
|
|
5
|
+
- A film on the stage path can now carry real keyed footage. Put the chroma-keyed frames of a clip (8-bit RGBA PNG, real transparency) under `stage/clips/<dir>/`, declare them in `stage/clips/clips.json`, and the page shows them with `LitStage.clip` from film time: `start = cue - (N-1)/fps` lands a frame on a cue. The scan holds declared clips to their own limits (12 clips, 360 frames each, 1500 in all, 40 MB each, 128 MB in all, long side up to 720 px, up to 30 fps), a frame folder that is not declared is still refused as a flipbook, cover mode takes none, and the flash audit and determinism replay still run on the final pixels.
|
|
6
|
+
|
|
7
|
+
## 0.1.5 — 2026-10-31
|
|
8
|
+
|
|
9
|
+
- 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.
|
|
10
|
+
- 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.
|
|
11
|
+
- 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`.
|
|
12
|
+
- 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.
|
|
13
|
+
- 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.
|
|
14
|
+
|
|
3
15
|
## 0.1.4 — 2026-10-28
|
|
4
16
|
|
|
5
17
|
- 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.
|
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` |
|
package/bin/litgravity.mjs
CHANGED
|
@@ -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
|
|