@llman-sdd/core 0.8.2 → 0.10.0

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.
Files changed (89) hide show
  1. package/package.json +1 -1
  2. package/src/archive/freeze.ts +15 -15
  3. package/src/archive/frozenCard.ts +3 -2
  4. package/src/change/collect.ts +17 -14
  5. package/src/change/deps.ts +54 -0
  6. package/src/change/frontmatter.ts +36 -5
  7. package/src/change/lifecycle.ts +124 -20
  8. package/src/change/nextId.ts +21 -7
  9. package/src/config/changeId.ts +0 -6
  10. package/src/config/load.ts +36 -2
  11. package/src/config/schema.ts +3 -7
  12. package/src/context/indexStore.ts +14 -14
  13. package/src/context/sddState.ts +1 -13
  14. package/src/context/tree.ts +9 -19
  15. package/src/git/spawnGit.ts +5 -1
  16. package/src/index.ts +37 -12
  17. package/src/init/defaultConfig.ts +14 -31
  18. package/src/init/init.ts +92 -30
  19. package/src/locale.ts +33 -0
  20. package/src/project/migrations.ts +196 -60
  21. package/src/report/graph/deps.ts +3 -38
  22. package/src/report/graph/nodes.ts +13 -19
  23. package/src/report/graph/types.ts +2 -6
  24. package/src/report/show.ts +16 -8
  25. package/src/report/specHelpers.ts +22 -28
  26. package/src/review/review.ts +18 -31
  27. package/src/self/completion.ts +206 -0
  28. package/src/spec/assignSpecIds.ts +9 -1
  29. package/src/spec/authoring.ts +11 -11
  30. package/src/spec/parser.ts +3 -1
  31. package/src/templates/skills.ts +3 -23
  32. package/src/util/datedId.ts +18 -0
  33. package/src/util/fsPort.ts +24 -0
  34. package/src/util/nextNumber.ts +30 -0
  35. package/src/util/semver.ts +21 -0
  36. package/src/validation/changeCheck.ts +133 -67
  37. package/src/validation/crossRoot.ts +86 -0
  38. package/src/validation/discover.ts +22 -13
  39. package/src/validation/roots.ts +2 -5
  40. package/src/validation/validate.ts +10 -19
  41. package/src/validation/{transitions.ts → xstateTransitions.ts} +81 -69
  42. package/templates/zh-Hans/skills/llman-sdd-apply-cycle.md +9 -7
  43. package/templates/zh-Hans/skills/llman-sdd-apply.md +5 -5
  44. package/templates/zh-Hans/skills/llman-sdd-archive.md +11 -2
  45. package/templates/zh-Hans/skills/llman-sdd-continue.md +1 -1
  46. package/templates/zh-Hans/skills/llman-sdd-draft.md +1 -1
  47. package/templates/zh-Hans/skills/llman-sdd-explore.md +2 -2
  48. package/templates/zh-Hans/skills/llman-sdd-ff.md +1 -1
  49. package/templates/zh-Hans/skills/llman-sdd-propose.md +8 -6
  50. package/templates/zh-Hans/skills/llman-sdd-quick.md +1 -1
  51. package/templates/zh-Hans/skills/llman-sdd-validate.md +1 -1
  52. package/templates/zh-Hans/skills/llman-sdd-verify.md +2 -2
  53. package/templates/zh-Hans/skills/llman-sdd-wayfinder.md +1 -1
  54. package/templates/zh-Hans/units/skills/git-native-flow.md +12 -6
  55. package/templates/zh-Hans/units/skills/index-fallback.md +1 -0
  56. package/templates/zh-Hans/units/skills/structured-protocol.md +1 -6
  57. package/templates/zh-Hans/units/spec/feature-contract.md +5 -33
  58. package/src/templates/locale.ts +0 -24
  59. package/templates/en/agents-root-stub.md +0 -9
  60. package/templates/en/llmanspec-agents-stub.md +0 -6
  61. package/templates/en/skills/llman-sdd-apply-cycle.md +0 -67
  62. package/templates/en/skills/llman-sdd-apply.md +0 -117
  63. package/templates/en/skills/llman-sdd-arch-review.md +0 -58
  64. package/templates/en/skills/llman-sdd-archive.md +0 -70
  65. package/templates/en/skills/llman-sdd-continue.md +0 -34
  66. package/templates/en/skills/llman-sdd-draft.md +0 -53
  67. package/templates/en/skills/llman-sdd-explore.md +0 -64
  68. package/templates/en/skills/llman-sdd-ff.md +0 -33
  69. package/templates/en/skills/llman-sdd-graph.md +0 -56
  70. package/templates/en/skills/llman-sdd-propose.md +0 -105
  71. package/templates/en/skills/llman-sdd-quick.md +0 -41
  72. package/templates/en/skills/llman-sdd-research.md +0 -35
  73. package/templates/en/skills/llman-sdd-specs-compact.md +0 -41
  74. package/templates/en/skills/llman-sdd-validate.md +0 -28
  75. package/templates/en/skills/llman-sdd-verify.md +0 -77
  76. package/templates/en/skills/llman-sdd-wayfinder.md +0 -83
  77. package/templates/en/units/skills/cli-footer.md +0 -2
  78. package/templates/en/units/skills/ethics-governance.md +0 -6
  79. package/templates/en/units/skills/git-native-flow-brief.md +0 -10
  80. package/templates/en/units/skills/git-native-flow.md +0 -50
  81. package/templates/en/units/skills/human-readable-summary.md +0 -9
  82. package/templates/en/units/skills/stage-guard.md +0 -17
  83. package/templates/en/units/skills/structured-protocol.md +0 -24
  84. package/templates/en/units/skills/validation-hints.md +0 -20
  85. package/templates/en/units/skills/version-drift.md +0 -3
  86. package/templates/en/units/spec/feature-contract.md +0 -38
  87. package/templates/en/units/workflow/archive-freeze-guidance.md +0 -9
  88. package/templates/zh-Hans/units/skills/git-native-flow-brief.md +0 -10
  89. package/templates/zh-Hans/units/workflow/archive-freeze-guidance.md +0 -10
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Shell-completion generation (completion capability r110): the command tree
3
+ * is captured as a plain IR in the CLI layer (commander is a CLI dependency —
4
+ * core stays pure), then rendered per shell here. No second command manifest:
5
+ * the IR is extracted from the live commander program on every invocation, so
6
+ * tree changes flow through automatically. Zero persistence, zero I/O.
7
+ */
8
+
9
+ export interface CompletionCommandSpec {
10
+ name: string;
11
+ /** Long flags only (e.g. `--directory`), including the ones on this node. */
12
+ flags: string[];
13
+ subcommands: CompletionCommandSpec[];
14
+ }
15
+
16
+ export type CompletionShell = 'bash' | 'zsh' | 'fish' | 'powershell' | 'elvish';
17
+
18
+ export const COMPLETION_SHELLS: readonly CompletionShell[] = [
19
+ 'bash',
20
+ 'zsh',
21
+ 'fish',
22
+ 'powershell',
23
+ 'elvish',
24
+ ];
25
+
26
+ /** The binary name baked into generated scripts and rc snippets (bin field). */
27
+ export const COMPLETION_BIN = 'llman-sdd';
28
+
29
+ export const COMPLETION_MARKER_START = '# >>> llman-sdd completion >>>';
30
+ export const COMPLETION_MARKER_END = '# <<< llman-sdd completion <<<';
31
+
32
+ export function isCompletionShell(value: string): value is CompletionShell {
33
+ return (COMPLETION_SHELLS as readonly string[]).includes(value);
34
+ }
35
+
36
+ /** Union of long flags across the whole tree, sorted, deduped. */
37
+ export function collectFlags(spec: CompletionCommandSpec): string[] {
38
+ const out = new Set<string>(spec.flags);
39
+ for (const sub of spec.subcommands) for (const f of collectFlags(sub)) out.add(f);
40
+ return [...out].toSorted();
41
+ }
42
+
43
+ /**
44
+ * Render a complete completion script for one shell. Every renderer MUST
45
+ * embed the bin name, every top-level command, and `--directory` — the BDD
46
+ * suite pins these spot-checks against the live commander tree.
47
+ */
48
+ export function renderCompletionScript(
49
+ spec: CompletionCommandSpec,
50
+ shell: CompletionShell,
51
+ ): string {
52
+ const top = spec.subcommands.map((c) => c.name);
53
+ const flags = collectFlags(spec);
54
+ switch (shell) {
55
+ case 'bash':
56
+ return renderBash(spec, top, flags);
57
+ case 'zsh':
58
+ return renderZsh(top, flags);
59
+ case 'fish':
60
+ return renderFish(spec, top, flags);
61
+ case 'powershell':
62
+ return renderPowerShell(top, flags);
63
+ case 'elvish':
64
+ return renderElvish(top, flags);
65
+ }
66
+ }
67
+
68
+ const header = (shell: string): string =>
69
+ `# ${COMPLETION_BIN} completion — ${shell} (generated by \`${COMPLETION_BIN} self completion --shell ${shell}\`; do not edit by hand)\n`;
70
+
71
+ function quoted(names: readonly string[]): string {
72
+ return names.map((n) => `'${n}'`).join(' ');
73
+ }
74
+
75
+ function renderBash(spec: CompletionCommandSpec, top: string[], flags: string[]): string {
76
+ const fn = `_${COMPLETION_BIN.replaceAll('-', '_')}_completion`;
77
+ const perCommand = spec.subcommands
78
+ .filter((c) => c.flags.length > 0)
79
+ .map((c) => ` ${c.name}) local flags="${c.flags.join(' ')} $flags" ;;`)
80
+ .join('\n');
81
+ return `${header('bash')}
82
+ ${fn}() {
83
+ local cur="\${COMP_WORDS[COMP_CWORD]}"
84
+ local commands="${top.join(' ')}"
85
+ local flags="${flags.join(' ')}"
86
+ if [[ "$cur" == -* ]]; then
87
+ case "\${COMP_WORDS[1]}" in
88
+ ${perCommand}
89
+ *) ;;
90
+ esac
91
+ COMPREPLY=( $(compgen -W "$flags" -- "$cur") )
92
+ else
93
+ COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
94
+ fi
95
+ }
96
+ complete -F ${fn} ${COMPLETION_BIN}
97
+ `;
98
+ }
99
+
100
+ function renderZsh(top: string[], flags: string[]): string {
101
+ return `${header('zsh')}
102
+ #compdef ${COMPLETION_BIN}
103
+ _${COMPLETION_BIN.replaceAll('-', '_')}() {
104
+ local -a cmds
105
+ cmds=(${quoted(top)})
106
+ if [[ "$CURRENT" == 2 && "$words[2]" != -* ]]; then
107
+ _describe 'command' cmds
108
+ else
109
+ local -a flgs
110
+ flgs=(${quoted(flags)})
111
+ _describe 'flag' flgs
112
+ fi
113
+ }
114
+ compdef _${COMPLETION_BIN.replaceAll('-', '_')} ${COMPLETION_BIN}
115
+ `;
116
+ }
117
+
118
+ function renderFish(spec: CompletionCommandSpec, top: string[], flags: string[]): string {
119
+ const lines: string[] = [
120
+ `complete -c ${COMPLETION_BIN} -f`,
121
+ `complete -c ${COMPLETION_BIN} -f -a '${top.join(' ')}' -n '__fish_is_first_arg'`,
122
+ ];
123
+ for (const f of flags) lines.push(`complete -c ${COMPLETION_BIN} -f -l ${f.replace(/^--/u, '')}`);
124
+ for (const c of spec.subcommands) {
125
+ for (const f of c.flags) {
126
+ lines.push(
127
+ `complete -c ${COMPLETION_BIN} -f -n '__fish_seen_subcommand_from ${c.name}' -l ${f.replace(/^--/u, '')}`,
128
+ );
129
+ }
130
+ if (c.subcommands.length > 0) {
131
+ lines.push(
132
+ `complete -c ${COMPLETION_BIN} -f -n '__fish_seen_subcommand_from ${c.name}' -a '${c.subcommands.map((s) => s.name).join(' ')}'`,
133
+ );
134
+ }
135
+ }
136
+ return `${header('fish')}${lines.join('\n')}\n`;
137
+ }
138
+
139
+ function renderPowerShell(top: string[], flags: string[]): string {
140
+ return `${header('powershell')}
141
+ Register-ArgumentCompleter -CommandName ${COMPLETION_BIN} -ScriptBlock {
142
+ param($wordToComplete, $commandAst, $cursorPosition)
143
+ $commands = @(${quoted(top)})
144
+ $flags = @(${quoted(flags)})
145
+ $pool = if ($wordToComplete.StartsWith('-')) { $flags } else { $commands }
146
+ $pool | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
147
+ [System.Management.Automation.CompletionResult]::new($_)
148
+ }
149
+ }
150
+ `;
151
+ }
152
+
153
+ function renderElvish(top: string[], flags: string[]): string {
154
+ return `${header('elvish')}
155
+ edit:completion:arg-completer[${COMPLETION_BIN}] = [@args] {
156
+ cur = $args[-1]
157
+ cmds = [${top.join(' ')}]
158
+ flgs = [${flags.join(' ')}]
159
+ if (str:has-prefix $cur -) {
160
+ put $@flgs
161
+ } else {
162
+ put $@cmds
163
+ }
164
+ }
165
+ `;
166
+ }
167
+
168
+ /** Full marker-wrapped block written into an rc/profile. */
169
+ export function completionBlock(snippet: string): string {
170
+ return `${COMPLETION_MARKER_START}\n${snippet}\n${COMPLETION_MARKER_END}`;
171
+ }
172
+
173
+ /**
174
+ * Marker-idempotent upsert (completion capability r111): an existing block is
175
+ * replaced in place (block count never grows); otherwise the block is
176
+ * appended. Pure string transform — the caller owns file I/O.
177
+ */
178
+ export function upsertCompletionBlock(
179
+ existing: string,
180
+ snippet: string,
181
+ ): { content: string; replaced: boolean } {
182
+ const block = completionBlock(snippet);
183
+ const startAt = existing.indexOf(COMPLETION_MARKER_START);
184
+ const endAt = existing.indexOf(COMPLETION_MARKER_END);
185
+ if (startAt >= 0 && endAt >= 0 && endAt >= startAt) {
186
+ const content = `${existing.slice(0, startAt)}${block}${existing.slice(endAt + COMPLETION_MARKER_END.length)}`;
187
+ return { content, replaced: true };
188
+ }
189
+ const glue = existing === '' || existing.endsWith('\n') ? '' : '\n';
190
+ return { content: `${existing}${glue}${block}\n`, replaced: false };
191
+ }
192
+
193
+ /**
194
+ * Bash rc fallback chain (r111): `.bashrc` → `.bash_profile` → `.profile`;
195
+ * when none exists the chain lands back on `.bashrc` (the caller creates it).
196
+ * `exists` is injected so core stays filesystem-free.
197
+ */
198
+ export function resolveBashRc(home: string, exists: (p: string) => boolean): string {
199
+ const bashrc = `${home}/.bashrc`;
200
+ if (exists(bashrc)) return bashrc;
201
+ const bashProfile = `${home}/.bash_profile`;
202
+ if (exists(bashProfile)) return bashProfile;
203
+ const profile = `${home}/.profile`;
204
+ if (exists(profile)) return profile;
205
+ return bashrc;
206
+ }
@@ -15,7 +15,15 @@ export function featureRelPath(fileName: string, specsDir: string): string {
15
15
  const root = norm(specsDir);
16
16
  let rel = norm(fileName);
17
17
  const prefix = `${root}/`;
18
- if (rel.startsWith(prefix)) rel = rel.slice(prefix.length);
18
+ if (rel.startsWith(prefix)) return rel.slice(prefix.length);
19
+ // Path-form independence (fix-review-sweep-path): callers may load entries
20
+ // with absolute file names while specsDir stays root-relative (the review
21
+ // sweep did exactly that). Locate the LAST whole-segment occurrence of the
22
+ // specs root inside the file name and keep the tail — the id must depend on
23
+ // the position inside the specs tree, never on the caller's path shape.
24
+ const needle = `/${root}/`;
25
+ const at = rel.lastIndexOf(needle);
26
+ if (at >= 0) return rel.slice(at + needle.length);
19
27
  return rel;
20
28
  }
21
29
 
@@ -5,6 +5,8 @@
5
5
  * stays untouched.
6
6
  */
7
7
 
8
+ import { type FsPort } from '../util/fsPort.ts';
9
+ import { nextNumber } from '../util/nextNumber.ts';
8
10
  import type { CapabilityDoc, RuleIR } from './ir.ts';
9
11
  import { specIdOf } from './ir.ts';
10
12
  import { BLOCK_KEYWORD_LINE_RE, officialKeywordsOrEn } from './keywords.ts';
@@ -18,11 +20,7 @@ export interface SpecEntryLike {
18
20
  doc: CapabilityDoc;
19
21
  }
20
22
 
21
- export interface WriteIo {
22
- exists(path: string): boolean;
23
- readText(path: string): string;
24
- writeText(path: string, content: string): void;
25
- }
23
+ export type WriteIo = Pick<FsPort, 'exists' | 'readText' | 'writeText'>;
26
24
 
27
25
  interface KeywordSet {
28
26
  rule: string;
@@ -237,12 +235,14 @@ export function planDedupe(
237
235
  opts: { apply?: boolean } = {},
238
236
  ): DedupePlanItem[] {
239
237
  const used = ruleReqIds(entries);
240
- let next = 1;
241
- const fresh = (): string => {
242
- while (used.has(`r${String(next)}`)) next += 1;
243
- used.add(`r${String(next)}`);
244
- return `r${String(next)}`;
245
- };
238
+ // Allocator primitive (unify-numeric-id-allocation): the remap sequence
239
+ // starts at max(used)+1 over the in-memory registry set (no second
240
+ // filesystem pass) and advances by one per allocation — never a
241
+ // smallest-free probing loop. Zero persisted state.
242
+ let next = nextNumber(
243
+ [...used].map((id) => Number(id.slice(1))).filter((n) => Number.isFinite(n)),
244
+ );
245
+ const fresh = (): string => `r${String(next++)}`;
246
246
  const plan: DedupePlanItem[] = [];
247
247
  for (const dup of duplicates) {
248
248
  // occurrences are in scan order (sorted files, in-file rule order); the
@@ -11,6 +11,7 @@
11
11
  import { AstBuilder, GherkinClassicTokenMatcher, Parser } from '@cucumber/gherkin';
12
12
  import type { GherkinDocument } from '@cucumber/messages';
13
13
 
14
+ import { normalizeLocale } from '../locale.ts';
14
15
  import {
15
16
  type CapabilityDoc,
16
17
  type CapabilityHeader,
@@ -27,7 +28,8 @@ export class SpecParseError extends Error {}
27
28
  let nodeCounter = 0;
28
29
 
29
30
  export function localeToGherkinLang(locale: string): string {
30
- return locale === 'zh-Hans' ? 'zh-CN' : locale;
31
+ const normalized = normalizeLocale(locale);
32
+ return normalized === 'zh-Hans' ? 'zh-CN' : normalized;
31
33
  }
32
34
 
33
35
  const makeIdGenerator = (): (() => string) => {
@@ -1,10 +1,10 @@
1
1
  import type { SddConfig } from '../config/schema.ts';
2
- import { renderTemplate, type UnitRegistry } from './engine.ts';
3
2
  /**
4
3
  * Skills rendering + init orchestration (init-generators capability, r19).
5
4
  * Port of predecessor templates.rs / update_skills.rs / init.rs semantics.
6
5
  */
7
- import { localeFallbacks } from './locale.ts';
6
+ import { localeFallbacks } from '../locale.ts';
7
+ import { renderTemplate, type UnitRegistry } from './engine.ts';
8
8
 
9
9
  export const DEFAULT_SKILL_FILES: readonly string[] = [
10
10
  'llman-sdd-explore.md',
@@ -29,17 +29,16 @@ export const OPTIONAL_SKILL_FILES: readonly string[] = [
29
29
  ];
30
30
 
31
31
  export const UNIT_FILES: readonly string[] = [
32
+ 'skills/index-fallback.md',
32
33
  'skills/validation-hints.md',
33
34
  'skills/human-readable-summary.md',
34
35
  'skills/git-native-flow.md',
35
- 'skills/git-native-flow-brief.md',
36
36
  'skills/stage-guard.md',
37
37
  'skills/ethics-governance.md',
38
38
  'skills/version-drift.md',
39
39
  'spec/feature-contract.md',
40
40
  'skills/structured-protocol.md',
41
41
  'skills/cli-footer.md',
42
- 'workflow/archive-freeze-guidance.md',
43
42
  ];
44
43
 
45
44
  export const ETHICS_KEYS: readonly string[] = [
@@ -50,30 +49,11 @@ export const ETHICS_KEYS: readonly string[] = [
50
49
  'ethics.escalation_policy',
51
50
  ];
52
51
 
53
- /** Framework-derived check_command (predecessor config.rs effective_run_command). */
54
- export function effectiveCheckCommand(specs: NonNullable<SddConfig['specs']>): string {
55
- if (specs.check_command) return specs.check_command;
56
- switch (specs.framework ?? '') {
57
- case 'pytest-bdd':
58
- return 'pytest {feature_dir} -k {feature_name} -v';
59
- case 'rstest-bdd':
60
- return 'cargo test --features bdd';
61
- case 'cucumber-js':
62
- return 'npx cucumber-js {feature_path}';
63
- case 'behave':
64
- return 'behave {feature_path}';
65
- default:
66
- return "echo 'No check_command configured. Set specs.check_command in config.yaml'";
67
- }
68
- }
69
-
70
52
  /** All-string globals (predecessor BTreeMap<String, String> semantics). */
71
53
  export function buildTemplateVars(config: SddConfig, version: string): Record<string, string> {
72
54
  const vars: Record<string, string> = { llman_version: version };
73
55
  if (config.specs) {
74
56
  vars['specs_enabled'] = 'true';
75
- vars['specs_framework'] = config.specs.framework ?? '';
76
- vars['specs_check_command'] = effectiveCheckCommand(config.specs);
77
57
  if (config.specs.verify_prompt) vars['specs_verify_prompt'] = config.specs.verify_prompt;
78
58
  }
79
59
  const extras = new Set<string>(config.extra_skills ?? []);
@@ -0,0 +1,18 @@
1
+ /**
2
+ * T25 single dated-archive-id grammar (`YYYY-MM-DD-<id>`): the prefix test and
3
+ * the id split are one regex family — freeze candidates, frozen cards and the
4
+ * graph's archived nodes must agree on what counts as a dated archive entry.
5
+ */
6
+ export const DATED_PREFIX_RE = /^\d{4}-\d{2}-\d{2}-/u;
7
+
8
+ /** `2026-01-01-old` → `old`; null when the name is not a dated entry. */
9
+ export function datedIdOf(name: string): string | null {
10
+ const m = name.match(new RegExp(`^${DATED_PREFIX_RE.source}(.+)$`, 'u'));
11
+ return m?.[1] ?? null;
12
+ }
13
+
14
+ /** Card form: dated id with the mandatory `.yaml` suffix (files, not dirs). */
15
+ export function datedCardIdOf(name: string, suffix: string): string | null {
16
+ if (!name.endsWith(suffix)) return null;
17
+ return datedIdOf(name.slice(0, -suffix.length));
18
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * T26 canonical filesystem port: every module declares the narrow `Pick` it
3
+ * consumes, so the structural surface is written once and the per-module
4
+ * shapes cannot drift. The root interface lists the full observed surface
5
+ * (superset union of all past local `*Io` interfaces; no node:fs, no clock).
6
+ */
7
+ export interface FsPort {
8
+ exists(path: string): boolean;
9
+ readText(path: string): string;
10
+ writeText(path: string, content: string): void;
11
+ rename(from: string, to: string): void;
12
+ listDir(path: string): string[];
13
+ isDirectory(path: string): boolean;
14
+ remove(path: string): void;
15
+ mkdirp(path: string): void;
16
+ removeDir(path: string): void;
17
+ moveDir(from: string, to: string): void;
18
+ /** Process liveness for the rebuild lock (injected, never polled env). */
19
+ processAlive(pid: number): boolean;
20
+ currentPid(): number;
21
+ /** Wall clock, injected (B17: core never calls new Date()). */
22
+ now(): Date;
23
+ mtimeMs(path: string): number;
24
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Numeric-id allocator primitive (unify-numeric-id-allocation).
3
+ *
4
+ * One primitive, everywhere max+1: every numeric id distribution (req id
5
+ * taking, dedupe remapping, change sequence numbers, template variables)
6
+ * consumes this function; call sites MUST NOT re-implement probing loops.
7
+ * Uniqueness is judged against the same surveyed set the distribution saw.
8
+ *
9
+ * Zero persisted state: the surveyed set is recomputed per invocation
10
+ * (rescan is the truth) — no counters, tombstones, or cache files.
11
+ */
12
+ export function nextNumber(used: Iterable<number>): number {
13
+ const max = maxUsedNumber(used);
14
+ return max === null ? 1 : max + 1;
15
+ }
16
+
17
+ /**
18
+ * Survey metadata companion: the maximum already-used number, `null` when the
19
+ * set is empty (or carries no finite numbers). Single-pass fold — never
20
+ * `Math.max(...spread)`, which risks argument-limit pressure on large sets.
21
+ */
22
+ export function maxUsedNumber(used: Iterable<number>): number | null {
23
+ let max: number | null = null;
24
+ for (const n of used) {
25
+ // Non-finite noise (NaN/±Infinity) never wins the fold; an empty (or
26
+ // fully non-numeric) set has no maximum.
27
+ if (Number.isFinite(n) && (max === null || n > max)) max = n;
28
+ }
29
+ return max;
30
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * T25 single semver compare: numeric major.minor.patch, non-numeric segments
3
+ * compare 0. `compareSemver` is the ordering primitive; `semverLt` is its
4
+ * boolean view (version-drift note) — one implementation, two signatures.
5
+ */
6
+ const dot = (v: string): number => Math.trunc(Number(v)) || 0;
7
+
8
+ export function compareSemver(a: string, b: string): number {
9
+ const pa = a.split('.');
10
+ const pb = b.split('.');
11
+ for (let i = 0; i < 3; i++) {
12
+ const ai = dot(pa[i] ?? '0');
13
+ const bi = dot(pb[i] ?? '0');
14
+ if (ai !== bi) return ai < bi ? -1 : 1;
15
+ }
16
+ return 0;
17
+ }
18
+
19
+ export function semverLt(a: string, b: string): boolean {
20
+ return compareSemver(a, b) < 0;
21
+ }