From d6048e59569e6bc1e473b64752682bc6d6d31020 Mon Sep 17 00:00:00 2001 From: oqyude Date: Fri, 27 Nov 2026 15:21:44 +0300 Subject: [PATCH] =?UTF-8?q?chore(.agent):=20=D1=81=D0=BE=D1=81=D1=82=D0=BE?= =?UTF-8?q?=D1=8F=D0=BD=D0=B8=D0=B5=20=D0=BF=D1=80=D0=B8=D0=B2=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BD=D0=BE=20=D0=BA=20MetaAgent=203.0.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - checkpoints.json переписан по схеме 3.0.0 (было 14 нарушений) - кит обновлён install.sh --update: metastate.sh, 06_METASTATE.md, README - decisions/index.json, .temp/ в .gitignore - project-state, handoff-summary, roadmap актуализированы; заведены req-T6/T7 --- .agent/checkpoints.json | 44 +- .agent/context/project-state.md | 77 ++- .agent/decisions/index.json | 4 + .agent/handoff-summary.md | 75 ++- .agent/requests/active/req-T6.json | 53 ++ .agent/requests/active/req-T7.json | 45 ++ .agent/roadmap/sources.md | 21 +- .agent/src/PROTOCOLS/06_METASTATE.md | 72 +++ .agent/src/README.md | 2 + .agent/src/install.sh | 14 + .agent/src/metastate.sh | 805 +++++++++++++++++++++++++++ .gitignore | 1 + 12 files changed, 1121 insertions(+), 92 deletions(-) create mode 100644 .agent/decisions/index.json create mode 100644 .agent/requests/active/req-T6.json create mode 100644 .agent/requests/active/req-T7.json create mode 100755 .agent/src/metastate.sh diff --git a/.agent/checkpoints.json b/.agent/checkpoints.json index 49570eb..13cfdf5 100644 --- a/.agent/checkpoints.json +++ b/.agent/checkpoints.json @@ -1,41 +1,27 @@ { - "metaagent_version": "2.1.0", - "session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", - "target_repo": "S:\\Git\\zeroq-qol-modules", - "goal": "Выполнить Work Loop: ESLint/Prettier, тесты для всех модулей, CI/CD pipeline.", + "metaagent_version": "3.0.0", + "session_id": "6f1c1d0a-5b7e-4e2f-9a63-2b6d8c4f71ae", + "target_repo": "/home/oqyude/External/Git/zeroq-qol-modules", + "goal": "Привести состояние MetaAgent к 3.0.0 и устранить дефекты типизации (tsc)", "project_type": "existing", - "config": { - "depth": 4, - "design": { - "adr": false, - "alternative_arch": false - }, - "red_team": false, - "risk_register": false, - "decomposition": { - "invariant_tests": false - }, - "handoff": { - "layer_structure": false - } - }, "phases": { - "analysis": "completed", - "roadmap": "skipped", + "init": "completed", + "analyse": "completed", + "roadmap": "completed", "design": "skipped", - "red_team": "skipped", "decomposition": "completed", - "environment": "completed", "execution": "completed", "metastate": "completed", "handoff": "completed" }, "tasks": [ - { "id": "T1", "title": "ESLint + Prettier", "type": "config", "status": "completed", "depends_on": [] }, - { "id": "T2", "title": "BaseModule tests", "type": "test", "status": "completed", "depends_on": [] }, - { "id": "T3", "title": "Attachment Clean Paste tests", "type": "test", "status": "completed", "depends_on": ["T2"] }, - { "id": "T4", "title": "Preserve Link Aliases tests", "type": "test", "status": "completed", "depends_on": ["T2"] }, - { "id": "T5", "title": "CI/CD pipeline", "type": "config", "status": "completed", "depends_on": ["T1", "T3", "T4"] } + { "id": "T1", "title": "Настроить ESLint и Prettier", "status": "archived" }, + { "id": "T2", "title": "Написать тесты для BaseModule", "status": "archived" }, + { "id": "T3", "title": "Написать тесты для Attachment Clean Paste", "status": "archived" }, + { "id": "T4", "title": "Написать тесты для Preserve Link Aliases", "status": "archived" }, + { "id": "T5", "title": "Создать CI/CD pipeline", "status": "archived" }, + { "id": "T6", "title": "Привести .agent к 3.0.0 и починить tsc", "status": "completed" }, + { "id": "T7", "title": "CI/CD Gitea: релиз по тегу с 3 ассетами", "status": "completed" } ], - "last_updated": "2026-07-30T16:47:00.000Z" + "last_updated": "2026-11-27T12:19:12Z" } diff --git a/.agent/context/project-state.md b/.agent/context/project-state.md index 4af4c31..f0aca99 100644 --- a/.agent/context/project-state.md +++ b/.agent/context/project-state.md @@ -1,20 +1,21 @@ # Project State -*Актуализировано: METASTATE 2026-07-30* -*MetaAgent v2.1.0* +*Актуализировано: 2026-11-27* +*MetaAgent v3.0.0* ## Общая информация | Поле | Значение | |------|----------| | Название | zeroq-qol-modules | -| Версия | 1.1.5 | +| Версия | 1.1.5 (тег `v1.1.5`) | | Тип | Obsidian-плагин (модульный) | | Язык | TypeScript 5.9 | -| Сборка | esbuild 0.17 | -| Тесты | ✅ 25 тестов (vitest) | -| Линтер | ✅ ESLint + Prettier | -| CI/CD | ✅ ci.yml (push/PR) + release.yml (теги v*) | +| Сборка | esbuild 0.17.19 → `main.js` 17.0 kb | +| Тесты | ✅ 25/25 (vitest 1.6, 3 файла) | +| Линтер | ✅ ESLint 8 + Prettier 3 (0 errors, 2 warnings) | +| Типы | ✅ `tsc --noEmit` чистый | +| CI/CD | ✅ `.gitea/workflows`: ci.yml (master/dev) + release.yml (теги `v*`) | ## Архитектура @@ -31,7 +32,7 @@ src/ └── preserve-link-aliases/ # Rename handler ``` -**Паттерн:** Модульный монолит (Plugin → Registry → Modules) +**Паттерн:** модульный монолит (Plugin → Registry → Modules) ## Стек @@ -39,18 +40,18 @@ src/ |-----------|--------| | TypeScript | 5.9.3 | | esbuild | 0.17.19 | -| Obsidian API | 1.13.1 | -| Node.js | 20 | -| ESLint | 9.x (typescript-eslint) | -| Prettier | 3.x | -| Vitest | 3.x | +| Obsidian API | latest (1.13.x) | +| Node.js | 24.22 (host-раннер), 22 локально | +| ESLint | 8.57 (typescript-eslint 7) | +| Prettier | 3.9 | +| Vitest | 1.6 | ## Конвенции - **Отступы:** tabs - **Файлы:** kebab-case - **Классы:** PascalCase -- **Типизация:** strictNullChecks, noImplicitAny +- **Типизация:** strictNullChecks, noImplicitAny, `skipLibCheck` - **Импорты:** `import type` для type-only, относительные внутри src ## Тестирование @@ -63,33 +64,49 @@ src/ ## CI/CD -- **ci.yml** — push/PR в main/dev → npm ci → lint → test -- **release.yml** — тег v* → npm ci → lint → test → build → verify version → GitHub Release (assets: main.js, manifest.json, styles.css) +- **ci.yml** — push/PR в `master`/`dev` → npm ci → lint → typecheck → test +- **release.yml** — тег `v*` → npm ci → lint → typecheck → test → build → сверка тега с `manifest.json`/`package.json` → Gitea Release с `main.js`, `manifest.json`, `styles.css` +- Публикация — `scripts/publish-release.mjs` (Gitea API, идемпотентно: существующий релиз переиспользуется, ассеты заменяются) +- Токен — `${{ secrets.GITEA_TOKEN }}` (job-token Gitea), права `contents: write` +- Раннер — `ci-sapphira`, **host mode** (`.runner`: `labels: ["native:host"]`), `runs-on: native`. + Поэтому в workflow нет `setup-node`/`cache: npm`: на хосте нет `tar`/`gzip`/`zstd`, + а Node/npm/git/curl/jq/python3 — из Nix-профиля раннера (node 24, npm 11, git 2.56). +- Прогон всего пайплайна воспроизведён на хосте с PATH раннера: `npm ci` 39 с, + lint/typecheck/test/build — зелёные. ## Состояние сессии | Артефакт | Статус | |----------|--------| -| MetaAgent | v2.1.0 ✅ | +| MetaAgent | v3.0.0 ✅ (кит обновлён `install.sh --update`) | | Project Loop | завершён | -| Work Loop | ✅ **5/5 выполнено** | -| Задач выполнено | 5/5 | -| Requests (active) | 0 | -| Requests (archive) | 5 | +| Work Loop | ✅ 7/7 | +| Requests (active) | 2 (`req-T6`, `req-T7`) | +| Requests (archive) | 5 (T1–T5) | ## Выполненные задачи | ID | Задача | Статус | |----|--------|--------| -| T1 | ESLint + Prettier | ✅ completed | -| T2 | BaseModule tests | ✅ completed | -| T3 | Attachment Clean Paste tests | ✅ completed | -| T4 | Preserve Link Aliases tests | ✅ completed | -| T5 | CI/CD pipeline | ✅ completed | +| T1 | ESLint + Prettier | ✅ archived | +| T2 | BaseModule tests | ✅ archived | +| T3 | Attachment Clean Paste tests | ✅ archived | +| T4 | Preserve Link Aliases tests | ✅ archived | +| T5 | CI/CD pipeline | ✅ archived | +| T6 | .agent под 3.0.0 + tsc | ✅ completed | +| T7 | Gitea CI/CD: релиз по тегу с 3 ассетами | ✅ completed | + +## Открытые вопросы + +- **Проверить на живом хосте**: Actions включены для репозитория; раннер `ci-sapphira` + (`native:host`) активен — метка `native` уже совпадает с `runs-on`. +- **Legacy-дубли в корне `.agent/`** — `task-manifest.json`, `task-manifest.md`, `analysis-report.md` (формат v2.1). Удаление требует решения владельца. +- **Undocumented Vault API** — `vault.getConfig` и `vault.getAvailablePath` используются как есть (типизированный cast). Публичная замена: `app.fileManager.getAvailablePathForAttachment` (API 1.5.7+), но она поднимает `minAppVersion` (сейчас 0.15.0). +- **ESLint 8 EOL** — при случае обновить до 9 + flat config. ## Примечания -- tsc --noEmit: 4 pre-existing type errors (obsidian.d.ts + unsafe casts) -- esbuild: сборка успешна (17.1kb) -- ESLint: 0 errors, 2 pre-existing warnings (no-empty-function, no-unused-vars) -- Все 5 задач Work Loop выполнены. Проект готов к дальнейшей разработке. +- `skipLibCheck: true` добавлен из-за несовместимости `obsidian.d.ts` с TS 5.9 (`Menu`/`Modal`/`PopoverSuggest` не реализуют `HistoryHandler`). +- `@types/node` добавлен в devDependencies — без него `tsc --noEmit` падал с TS2688. +- `vitest.config.ts`: неиспользуемый `transformMode` удалён (в Vitest 1.6 ключ не поддерживался на верхнем уровне). +- Сборка побайтово совпадает с закоммиченным `main.js`. diff --git a/.agent/decisions/index.json b/.agent/decisions/index.json new file mode 100644 index 0000000..47267b2 --- /dev/null +++ b/.agent/decisions/index.json @@ -0,0 +1,4 @@ +{ + "version": "3.0", + "decisions": [] +} diff --git a/.agent/handoff-summary.md b/.agent/handoff-summary.md index a06a74e..ba66f00 100644 --- a/.agent/handoff-summary.md +++ b/.agent/handoff-summary.md @@ -1,42 +1,73 @@ # Handoff Summary -*Дата: 2026-07-* -*MetaAgent v2.1.0* +*Дата: 2026-11-27* +*MetaAgent v3.0.0* ## Контекст zeroq-qol-modules — модульный Obsidian-плагин с независимо включаемыми QoL-модулями. -**Текущая версия:** 1.1.5 +**Текущая версия:** 1.1.5 · **Ветка:** `master` (единственная в origin) · **Состояние:** чисто. -## Что сделано (Work Loop: 5/5 ✅) +## Что сделано + +### Work Loop 2026-07 (архив, T1–T5) - **T1** — ESLint + Prettier: typescript-eslint, tabs, скрипты lint/format -- **T2** — BaseModule тесты: vitest, 5 тестов (абстрактный класс, регистрация) -- **T3** — Attachment Clean Paste тесты: 12 тестов (paste/drop, shouldProcess, processFile) -- **T4** — Preserve Link Aliases тесты: 8 тестов (processContent, canvas, rename) -- **T5** — CI/CD: ci.yml (lint+test на push/PR) + release.yml (тег v* → build+release) +- **T2** — BaseModule: 5 тестов +- **T3** — Attachment Clean Paste: 12 тестов +- **T4** — Preserve Link Aliases: 8 тестов +- **T5** — CI/CD: `ci.yml` + `release.yml` + +### T6 (2026-11-27) + +- `.agent/` приведён к 3.0.0: `checkpoints.json` переписан по схеме, кит обновлён + `install.sh --update` (13 файлов, добавлен `metastate.sh`), создан `decisions/index.json`. +- `tsc --noEmit` **зелёный**: добавлен `@types/node@20`, `skipLibCheck`, + двойной cast для настроек модулей, типизированный cast legacy Vault API, + тестовые моки типизированы (`VaultMock`, `makeFile`). +- `vitest.config.ts`: удалён неподдерживаемый ключ `transformMode`. +- Тесты/линт/формат/сборка перепроверены после изменений. + +### T7 (2026-11-27) + +- Workflow перенесены в `.gitea/workflows` (GitHub Actions на Gitea-хосте не исполнялись, + `softprops/action-gh-release` там не работает): `ci.yml` (master/dev) и `release.yml` (теги `v*`). +- Под раннер `ci-sapphira` (host mode, метка `native`): `runs-on: native`, без `setup-node` + и `cache: npm` — на хосте нет `tar`/`zstd`, используется хостовый Node 24 / npm 11. +- Релиз публикуется через Gitea API скриптом `scripts/publish-release.mjs` с ассетами + `main.js`, `manifest.json`, `styles.css`; публикация идемпотентна (повторный прогон + переиспользует релиз и заменяет ассеты). +- Сверка версии усилена: тег = `manifest.json` = `package.json`. +- Добавлен скрипт `npm run typecheck`; шаги lint/typecheck/test теперь и в релизном пайплайне. +- Скрипт проверен на локальном mock-сервере Gitea API: создание релиза, загрузка трёх + ассетов, повторный прогон (DELETE + POST). +- Весь пайплайн прогнан на хосте с реальным PATH раннера (node 24.22, npm 11.19, git 2.56): + `npm ci` 39 с, lint/typecheck/test/build зелёные, `main.js` 17.0 kb. ## Состояние | Показатель | Значение | |------------|----------| | Тесты | 25/25 ✅ | -| Линтер | 0 errors ✅ (2 warnings) | -| Prettier | passed ✅ | -| CI/CD | ci.yml + release.yml ✅ | -| git status | рабочий, чисто | +| Линтер | 0 errors, 2 warnings ✅ | +| Prettier | passed (src/ + tests/) ✅ | +| `tsc --noEmit` | clean ✅ | +| Сборка | 17.0 kb ✅ | +| `metastate.sh --check` | ok ✅ | +| git status | изменённые файлы не закоммичены | ## Не тронуто -- modules.json (настройки включения модулей) -- locales/ (двуязычные строки) -- main.ts, settings.ts, types.ts -- scripts/release.sh -- tsc --noEmit: 4 pre-existing type errors остаются +- `main.ts`, `settings.ts`, `types.ts`, `locales/` +- `scripts/release.sh` +- Legacy-дубли в корне `.agent/`: `task-manifest.json`, `task-manifest.md`, `analysis-report.md` -## Следующие шаги (опционально) +## Следующие шаги -- Наполнить `.agent/rules/project-rules.md` -- Исправить pre-existing type errors -- Написать e2e-тест для плагина в среде Obsidian -- Добавить новые модули +1. Убедиться, что Actions включены для репозитория на `git.zeroq.su` (runner `ci-sapphira` уже активен, метка `native`). +2. Проверить права `GITEA_TOKEN` (`contents: write`) в настройках Actions репозитория. +3. Прогнать первый релиз: `bash scripts/release.sh patch` → `git push && git push --tags`. +4. Запустить `metastate.sh --archive`, чтобы перенести `req-T6`/`req-T7` в архив после ревью. +5. Решить судьбу legacy-дублей в `.agent/`. +6. Опционально: перейти с undocumented Vault API на `fileManager.getAvailablePathForAttachment`. +7. Опционально: ESLint 9 + flat config. diff --git a/.agent/requests/active/req-T6.json b/.agent/requests/active/req-T6.json new file mode 100644 index 0000000..ba374eb --- /dev/null +++ b/.agent/requests/active/req-T6.json @@ -0,0 +1,53 @@ +{ + "template_version": "1.0", + "request_id": "req-T6", + "task_id": "T6", + "title": "Привести .agent к 3.0.0 и починить tsc", + "status": "ready_for_review", + "created_at": "2026-11-27T11:54:00.000Z", + "goal": "Устранить дрейф состояния MetaAgent и дефекты типизации, не меняя поведение плагина", + + "changes": { + "summary": "Кит в .agent/src обновлён до канона 2026-11-07 (metastate.sh, 06_METASTATE.md, install.sh, README); checkpoints.json переписан по схеме 3.0.0 (было 14 нарушений); создан decisions/index.json; обновлены project-state, handoff-summary, roadmap. tsc --noEmit сделан зелёным: @types/node@20, skipLibCheck, двойной cast настроек, типизированный legacy-интерфейс Vault, типизированные тестовые моки; убран неподдерживаемый ключ transformMode из vitest.config.ts.", + "commits": [], + "files_changed": [ + ".agent/checkpoints.json", + ".agent/context/project-state.md", + ".agent/handoff-summary.md", + ".agent/roadmap/sources.md", + ".agent/decisions/index.json", + ".agent/src/install.sh", + ".agent/src/metastate.sh", + ".agent/src/PROTOCOLS/06_METASTATE.md", + ".agent/src/README.md", + ".agent/requests/active/req-T6.json", + ".gitignore", + "package.json", + "package-lock.json", + "tsconfig.json", + "vitest.config.ts", + "src/modules/attachment-clean-paste/index.ts", + "src/modules/preserve-link-aliases/index.ts", + "tests/modules/attachment-clean-paste.test.ts", + "tests/modules/preserve-link-aliases.test.ts", + "tests/setup.ts" + ] + }, + + "verification": { + "tests_passed": "25/25 (3 files)", + "lint": "0 errors, 2 warnings", + "prettier": "passed (src/ + tests/)", + "tsc": "clean (tsc --noEmit)", + "build": "ok, main.js 17.0 kb, идентичен закоммиченному", + "metastate_check": "ok", + "lsp_clean": true + }, + + "fulfills_ac": [ + "checkpoints.json проходит metastate.sh --check", + ".agent/src соответствует каноническому киту (install.sh --update)", + "tsc --noEmit не выдаёт ошибок", + "Поведение плагина не изменено: 25/25 тестов и сборка без диффа" + ] +} diff --git a/.agent/requests/active/req-T7.json b/.agent/requests/active/req-T7.json new file mode 100644 index 0000000..1836889 --- /dev/null +++ b/.agent/requests/active/req-T7.json @@ -0,0 +1,45 @@ +{ + "template_version": "1.0", + "request_id": "req-T7", + "task_id": "T7", + "title": "CI/CD Gitea: автоматический релиз по тегу с main.js, manifest.json, styles.css", + "status": "ready_for_review", + "created_at": "2026-11-27T12:09:42.000Z", + "goal": "Сделать так, чтобы релиз плагина собирался и публиковался автоматически на Gitea-хосте с тремя ассетами", + + "changes": { + "summary": "Workflow перенесены из .github/workflows (GitHub API, на Gitea не исполнялись) в .gitea/workflows. Подбирались под host-mode раннер ci-sapphira (метка native): runs-on: native, без setup-node и cache: npm, так как на хосте нет tar/zstd, а node 24.22/npm 11.19/git 2.56/curl/jq/python3 есть в PATH раннера. ci.yml: push/PR в master/dev → npm ci, lint, typecheck, test. release.yml: тег v* → npm ci, lint, typecheck, test, build → сверка тега с manifest.json и package.json → публикация релиза через Gitea API скриптом scripts/publish-release.mjs (ассеты main.js, manifest.json, styles.css; идемпотентно: существующий релиз переиспользуется, ассеты заменяются). Добавлен npm script typecheck.", + "commits": [], + "files_changed": [ + ".gitea/workflows/ci.yml", + ".gitea/workflows/release.yml", + ".github/workflows/ci.yml", + ".github/workflows/release.yml", + "scripts/publish-release.mjs", + "package.json", + ".agent/checkpoints.json", + ".agent/context/project-state.md", + ".agent/handoff-summary.md", + ".agent/requests/active/req-T7.json" + ] + }, + + "verification": { + "tests_passed": "25/25 (3 files)", + "lint": "0 errors, 2 warnings", + "typecheck": "clean (tsc --noEmit)", + "build": "ok, main.js 17.0 kb", + "yaml": "ci.yml и release.yml парсятся js-yaml", + "publish_script": "node --check ok; прогон на mock Gitea API: создание релиза + 3 ассета, повторный прогон → DELETE+POST без дублей", + "runner_preflight": "полный пайплайн на хосте с PATH раннера (node 24.22.2, npm 11.19.1, git 2.56.0): npm ci 39 с, lint 0 errors, typecheck clean, tests 25/25, build 17.0 kb; publish-скрипт повторён под node 24", + "lsp_clean": true + }, + + "fulfills_ac": [ + "Релиз создаётся автоматически по тегу v*", + "В релиз попадают ровно main.js, manifest.json, styles.css", + "Тег обязан совпадать с manifest.json и package.json", + "Повторный запуск workflow не ломается и не плодит дубли ассетов", + "CI покрывает master (единственная ветка origin)" + ] +} diff --git a/.agent/roadmap/sources.md b/.agent/roadmap/sources.md index 22356b8..1033eba 100644 --- a/.agent/roadmap/sources.md +++ b/.agent/roadmap/sources.md @@ -1,26 +1,25 @@ # Roadmap — Sources -*Создано: METASTATE 2026-07-30* +*Создано: METASTATE 2026-07-30 · закрыто: 2026-11-27* *Источник: манифест задач предыдущей сессии (analysis + decomposition)* ## Источники | Источник | Описание | Статус | |----------|----------|--------| -| analysis-report.md (v1.1.0) | Выявлено отсутствие тестов, линтера, CI | ✅ учтено в задачах T1-T5 | +| analysis-report.md (v1.1.0) | Выявлено отсутствие тестов, линтера, CI | ✅ отработано задачами T1-T5 | ## Бэклог | ID | Задача | Приоритет | Источник | Статус | |----|--------|-----------|----------|--------| -| T1 | Настроить ESLint и Prettier | high | analysis | pending | -| T2 | Написать тесты для BaseModule | high | analysis | pending | -| T3 | Тесты для Attachment Clean Paste | high | analysis | pending (блок: T2) | -| T4 | Тесты для Preserve Link Aliases | high | analysis | pending (блок: T2) | -| T5 | CI workflow для тестов и линтинга | medium | analysis | pending (блок: T1, T3, T4) | +| T1 | Настроить ESLint и Prettier | high | analysis | ✅ completed | +| T2 | Написать тесты для BaseModule | high | analysis | ✅ completed | +| T3 | Тесты для Attachment Clean Paste | high | analysis | ✅ completed (после T2) | +| T4 | Тесты для Preserve Link Aliases | high | analysis | ✅ completed (после T2) | +| T5 | CI workflow для тестов и линтинга | medium | analysis | ✅ completed (после T1, T3, T4) | -## Приоритеты выполнения +## Закрытие -1. **T1 + T2** (параллельно, без зависимостей) -2. **T3 + T4** (после T2) -3. **T5** (после T1, T3, T4) +Все источники отработаны, новых задач нет. Roadmap закрыт 2026-11-27. +Дальнейшие задачи — из открытых вопросов `.agent/context/project-state.md`. diff --git a/.agent/src/PROTOCOLS/06_METASTATE.md b/.agent/src/PROTOCOLS/06_METASTATE.md index dca2fcd..21fcdfe 100644 --- a/.agent/src/PROTOCOLS/06_METASTATE.md +++ b/.agent/src/PROTOCOLS/06_METASTATE.md @@ -15,6 +15,71 @@ Может запускаться многократно — после каждой группы выполненных задач. +## Исполняемое ядро (без директора) + +Фаза выполняется скриптом кита; он лежит в проекте рядом с протоколами: + +```bash +bash .agent/src/metastate.sh --check # checkpoints.json против схемы +bash .agent/src/metastate.sh --requests # что ждёт в requests/active/ и сколько +bash .agent/src/metastate.sh --archive # approved|done|completed|implemented → archive/requests/ +bash .agent/src/metastate.sh --manifest # manifest.md → manifest.json +bash .agent/src/metastate.sh --handoff # .agent/handoff-summary.md +``` + +Ни `metaagent`, ни `state/`, ни сервера, ни конфига не нужно: скрипт находит +корень проекта по **своему расположению** (идёт вверх, пока не найдёт +`.agent/`), поэтому `cd / && bash /.agent/src/metastate.sh --check` — тот +же прогон, что и из корня проекта. Зависимости: bash и python3 (стандартная +библиотека); без npm, без сети, без `jq`. + +`--dry` есть у каждого режима, который пишет (`--archive`, `--manifest`, +`--handoff`): печатает план и не пишет ничего. У `--check` и `--requests` он +принимается и ничего не меняет — эти два режима не пишут никогда. + +Коды выхода: **0** — хорошо; **1** — найдена настоящая проблема (нарушение +схемы, request без статуса, коллизия в архиве); **2** — ошибка вызова; +**3** — нет предусловия (нет `.agent/`, нет `python3`, нет схемы, нет +`checkpoints.json`, нет `manifest.md`, нет парсера MD). + +### Что именно делает каждый режим + +- **`--check`** — минимальный валидатор схемы: `type` (включая форму + `["string","null"]`), `required`, `enum`, `pattern`, + `additionalProperties:false`, `items`. **Не** проверяет `format` + (date-time в draft 2020-12 — аннотация, а не ограничение) и аннотации + `$schema`/`$id`/`title`/`description`. Отсутствие ключа фазы — замечание, а не + ошибка: схема его не требует, `00_INIT.md` §0.8 требует. Свободный текст в + статусе фазы (`completed (2026-10-25: ...)`) — нарушение `enum`, и это + намеренно: именно так выглядит `.agent/checkpoints.json` самого репозитория + metaagent, и именно поэтому проверка существует. +- **`--requests`** — только чтение: перечисляет файлы `active/`, их статусы и + возраст, считает по статусам и говорит, сколько `approved` и как давно. + В форме request нет `approved_at`, поэтому возраст берётся из `created_at` + (или mtime файла) — это **верхняя** граница того, сколько request висит + одобренным; источник возраста печатается. +- **`--archive`** — переносит только `approved|done|completed|implemented`; + `pending`/`in_progress`/`ready_for_review` остаются в `active/`, файл без + статуса остаётся и делает код выхода 1. Индекс — + `.agent/archive/requests/index.json`: отсортирован по `id`, дополняется + (запись с тем же `id` заменяется, не дублируется) и пишется только когда + что-то реально переехало. Существующий файл в архиве не перезаписывается — + коллизия это отказ, а не «тихо затрём». +- **`--manifest`** — **не парсит MD**. Единственный парсер — + `tools/manifest-json.sh` из репозитория metaagent; скрипт ищет его в + `$METASTATE_MANIFEST_TOOL`, затем в `/tools/manifest-json.sh`, и если + его нет — отказывает с кодом 3 и называет, что поставить. Копии парсера кит + намеренно не несёт: вторая копия — второй ответ на вопрос «что говорит MD», а + это и есть болезнь. Остальные четыре режима парсера не требуют. +- **`--handoff`** — `.agent/handoff-summary.md` из артефактов: сессия, таблица + фаз, счётчики задач из `manifest.json`, счётчики requests и архив, список ADR. + Числа, а не проза; повторный прогон на неизменных артефактах файл не трогает + (и не меняет его mtime). + +Скрипт — файл кита: установщик кладёт его в `.agent/src/metastate.sh` (ряд +`KIT-MANIFEST.tsv`), поэтому `--update` обновляет его вместе с остальным китом, +а `framework-check` видит его дрейф. Тест: `tests/sh-metastate-kit.sh`. + ## Вход - `.agent/requests/active/` — все request-ы со статусом `ready_for_review` @@ -91,6 +156,13 @@ } ``` +**Что делает ядро.** `--archive` ведёт индекс ПО КОЛЛЕКЦИИ: +`.agent/archive/requests/index.json` (`{"version", "requests": [...]}`, +отсортирован по `id`). Сводный `archive/index.json` из этого шага ядро не +пишет: две записи одного факта — это две записи, которые разойдутся. Когда +появятся архиваторы задач и чекпоинтов, у каждой коллекции будет свой индекс +рядом с её файлами. + ### 6.7. Создать handoff-summary Создать `.agent/handoff-summary.md` — полная сводка для следующего агента: diff --git a/.agent/src/README.md b/.agent/src/README.md index 58714dd..4da2b65 100644 --- a/.agent/src/README.md +++ b/.agent/src/README.md @@ -67,6 +67,7 @@ DESIGN выполняется только для greenfield/scaffold-проек | `.agent/checkpoints.json` | литерал `PROTOCOLS/00_INIT.md` §0.8, по `TEMPLATES/schemas/checkpoints-schema.json` (`phases.init = completed`) | | `.agent/rules/project-rules.md` | `TEMPLATES/project-rules.md` | | `.agent/decisions/index.json` | пустой реестр ADR, по `TEMPLATES/schemas/decisions-index-schema.json` | +| `.agent/src/metastate.sh` | исполняемое ядро METASTATE (`--check`, `--requests`, `--archive`, `--manifest`, `--handoff`) — работает без директора | | `.temp/` + строка `.temp/` в `.gitignore` | — | | `AGENTS.md` | `AGENTS.template.md` с подставленным `{VERSION}` | @@ -161,6 +162,7 @@ project has: | `.agent/checkpoints.json` | the `PROTOCOLS/00_INIT.md` §0.8 literal, per `TEMPLATES/schemas/checkpoints-schema.json` (`phases.init = completed`) | | `.agent/rules/project-rules.md` | `TEMPLATES/project-rules.md` | | `.agent/decisions/index.json` | an empty ADR index, per `TEMPLATES/schemas/decisions-index-schema.json` | +| `.agent/src/metastate.sh` | the executable core of METASTATE (`--check`, `--requests`, `--archive`, `--manifest`, `--handoff`) — runs with no director | | `.temp/` + a `.temp/` line in `.gitignore` | — | | `AGENTS.md` | `AGENTS.template.md` with `{VERSION}` substituted | diff --git a/.agent/src/install.sh b/.agent/src/install.sh index 4433046..bdba365 100755 --- a/.agent/src/install.sh +++ b/.agent/src/install.sh @@ -274,6 +274,12 @@ copy_dir "$METAAGENT_SRC/COMMANDS" "$SRC_DIR" copy_dir "$METAAGENT_SRC/TEMPLATES" "$SRC_DIR" copy_dir "$METAAGENT_SRC/FUTURE" "$SRC_DIR" copy_file "$METAAGENT_SRC/install.sh" "$SRC_DIR" +# The executable core of the METASTATE phase (2026-11-07): the five operations +# 06_METASTATE.md asks for, with no director. A kit file, so it lands in +# `.agent/src/` like every other row of KIT-MANIFEST.tsv — `framework-check` +# compares `/.agent/src/`, and a kit file outside src/ would be +# invisible to drift detection. +copy_file "$METAAGENT_SRC/metastate.sh" "$SRC_DIR" # --- phase 3: INIT artefacts --------------------------------------------- # 00_INIT.md §0.4 and §0.6-§0.9. These files are the DATA OF THE PROJECT, not @@ -461,6 +467,14 @@ echo "" echo " INIT artefacts (checkpoints, rules, decisions, .gitignore, AGENTS.md) are" echo " the project's data: this installer writes them only when they are absent." echo "" +echo " METASTATE without a director:" +echo " bash .agent/src/metastate.sh --check # checkpoints vs the schema" +echo " bash .agent/src/metastate.sh --requests # what waits in requests/active/" +echo " bash .agent/src/metastate.sh --archive # approved -> archive/requests/" +echo " bash .agent/src/metastate.sh --manifest # manifest.md -> manifest.json" +echo " bash .agent/src/metastate.sh --handoff # .agent/handoff-summary.md" +echo " (--dry for every mode that writes; --help for the detail)" +echo "" if (( FAIL_COUNT == 0 )); then ok "Installation completed successfully." else diff --git a/.agent/src/metastate.sh b/.agent/src/metastate.sh new file mode 100755 index 0000000..5c2e284 --- /dev/null +++ b/.agent/src/metastate.sh @@ -0,0 +1,805 @@ +#!/usr/bin/env bash +# metastate.sh — the METASTATE phase as an EXECUTABLE CORE, with no director. +# +# WHY (2026-11-07, owner requirement A1) +# -------------------------------------- +# The kit could be installed and still be unusable: `PROTOCOLS/06_METASTATE.md` +# told an agent to "review the requests, sync the manifest, write the handoff", +# and every one of those sentences was an instruction to a language model with +# no executable answer. In a project that carries ONLY the kit — no `metaagent` +# router, no `state/`, no `tools/`, no `opencode` server — the phase either +# happened by improvisation or did not happen at all. The repository's own +# `.agent/` shows the result: 28 requests stuck at `approved` forever, a +# `checkpoints.json` whose phase statuses are free text +# ("completed (2026-10-25: ...)") and therefore violate its own schema, and a +# handoff summary written by hand. +# +# This file is the five operations that phase actually needs, and nothing else: +# +# --check validate `.agent/checkpoints.json` against +# `.agent/src/TEMPLATES/schemas/checkpoints-schema.json` +# --requests list `.agent/requests/active/*.json` with their status, and +# say how many are `approved` and for how long +# --archive move the approved/done requests to `.agent/archive/requests/` +# and append them to that collection's `index.json` +# --manifest regenerate `.agent/tasks/manifest.json` from `manifest.md` — +# by DELEGATING to the one MD parser (see below) +# --handoff write `.agent/handoff-summary.md` from the artefacts +# +# WHERE IT RUNS, AND HOW IT FINDS THE PROJECT +# ------------------------------------------- +# From inside the project, with `.agent/` next to it. There is no `metaagent`, +# no `state/`, no server and no config: the project root is resolved from THIS +# FILE'S OWN LOCATION, never from `$PWD`, so `cd / && bash /.agent/src/metastate.sh +# --check` is the same run as from the project root. The rule is "walk up from +# the directory this file lives in until a directory containing `.agent/` is +# found" — that covers both the installed copy (`/.agent/src/metastate.sh` +# → ``) and the kit checkout (`framework/metastate.sh` → the repo), and it +# does not depend on counting `../..` levels correctly. +# +# WHERE THE FILE IS INSTALLED, AND WHY THERE +# ------------------------------------------ +# `framework/metastate.sh` is a KIT FILE, so `install.sh` copies it into +# `/.agent/src/metastate.sh`, exactly like `.agent/src/install.sh`. +# It is NOT under `TEMPLATES/` (it is not a template a project fills in), and +# it is NOT at `.agent/metastate.sh`: `KIT-MANIFEST.tsv` describes `.agent/src/` +# file for file, `framework-check` compares `/.agent/src/`, and +# `tests/sh-framework-check.sh` group G demands that the installed set inside +# `.agent/src/` IS the manifest's set. A kit file outside `src/` would be +# invisible to drift detection (it would read as "missing" in every repository) +# and would break the one invariant that keeps the installer and the manifest +# from drifting apart. Being kit code rather than project data, `--update` +# refreshing it is correct — the same rule that already applies to +# `.agent/src/install.sh`. +# +# THE MANIFEST PARSER: DELEGATION, NOT A SECOND COPY +# -------------------------------------------------- +# `--manifest` does NOT parse `manifest.md`. `tools/manifest-json.sh` in the +# metaagent repository is the ONE answer to "what does the MD say", and the +# director's own `lib/cmd_manifest.sh` argues at length that a second parser is +# a second answer — the disease, not the cure. Carrying a copy inside the kit +# would create exactly that drift (two files, one of which is edited), so this +# script looks the parser up and REFUSES, with the fix in the message, when it +# is not there: +# +# $METASTATE_MANIFEST_TOOL, else /tools/manifest-json.sh +# +# The other four modes need no parser and no director. This is a deliberate +# gap, not an oversight: the follow-up that closes it is to ship that parser as +# a kit file and point `lib/cmd_manifest.sh` at the kit's copy, so that there is +# one parser and it travels with the kit. +# +# `--check`: WHICH PARTS OF THE SCHEMA ARE ENFORCED +# ------------------------------------------------- +# No `jsonschema` package (it is not installed on the fleet, and this script has +# to run on a bare project). The validator is minimal and implements EXACTLY the +# keywords `checkpoints-schema.json` uses: +# +# ENFORCED type (including the ["string","null"] list form), required, enum, +# pattern (Python `re.search`, i.e. unanchored unless the pattern +# anchors itself — this schema's `^...$` does), properties, +# additionalProperties:false, items +# NOT ENFORCED `format` (the schema annotates `last_updated` as date-time; +# draft 2020-12 treats `format` as annotation-only by default, and +# no validator here implements it — a run that claimed to check it +# would be lying about what it proved), and `$schema` / `$id` / +# `title` / `description`, which are annotations, not constraints. +# +# One thing the schema does NOT require and the protocol DOES: all eight phase +# keys. `phases` has `additionalProperties:false` but no `required`, so +# `{"phases":{}}` is schema-valid. `--check` therefore reports a missing phase +# key as a NOTE (not a failure) and names `00_INIT.md` §0.8 as the authority. +# +# USAGE +# ----- +# bash .agent/src/metastate.sh --check [--dry] +# bash .agent/src/metastate.sh --requests [--dry] +# bash .agent/src/metastate.sh --archive [--dry] +# bash .agent/src/metastate.sh --manifest [--dry] +# bash .agent/src/metastate.sh --handoff [--dry] +# bash .agent/src/metastate.sh --help +# +# --dry print the plan, write NOTHING. It exists for every mode that writes +# (`--archive`, `--manifest`, `--handoff`); on the two read-only modes +# it is accepted and changes nothing, because they never write. +# +# ENVIRONMENT (overrides, for tests and for an unusual layout) +# METASTATE_CHECKPOINTS default /.agent/checkpoints.json +# METASTATE_SCHEMA default /.agent/src/TEMPLATES/schemas/checkpoints-schema.json +# METASTATE_MANIFEST_TOOL default /tools/manifest-json.sh +# +# EXIT +# 0 ok, or a --dry plan that found nothing to complain about +# 1 a real problem was found: schema violations, a request that cannot be +# classified, a destination collision, an unreadable file. A --dry plan +# exits 1 for the same reason the real run would — the answer must not +# change just because nothing was written +# 2 usage error (unknown mode/flag) +# 3 a required prerequisite is missing: no `.agent/` at or above this file, +# no python3, no schema, no checkpoints.json, no manifest.md, no MD parser +# +# bash + python3 (stdlib only), no npm, no network, no jq. + +set -u + +MODE="" +DRY=0 + +_usage() { + sed -n '/^# USAGE$/,/^# bash + python3/p' "$0" | sed 's/^# \{0,1\}//' +} + +while [ $# -gt 0 ]; do + case "$1" in + --check) MODE="check"; shift ;; + --requests) MODE="requests"; shift ;; + --archive) MODE="archive"; shift ;; + --manifest) MODE="manifest"; shift ;; + --handoff) MODE="handoff"; shift ;; + --dry) DRY=1; shift ;; + -h|--help) _usage; exit 0 ;; + *) + echo "metastate: unknown argument '$1' (modes: --check, --requests, --archive, --manifest, --handoff; flags: --dry, --help)" >&2 + exit 2 ;; + esac +done + +if [ -z "$MODE" ]; then + echo "metastate: no mode given — pick one of --check, --requests, --archive, --manifest, --handoff (--help for the detail)" >&2 + exit 2 +fi + +# --- the project root: from this file's location, never from $PWD ----------- +_self="${BASH_SOURCE[0]}" +_here="$(cd "$(dirname "$_self")" 2>/dev/null && pwd)" || { + echo "metastate: cannot resolve the directory of $_self" >&2 + exit 3 +} + +_root="" +_d="$_here" +_i=0 +while [ "$_i" -lt 6 ]; do + if [ -d "$_d/.agent" ]; then + _root="$_d" + break + fi + _parent="$(dirname "$_d")" + [ "$_parent" = "$_d" ] && break + _d="$_parent" + _i=$((_i + 1)) +done + +if [ -z "$_root" ]; then + echo "metastate: no .agent/ directory at or above $_here" >&2 + echo " this script is the kit's METASTATE core and expects to live at /.agent/src/metastate.sh" >&2 + echo " (or at /framework/metastate.sh in the metaagent checkout); run framework/install.sh first" >&2 + exit 3 +fi + +AGENT_DIR="$_root/.agent" +CHECKPOINTS="${METASTATE_CHECKPOINTS:-$AGENT_DIR/checkpoints.json}" +SCHEMA="${METASTATE_SCHEMA:-$AGENT_DIR/src/TEMPLATES/schemas/checkpoints-schema.json}" +# The schema travels with the script. In an installed project the primary path +# and the fallback are the SAME file (`/.agent/src/TEMPLATES/...`); in the +# kit checkout (`framework/metastate.sh`, where there is no `.agent/src/`) the +# fallback is what makes the mode runnable at all. An explicit METASTATE_SCHEMA +# is never overridden, and the path actually used is always printed. +if [ -z "${METASTATE_SCHEMA:-}" ] && [ ! -f "$SCHEMA" ] \ + && [ -f "$_here/TEMPLATES/schemas/checkpoints-schema.json" ]; then + SCHEMA="$_here/TEMPLATES/schemas/checkpoints-schema.json" +fi + +ACTIVE_DIR="$AGENT_DIR/requests/active" +ARCHIVE_DIR="$AGENT_DIR/archive/requests" +ARCHIVE_INDEX="$ARCHIVE_DIR/index.json" +MANIFEST_MD="$AGENT_DIR/tasks/manifest.md" +MANIFEST_JSON="$AGENT_DIR/tasks/manifest.json" +DECISIONS_INDEX="$AGENT_DIR/decisions/index.json" +HANDOFF_MD="$AGENT_DIR/handoff-summary.md" + +# --- --manifest: delegate to the ONE parser, or refuse with the fix --------- +# Handled in bash on purpose: the parser is a program, not a JSON pass, and +# its exit codes (0 ok | 1 stale | 2 usage | 3 missing/unreadable | 4 no task +# rows) are the answer the caller needs. Nothing is invented on top of them. +if [ "$MODE" = "manifest" ]; then + _tool="${METASTATE_MANIFEST_TOOL:-$_root/tools/manifest-json.sh}" + if [ ! -f "$_tool" ]; then + echo "metastate: --manifest needs the ONE parser of manifest.md, and it is not installed" >&2 + echo " looked for: $_tool" >&2 + echo " override: METASTATE_MANIFEST_TOOL=" >&2 + echo "" >&2 + echo " The kit deliberately carries NO second parser: tools/manifest-json.sh in the" >&2 + echo " metaagent repository is the only answer to \"what does the MD say\", and a copy" >&2 + echo " would drift from it. Install that file (or point the variable at it)." >&2 + echo " --check, --requests, --archive and --handoff do not need it." >&2 + exit 3 + fi + if [ ! -f "$MANIFEST_MD" ]; then + echo "metastate: --manifest: no $MANIFEST_MD — the MD is the source, and there is nothing to parse" >&2 + exit 3 + fi + if [ "$DRY" = "1" ]; then + if bash "$_tool" --check --quiet "$MANIFEST_MD" "$MANIFEST_JSON" >/dev/null 2>&1; then + echo "manifest --dry: $MANIFEST_JSON is what $MANIFEST_MD produces — nothing to write" + else + echo "manifest --dry: $MANIFEST_JSON is not what $MANIFEST_MD produces — would regenerate" + fi + exit 0 + fi + echo "manifest: delegating to $_tool (the ONE parser of manifest.md — this script parses nothing)" + bash "$_tool" "$MANIFEST_MD" "$MANIFEST_JSON" + exit $? +fi + +command -v python3 >/dev/null 2>&1 || { + echo "metastate: python3 is required (stdlib only) — the director and every fleet host have it" >&2 + exit 3 +} + +exec python3 - "$MODE" "$DRY" "$_root" "$CHECKPOINTS" "$SCHEMA" "$ACTIVE_DIR" \ + "$ARCHIVE_DIR" "$ARCHIVE_INDEX" "$MANIFEST_JSON" "$DECISIONS_INDEX" "$HANDOFF_MD" <<'PY' +import json +import os +import re +import sys +import time +from datetime import datetime, timezone + +(mode, dry_s, root, checkpoints_path, schema_path, active_dir, + archive_dir, archive_index, manifest_json, decisions_index, + handoff_md) = sys.argv[1:12] +dry = dry_s == "1" + +AGENT_DIR = os.path.join(root, ".agent") + +PHASES = ["init", "analyse", "roadmap", "design", "decomposition", + "execution", "metastate", "handoff"] + +# What --archive is allowed to move, and what it must leave alone. Anything +# else is UNCLASSIFIED: a fact about the file that a reader must see, not a +# word to guess a synonym for. +MOVABLE = {"approved", "done", "completed", "implemented"} +KEEP = {"pending", "in_progress", "ready_for_review", "rejected", "reopened"} + + +def die(msg, code): + sys.stderr.write("metastate: " + msg + "\n") + raise SystemExit(code) + + +def now_utc(): + return datetime.now(timezone.utc) + + +def iso(dt): + return dt.strftime("%Y-%m-%dT%H:%M:%SZ") + + +def collapse(s): + return " ".join(str(s).split()) + + +def read_json(path): + with open(path, "rb") as fh: + return json.loads(fh.read().decode("utf-8")) + + +def parse_iso(s): + """A tolerant ISO-8601 reader: Z, +hh:mm, a naive stamp, a date alone.""" + if not isinstance(s, str): + return None + s = s.strip() + if not s: + return None + s = s.replace("Z", "+00:00") + try: + dt = datetime.fromisoformat(s) + except ValueError: + return None + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt + + +# --------------------------------------------------------------------------- +# --check: the minimal schema validator. +# +# The keyword list is exactly what checkpoints-schema.json uses (see the +# header: `format` and the annotations are NOT enforced, and the file says so +# rather than pretending). +# --------------------------------------------------------------------------- +def typename(v): + if v is None: + return "null" + if isinstance(v, bool): + return "boolean" + if isinstance(v, dict): + return "object" + if isinstance(v, list): + return "array" + if isinstance(v, str): + return "string" + return "number" + + +def validate(node, sch, path, errors): + t = sch.get("type") + if t is not None: + allowed = t if isinstance(t, list) else [t] + if typename(node) not in allowed: + errors.append("%s: type is %s, the schema allows %s" + % (path, typename(node), allowed)) + return + if "enum" in sch and node not in sch["enum"]: + errors.append("%s: %r is not one of %r" % (path, node, sch["enum"])) + if "pattern" in sch and isinstance(node, str): + if re.search(sch["pattern"], node) is None: + errors.append("%s: %r does not match %s" + % (path, node, sch["pattern"])) + if isinstance(node, dict): + for key in sch.get("required", []): + if key not in node: + errors.append("%s: required key %r is missing" % (path, key)) + props = sch.get("properties", {}) + if sch.get("additionalProperties") is False: + for key in node: + if key not in props: + errors.append("%s: key %r is not declared by the schema" + % (path, key)) + for key, val in node.items(): + if key in props: + validate(val, props[key], path + "." + key, errors) + if isinstance(node, list) and "items" in sch: + for i, val in enumerate(node): + validate(val, sch["items"], "%s[%d]" % (path, i), errors) + + +def mode_check(): + if not os.path.isfile(schema_path): + die("no schema at %s — the kit ships it at .agent/src/TEMPLATES/schemas/; " + "cannot validate without it (METASTATE_SCHEMA overrides the path)" + % schema_path, 3) + if not os.path.isfile(checkpoints_path): + die("no checkpoints at %s — INIT creates it (run install.sh)" + % checkpoints_path, 3) + try: + schema = read_json(schema_path) + except (OSError, ValueError) as exc: + die("schema %s is not readable JSON: %s" % (schema_path, exc), 3) + try: + doc = read_json(checkpoints_path) + except (OSError, ValueError) as exc: + die("%s is not readable JSON: %s" % (checkpoints_path, exc), 1) + + errors = [] + validate(doc, schema, "$", errors) + + phases = doc.get("phases") if isinstance(doc, dict) else None + missing = [p for p in PHASES if not isinstance(phases, dict) or p not in phases] + tasks = doc.get("tasks") if isinstance(doc, dict) else None + n_tasks = len(tasks) if isinstance(tasks, list) else 0 + + if errors: + print("check: FAILED — %d violation(s) in %s" % (len(errors), checkpoints_path)) + print(" schema: %s" % schema_path) + for e in errors: + print(" " + e) + print("") + print(" The schema is the contract: fix the file, not the check. A phase status is") + print(" one of pending|in_progress|completed|failed|skipped — the date and the note") + print(" belong in the request, the manifest row or the handoff summary.") + return 1 + + print("check: ok — %s satisfies %s (%d phase(s), %d task(s))" + % (checkpoints_path, schema_path, len(PHASES) - len(missing), n_tasks)) + if missing: + print(" note: %s absent — the schema does not require it, 00_INIT.md §0.8 does" + % ", ".join("phases." + p for p in missing)) + return 0 + + +# --------------------------------------------------------------------------- +# --requests: what is in active/, and how long it has been approved. +# +# READ-ONLY. `approved` is the status this repository's own `.agent/` proved +# can be permanent (28 files), so the age is the number that matters. +# The request shape has no `approved_at`, so the age comes from `created_at` +# and is an UPPER BOUND on how long it has been approved; when even that is +# missing the file's mtime is used, and the source is printed. +# --------------------------------------------------------------------------- +def request_rows(): + rows = [] + if not os.path.isdir(active_dir): + return rows + for name in sorted(os.listdir(active_dir)): + if not name.endswith(".json"): + continue + path = os.path.join(active_dir, name) + if not os.path.isfile(path): + continue + entry, err = None, "" + try: + entry = read_json(path) + except (OSError, ValueError) as exc: + err = "not readable JSON: %s" % (exc,) + status = "" + if isinstance(entry, dict) and isinstance(entry.get("status"), str): + status = entry["status"].strip().lower() + if err: + status = "" + age, source = None, "" + if isinstance(entry, dict): + for key in ("created_at", "approved_at"): + dt = parse_iso(entry.get(key)) + if dt is not None: + age = (now_utc() - dt).days + source = key + break + if age is None: + try: + age = int((time.time() - os.path.getmtime(path)) // 86400) + source = "mtime" + except OSError: + age, source = None, "" + rid = name[:-5] + title = "" + if isinstance(entry, dict): + rid = entry.get("id") or entry.get("request_id") or rid + title = collapse(entry.get("title", ""))[:60] + rows.append({"file": name, "path": path, "id": rid, "status": status, + "age": age, "age_source": source, "title": title, + "error": err, "entry": entry}) + return rows + + +def status_counts(rows): + counts = {} + for r in rows: + key = r["status"] or "(no status)" + counts[key] = counts.get(key, 0) + 1 + return counts + + +def mode_requests(): + rows = request_rows() + if not os.path.isdir(active_dir): + die("no %s — INIT creates it (run install.sh)" % active_dir, 3) + print("requests: %d file(s) in %s" % (len(rows), active_dir)) + if not rows: + print(" (none — nothing is waiting for review)") + return 0 + + approved = [r for r in rows if r["status"] == "approved"] + for r in rows: + age = " ?" if r["age"] is None else "%4dd" % r["age"] + src = " (%s)" % r["age_source"] if r["age_source"] else "" + status = r["status"] or "(no status)" + print(" %-28s %-14s age %s%s %s" + % (r["file"], status, age, src, r["title"])) + + counts = status_counts(rows) + order = ["approved", "completed", "done", "implemented", "pending", + "in_progress", "ready_for_review", "rejected", "reopened", + "(no status)"] + parts = ["%s=%d" % (k, counts[k]) for k in order if k in counts] + parts += ["%s=%d" % (k, v) for k, v in sorted(counts.items()) if k not in order] + print("summary: " + " ".join(parts)) + + if approved: + dated = [r for r in approved if r["age"] is not None] + oldest = max(dated, key=lambda r: r["age"]) if dated else None + over30 = [r for r in dated if r["age"] >= 30] + line = "approved: %d still in active/" % len(approved) + if oldest is not None: + line += " — oldest %dd (%s)" % (oldest["age"], oldest["id"]) + line += " — %d older than 30d" % len(over30) + print(line) + print(" age comes from created_at (the request shape has no approved_at), so it is") + print(" an upper bound on how long the file has been approved; `--archive` moves it.") + else: + print("approved: 0 — nothing is waiting to be archived") + return 0 + + +# --------------------------------------------------------------------------- +# --archive: move what is finished, keep what is not, index what moved. +# +# REFUSES (leaves in active/, and says why): +# status in KEEP pending / in_progress / ready_for_review / ... +# no status, unreadable UNCLASSIFIED — reported, and the run exits 1 +# the destination exists a collision is never resolved by overwriting +# The index is `.agent/archive/requests/index.json`, sorted by id, and is only +# touched when something actually moved (so a second run writes nothing). +# --------------------------------------------------------------------------- +def mode_archive(): + if not os.path.isdir(active_dir): + die("no %s — INIT creates it (run install.sh)" % active_dir, 3) + + rows = request_rows() + plan, unclassified, kept = [], [], [] + for r in rows: + if r["error"]: + unclassified.append((r, r["error"])) + elif r["status"] in MOVABLE: + plan.append(r) + elif r["status"] in KEEP: + kept.append(r) + else: + unclassified.append((r, "no usable status")) + + print("archive: %d of %d request(s) in %s can move to %s" + % (len(plan), len(rows), active_dir, archive_dir)) + for r in plan: + dst = os.path.join(archive_dir, r["file"]) + note = " (destination exists — refusing to overwrite)" if os.path.exists(dst) else "" + print(" move %-28s (status=%s)%s" % (r["file"], r["status"], note)) + for r in kept: + print(" keep %-28s (status=%s — not approved)" % (r["file"], r["status"])) + for r, why in unclassified: + print(" skip %-28s (%s — left in active/)" % (r["file"], why)) + + problems = len(unclassified) + movable = [r for r in plan + if not os.path.exists(os.path.join(archive_dir, r["file"]))] + problems += len(plan) - len(movable) + + if dry: + if movable: + print(" index: %s would gain %d entr%s" + % (archive_index, len(movable), "y" if len(movable) == 1 else "ies")) + print("archive --dry: nothing written — %d file(s) would move" % len(movable)) + return 1 if problems else 0 + + if not movable: + print("archive: nothing to move — active/ is unchanged") + return 1 if problems else 0 + + os.makedirs(archive_dir, exist_ok=True) + moved = [] + for r in movable: + src = r["path"] + dst = os.path.join(archive_dir, r["file"]) + try: + os.replace(src, dst) + except OSError as exc: + sys.stderr.write("metastate: cannot move %s: %s\n" % (src, exc)) + problems += 1 + continue + moved.append((r, dst)) + print(" moved %-28s → %s" % (r["file"], dst)) + + # The index: read, merge by id (an id already indexed is replaced, never + # duplicated), sort by id, write atomically. + index = {"version": "3.0.0", "requests": []} + if os.path.isfile(archive_index): + try: + old = read_json(archive_index) + if isinstance(old, dict) and isinstance(old.get("requests"), list): + index = old + else: + sys.stderr.write("metastate: %s is not an index — rebuilding it from the " + "archive directory\n" % archive_index) + except (OSError, ValueError) as exc: + sys.stderr.write("metastate: %s is not readable JSON (%s) — rebuilding it\n" + % (archive_index, exc)) + entries = {} + for e in index.get("requests", []): + if isinstance(e, dict) and e.get("id"): + entries[e["id"]] = e + stamp = iso(now_utc()) + for r, _dst in moved: + e = r["entry"] if isinstance(r["entry"], dict) else {} + entry = { + "id": r["id"], + "task_id": e.get("task_id") or e.get("task") or "", + "title": collapse(e.get("title", "")), + "status": r["status"], + "archived_at": stamp, + } + entries[entry["id"]] = entry + index["version"] = index.get("version") or "3.0.0" + index["requests"] = [entries[k] for k in sorted(entries)] + + body = json.dumps(index, ensure_ascii=False, indent=1, sort_keys=False) + "\n" + tmp = "%s.new.%d" % (archive_index, os.getpid()) + try: + with open(tmp, "wb") as fh: + fh.write(body.encode("utf-8")) + os.replace(tmp, archive_index) + except OSError as exc: + sys.stderr.write("metastate: cannot write %s: %s\n" % (archive_index, exc)) + return 1 + print("index: %s — %d entr%s, sorted by id" + % (archive_index, len(index["requests"]), + "y" if len(index["requests"]) == 1 else "ies")) + + if problems: + print("archive: %d request(s) could not be handled — see above" % problems) + return 1 + return 0 + + +# --------------------------------------------------------------------------- +# --handoff: the summary, from the artefacts. Numbers, not prose. +# --------------------------------------------------------------------------- +def mode_handoff(): + if not os.path.isfile(checkpoints_path): + die("no checkpoints at %s — a handoff summarises the session state, and there " + "is none (run install.sh)" % checkpoints_path, 3) + try: + cp = read_json(checkpoints_path) + except (OSError, ValueError) as exc: + die("%s is not readable JSON: %s" % (checkpoints_path, exc), 1) + if not isinstance(cp, dict): + die("%s is not a JSON object" % checkpoints_path, 1) + + phases = cp.get("phases") if isinstance(cp.get("phases"), dict) else {} + rows = request_rows() + counts = status_counts(rows) + approved = [r for r in rows if r["status"] == "approved"] + + tasks, task_src = None, "absent — run --manifest (or install the MD parser)" + if os.path.isfile(manifest_json): + try: + m = read_json(manifest_json) + if isinstance(m, dict) and isinstance(m.get("tasks"), list): + tasks = m["tasks"] + task_src = "manifest.json, source_sha256 %s" % ( + (m.get("source_sha256") or "")[:12] or "(none)") + except (OSError, ValueError) as exc: + task_src = "manifest.json is not readable JSON: %s" % (exc,) + + decisions = None + if os.path.isfile(decisions_index): + try: + d = read_json(decisions_index) + if isinstance(d, dict) and isinstance(d.get("decisions"), list): + decisions = d["decisions"] + except (OSError, ValueError): + decisions = None + + archived = None + if os.path.isfile(archive_index): + try: + a = read_json(archive_index) + if isinstance(a, dict) and isinstance(a.get("requests"), list): + archived = a["requests"] + except (OSError, ValueError): + archived = None + + task_counts = {} + if tasks is not None: + for t in tasks: + st = t.get("status") if isinstance(t, dict) else None + key = st if isinstance(st, str) and st else "(no status)" + task_counts[key] = task_counts.get(key, 0) + 1 + + goal = cp.get("goal") + goal = collapse(goal) if isinstance(goal, str) and goal.strip() else "(unset)" + + L = [] + L.append("# Handoff summary") + L.append("") + L.append("Written by `.agent/src/metastate.sh --handoff` (MetaAgent kit). Every number") + L.append("below is read from an artefact; nothing here is prose invention.") + L.append("") + L.append("## Session") + L.append("") + L.append("- session: `%s`" % (cp.get("session_id") or "(unset)")) + L.append("- metaagent version: `%s`" % (cp.get("metaagent_version") or "(unset)")) + L.append("- goal: %s" % goal) + L.append("- project type: %s" % (cp.get("project_type") or "(unset)")) + L.append("- target repo: %s" % (cp.get("target_repo") or "(unset)")) + L.append("- last updated (checkpoints): %s" % (cp.get("last_updated") or "(unset)")) + L.append("") + L.append("## Phases (`checkpoints.json`)") + L.append("") + L.append("| phase | status |") + L.append("|---|---|") + for p in PHASES: + st = phases.get(p) + L.append("| %s | %s |" % (p, collapse(st) if st else "(absent)")) + extra = [k for k in phases if k not in PHASES] + if extra: + L.append("") + L.append("Undeclared phase keys: %s" % ", ".join(sorted(extra))) + L.append("") + L.append("## Tasks (`manifest.json`)") + L.append("") + if tasks is None: + L.append("- total: unknown — %s" % task_src) + else: + L.append("- total: %d" % len(tasks)) + if task_counts: + L.append("- by status: %s" + % " · ".join("%s %d" % (k, task_counts[k]) + for k in sorted(task_counts))) + L.append("- source: %s" % task_src) + L.append("") + L.append("## Requests (`.agent/requests/active/`)") + L.append("") + L.append("- active: %d" % len(rows)) + if counts: + L.append("- by status: %s" + % " · ".join("%s %d" % (k, counts[k]) for k in sorted(counts))) + if approved: + dated = [r for r in approved if r["age"] is not None] + oldest = max(dated, key=lambda r: r["age"]) if dated else None + line = "- approved and still active: %d" % len(approved) + if oldest is not None: + line += " (oldest %dd: `%s`)" % (oldest["age"], oldest["id"]) + L.append(line) + L.append("- ids: %s" % ", ".join("`%s`" % r["id"] for r in approved)) + else: + L.append("- approved and still active: 0") + if archived is None: + L.append("- archive index: absent (`.agent/archive/requests/index.json`)") + else: + L.append("- archived requests: %d (`.agent/archive/requests/index.json`)" + % len(archived)) + L.append("") + L.append("## ADRs (`.agent/decisions/index.json`)") + L.append("") + if decisions is None: + L.append("- index: absent or unreadable") + elif not decisions: + L.append("- decisions: 0") + else: + L.append("- decisions: %d" % len(decisions)) + for d in decisions: + if not isinstance(d, dict): + continue + L.append(" - ADR-%s %s%s" + % (d.get("id") or "???", collapse(d.get("title", "")) or "(untitled)", + " [%s]" % d["status"] if d.get("status") else "")) + L.append("") + L.append("## Sources") + L.append("") + L.append("- checkpoints: `.agent/checkpoints.json`") + L.append("- tasks: `.agent/tasks/manifest.json`") + L.append("- requests: `.agent/requests/active/`") + L.append("- archive: `.agent/archive/requests/index.json`") + L.append("- decisions: `.agent/decisions/index.json`") + L.append("") + body = "\n".join(L) + + if dry: + print("handoff --dry: would write %s" % handoff_md) + print(" %d phase(s), %d task(s), %d active request(s), %d decision(s)" + % (len(PHASES), 0 if tasks is None else len(tasks), len(rows), + 0 if decisions is None else len(decisions))) + return 0 + + old = None + try: + with open(handoff_md, "rb") as fh: + old = fh.read() + except OSError: + pass + if old == body.encode("utf-8"): + print("handoff: %s — unchanged (the artefacts produce the same summary)" % handoff_md) + return 0 + tmp = "%s.new.%d" % (handoff_md, os.getpid()) + try: + with open(tmp, "wb") as fh: + fh.write(body.encode("utf-8")) + os.replace(tmp, handoff_md) + except OSError as exc: + die("cannot write %s: %s" % (handoff_md, exc), 1) + print("handoff: wrote %s — %d phase(s), %d task(s), %d active request(s), %d decision(s)" + % (handoff_md, len(PHASES), 0 if tasks is None else len(tasks), len(rows), + 0 if decisions is None else len(decisions))) + return 0 + + +if mode == "check": + raise SystemExit(mode_check()) +if mode == "requests": + raise SystemExit(mode_requests()) +if mode == "archive": + raise SystemExit(mode_archive()) +if mode == "handoff": + raise SystemExit(mode_handoff()) +die("unknown mode %r" % mode, 2) +PY diff --git a/.gitignore b/.gitignore index 52b52f3..b9214b9 100644 --- a/.gitignore +++ b/.gitignore @@ -139,3 +139,4 @@ main.js .yarn/install-state.gz .pnp.* +.temp/