fix(#4378): mint collision-free SEED-YYMMDD-xxx seed ids instead of a shared count (#4754)

* test(#4378): regression tests for collision-free seed ids

* fix(#4378): mint collision-free SEED-YYMMDD-xxx ids, not a shared count

plant-seed derived the next seed id from 'ls .planning/seeds/SEED-*.md | wc -l'.
.planning/seeds/ is shared but each worktree only sees what has merged, so two
workstreams planting before either merges computed the same id and git merged
both files silently.

The id is now the local date plus a 3-char random base36 suffix -- the shape
.planning/quick/ already uses -- computed from knowledge one worktree has alone,
with a same-day regen guard. deriveSeedIdentity learns the new canonical grammar
alongside legacy SEED-NNN (whose parsing never changes), the --enrich parser and
the filename-prefix fallback keep the full new-format id, and the docs that
state the filename shape move to it.

The prefix fallback previously truncated any non-pure-numeric id at
'SEED-<digits>' -- the same one-id-two-answers ambiguity the issue reports,
reproduced one level down.

* fix(#4378): harden seed id generation per adversarial review

- parse-idea: anchor the --enrich extractor to the flag and capture the
  complete id, uppercase-tolerant; a leftmost 'SEED-[0-9]+' truncated an
  uppercase or malformed suffix to its date and enriched an arbitrary
  same-day seed via head -1. Ambiguous and unmatched targets now fail
  closed instead.
- generate-seed-id: tolerate the expected SIGPIPE under pipefail, abort
  loudly when the suffix cannot be drawn (an empty suffix would collapse
  every seed's id to the bare date), and run the same-day regen guard as
  a find existence test (the 'ls <glob>' shape trips the #3409 drift
  guard and degenerates under a stray nullglob).
- deriveSeedIdentity: document the theoretical legacy/new grammar
  ambiguity (6-digit counter + 3-char base36 slug, no frontmatter).
- changeset: state the residual same-day collision bound instead of
  implying zero.

Emitted-Drift-Ack-Growth: plant-seed.md — the counting step became hardened date+random generation with explicit failure modes; growth is the failure handling, not duplicated logic

* fix(#4378): address standards and spec review findings

- tests: move the allow-test-rule marker to its suppression site (the
  file-header placement was inert per CONTRIBUTING site-scoping); add
  width-boundary coverage (5/7-digit dates, 2/4-char suffixes pin the
  documented branch behavior); add a writer-to-reader parity property
  that parses the mint widths out of the shipped workflow so the two
  grammar owners cannot drift; cover uppercase ids end-to-end in the
  reader.
- plant-seed.md: draw/retry restructured as one loop with a loud
  terminal failure; SEED_SUFX renamed SEED_SUFFIX; regen guard drops
  the redundant head -1; the ambiguity error no longer advises an
  impossible 'complete id' for duplicate legacy ids.
- commands.cts: refresh the cmdListSeeds comment still describing
  SEED-NNN as the only canonical form.
- changeset: drop the audit claim the spec axis showed to be an
  overstatement (audit's id display is filename-derived, pre-existing).
- remove a stray untracked artifact file swept into the tree.

* test(#4378): correct boundary expectations to the module's real branch behavior

The first matrix run on the boundary tests caught my hand-trace of the
regex branches, not a module defect: the slug regex's alternation
backtracks to the legacy branch whenever the canonical branch cannot
complete (so the slug is the remainder after the legacy numeric
prefix), and the 7-digit case fails the canonical branch at its 7th
digit before the dash. Pin the verified values.

* docs(#4378): backfill changeset PR number

* fix(#4378): audit seed identity uses the canonical grammar

Review of this PR found the audit surface publishing a fused filename
stem (SEED-081-region for SEED-081-region.md) where list-seeds reports
the canonical id -- one id, two answers across surfaces, the same
ambiguity class the issue files. scanSeeds now derives identity through
the SAME deriveSeedIdentity the list-seeds gate uses (frontmatter id,
then filename id-prefix, then stem), and audit-open acknowledge
resolves --seed-id by scanning for the derived identity, falling back
to the literal stem so callers scripted against pre-canonical output
keep working. Roll-in per the fix-inline rule: found during this PR's
review, same seed-identity seam.

RED probe: pre-fix audit published seed_id SEED-081-region-becomes /
slug 081-region-becomes for a legacy seeded file; post-fix SEED-081 /
region-becomes, matching list-seeds.

* test(#4378): probe timeout uses the class norm after windows-lane timeout

The windows conformance shard failed its bounded sh -c probes at the
local 5000ms bound (cold sh.exe spawn under shard load) while the
identical code passed this PR's two earlier windows waves. The probe
now uses PROBE_TIMEOUT_MS from the class-norm module instead of a local
override, per the helpers/timeouts.cjs convention.

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-09-15 11:41:29 -04:00
committed by GitHub
parent cbbde6786a
commit 779f67cb11
17 changed files with 699 additions and 49 deletions

View File

@@ -2567,3 +2567,107 @@ describe('bug #950: quick-task SUMMARY must carry status: complete', () => {
});
});
}
// ────────────────────────────────────────────────────────────────────────
// #4378 — audit seed identity agrees with list-seeds; acknowledge resolves
// by canonical id (legacy stems still resolve for back-compat).
// ────────────────────────────────────────────────────────────────────────
{
const fs = require('node:fs');
const path = require('node:path');
const { cleanup } = require('./helpers.cjs');
function readJson4546(result) {
assert.ok(result.success, `command must succeed. stdout: ${result.output}\nstderr: ${result.error}`);
return JSON.parse(result.output);
}
function auditJson(tmpDir) {
return readJson4546(runGsdTools(['audit-open', '--json'], tmpDir));
}
function ack4546(tmpDir, args) {
return runGsdTools(['audit-open', 'acknowledge', ...args, '--json'], tmpDir);
}
describe('audit seed identity agrees with list-seeds (#4378)', () => {
let tmpDir;
beforeEach(() => { tmpDir = createTempProject('gsd-4378-seedident-'); });
afterEach(() => { cleanup(tmpDir); });
function planningPath(...segs) {
return path.join(tmpDir, '.planning', ...segs);
}
function seedItem(output, seedId) {
const item = output.items.seeds.find((s) => s.seed_id === seedId);
assert.ok(item, `expected a seed item with seed_id ${seedId}; got: ${JSON.stringify(output.items.seeds.map((s) => s.seed_id))}`);
return item;
}
test('legacy seed publishes the canonical frontmatter id, not the fused filename stem', () => {
const seedsDir = planningPath('seeds');
fs.mkdirSync(seedsDir, { recursive: true });
fs.writeFileSync(path.join(seedsDir, 'SEED-081-region-becomes.md'),
'---\nid: SEED-081\nstatus: dormant\n---\n# SEED-081: region idea\n', 'utf8');
const output = auditJson(tmpDir);
const item = seedItem(output, 'SEED-081');
assert.strictEqual(item.slug, 'region-becomes',
'slug is the remainder after the canonical id, matching list-seeds');
assert.ok(!output.items.seeds.some((s) => s.seed_id === 'SEED-081-region-becomes'),
'the fused filename stem must not resurface as a second id');
});
test('date-suffixed seed publishes its full id (never truncated at the date prefix)', () => {
const seedsDir = planningPath('seeds');
fs.mkdirSync(seedsDir, { recursive: true });
fs.writeFileSync(path.join(seedsDir, 'SEED-260914-k3x-my-slug.md'),
'---\nid: SEED-260914-k3x\nstatus: dormant\n---\n# SEED-260914-k3x: idea\n', 'utf8');
const output = auditJson(tmpDir);
const item = seedItem(output, 'SEED-260914-k3x');
assert.strictEqual(item.slug, 'my-slug');
});
test('acknowledge resolves the canonical id to the real file and writes the marker', () => {
const seedsDir = planningPath('seeds');
fs.mkdirSync(seedsDir, { recursive: true });
const legacyFile = path.join(seedsDir, 'SEED-081-region-becomes.md');
fs.writeFileSync(legacyFile,
'---\nid: SEED-081\nstatus: dormant\n---\n# SEED-081: region idea\n', 'utf8');
const result = ack4546(tmpDir, ['--category', 'seeds', '--seed-id', 'SEED-081', '--milestone', 'v1.0', '--at', '2026-09-15']);
assert.ok(result.success, `acknowledge by canonical id must succeed. stderr: ${result.error}`);
assert.match(fs.readFileSync(legacyFile, 'utf-8'), /^status: dormant$/m,
'verdict-preserving: the seed status line must be unchanged');
const after = auditJson(tmpDir);
assert.equal(after.counts.seeds, 0, 'acknowledged seed drops out of counts');
});
test('full filename stem still resolves (back-compat with pre-canonical callers)', () => {
const seedsDir = planningPath('seeds');
fs.mkdirSync(seedsDir, { recursive: true });
fs.writeFileSync(path.join(seedsDir, 'SEED-081-region-becomes.md'),
'---\nid: SEED-081\nstatus: dormant\n---\nbody\n', 'utf8');
const result = ack4546(tmpDir, ['--category', 'seeds', '--seed-id', 'SEED-081-region-becomes', '--milestone', 'v1.0', '--at', '2026-09-15']);
assert.ok(result.success, `acknowledge by legacy stem must succeed. stderr: ${result.error}`);
});
test('an unknown seed id still fails with the file-not-found error', () => {
const seedsDir = planningPath('seeds');
fs.mkdirSync(seedsDir, { recursive: true });
fs.writeFileSync(path.join(seedsDir, 'SEED-081-region-becomes.md'),
'---\nid: SEED-081\nstatus: dormant\n---\nbody\n', 'utf8');
const result = ack4546(tmpDir, ['--category', 'seeds', '--seed-id', 'SEED-999', '--milestone', 'v1.0', '--at', '2026-09-15']);
assert.equal(result.success, false, 'an unresolvable id must fail');
assert.match(String(result.error), /file not found: seeds\/SEED-999\.md/,
'the error names the unresolvable id exactly as before');
});
});
}

View File

@@ -22,13 +22,18 @@ const os = require('os');
const { evaluatePredicate } = require('../gsd-core/bin/lib/gate-predicate-evaluator.cjs');
const { buildPredicateDeps, parsePredicateFlags } = require('../gsd-core/bin/lib/check-command-router.cjs');
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
const { PROBE_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
/**
* A real, bounded `sh -c` subprocess spawned via the production
* runBoundedShell dependency -- the describe block's own name is "real
* bounded sh -c subprocess."
*/
const BOUNDED_SHELL_PROBE_TIMEOUT_MS = 5000;
// #4378 (windows conformance lane): the local 5000ms bound timed out on a
// cold sh.exe spawn under windows-latest shard load while the identical code
// passed twice earlier the same day -- the probe now uses the class norm
// (tests/helpers/timeouts.cjs PROBE_TIMEOUT_MS) instead of a local override.
const BOUNDED_SHELL_PROBE_TIMEOUT_MS = PROBE_TIMEOUT_MS;
/**
* The same runBoundedShell call as BOUNDED_SHELL_PROBE_TIMEOUT_MS, but

View File

@@ -87,4 +87,117 @@ describe('list-seeds: deriveSeedIdentity properties', () => {
)
);
});
// ── #4378: the new-format grammar `SEED-YYMMDD-xxx` (date + 3 base36 chars) ──
// New-format short suffix: exactly 6 digits, hyphen, exactly 3 lowercase base36.
const seedDate = fc.integer({ min: 0, max: 99 })
.map((n) => String(n).padStart(2, '0'))
.chain((yy) =>
fc.integer({ min: 1, max: 12 }).map((m) => yy + String(m).padStart(2, '0'))
.chain((ym) =>
fc.integer({ min: 1, max: 31 }).map((d) => ym + String(d).padStart(2, '0'))
)
);
const seedSuffix = fc.tuple(
fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789'.split('')),
fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789'.split('')),
fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789'.split('')),
).map(([a, b, c]) => a + b + c);
// (e) Canonical new format: frontmatter id wins; slug is the filename remainder.
test('property: new-format id `SEED-YYMMDD-xxx` round-trips (#4378)', () => {
fc.assert(
fc.property(seedDate, seedSuffix, slug, (date, suf, s) => {
const id = `SEED-${date}-${suf}`;
const stem = `${id}-${s}`;
const result = deriveSeedIdentity(stem, id);
assert.strictEqual(result.seed_id, id);
assert.strictEqual(result.slug, s);
})
);
});
// (f) The filename-prefix fallback must keep the FULL new-format id. Truncating
// at `SEED-<digits>` (the date) gives every same-day seed the same id — the
// exact ambiguity #4378 files.
test('property: missing id falls back to the full new-format prefix (#4378)', () => {
fc.assert(
fc.property(
seedDate,
seedSuffix,
slug,
fc.oneof(fc.constant(undefined), fc.constant(''), fc.constant(42)),
(date, suf, s, badId) => {
const stem = `SEED-${date}-${suf}-${s}`;
const result = deriveSeedIdentity(stem, badId);
assert.strictEqual(result.seed_id, `SEED-${date}-${suf}`);
assert.strictEqual(result.slug, s);
}
)
);
});
// (g) Width boundaries — the new grammar is exactly 6 digits + exactly 3
// base36 chars; off-by-one widths must resolve through the documented
// grammar branches, never by mis-parsing as a different seed's id
// (CLAUDE.md: boundary coverage at limit-1 / limit / limit+1). Verified
// against the real module: the SLUG regex's alternation backtracks to the
// legacy branch whenever the canonical branch cannot complete, so the slug
// is always the remainder after the legacy numeric prefix for these
// off-grammar stems.
describe('width boundaries (limit-1 / limit+1 vs the new grammar)', () => {
test('5-digit date (limit-1) parses as legacy', () => {
const r = deriveSeedIdentity('SEED-26091-k3x-slug', 'SEED-26091');
assert.strictEqual(r.seed_id, 'SEED-26091');
assert.strictEqual(r.slug, 'k3x-slug');
});
test('7-digit date (limit+1) parses as legacy (the 7th digit breaks the {6}-dash anchor)', () => {
const r = deriveSeedIdentity('SEED-2609147-k3x-slug', 'SEED-2609147');
assert.strictEqual(r.seed_id, 'SEED-2609147');
assert.strictEqual(r.slug, 'k3x-slug');
});
test('4-char suffix (limit+1): canonical frontmatter wins; without frontmatter the id prefix absorbs exactly 3 suffix chars', () => {
// Off-grammar input is never minted by the writer (it length-checks the
// draw), so this pins the parser's documented greedy-then-legacy
// behavior rather than a contract the writer can produce.
assert.deepStrictEqual(
deriveSeedIdentity('SEED-260914-k3xy-slug', 'SEED-260914'),
{ seed_id: 'SEED-260914', slug: 'k3xy-slug' }
);
assert.deepStrictEqual(
deriveSeedIdentity('SEED-260914-k3xy-slug', ''),
{ seed_id: 'SEED-260914-k3x', slug: 'k3xy-slug' },
'the prefix fallback has no trailing anchor, so the new-format branch absorbs exactly 3 suffix chars; the slug regex backtracks to legacy and keeps the whole remainder'
);
});
test('2-char suffix (limit-1) never parses as new-format', () => {
const withFm = deriveSeedIdentity('SEED-260914-k3', 'SEED-260914-k3');
assert.strictEqual(withFm.seed_id, 'SEED-260914',
'a frontmatter id matching NO grammar is ignored; the filename fallback applies');
assert.strictEqual(withFm.slug, 'k3');
const noFm = deriveSeedIdentity('SEED-260914-k3', '');
assert.strictEqual(noFm.seed_id, 'SEED-260914');
assert.strictEqual(noFm.slug, 'k3');
});
test('property: a 5-digit date (below the {6} width) always resolves to the legacy numeric prefix', () => {
fc.assert(
fc.property(
fc.integer({ min: 10000, max: 99999 }), // 5-digit date, below {6}
fc.stringMatching(/^[a-z0-9]{2}([a-z0-9])?$/), // 2 or 4 suffix chars
slug,
(date, suf, s) => {
const stem = `SEED-${date}-${suf}-${s}`;
const r = deriveSeedIdentity(stem, '');
assert.strictEqual(r.seed_id, `SEED-${date}`,
'a short date can never start a new-format id');
}
)
);
});
});
});

View File

@@ -213,4 +213,70 @@ describe('list-seeds command', () => {
assert.ok(result.success, `Command failed: ${result.error}`);
assert.strictEqual(result.output.trim(), '1');
});
// ── #4378: seed ids are `SEED-YYMMDD-xxx` (date + random base36), not a count ──
test('new-format id (SEED-YYMMDD-xxx) is canonical, not truncated to its date prefix (#4378)', () => {
writeSeed(tmpDir, 'SEED-260914-k3x-my-slug.md',
{ id: 'SEED-260914-k3x', status: 'dormant', planted: '2026-09-14' },
'SEED-260914-k3x: my idea');
const output = JSON.parse(runGsdTools('list-seeds', tmpDir).output);
assert.strictEqual(output.count, 1);
const s = output.seeds[0];
// The filename-prefix fallback matches `SEED-<digits>` and would truncate a
// new-format id to its date (`SEED-260914`), which is exactly the ambiguity
// #4378 files: two same-day seeds then share one id.
assert.strictEqual(s.seed_id, 'SEED-260914-k3x');
assert.strictEqual(s.slug, 'my-slug');
});
test('same-day seeds with distinct suffixes list as distinct ids (#4378)', () => {
// The reported incident: two workstreams plant before either merges and the
// counting scheme gives both the same number. With collision-free ids the
// reader must surface two DISTINCT ids — one id must never have two answers.
writeSeed(tmpDir, 'SEED-260914-k3x-my-slug.md',
{ id: 'SEED-260914-k3x', status: 'dormant' }, 'SEED-260914-k3x: my idea');
writeSeed(tmpDir, 'SEED-260914-b2c-other-slug.md',
{ id: 'SEED-260914-b2c', status: 'dormant' }, 'SEED-260914-b2c: other idea');
const output = JSON.parse(runGsdTools('list-seeds', tmpDir).output);
assert.strictEqual(output.count, 2);
const ids = output.seeds.map(s => s.seed_id).sort();
assert.deepStrictEqual(ids, ['SEED-260914-b2c', 'SEED-260914-k3x']);
const slugs = output.seeds.map(s => s.slug).sort();
assert.deepStrictEqual(slugs, ['my-slug', 'other-slug']);
});
test('legacy counter id and new-format id coexist (#4378)', () => {
writeSeed(tmpDir, 'SEED-081-region.md',
{ id: 'SEED-081', status: 'dormant' }, 'SEED-081: region idea');
writeSeed(tmpDir, 'SEED-260914-k3x-fresh.md',
{ id: 'SEED-260914-k3x', status: 'dormant' }, 'SEED-260914-k3x: fresh idea');
const output = JSON.parse(runGsdTools('list-seeds', tmpDir).output);
assert.strictEqual(output.count, 2);
const byId = Object.fromEntries(output.seeds.map(s => [s.seed_id, s]));
assert.strictEqual(byId['SEED-081'].slug, 'region');
assert.strictEqual(byId['SEED-260914-k3x'].slug, 'fresh');
});
test('filename fallback keeps the full new-format id (not just the date prefix) (#4378)', () => {
fs.writeFileSync(path.join(seedsDir(tmpDir), 'SEED-260914-k3x-bare.md'),
'no frontmatter, no heading\n');
const output = JSON.parse(runGsdTools('list-seeds', tmpDir).output);
assert.strictEqual(output.count, 1);
const s = output.seeds[0];
assert.strictEqual(s.seed_id, 'SEED-260914-k3x');
assert.strictEqual(s.slug, 'bare');
});
test('uppercase new-format id is canonical end-to-end (#4378)', () => {
// The docs display SEED-YYMMDD-XXX and the writer's enrich path is
// uppercase-tolerant, so the reader must be too — an uppercase id must
// survive verbatim, never be truncated to its date prefix.
writeSeed(tmpDir, 'SEED-260914-K3X-Upper.md',
{ id: 'SEED-260914-K3X', status: 'dormant' }, 'SEED-260914-K3X: upper');
const output = JSON.parse(runGsdTools('list-seeds', tmpDir).output);
assert.strictEqual(output.count, 1);
assert.strictEqual(output.seeds[0].seed_id, 'SEED-260914-K3X');
assert.strictEqual(output.seeds[0].slug, 'Upper');
});
});

View File

@@ -0,0 +1,249 @@
'use strict';
/**
* Writer-contract tests for seed id generation (#4378).
*
* Defect: plant-seed.md derived the next seed id from `ls | wc -l` — a count of
* files the local worktree happens to see. Two workstreams planting before
* either merges computed the same id and git merged both files silently.
*
* Contract shipped by the fix:
* 1. `generate-seed-id` derives `SEED-YYMMDD-xxx` from the local date plus a
* 3-char random base36 suffix — computable in one worktree alone — with a
* loud failure when the suffix cannot be drawn, a same-day regen guard,
* and NO shared counter.
* 2. The `parse-idea` enrich pattern is anchored to the `--enrich` flag and
* captures the COMPLETE id, uppercase-tolerant (legacy `SEED-NNN` still
* resolves) — writer and reader grammars must not diverge (the reader
* grammar is pinned behaviorally in tests/list-seeds.test.cjs /
* .property.test.cjs on the SAME sample ids, and the parity property at
* the bottom of this file proves every id the writer grammar can mint
* round-trips through the reader). A truncated or ambiguous target fails
* closed instead of enriching an arbitrary same-day seed.
* 3. No counting-era placeholder (`SEED-{PADDED}`) survives anywhere in the
* file — a stale placeholder would write malformed ids at runtime.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const fc = require('./helpers/fast-check-setup.cjs');
const ROOT = path.join(__dirname, '..');
const PLANT_SEED_PATH = path.join(ROOT, 'gsd-core', 'workflows', 'plant-seed.md');
// allow-test-rule: source-text-is-the-product (#4378)
// The readFileSync below is the marker's suppression site: plant-seed.md is
// runtime-loaded text — the workflow IS its markdown — so asserting on the
// shipped `generate-seed-id` and `parse-idea` text tests the deployed contract
// (the alternative — executing cross-worktree collisions end-to-end — is not
// reproducible in a single checkout).
function readPlantSeedNormalized() {
const src = fs.readFileSync(PLANT_SEED_PATH, 'utf8');
return src.replace(/\r\n/g, '\n');
}
/** Extract the body of a named <step> block, or throw naming the missing step. */
function stepBlock(src, stepName) {
const start = src.indexOf(`<step name="${stepName}">`);
assert.ok(start !== -1, `plant-seed.md must contain <step name="${stepName}">`);
const end = src.indexOf('</step>', start);
assert.ok(end !== -1, `<step name="${stepName}"> must be closed`);
return src.slice(start, end);
}
describe('plant-seed id contract (#4378)', () => {
const src = readPlantSeedNormalized();
test('generate-seed-id derives the id from local date + random, never a shared count (#4378)', () => {
const block = stepBlock(src, 'generate-seed-id');
// Date component: local YYMMDD.
assert.match(
block,
/date \+%y%m%d/,
'generate-seed-id must derive the date part via `date +%y%m%d`'
);
// Random base36 suffix: exactly 3 chars of [a-z0-9]. urandom is present on
// every supported platform (macOS, Linux, Git Bash). `tr` reads an infinite
// stream, so the pipeline takes a harmless SIGPIPE once `head -c` has its
// bytes — `|| true` keeps that from aborting the step under pipefail.
assert.match(
block,
/tr -dc 'a-z0-9'/,
'generate-seed-id must draw the suffix from [a-z0-9] (base36)'
);
assert.match(
block,
/head -c 3/,
'generate-seed-id must take exactly 3 random characters'
);
assert.match(
block,
/\|\| true/,
'the suffix draw must tolerate the expected SIGPIPE under pipefail'
);
// A missing /dev/urandom must fail LOUDLY, not mint `SEED-<date>-` (whose
// ids would all collapse to the bare date — the #4378 collision reborn).
assert.match(
block,
/\[ \$\{#SEED_SUFFIX\} -ne 3 \]/,
'the drawn suffix must be length-checked; an empty suffix must abort the step'
);
assert.match(
block,
/could not draw a random id suffix/,
'the empty-suffix abort must say so on stderr'
);
assert.match(
block,
/SEED-\$\{SEED_DATE\}-\$\{SEED_SUFFIX\}/,
'generate-seed-id must assemble SEED-<date>-<suffix>'
);
// Same-day regen guard — as a find existence test, never `ls <glob>`
// (under a stray nullglob that shape silently degenerates: #3409 drift
// guard, Detector B) — with a loud terminal failure if the retry also
// collides.
assert.match(
block,
/find \.planning\/seeds -maxdepth 1 -name "\$\{SEED_ID\}-\*\.md"/,
'generate-seed-id must check the freshly drawn id against existing same-day seeds via find'
);
assert.match(
block,
/could not draw an unused seed id/,
'a regen retry that also collides must abort loudly, not ship a duplicate'
);
assert.doesNotMatch(
block,
/ls .*SEED_ID.*\*\.md/,
'the regen guard must not use the `ls <glob>` shape (#3409 Detector B)'
);
// The shared counter must be GONE — every counting idiom of the old step.
assert.doesNotMatch(block, /wc -l/, 'the `wc -l` counter must not remain');
assert.doesNotMatch(
block,
/NEXT=\$\(\(EXISTING/,
'the `NEXT=$((EXISTING + 1))` derivation must not remain'
);
assert.doesNotMatch(
src,
/printf "%03d" \$NEXT/,
'the `%03d` padding of the counted id must not remain anywhere in the file'
);
});
test('enrich flag parsing is flag-anchored, complete, and uppercase-tolerant (#4378)', () => {
const block = stepBlock(src, 'parse-idea');
const m = block.match(/grep -oE '([^']+)'/);
assert.ok(m, 'parse-idea must extract the enrich target via `grep -oE`');
const pattern = m[1];
// The extraction must be ANCHORED to the --enrich flag: a leftmost
// `SEED-[0-9]+` would grab a seed id mentioned anywhere in $ARGUMENTS
// instead of the one the flag names (#4378 review).
assert.match(
pattern,
/\\-\\-enrich/,
'the extractor pattern must anchor on the --enrich flag'
);
// The pattern is executed by grep -E at runtime; exercise the same grammar
// through the JS regex engine, translating the one POSIX class grep
// understands and JS does not (`[[:space:]]` -> `[ \t]`).
const jsPattern = pattern.replace(/\[\[:space:\]\]/g, '[ \\t]');
const re = new RegExp(jsPattern);
const targetOf = (args) => {
const match = args.match(re);
assert.ok(match, `pattern must match: ${args}`);
return match[0].replace(/^.*[ \t]/, '');
};
// New-format id: the FULL id must be captured, never truncated at the date
// — and uppercase-tolerant, since the docs display SEED-YYMMDD-XXX.
assert.strictEqual(
targetOf('--seed --enrich SEED-260914-K3X'),
'SEED-260914-K3X',
'an uppercase new-format id must be captured in full'
);
assert.strictEqual(
targetOf('--seed --enrich SEED-260914-k3x'),
'SEED-260914-k3x',
'a lowercase new-format id must be captured in full'
);
// Legacy id: still resolves, still captured whole.
assert.strictEqual(targetOf('--seed --enrich SEED-081'), 'SEED-081');
// A seed id mentioned in the idea text must NOT be picked up when the flag
// names a different seed.
assert.strictEqual(
targetOf('"see SEED-5 first" --enrich SEED-7'),
'SEED-7',
'the extractor must follow the --enrich flag, not the leftmost id'
);
// Truncated/ambiguous targets fail closed instead of enriching an
// arbitrary same-day seed (`head -1` over a date glob).
assert.match(
block,
/matches multiple seed files/,
'a target matching several seed files must fail closed, naming the files'
);
assert.match(
block,
/no seed file matches/,
'a target matching no seed file must fail closed instead of falling back'
);
assert.match(
block,
/-gt 1/,
'the ambiguity check must compare the match count, not take head -1'
);
});
test('no counting-era placeholder remains (#4378)', () => {
assert.doesNotMatch(
src,
/SEED-\{PADDED\}/,
'the SEED-{PADDED} placeholder would write malformed ids at runtime; write-seed/confirm must use {SEED_ID}'
);
assert.match(src, /\{SEED_ID\}/, 'write-seed/confirm must reference {SEED_ID}');
});
test('parity: every id the writer grammar can mint round-trips through the reader (#4378)', () => {
// The writer (plant-seed.md generate-seed-id) and the reader
// (deriveSeedIdentity) are parallel surfaces owning one grammar — per
// CLAUDE.md's generative-fix rule their agreement must be ASSERTED, not
// assumed. The widths are parsed out of the shipped MINT sites (the
// `date +%y%m%d` directive and the `head -c N` draw) so a width drift on
// either side fails here. (The enrich matcher is deliberately wider — it
// must also accept legacy `SEED-NNN` — so it is not the parity source.)
const { deriveSeedIdentity } = require('../gsd-core/bin/lib/commands.cjs');
const genBlock = stepBlock(src, 'generate-seed-id');
const suffixWidth = Number(genBlock.match(/head -c (\d+)/)?.[1]);
const dateFormat = genBlock.match(/date \+(\S+)/)?.[1] ?? '';
const dateWidth = (dateFormat.match(/%[ymd]/g) ?? []).length * 2;
assert.ok(dateWidth > 0, 'writer mint block must declare the date format via %y%m%d');
assert.ok(suffixWidth > 0, 'writer mint block must declare the suffix width via head -c N');
const digits = fc.integer({ min: 0, max: 10 ** dateWidth - 1 })
.map((n) => String(n).padStart(dateWidth, '0'));
const base36 = fc.tuple(
...Array.from({ length: suffixWidth }, () =>
fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789'.split('')))
).map((parts) => parts.join(''));
fc.assert(
fc.property(digits, base36, fc.stringMatching(/^[a-z0-9][a-z0-9-]{0,20}$/), (date, suf, slug) => {
const id = `SEED-${date}-${suf}`;
const result = deriveSeedIdentity(`${id}-${slug}`, id);
assert.strictEqual(result.seed_id, id, `reader must accept the writer's id ${id}`);
assert.strictEqual(result.slug, slug);
}),
{ numRuns: 200 }
);
});
});