@bonesofspring/ai-rules 0.2.45 → 0.2.46

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
+ ## 0.2.46
4
+
5
+ ### The manifest writer validates before it writes
6
+
7
+ - **Why.** A review of the 0.2.45 writer found four gaps: an unconditional `archive/` ban that contradicted the hook compacting a closed entry into `archive/<date>/`, path guards that only matched a leading `../`, `init` writing a skeleton outside `.manifest.lock`, and `--outcome blocked` landing as `status: "completed"`.
8
+ - **Paths.** `upsert` and `check` normalize each `authoritativePaths` entry before judging it, so `reports/../../x.md`, `./archive/x.md`, and `.` hit the same guards as `../x.md` and `archive/x.md`; `reports/../review.md` is stored as `review.md`. `archive/` is accepted only on a `completed` or `superseded` entry — the state the hook leaves after it relocates a closed body — so `check` is green again for an archived task.
9
+ - **Outcome → status.** An outcome now implies the artifact status (`completed` → `completed`; `blocked` / `changes_requested` / `validation_failed` → `blocked`), a contradictory `--status` is rejected with exit 1, and `check` reports a stored `status`/`receipt.outcome` mismatch instead of blessing it. A manifest written before this release may carry such a pair; `check` names the entry and the expected status.
10
+ - **Concurrency.** `init` takes the same `.manifest.lock` as `upsert` and re-checks existence after acquiring it, so entries a concurrent producer already wrote are never replaced by the empty skeleton.
11
+ - **Read safety.** A non-array `artifacts` (or a missing key) is a hard read error (exit 2) that leaves the file untouched: `check` cannot bless a corrupt file and a later `upsert` cannot drop its entries. An empty array belongs only to a new skeleton.
12
+ - **Gate.** `test-manifest-writer.mjs` gains path normalization, archive scope, outcome→status, stored-contradiction, and init/upsert race cases; `check:preset-structure` and `check-rule-eval.mjs` pass.
13
+
14
+ ### Upgrade
15
+
16
+ - Run `npx @bonesofspring/ai-rules update`. Seeding the writer is skip-if-exists, so delete `.ai.local/scripts/manifest.mjs` first to take the hardened copy, then re-run `node .ai.local/scripts/manifest.mjs check --slug <slug>` on completed tasks.
17
+
3
18
  ## 0.2.45
4
19
 
5
20
  ### The manifest is a whole-file merge, not a fragment edit
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bonesofspring/ai-rules",
3
- "version": "0.2.45",
3
+ "version": "0.2.46",
4
4
  "description": "Presets of Cursor, Claude, Mavis, and OpenCode rules/commands for Revy Ross personal use",
5
5
  "license": "MIT",
6
6
  "author": "Revy Ross",
@@ -11,9 +11,10 @@
11
11
  * init --slug <slug> create the skeleton when absent
12
12
  * upsert --slug <slug> --id <id> --producer <agent> … merge one owned entry + receipt
13
13
  * get --slug <slug> --id <id> print one entry
14
- * check --slug <slug> validate; exit 1 on any problem
14
+ * check --slug <slug> validate; exit 1 on schema problems, 2 on an unreadable file
15
15
  *
16
- * Exit codes: 0 ok, 1 usage/validation, 2 manifest parse error (nothing written).
16
+ * Exit codes: 0 ok, 1 usage/validation, 2 unreadable manifest (invalid JSON or a
17
+ * non-array `artifacts`); nothing is written on 2.
17
18
  */
18
19
 
19
20
  import fs from 'node:fs';
@@ -27,10 +28,18 @@ export const DEFAULT_TEAM_ROOT = path.join(process.cwd(), '.ai.local', 'team');
27
28
 
28
29
  const ARTIFACT_STATUSES = ['planned', 'in_progress', 'completed', 'blocked', 'superseded'];
29
30
  const TERMINAL_STATUSES = new Set(['completed', 'blocked', 'superseded']);
31
+ // The hook compacts a closed entry's body into `archive/<date>/` only for `completed`.
32
+ const ARCHIVABLE_STATUSES = new Set(['completed', 'superseded']);
30
33
  const OUTCOMES = ['completed', 'blocked', 'changes_requested', 'validation_failed'];
31
- // `changes_requested` / `validation_failed` block the pipeline but keep their own
32
- // outcome vocabulary, so the artifact status is `blocked` (agent-artifact-contracts).
33
- const BLOCKING_OUTCOMES = new Set(['changes_requested', 'validation_failed']);
34
+ // An outcome implies the artifact status: `blocked` and the two blocking review
35
+ // outcomes are non-advancing, so they land on `blocked` (agent-artifact-contracts).
36
+ // `superseded` stays a lifecycle override on top of any receipt.
37
+ const OUTCOME_STATUS = {
38
+ completed: 'completed',
39
+ blocked: 'blocked',
40
+ changes_requested: 'blocked',
41
+ validation_failed: 'blocked',
42
+ };
34
43
 
35
44
  const USAGE = `usage:
36
45
  manifest.mjs init --slug <slug> [--root <team-dir>]
@@ -49,6 +58,13 @@ const fail = (message, code = 1) => {
49
58
 
50
59
  const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
51
60
 
61
+ const describeShape = (value) => {
62
+ if (value === undefined) return 'no "artifacts" key';
63
+ if (value === null) return 'null';
64
+ if (Array.isArray(value)) return 'an array';
65
+ return `a ${typeof value}`;
66
+ };
67
+
52
68
  const parseArgs = (argv) => {
53
69
  const [command, ...rest] = argv;
54
70
  const flags = {};
@@ -77,14 +93,24 @@ const csv = (value) =>
77
93
  export const manifestPath = (slug, teamRoot = DEFAULT_TEAM_ROOT) =>
78
94
  path.join(teamRoot, 'tasks', slug, MANIFEST_FILE);
79
95
 
80
- /** Task-directory-relative path guard; mirrors the hook's receipt rejection. */
81
- export function assertAuthoritativePath(value, slug) {
96
+ /**
97
+ * Task-directory-relative path guard; mirrors the hook's receipt rejection.
98
+ * `status` scopes the archive ban: the hook relocates a closed entry's body to
99
+ * `archive/<date>/` and rewrites that entry's `authoritativePaths`, so only an
100
+ * open entry is required to cite current files.
101
+ */
102
+ export function assertAuthoritativePath(value, slug, status) {
82
103
  if (typeof value !== 'string' || value.trim() === '') fail('authoritativePaths entries must be non-empty strings');
83
104
  const candidate = value.trim();
84
105
  if (path.isAbsolute(candidate)) {
85
106
  fail(`authoritativePaths must be relative to the task directory, got absolute "${candidate}"`);
86
107
  }
87
- const normalized = candidate.split(path.sep).join('/');
108
+ // Normalize before judging, or `reports/../../x.md` and `./archive/x.md` slip
109
+ // past the guards written for `../x.md` and `archive/x.md`.
110
+ const normalized = path.posix.normalize(candidate.split(path.sep).join('/'));
111
+ if (normalized === '.' || normalized === '') {
112
+ fail(`authoritativePaths must name a file inside the task directory, got "${candidate}"`);
113
+ }
88
114
  if (normalized === '..' || normalized.startsWith('../')) {
89
115
  fail(`authoritativePaths must stay inside the task directory, got "${candidate}"`);
90
116
  }
@@ -93,7 +119,11 @@ export function assertAuthoritativePath(value, slug) {
93
119
  `authoritativePaths are task-relative ("brief.md"), got the repo-root form "${candidate}" — use evidencePaths for anything outside the task directory`,
94
120
  );
95
121
  }
96
- if (normalized.startsWith('archive/')) fail(`authoritativePaths must point at current files, got archived "${candidate}"`);
122
+ if ((normalized === 'archive' || normalized.startsWith('archive/')) && !ARCHIVABLE_STATUSES.has(status)) {
123
+ fail(
124
+ `authoritativePaths must point at current files, got archived "${candidate}" — only a completed or superseded entry may cite archive/`,
125
+ );
126
+ }
97
127
  void slug;
98
128
  return normalized;
99
129
  }
@@ -105,7 +135,12 @@ const skeleton = (slug) => ({
105
135
  artifacts: [],
106
136
  });
107
137
 
108
- /** Read the manifest; `{ manifest, exists }`. Throws exitCode 2 on invalid JSON. */
138
+ /**
139
+ * Read the manifest; `{ manifest, exists }`. Returns the file as parsed, without
140
+ * repairing it. Throws exitCode 2 on invalid JSON or a non-array `artifacts`, so a
141
+ * corrupt file can never be blessed by `check` and then rewritten by `upsert`.
142
+ * An empty `artifacts` array exists only in the skeleton for a new manifest.
143
+ */
109
144
  export function readManifest(slug, teamRoot = DEFAULT_TEAM_ROOT) {
110
145
  const filePath = manifestPath(slug, teamRoot);
111
146
  if (!fs.existsSync(filePath)) return { manifest: skeleton(slug), exists: false, filePath };
@@ -126,7 +161,13 @@ export function readManifest(slug, teamRoot = DEFAULT_TEAM_ROOT) {
126
161
  'Re-run the merge with this writer to drop the stray key.\n',
127
162
  );
128
163
  }
129
- if (!Array.isArray(parsed.artifacts)) parsed.artifacts = [];
164
+ if (!Array.isArray(parsed.artifacts)) {
165
+ fail(
166
+ `${filePath}: "artifacts" must be an array, got ${describeShape(parsed.artifacts)}. ` +
167
+ 'Repair the file by hand (merge the artifact entries into the array) and retry; nothing was written.',
168
+ 2,
169
+ );
170
+ }
130
171
  return { manifest: parsed, exists: true, filePath };
131
172
  }
132
173
 
@@ -180,11 +221,14 @@ const buildEntry = (flags, slug) => {
180
221
  if (!producer) fail('--producer is required');
181
222
  const outcome = flags.outcome;
182
223
  if (outcome && !OUTCOMES.includes(outcome)) fail(`--outcome must be one of ${OUTCOMES.join(' | ')}`);
183
- let status = flags.status || (outcome ? 'completed' : 'in_progress');
184
- if (outcome && BLOCKING_OUTCOMES.has(outcome)) status = 'blocked';
224
+ const impliedStatus = outcome ? OUTCOME_STATUS[outcome] : null;
225
+ const status = flags.status || impliedStatus || 'in_progress';
185
226
  if (!ARTIFACT_STATUSES.includes(status)) fail(`--status must be one of ${ARTIFACT_STATUSES.join(' | ')}`);
227
+ if (impliedStatus && status !== impliedStatus && status !== 'superseded') {
228
+ fail(`--status ${status} contradicts --outcome ${outcome}; use --status ${impliedStatus} (superseded is also allowed)`);
229
+ }
186
230
  if (TERMINAL_STATUSES.has(status) && !outcome) fail(`--outcome is required when --status is ${status}`);
187
- const authoritativePaths = csv(flags.paths).map((value) => assertAuthoritativePath(value, slug));
231
+ const authoritativePaths = csv(flags.paths).map((value) => assertAuthoritativePath(value, slug, status));
188
232
  if (authoritativePaths.length === 0) fail('--paths is required (comma-separated task-relative paths)');
189
233
  const entry = {
190
234
  id,
@@ -216,6 +260,7 @@ export function validateManifest(manifest, slug) {
216
260
  if (typeof manifest.updatedAt !== 'string' || Number.isNaN(Date.parse(manifest.updatedAt))) {
217
261
  problems.push('updatedAt must be an ISO 8601 timestamp');
218
262
  }
263
+ // readManifest already rejects a non-array file; keep the contract check for direct callers.
219
264
  if (!Array.isArray(manifest.artifacts)) return [...problems, 'artifacts must be an array'];
220
265
  if (manifest.entries !== undefined) problems.push('top-level "entries" is not part of the schema; merge into "artifacts"');
221
266
  const seen = new Set();
@@ -235,7 +280,7 @@ export function validateManifest(manifest, slug) {
235
280
  } else {
236
281
  for (const value of entry.authoritativePaths) {
237
282
  try {
238
- assertAuthoritativePath(value, slug);
283
+ assertAuthoritativePath(value, slug, entry.status);
239
284
  } catch (error) {
240
285
  problems.push(`${at}.authoritativePaths: ${error.message}`);
241
286
  }
@@ -252,6 +297,17 @@ export function validateManifest(manifest, slug) {
252
297
  problems.push(`${at}.receipt.outcome is required when status is ${entry.status}`);
253
298
  }
254
299
  }
300
+ if (
301
+ isRecord(entry.receipt) &&
302
+ OUTCOMES.includes(entry.receipt.outcome) &&
303
+ ARTIFACT_STATUSES.includes(entry.status) &&
304
+ entry.status !== OUTCOME_STATUS[entry.receipt.outcome] &&
305
+ entry.status !== 'superseded'
306
+ ) {
307
+ problems.push(
308
+ `${at}.status "${entry.status}" contradicts receipt.outcome "${entry.receipt.outcome}"; expected "${OUTCOME_STATUS[entry.receipt.outcome]}"`,
309
+ );
310
+ }
255
311
  });
256
312
  return problems;
257
313
  }
@@ -269,12 +325,21 @@ export function runCli(argv) {
269
325
 
270
326
  if (command === 'init') {
271
327
  const filePath = manifestPath(slug, teamRoot);
272
- if (fs.existsSync(filePath)) {
273
- process.stdout.write(`${filePath} already exists; left untouched\n`);
274
- return 0;
328
+ fs.mkdirSync(taskDir, { recursive: true });
329
+ // Same lock as `upsert`, plus a re-check under it: a concurrent producer that
330
+ // wrote entries first must not be replaced by the empty skeleton.
331
+ const lockPath = path.join(taskDir, '.manifest.lock');
332
+ const token = acquireLock(lockPath, { timeoutMs: 5000 });
333
+ let created = false;
334
+ try {
335
+ if (!fs.existsSync(filePath)) {
336
+ writeManifestSync(filePath, skeleton(slug));
337
+ created = true;
338
+ }
339
+ } finally {
340
+ releaseLock(lockPath, token);
275
341
  }
276
- writeManifestSync(filePath, skeleton(slug));
277
- process.stdout.write(`${filePath} created\n`);
342
+ process.stdout.write(created ? `${filePath} created\n` : `${filePath} already exists; left untouched\n`);
278
343
  return 0;
279
344
  }
280
345
 
@@ -75,7 +75,7 @@ A producer finishes its step by upserting only its owned artifact entry and term
75
75
  - `evidencePaths`: authoritative files that support the outcome
76
76
  - `authoritativePaths`: paths relative to the task directory (`brief.md`). A repo-root path (`.ai.local/team/tasks/<slug>/brief.md`) resolves outside that directory and the hook rejects the receipt.
77
77
 
78
- `changes_requested` and `validation_failed` use artifact `status: "blocked"` while retaining their distinct receipt outcome. A later successful attempt updates the same owned entry to `completed`; timestamps and evidence must reflect the latest result. Do not infer success from a Markdown filename alone.
78
+ `changes_requested` and `validation_failed` use artifact `status: "blocked"` while retaining their distinct receipt outcome; `outcome: "blocked"` maps to `status: "blocked"` too. A later successful attempt updates the same owned entry to `completed`; timestamps and evidence must reflect the latest result. Do not infer success from a Markdown filename alone.
79
79
 
80
80
  `blocked` is terminal for the producer attempt but non-advancing for the pipeline: the hook persists `status.state` / `phase` as `blocked` and emits no next-agent handoff. A receipt must either carry the active `attemptId` or belong to the step's assigned output entry. Its terminal timestamp must be at or after the active attempt's `startedAt`; otherwise the hook keeps the attempt active in `awaiting_artifact_receipt` and does not advance or retry.
81
81
 
@@ -108,7 +108,7 @@ The manifest is a **whole-file merge target**, never a substring patch. Producer
108
108
  --acs AC-1 --tasks T1 --attempt <attemptId>
109
109
  node .ai.local/scripts/manifest.mjs check --slug <slug>
110
110
  ```
111
- It rejects absolute paths, `..` escapes, and repo-root `authoritativePaths`, and it drops a stray top-level `entries` key.
111
+ It normalizes each path before judging it, so `reports/../../x.md` and `./archive/x.md` hit the same guards as `../x.md` and `archive/x.md`; it rejects absolute paths, `..` escapes, and repo-root `authoritativePaths`, and it drops a stray top-level `entries` key. `archive/` is accepted only on a `completed` or `superseded` entry, because the hook relocates a closed body there and rewrites that entry's paths. An outcome implies the status (`completed` → `completed`; `blocked` / `changes_requested` / `validation_failed` → `blocked`); a contradictory `--status` is rejected and `check` reports a stored mismatch. `init` takes the same `.manifest.lock` and re-checks existence after acquiring it, so it never replaces entries a concurrent `upsert` already wrote. A non-array `artifacts` (or a missing key) is a hard read error (exit 2) that leaves the file untouched: repair the file by hand — an empty array belongs only to a new skeleton.
112
112
  5. Never patch the JSON with a fragment/replace edit (`edit`, `str_replace`, `apply_patch`). A single-byte mismatch aborts the receipt mid-task, leaves the manifest out of sync with the produced artifact, and stalls the step in `awaiting_artifact_receipt`.
113
113
  6. A failed merge or parse is a retry signal, not a guess signal: re-read, merge again, at most twice, then report `blocked` with the parse/merge error. Never leave the file truncated or half-written.
114
114
  7. Parallel wave: the writer holds `.manifest.lock` in the task directory, so concurrent producers serialize. A hand-written merge must take the same lock. Entry `id` uniqueness stays the only shared invariant — the manifest is not a coordination lock.