@bonesofspring/ai-rules 0.2.55 → 0.2.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ### Confirmed task delete
6
+
7
+ - **New endpoint.** `DELETE /api/v1/tasks/{slug}` (operationId `deleteTask`) deletes one task through the canonical CLI implementation, executed as one bounded child (30 s, `SIGKILL`): `200` with `{"slug":"<S>"}`, strict `404 E_NOT_FOUND`, `409 E_ACTIVE_TASK` with `details.activeSlug` when the slug is the active task, `503 E_DISABLED` under the kill switch, `503 E_BUSY` at the child deadline; the request body is ignored. The frozen contract grows to 23 operations (`docs/openapi/team-db.v1.json`, regenerated by the gate only), `E_ACTIVE_TASK` joins the error enum, and a 405 on the shared task path now advertises `Allow: GET, HEAD, DELETE`.
8
+ - **Folder first, then rows.** The task folder `.ai.local/team/tasks/<slug>/` is removed before one transaction deletes the task's search rows and the task row (every child row goes by foreign-key cascade); a crash between the legs converges toward deleted — the next `sync` marks the leftover rows absent and `--prune` removes them, so content never resurrects. A symlink at the task path is refused, never followed; the slug is validated at the API, the proxy, and the child.
9
+ - **CLI parity.** `team-db.mjs delete --slug <S> [--root <dir>] [--json]` is the single deletion implementation; exit `0` deleted or converged, `1` refusal (unknown slug, active task, kill switch, folder-delete failure), `2` database-level failure (without `node:sqlite` it refuses rather than deleting the folder only), `3` usage, `4` busy database. `--json` prints exactly one machine-readable line.
10
+ - **team-tasks-ui.** The task list and the task detail gain a danger-styled delete affordance over the same-origin proxy; the shared confirmation dialog names the slug, both consequences and irreversibility before any request, cancels with `Escape`/backdrop/`Cancel`, and renders the API error verbatim — including the active-task guard (`409`) and the converged "already deleted" state (`404`).
11
+ - **Docs and gates.** `docs/TEAM-DB.md` states the two-mutation policy; the API suite (16 checks) and the security suite (15 checks) pin the new route, the `Allow` header, the guard, the kill switch, hostile slugs, and the fault-injected leg order.
12
+
13
+ ### Upgrade
14
+
15
+ - Run `npx @bonesofspring/ai-rules update`, then delete the four changed modules in `.ai.local/scripts/` (`team-db.mjs`, `team-db-project.mjs`, `team-db-api.mjs`, `team-db-openapi.mjs`) to take the delete verb and route; seeding stays skip-if-exists.
16
+ - `AI_RULES_TEAM_DB_DISABLE=1` still stops every write point: the delete answers `503 E_DISABLED` over the API and refuses with exit 1 in the CLI.
17
+
3
18
  ## 0.2.55
4
19
 
5
20
  ### $mol preset (eleventh stack)
package/docs/TEAM-DB.md CHANGED
@@ -8,10 +8,10 @@ The projection is installed by `init` as six modules under `.ai.local/scripts/`:
8
8
 
9
9
  | Module | Role |
10
10
  |---|---|
11
- | `team-db.mjs` | CLI: `init`, `sync`, `migrate-tasks`, `check`, `serve` |
11
+ | `team-db.mjs` | CLI: `init`, `sync`, `delete`, `migrate-tasks`, `check`, `serve` |
12
12
  | `team-db-schema.mjs` | capability probe, embedded migrations, pragmas, fingerprint, integrity |
13
- | `team-db-project.mjs` | parsers, idempotent projector, retention, search |
14
- | `team-db-api.mjs` | read-only `node:http` server, query layer, security boundary |
13
+ | `team-db-project.mjs` | parsers, idempotent projector, confirmed task deletion, retention, search |
14
+ | `team-db-api.mjs` | `node:http` server (reads plus two bounded mutations), query layer, security boundary |
15
15
  | `team-db-openapi.mjs` | the OpenAPI 3.1 document source |
16
16
  | `team-db-dashboard.mjs` | the no-build dashboard (HTML, CSS, JS strings) |
17
17
 
@@ -22,11 +22,16 @@ The projection is installed by `init` as six modules under `.ai.local/scripts/`:
22
22
  No agent writes a lifecycle field through the projection.
23
23
  - **The database is rebuildable.** Delete `team.db*` and run `sync`; the next run recreates
24
24
  the schema and reconverges. A schema fingerprint mismatch rebuilds automatically.
25
- - **Writes are isolated.** A projection failure never fails a file write or a receipt. The
26
- hook and `manifest.mjs` run a bounded child (5 s, `SIGKILL`) and append one line to
27
- `team-db-errors.log` on failure.
28
- - **One read-only surface.** `POST /api/v1/sync` is the only mutation; every other route is
29
- `GET`/`HEAD`. There is no write-back, no telemetry, and no outbound request.
25
+ - **Writes are isolated.** A projection or deletion failure never fails a file write or a
26
+ receipt. The hook and `manifest.mjs` each run a bounded child (5 s, `SIGKILL`) and append
27
+ one line to `team-db-errors.log` on failure; the confirmed task delete runs its own
28
+ bounded child (30 s, `SIGKILL`), and its failure reaches the caller through the one error
29
+ envelope, or one stderr line on the CLI.
30
+ - **Two bounded mutations.** `POST /api/v1/sync` re-runs the projector; `DELETE
31
+ /api/v1/tasks/{slug}` deletes one confirmed task (the folder first, then the rows). Every
32
+ other route is `GET`/`HEAD`, and both mutations run as bounded child processes — the
33
+ server process never opens a writable connection, and the kill switch stops both before a
34
+ child is spawned. There is no write-back, no telemetry, and no outbound request.
30
35
  - **Local only.** The server binds loopback by default, checks `Host` and `Origin`, sends no
31
36
  CORS header, and serves raw documents from SQLite by exact `(slug, path)` lookup.
32
37
 
@@ -63,6 +68,7 @@ below the floor, or a build without `node:sqlite`, is detected at runtime:
63
68
  | `manifest.mjs` upsert | one line, return 0 after the receipt | silent, return 0 |
64
69
  | `team-db.mjs init` / `sync` / `migrate-tasks` | one line, exit 0, no file | one line, exit 0, no file |
65
70
  | `team-db.mjs check` | one line, exit 1 | one line, exit 1 |
71
+ | `team-db.mjs delete` | one line, exit 2 | one line, exit 1 |
66
72
  | `team-db.mjs serve` | one line, exit 0 | one line, exit 0 |
67
73
 
68
74
  The file-only pipeline is unchanged: `status.json` / `metrics.json` writes, manifest upserts,
@@ -75,6 +81,7 @@ node .ai.local/scripts/team-db.mjs init [--root <team-dir>] [--rebuild]
75
81
  node .ai.local/scripts/team-db.mjs sync [--root <team-dir>] [--slug <slug>] [--quiet] [--json]
76
82
  [--maintain] [--prune] [--vacuum]
77
83
  [--rebuild | --no-rebuild] [--deadline-ms <n>]
84
+ node .ai.local/scripts/team-db.mjs delete --slug <slug> [--root <team-dir>] [--json]
78
85
  node .ai.local/scripts/team-db.mjs migrate-tasks [--root <team-dir>] [--quiet] [--json]
79
86
  [--rebuild | --no-rebuild]
80
87
  node .ai.local/scripts/team-db.mjs check [--root <team-dir>]
@@ -82,9 +89,11 @@ node .ai.local/scripts/team-db.mjs serve [--root <team-dir>] [--host <addr>] [--
82
89
  [--allow-remote] [--open]
83
90
  ```
84
91
 
85
- Exit codes: `0` ok, `1` at least one task failed or a migration checksum drifted, `2`
86
- database-level failure, `3` usage, `4` deadline or busy database on the hook-shaped `--slug`
87
- path.
92
+ Exit codes: `0` ok, `1` at least one task failed, a delete refusal (unknown slug, active
93
+ task, kill switch, folder-delete failure) or a migration checksum drifted, `2`
94
+ database-level failure — a `delete` without `node:sqlite` refuses here rather than deleting
95
+ the folder only, `3` usage, `4` deadline or busy database (the hook-shaped `sync --slug`
96
+ deadline, or a delete that meets a locked database).
88
97
 
89
98
  `sync` is idempotent: a second run reports `inserted=0 updated=0 unchanged=<n>`. One changed
90
99
  byte changes exactly one document hash and one task content hash. A removed task directory is
@@ -102,6 +111,20 @@ suppresses only the human line. `failed` is an overlay counter — a malformed t
102
111
  `inserted`/`updated` **and** in `failed`, so the counters are not a partition. `--slug`,
103
112
  `--maintain`, `--prune`, `--vacuum`, and `--deadline-ms` do not apply to this verb (exit 3).
104
113
 
114
+ `delete` removes one task on explicit request. The slug is validated against the shared
115
+ pattern and confined to `.ai.local/team/tasks/<slug>/` — a symlink at that path is refused
116
+ with `E_NOT_FOUND`, never followed or removed. The kill switch refuses with `E_DISABLED`
117
+ before anything runs; a task whose slug equals `active-task.json`'s slug is refused with
118
+ `E_ACTIVE_TASK`; an unknown slug is refused with `E_NOT_FOUND`. The deletion itself is
119
+ folder first, then one transaction that removes the task's search rows and the task row
120
+ (every child row goes by foreign-key cascade); no `sync_runs` row is written. If the
121
+ process dies between the two legs, the next `sync` marks the leftover rows absent and
122
+ `sync --prune` removes them — content never resurrects. Repeating a finished delete
123
+ refuses with `E_NOT_FOUND`. With `--json` the command prints exactly one machine-readable
124
+ line: `{ ok: true, slug, folderRemoved, rowsDeleted }` on success, `{ ok: false, code,
125
+ message }` on a refusal. The delete runs wherever the command runs: the team root it
126
+ targets must be on the same host.
127
+
105
128
  ## Environment names
106
129
 
107
130
  | Name | Effect |
@@ -142,6 +165,17 @@ JS are served from `/assets/`, and the OpenAPI 3.1 document is at `/openapi.json
142
165
  document is checked in at `packages/ai-rules/docs/openapi/team-db.v1.json`; the gate is
143
166
  `node scripts/check-team-db-contract.mjs`.
144
167
 
168
+ The API exposes the delete as `DELETE /api/v1/tasks/{slug}` — the same canonical deletion
169
+ as the CLI, executed as one bounded child. It answers `200` with `{"slug":"<S>"}` on
170
+ success, `404 E_NOT_FOUND` for an unknown slug, `409 E_ACTIVE_TASK` with
171
+ `details.activeSlug` when the slug is the active task, `503 E_DISABLED` when the kill
172
+ switch is set, and `503 E_BUSY` when the child is killed at its 30 s bound; a wrong method
173
+ on the shared path answers `405` with `Allow: GET, HEAD, DELETE`, and the request body is
174
+ ignored. An unexpected child failure maps to the generic `E_INTERNAL` envelope with one
175
+ trimmed stderr line from the child. The delete executes wherever the API runs — the host
176
+ that owns `.ai.local/team/`; a UI that only proxies to the API (for example the
177
+ containerized team-tasks-ui) deletes through it on that same host.
178
+
145
179
  Security boundary: loopback bind by default (`--host` outside loopback needs
146
180
  `--allow-remote`, and a wildcard address is refused), exact `Host`/`Origin` allow-list,
147
181
  no `Access-Control-*` header, hardened response headers, request bodies bounded at 1 KiB,
@@ -156,7 +190,9 @@ for tasks absent longer than 90 days while keeping normalized rows and hashes.
156
190
 
157
191
  ## Rollback
158
192
 
159
- 1. Set `AI_RULES_TEAM_DB_DISABLE=1`. Every write point and `serve` becomes a no-op with exit 0.
193
+ 1. Set `AI_RULES_TEAM_DB_DISABLE=1`. Every write point becomes a no-op: the hook,
194
+ `manifest.mjs`, `init`/`sync`/`migrate-tasks` and `serve` exit 0; `delete` refuses with
195
+ exit 1 and touches nothing.
160
196
  2. Delete the projection: `rm -f .ai.local/team/team.db .ai.local/team/team.db-wal
161
197
  .ai.local/team/team.db-shm .ai.local/team/team-db-errors.log`. No task file is touched.
162
198
  3. Revert the code: remove the hook region and the `projectAfterReceipt` call, delete the six
@@ -3,8 +3,8 @@
3
3
  "jsonSchemaDialect": "https://json-schema.org/draft/2020-12/schema",
4
4
  "info": {
5
5
  "title": "Agent team SQLite projection API",
6
- "summary": "Read-only projection of `.ai.local/team`. Task files are authoritative; the database is a rebuildable copy. The only mutation is an idempotent rescan.",
7
- "description": "Loopback-only operator API. No authentication by design, no CORS, no outbound request. Errors use one `{error:{code,message,details?}}` envelope. Every non-GET/HEAD request to a read-only path returns 405 `E_METHOD_NOT_ALLOWED` with `Allow: GET, HEAD`; `GET` and `HEAD` on `/api/v1/sync` return 405 with `Allow: POST`.",
6
+ "summary": "Projection of `.ai.local/team`. Task files are authoritative; the database is a rebuildable copy. Two mutations exist — the idempotent rescan and the confirmed task delete — and both run as bounded child processes.",
7
+ "description": "Loopback-only operator API. No authentication by design, no CORS, no outbound request. Errors use one `{error:{code,message,details?}}` envelope. Every non-GET/HEAD request to a read-only path returns 405 `E_METHOD_NOT_ALLOWED` with `Allow: GET, HEAD`; `GET` and `HEAD` on `/api/v1/sync` return 405 with `Allow: POST`; any other method on `/api/v1/tasks/{slug}` returns 405 with `Allow: GET, HEAD, DELETE`.",
8
8
  "version": "1.0.0",
9
9
  "x-api-major": 1
10
10
  },
@@ -759,6 +759,107 @@
759
759
  }
760
760
  },
761
761
  "security": []
762
+ },
763
+ "delete": {
764
+ "tags": [
765
+ "tasks"
766
+ ],
767
+ "summary": "Delete one task: the task folder first, then its projection rows",
768
+ "description": "Confirmed, destructive and irreversible. The task folder `.ai.local/team/tasks/{slug}` is removed before the database rows, so a crash between the two legs converges toward deleted on the next rescan and never resurrects content. The row delete is one transaction: the task row plus every child row by cascade, plus the task's search rows. The slug in `active-task.json` is refused with 409 `E_ACTIVE_TASK`. An unknown slug answers 404 `E_NOT_FOUND` and touches nothing. The request body is ignored and no query parameters are declared. Executed as a bounded child process; `AI_RULES_TEAM_DB_DISABLE=1` answers 503 `E_DISABLED` before anything runs.",
769
+ "operationId": "deleteTask",
770
+ "parameters": [
771
+ {
772
+ "name": "slug",
773
+ "in": "path",
774
+ "required": true,
775
+ "description": "Task directory name.",
776
+ "schema": {
777
+ "type": "string",
778
+ "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$"
779
+ }
780
+ }
781
+ ],
782
+ "responses": {
783
+ "200": {
784
+ "description": "The deleted slug",
785
+ "content": {
786
+ "application/json": {
787
+ "schema": {
788
+ "$ref": "#/components/schemas/TaskDeleteResult"
789
+ }
790
+ }
791
+ }
792
+ },
793
+ "400": {
794
+ "description": "Malformed request: an invalid slug",
795
+ "content": {
796
+ "application/json": {
797
+ "schema": {
798
+ "$ref": "#/components/schemas/ErrorEnvelope"
799
+ }
800
+ }
801
+ }
802
+ },
803
+ "403": {
804
+ "description": "A non-loopback Host or Origin was rejected before routing",
805
+ "content": {
806
+ "application/json": {
807
+ "schema": {
808
+ "$ref": "#/components/schemas/ErrorEnvelope"
809
+ }
810
+ }
811
+ }
812
+ },
813
+ "404": {
814
+ "description": "The task does not exist in the projection or on disk",
815
+ "content": {
816
+ "application/json": {
817
+ "schema": {
818
+ "$ref": "#/components/schemas/ErrorEnvelope"
819
+ }
820
+ }
821
+ }
822
+ },
823
+ "405": {
824
+ "description": "The route does not accept this method; the response carries an Allow header",
825
+ "headers": {
826
+ "Allow": {
827
+ "description": "HTTP methods allowed on this path, for example `GET, HEAD`",
828
+ "schema": {
829
+ "type": "string"
830
+ }
831
+ }
832
+ },
833
+ "content": {
834
+ "application/json": {
835
+ "schema": {
836
+ "$ref": "#/components/schemas/ErrorEnvelope"
837
+ }
838
+ }
839
+ }
840
+ },
841
+ "409": {
842
+ "description": "The slug is the active task; the delete is refused with `details.activeSlug` naming it",
843
+ "content": {
844
+ "application/json": {
845
+ "schema": {
846
+ "$ref": "#/components/schemas/ErrorEnvelope"
847
+ }
848
+ }
849
+ }
850
+ },
851
+ "503": {
852
+ "description": "The projection is disabled, the database is missing, unusable, busy, or the child exceeded its time bound",
853
+ "content": {
854
+ "application/json": {
855
+ "schema": {
856
+ "$ref": "#/components/schemas/ErrorEnvelope"
857
+ }
858
+ }
859
+ }
860
+ }
861
+ },
862
+ "security": []
762
863
  }
763
864
  },
764
865
  "/api/v1/tasks/{slug}/pipeline": {
@@ -2490,6 +2591,7 @@
2490
2591
  "E_DOC_NOT_FOUND",
2491
2592
  "E_DOC_BINARY",
2492
2593
  "E_DOC_CONTENT_OMITTED",
2594
+ "E_ACTIVE_TASK",
2493
2595
  "E_RANGE",
2494
2596
  "E_DISABLED",
2495
2597
  "E_DB_MISSING",
@@ -2842,6 +2944,24 @@
2842
2944
  }
2843
2945
  ]
2844
2946
  },
2947
+ "TaskDeleteResult": {
2948
+ "type": "object",
2949
+ "additionalProperties": false,
2950
+ "properties": {
2951
+ "slug": {
2952
+ "type": "string",
2953
+ "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$"
2954
+ }
2955
+ },
2956
+ "required": [
2957
+ "slug"
2958
+ ],
2959
+ "examples": [
2960
+ {
2961
+ "slug": "agent-team-sqlite-dashboard"
2962
+ }
2963
+ ]
2964
+ },
2845
2965
  "TaskDetail": {
2846
2966
  "type": "object",
2847
2967
  "additionalProperties": false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bonesofspring/ai-rules",
3
- "version": "0.2.55",
3
+ "version": "0.2.56",
4
4
  "description": "Presets of Cursor, Claude, Mavis, OpenCode, and ZCode rules/commands for Revy Ross personal use",
5
5
  "license": "MIT",
6
6
  "author": "Revy Ross",
@@ -1,9 +1,12 @@
1
1
  /**
2
- * Read-only HTTP API and dashboard host for the `.ai.local/team` projection.
2
+ * HTTP API and dashboard host for the `.ai.local/team` projection.
3
3
  *
4
4
  * `node:http` only. The surface is loopback-only by default, sends no CORS
5
- * header, reads files through SQLite rows (never through a request path), and
6
- * the single non-GET operation re-runs the projector in a child process.
5
+ * header, and reads files through SQLite rows (never through a request path).
6
+ * The two mutating operations — the idempotent rescan and the confirmed task
7
+ * delete — each run one bounded child process; the server itself never opens a
8
+ * writable connection and the kill switch stops both mutations before a child
9
+ * is spawned.
7
10
  *
8
11
  * Every SQL statement in this module is a static string with bound parameters.
9
12
  * The only interpolated fragments are the module-level constants `TASK_FILTER`,
@@ -83,6 +86,7 @@ const CODE_STATUS_ROWS = [
83
86
  ['E_DOC_NOT_FOUND', 404],
84
87
  ['E_DOC_BINARY', 410],
85
88
  ['E_DOC_CONTENT_OMITTED', 409],
89
+ ['E_ACTIVE_TASK', 409],
86
90
  ['E_RANGE', 416],
87
91
  ['E_DISABLED', 503],
88
92
  ['E_DB_MISSING', 503],
@@ -974,6 +978,56 @@ const runSyncChild = (db, settings) => {
974
978
  };
975
979
  };
976
980
 
981
+ /* --------------------------------- delete ---------------------------------- */
982
+
983
+ /**
984
+ * Delete one task through the canonical CLI implementation in a bounded child.
985
+ *
986
+ * The kill switch is checked before anything runs; the server process never
987
+ * opens a writable connection. The child prints exactly one JSON line: the
988
+ * result on success, `{ ok: false, code, message }` on a refusal — and every
989
+ * refusal code is mapped back into the one documented envelope, so no
990
+ * unspecified code ever leaks. The 30 s `SIGKILL` bound and the sanitized
991
+ * one-line stderr detail are the rescan child's own.
992
+ */
993
+ const runDeleteChild = (slug, settings) => {
994
+ if (isKillSwitchSet()) fail('E_DISABLED', 503, 'the projection is disabled by AI_RULES_TEAM_DB_DISABLE');
995
+ const script = path.join(moduleDirectory, 'team-db.mjs');
996
+ if (!fs.existsSync(script)) fail('E_DB_MISSING', 503, 'team-db.mjs is not installed next to the server');
997
+ const child = spawnSync(
998
+ process.execPath,
999
+ [script, 'delete', '--slug', slug, '--json', '--root', settings.teamRoot],
1000
+ { cwd: settings.cwd, env: { ...process.env, AI_RULES_TEAM_DB_PATH: settings.dbPath }, encoding: 'utf8', timeout: SYNC_CHILD_TIMEOUT_MS, killSignal: 'SIGKILL', stdio: ['ignore', 'pipe', 'pipe'] },
1001
+ );
1002
+ if (child.error && child.error.code === 'ETIMEDOUT') fail('E_BUSY', 503, `the delete of ${slug} exceeded 30 s and was killed`);
1003
+ if (child.error) fail('E_INTERNAL', 500, 'the delete child could not start');
1004
+ let parsed = null;
1005
+ try {
1006
+ parsed = JSON.parse(String(child.stdout || '').trim());
1007
+ } catch {
1008
+ parsed = null;
1009
+ }
1010
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
1011
+ // One `path: reason` line, never prompt content, so an operator can act.
1012
+ const detail = String(child.stderr || '')
1013
+ .split('\n')
1014
+ .map((line) => line.trim())
1015
+ .find((line) => line.length > 0);
1016
+ fail('E_INTERNAL', 500, `the delete exited ${child.status} without a parseable result${detail ? ` (${detail.slice(0, 300)})` : ''}`);
1017
+ }
1018
+ if (parsed.ok === false) {
1019
+ const code = typeof parsed.code === 'string' ? parsed.code : 'E_INTERNAL';
1020
+ // The guard fires only when the target is the active slug, so the detail
1021
+ // names it exactly; the message the child printed names it too.
1022
+ const details = code === 'E_ACTIVE_TASK' ? { activeSlug: slug } : undefined;
1023
+ fail(mapTeamDbCode(code), mapTeamDbCode(code, true), String(parsed.message ?? `the delete of ${slug} was refused`), details);
1024
+ }
1025
+ if (parsed.ok !== true || typeof parsed.slug !== 'string') {
1026
+ fail('E_INTERNAL', 500, `the delete of ${slug} reported neither a success nor a documented refusal`);
1027
+ }
1028
+ return { slug: parsed.slug };
1029
+ };
1030
+
977
1031
  /* --------------------------------- routing -------------------------------- */
978
1032
 
979
1033
  const route = (method, routePath, operationId, handler) => ({
@@ -1016,6 +1070,13 @@ export const ROUTES = [
1016
1070
  route('GET', '/api/v1/tasks/{slug}', 'getTask', (context) => ({
1017
1071
  json: getTaskDetail(context.db(), context.params.slug),
1018
1072
  })),
1073
+ route('DELETE', '/api/v1/tasks/{slug}', 'deleteTask', (context) => {
1074
+ // The kill switch answers before any read or child spawn; the existence
1075
+ // pre-read fast-fails an unknown slug through the read-only handle.
1076
+ if (isKillSwitchSet()) fail('E_DISABLED', 503, 'the projection is disabled by AI_RULES_TEAM_DB_DISABLE');
1077
+ requireTask(context.db(), context.params.slug);
1078
+ return { json: runDeleteChild(context.params.slug, context.settings) };
1079
+ }),
1019
1080
  taskRoute('getTaskPipeline', { path: 'pipeline', handler: getPipeline }),
1020
1081
  taskRoute('listTaskAttempts', { path: 'attempts', handler: listAttempts }),
1021
1082
  taskRoute('listTaskEvents', { path: 'events', handler: listEvents }),
@@ -1155,7 +1216,12 @@ const handle = async (req, res, settings) => {
1155
1216
  if (!entry) {
1156
1217
  const allowed = methodsFor(pathname);
1157
1218
  if (allowed.length > 0) {
1158
- const allow = allowed.includes('GET') ? 'GET, HEAD' : allowed.join(', ');
1219
+ // HEAD rides the GET entry, so a path that serves GET advertises it;
1220
+ // the shared task path advertises `GET, HEAD, DELETE`, never a
1221
+ // GET-biased list that hides DELETE.
1222
+ const allow = allowed.includes('GET')
1223
+ ? ['GET', 'HEAD', ...allowed.filter((candidate) => candidate !== 'GET')].join(', ')
1224
+ : allowed.join(', ');
1159
1225
  sendJson(req, res, 405, { error: { code: 'E_METHOD_NOT_ALLOWED', message: `${method} is not allowed on ${pathname}` } }, { Allow: allow });
1160
1226
  return;
1161
1227
  }
@@ -1,5 +1,6 @@
1
1
  /**
2
- * The OpenAPI 3.1 document for the read-only team-db API.
2
+ * The OpenAPI 3.1 document for the team-db API: reads plus two bounded
3
+ * mutations (the idempotent rescan and the confirmed task delete).
3
4
  *
4
5
  * This module is the single source of the checked-in
5
6
  * `packages/ai-rules/docs/openapi/team-db.v1.json`: `check-team-db-contract.mjs
@@ -61,6 +62,7 @@ export const ERROR_CODES = [
61
62
  'E_DOC_NOT_FOUND',
62
63
  'E_DOC_BINARY',
63
64
  'E_DOC_CONTENT_OMITTED',
65
+ 'E_ACTIVE_TASK',
64
66
  'E_RANGE',
65
67
  'E_DISABLED',
66
68
  'E_DB_MISSING',
@@ -225,6 +227,12 @@ const schemas = {
225
227
  },
226
228
  ['items', 'total', 'limit', 'offset', 'nextOffset'],
227
229
  ),
230
+ TaskDeleteResult: object(
231
+ {
232
+ slug: { type: 'string', pattern: SLUG_PATTERN },
233
+ },
234
+ ['slug'],
235
+ ),
228
236
  TaskDetail: object(
229
237
  {
230
238
  task: ref('TaskSummary'),
@@ -813,6 +821,7 @@ const EXAMPLES = {
813
821
  ErrorEnvelope: [{ error: { code: 'E_VALIDATION', message: 'limit must be an integer between 1 and 200', details: { parameter: 'limit' } } }],
814
822
  TaskSummary: [taskSummaryExample],
815
823
  TaskList: [{ items: [taskSummaryExample], total: 90, limit: 50, offset: 0, nextOffset: 50 }],
824
+ TaskDeleteResult: [{ slug: 'agent-team-sqlite-dashboard' }],
816
825
  TaskDetail: [detailExample],
817
826
  Pipeline: [
818
827
  {
@@ -1106,9 +1115,9 @@ export const OPENAPI_DOCUMENT = {
1106
1115
  info: {
1107
1116
  title: 'Agent team SQLite projection API',
1108
1117
  summary:
1109
- 'Read-only projection of `.ai.local/team`. Task files are authoritative; the database is a rebuildable copy. The only mutation is an idempotent rescan.',
1118
+ 'Projection of `.ai.local/team`. Task files are authoritative; the database is a rebuildable copy. Two mutations exist — the idempotent rescan and the confirmed task delete — and both run as bounded child processes.',
1110
1119
  description:
1111
- 'Loopback-only operator API. No authentication by design, no CORS, no outbound request. Errors use one `{error:{code,message,details?}}` envelope. Every non-GET/HEAD request to a read-only path returns 405 `E_METHOD_NOT_ALLOWED` with `Allow: GET, HEAD`; `GET` and `HEAD` on `/api/v1/sync` return 405 with `Allow: POST`.',
1120
+ 'Loopback-only operator API. No authentication by design, no CORS, no outbound request. Errors use one `{error:{code,message,details?}}` envelope. Every non-GET/HEAD request to a read-only path returns 405 `E_METHOD_NOT_ALLOWED` with `Allow: GET, HEAD`; `GET` and `HEAD` on `/api/v1/sync` return 405 with `Allow: POST`; any other method on `/api/v1/tasks/{slug}` returns 405 with `Allow: GET, HEAD, DELETE`.',
1112
1121
  version: API_VERSION,
1113
1122
  'x-api-major': API_MAJOR,
1114
1123
  },
@@ -1210,6 +1219,23 @@ export const OPENAPI_DOCUMENT = {
1210
1219
  },
1211
1220
  '/api/v1/tasks/{slug}': {
1212
1221
  get: taskScopedOperation(['tasks'], 'One task with routing and counts', 'getTask', 'TaskDetail'),
1222
+ delete: operation({
1223
+ tags: ['tasks'],
1224
+ summary: 'Delete one task: the task folder first, then its projection rows',
1225
+ description:
1226
+ 'Confirmed, destructive and irreversible. The task folder `.ai.local/team/tasks/{slug}` is removed before the database rows, so a crash between the two legs converges toward deleted on the next rescan and never resurrects content. The row delete is one transaction: the task row plus every child row by cascade, plus the task\'s search rows. The slug in `active-task.json` is refused with 409 `E_ACTIVE_TASK`. An unknown slug answers 404 `E_NOT_FOUND` and touches nothing. The request body is ignored and no query parameters are declared. Executed as a bounded child process; `AI_RULES_TEAM_DB_DISABLE=1` answers 503 `E_DISABLED` before anything runs.',
1227
+ operationId: 'deleteTask',
1228
+ parameters: [slugParameter],
1229
+ responses: {
1230
+ 200: jsonResponse('TaskDeleteResult', 'The deleted slug'),
1231
+ 400: errorResponse('Malformed request: an invalid slug'),
1232
+ 403: errorResponse('A non-loopback Host or Origin was rejected before routing'),
1233
+ 404: errorResponse('The task does not exist in the projection or on disk'),
1234
+ 405: methodNotAllowedResponse,
1235
+ 409: errorResponse('The slug is the active task; the delete is refused with `details.activeSlug` naming it'),
1236
+ 503: errorResponse('The projection is disabled, the database is missing, unusable, busy, or the child exceeded its time bound'),
1237
+ },
1238
+ }),
1213
1239
  },
1214
1240
  '/api/v1/tasks/{slug}/pipeline': {
1215
1241
  get: taskScopedOperation(['pipeline'], 'Pipeline steps with derived state', 'getTaskPipeline', 'Pipeline'),
@@ -1,11 +1,14 @@
1
1
  /**
2
- * Parsers and projector for the `.ai.local/team` SQLite projection.
2
+ * Parsers, the idempotent projector, confirmed task deletion, retention and
3
+ * search for the `.ai.local/team` SQLite projection.
3
4
  *
4
5
  * Files are authoritative. One task directory is one transaction: parse the
5
6
  * known artifacts, upsert every normalized row by its natural key, store every
6
7
  * regular file as a raw document, and rebuild the task's search rows. A
7
8
  * malformed input is recorded and the rest of the tree still projects; a
8
- * database-level failure aborts the run.
9
+ * database-level failure aborts the run. Deleting a task removes the folder
10
+ * before the rows, so a crash between the legs converges toward deleted on
11
+ * the next rescan and never resurrects content.
9
12
  *
10
13
  * Nothing here writes a lifecycle file. `status.json` and `metrics.json` are
11
14
  * read-only inputs.
@@ -16,12 +19,14 @@ import fs from 'node:fs';
16
19
  import path from 'node:path';
17
20
 
18
21
  import {
22
+ DEFAULT_TEAM_ROOT,
19
23
  SEARCH_MODE_FTS5,
20
24
  TeamDbError,
21
25
  chmodDatabaseFiles,
22
26
  integrityCheck,
23
27
  isBusyError,
24
28
  isCorruptError,
29
+ isKillSwitchSet,
25
30
  openTeamDb,
26
31
  readSearchMode,
27
32
  teamDbFail,
@@ -1581,6 +1586,142 @@ export function syncProjection(options = {}) {
1581
1586
  }
1582
1587
  }
1583
1588
 
1589
+ /**
1590
+ * Delete one task: the folder first (files are authoritative), then the rows.
1591
+ *
1592
+ * The two legs converge prior partial states: a folder without rows loses
1593
+ * only the folder; rows without a folder lose only the rows. The row leg is
1594
+ * one transaction — the task row plus every child row by foreign-key cascade,
1595
+ * plus the task's standalone search rows. The active-task guard and the slug
1596
+ * confinement run before any leg, and a symlink at `tasks/<slug>` is refused,
1597
+ * never followed or removed.
1598
+ *
1599
+ * Returns the one-line result the CLI prints and the API child parses:
1600
+ * `{ ok: true, slug, folderRemoved, rowsDeleted }`. Throws `TeamDbError`:
1601
+ * `E_DISABLED` (kill switch, exit 1), `E_USAGE` (bad slug, exit 3),
1602
+ * `E_NOT_FOUND` (nothing to delete, exit 1), `E_ACTIVE_TASK` (the guard,
1603
+ * exit 1), `E_INTERNAL` (the folder leg failed, exit 1), and the
1604
+ * database-level `E_DB_BUSY` (exit 4) / `E_DB_CORRUPT` (exit 2).
1605
+ */
1606
+ export function deleteTaskProjection(options = {}) {
1607
+ const slug = typeof options.slug === 'string' ? options.slug : '';
1608
+ if (isKillSwitchSet(options.env ?? process.env)) {
1609
+ teamDbFail('E_DISABLED', 'disabled by AI_RULES_TEAM_DB_DISABLE', 1);
1610
+ }
1611
+ if (!SLUG_RE.test(slug)) {
1612
+ teamDbFail('E_USAGE', `delete needs a slug matching ${SLUG_RE.source}`, 3);
1613
+ }
1614
+ const teamRoot = path.resolve(options.teamRoot || process.env.AI_RULES_TEAM_DB_ROOT || DEFAULT_TEAM_ROOT);
1615
+ const tasksRoot = path.join(teamRoot, 'tasks');
1616
+ const taskDir = path.join(tasksRoot, slug);
1617
+
1618
+ // The guard reads the team root, not the database, and runs before any leg.
1619
+ // The parse stays inside the try; the refusal lives outside it, so a named
1620
+ // guard failure is never mistaken for an unreadable guard file. An
1621
+ // unreadable or missing guard file does not block the delete.
1622
+ let guardSlug = null;
1623
+ try {
1624
+ const guard = JSON.parse(fs.readFileSync(path.join(teamRoot, 'active-task.json'), 'utf8'));
1625
+ guardSlug = guard && typeof guard.slug === 'string' ? guard.slug : null;
1626
+ } catch {
1627
+ guardSlug = null;
1628
+ }
1629
+ if (guardSlug === slug) {
1630
+ teamDbFail(
1631
+ 'E_ACTIVE_TASK',
1632
+ `${slug} is the active task; a pipeline may be writing into it, and deletion is blocked while it is active`,
1633
+ 1,
1634
+ );
1635
+ }
1636
+
1637
+ // Presence is a real directory on an lstat: a symlink (or any other
1638
+ // non-directory) is refused with the unknown-slug outcome and is never
1639
+ // followed or removed.
1640
+ let dirState = 'absent';
1641
+ try {
1642
+ dirState = fs.lstatSync(taskDir).isDirectory() ? 'present' : 'not-a-directory';
1643
+ } catch {
1644
+ dirState = 'absent';
1645
+ }
1646
+ if (dirState === 'not-a-directory') {
1647
+ teamDbFail('E_NOT_FOUND', `no task "${slug}" in the team root; its path is not a task directory, and nothing was deleted`, 1);
1648
+ }
1649
+
1650
+ let handle = null;
1651
+ try {
1652
+ handle = openTeamDb({ teamRoot, dbPath: options.dbPath, env: options.env });
1653
+ } catch (error) {
1654
+ if (isBusyError(error)) teamDbFail('E_DB_BUSY', `${slug}: ${error.message}`, 4);
1655
+ if (isCorruptError(error)) teamDbFail('E_DB_CORRUPT', `${slug}: ${error.message}`, 2);
1656
+ throw error;
1657
+ }
1658
+ const { db } = handle;
1659
+
1660
+ try {
1661
+ let rowExists = false;
1662
+ try {
1663
+ rowExists = db.prepare('SELECT slug FROM tasks WHERE slug = ?').get(slug) !== undefined;
1664
+ } catch (error) {
1665
+ if (isBusyError(error)) teamDbFail('E_DB_BUSY', `${slug}: ${error.message}`, 4);
1666
+ if (isCorruptError(error)) teamDbFail('E_DB_CORRUPT', `${slug}: ${error.message}`, 2);
1667
+ throw error;
1668
+ }
1669
+
1670
+ if (!rowExists && dirState !== 'present') {
1671
+ teamDbFail('E_NOT_FOUND', `no task "${slug}" in the projection or the team root`, 1);
1672
+ }
1673
+
1674
+ if (dirState === 'present') {
1675
+ // Belt and braces: the slug pattern admits no separator or dot segment,
1676
+ // so the task directory is tasksRoot/<slug> by construction; the
1677
+ // realpath prefix check also closes an ancestor-symlink escape.
1678
+ const realTaskDir = fs.realpathSync(taskDir);
1679
+ const realTasksRoot = fs.realpathSync(tasksRoot);
1680
+ if (!realTaskDir.startsWith(realTasksRoot + path.sep)) {
1681
+ teamDbFail('E_INTERNAL', `${slug}: the task folder resolves outside the tasks root; nothing was deleted`, 1);
1682
+ }
1683
+ // Leg A — files first. The next rescan finds no directory and
1684
+ // reconciles the rows toward deleted; content can never resurrect.
1685
+ try {
1686
+ fs.rmSync(taskDir, { recursive: true, force: true });
1687
+ } catch (error) {
1688
+ teamDbFail('E_INTERNAL', `${slug}: the task folder could not be deleted (${error.message}); the row leg did not run`, 1);
1689
+ }
1690
+ }
1691
+
1692
+ // Leg B — one transaction. `DELETE FROM tasks` cascades every child table
1693
+ // under `PRAGMA foreign_keys=ON`; `search_fts` is a standalone FTS table
1694
+ // with no foreign key, so its rows are deleted explicitly.
1695
+ let rowsDeleted = 0;
1696
+ if (rowExists) {
1697
+ try {
1698
+ db.exec('BEGIN IMMEDIATE');
1699
+ if (hasSearchTable(db)) db.prepare('DELETE FROM search_fts WHERE task_slug = ?').run(slug);
1700
+ rowsDeleted = db.prepare('DELETE FROM tasks WHERE slug = ?').run(slug).changes;
1701
+ db.exec('COMMIT');
1702
+ } catch (error) {
1703
+ try {
1704
+ db.exec('ROLLBACK');
1705
+ } catch {
1706
+ /* the failed transaction is already unwound */
1707
+ }
1708
+ if (isBusyError(error)) teamDbFail('E_DB_BUSY', `${slug}: ${error.message}`, 4);
1709
+ if (isCorruptError(error)) teamDbFail('E_DB_CORRUPT', `${slug}: ${error.message}`, 2);
1710
+ throw error;
1711
+ }
1712
+ }
1713
+
1714
+ chmodDatabaseFiles(handle.dbPath);
1715
+ return { ok: true, slug, folderRemoved: dirState === 'present', rowsDeleted };
1716
+ } finally {
1717
+ try {
1718
+ db.close();
1719
+ } catch {
1720
+ /* a close error after a settled leg is not a delete failure */
1721
+ }
1722
+ }
1723
+ }
1724
+
1584
1725
  /** Human summary for a `sync` run. */
1585
1726
  export function describeSyncResult(result) {
1586
1727
  return (
@@ -7,16 +7,25 @@
7
7
  * sync [--root <team-dir>] [--slug <slug>] [--quiet] [--json]
8
8
  * [--maintain] [--prune] [--vacuum] [--rebuild | --no-rebuild]
9
9
  * [--deadline-ms <n>] project files into the database
10
+ * delete --slug <slug> [--root <team-dir>] [--json]
11
+ * delete one task folder, then its rows
10
12
  * migrate-tasks [--root <team-dir>] [--quiet] [--json]
11
13
  * [--rebuild | --no-rebuild] create or reconcile the database
12
14
  * serve [--root <team-dir>] [--host <addr>] [--port <n>] [--allow-remote]
13
- * [--open] read-only API + dashboard
15
+ * [--open] loopback API + dashboard
14
16
  *
15
- * Exit codes: 0 ok, 1 at least one task failed or a migration checksum drifted,
16
- * 2 database-level failure, 3 usage, 4 deadline or busy.
17
+ * Exit codes: 0 ok, 1 at least one task failed, a delete refusal (unknown slug,
18
+ * active-task guard, kill switch, folder-delete failure) or a migration
19
+ * checksum drifted, 2 database-level failure, 3 usage, 4 deadline or busy.
17
20
  *
18
21
  * A runtime without `node:sqlite` prints one line and stays file-only:
19
- * `init`/`sync`/`migrate-tasks` exit 0 without creating a database, `check` exits 1.
22
+ * `init`/`sync`/`migrate-tasks` exit 0 without creating a database, `check` and
23
+ * `delete` exit non-zero (`delete` never deletes the folder while the row leg
24
+ * cannot run).
25
+ *
26
+ * With `--json`, `delete` prints exactly one machine-readable line: the result
27
+ * `{ ok: true, slug, folderRemoved, rowsDeleted }` on success, or
28
+ * `{ ok: false, code, message }` on a refusal.
20
29
  */
21
30
 
22
31
  import fs from 'node:fs';
@@ -38,7 +47,7 @@ import {
38
47
  openTeamDb,
39
48
  teamDbFail,
40
49
  } from './team-db-schema.mjs';
41
- import { describeSyncResult, syncProjection } from './team-db-project.mjs';
50
+ import { deleteTaskProjection, describeSyncResult, syncProjection } from './team-db-project.mjs';
42
51
 
43
52
  const USAGE = `usage:
44
53
  team-db.mjs init [--root <team-dir>] [--rebuild]
@@ -46,6 +55,7 @@ const USAGE = `usage:
46
55
  team-db.mjs sync [--root <team-dir>] [--slug <slug>] [--quiet] [--json]
47
56
  [--maintain] [--prune] [--vacuum] [--rebuild | --no-rebuild]
48
57
  [--deadline-ms <n>]
58
+ team-db.mjs delete --slug <slug> [--root <team-dir>] [--json]
49
59
  team-db.mjs migrate-tasks [--root <team-dir>] [--quiet] [--json]
50
60
  [--rebuild | --no-rebuild]
51
61
  team-db.mjs serve [--root <team-dir>] [--host <addr>] [--port <n>]
@@ -53,11 +63,12 @@ const USAGE = `usage:
53
63
 
54
64
  const VALUE_FLAGS = new Set(['root', 'slug', 'deadline-ms', 'host', 'port']);
55
65
  const BOOLEAN_FLAGS = new Set(['quiet', 'json', 'maintain', 'prune', 'vacuum', 'rebuild', 'no-rebuild', 'allow-remote', 'open']);
56
- const COMMANDS = new Set(['init', 'check', 'sync', 'migrate-tasks', 'serve']);
66
+ const COMMANDS = new Set(['init', 'check', 'sync', 'delete', 'migrate-tasks', 'serve']);
57
67
  const ALLOWED_FLAGS = {
58
68
  init: new Set(['root', 'rebuild']),
59
69
  check: new Set(['root']),
60
70
  sync: new Set(['root', 'slug', 'quiet', 'json', 'maintain', 'prune', 'vacuum', 'rebuild', 'no-rebuild', 'deadline-ms']),
71
+ delete: new Set(['root', 'slug', 'json']),
61
72
  'migrate-tasks': new Set(['root', 'quiet', 'json', 'rebuild', 'no-rebuild']),
62
73
  serve: new Set(['root', 'host', 'port', 'allow-remote', 'open']),
63
74
  };
@@ -175,6 +186,38 @@ const runSync = (flags) => {
175
186
  return result.exitCode;
176
187
  };
177
188
 
189
+ const runDelete = (flags) => {
190
+ // The kill switch refuses before any leg; `--json` still answers with the
191
+ // one failure line so an API child can map the code.
192
+ if (isKillSwitchSet(process.env)) {
193
+ disabledLine();
194
+ if (flags.json) process.stdout.write(`${JSON.stringify({ ok: false, code: 'E_DISABLED', message: 'disabled by AI_RULES_TEAM_DB_DISABLE' })}\n`);
195
+ return 1;
196
+ }
197
+ // Without node:sqlite the row leg cannot run, and a delete that leaves its
198
+ // rows behind is not a delete; refuse instead of deleting the folder only.
199
+ if (!isSqliteAvailable(process.env)) {
200
+ unavailableLine();
201
+ if (flags.json) process.stdout.write(`${JSON.stringify({ ok: false, code: 'E_INTERNAL', message: INDEX_UNAVAILABLE_LINE })}\n`);
202
+ return 2;
203
+ }
204
+ try {
205
+ const result = deleteTaskProjection({ teamRoot: teamRootFrom(flags), slug: flags.slug, env: process.env });
206
+ if (flags.json) {
207
+ process.stdout.write(`${JSON.stringify(result)}\n`);
208
+ } else {
209
+ process.stdout.write(`delete: slug=${result.slug} folderRemoved=${result.folderRemoved} rowsDeleted=${result.rowsDeleted}\n`);
210
+ }
211
+ return 0;
212
+ } catch (error) {
213
+ const code = error instanceof TeamDbError ? error.code : 'E_INTERNAL';
214
+ const exitCode = error instanceof TeamDbError ? error.exitCode : 2;
215
+ if (flags.json) process.stdout.write(`${JSON.stringify({ ok: false, code, message: error.message })}\n`);
216
+ process.stderr.write(`${error.message}\n`);
217
+ return exitCode;
218
+ }
219
+ };
220
+
178
221
  const runMigrateTasks = (flags) => {
179
222
  if (cannotProject(process.env)) return 0;
180
223
  if (flags.rebuild && flags['no-rebuild']) teamDbFail('E_USAGE', '--rebuild and --no-rebuild are exclusive', 3);
@@ -268,6 +311,7 @@ export async function runCli(argv) {
268
311
  }
269
312
  if (command === 'init') return runInit(flags);
270
313
  if (command === 'check') return runCheck(flags);
314
+ if (command === 'delete') return runDelete(flags);
271
315
  if (command === 'migrate-tasks') return runMigrateTasks(flags);
272
316
  if (command === 'serve') return runServe(flags);
273
317
  return runSync(flags);