@llman-sdd/core 0.10.1 → 0.12.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 (119) hide show
  1. package/package.json +11 -8
  2. package/src/archive/freeze.ts +41 -15
  3. package/src/archive/frozenCard.ts +57 -9
  4. package/src/archive/ignoreChain.ts +2 -6
  5. package/src/archive/sevenzip.ts +0 -1
  6. package/src/change/closeOutHarness.ts +17 -0
  7. package/src/change/collect.ts +0 -5
  8. package/src/change/frontmatter.ts +15 -7
  9. package/src/change/id.ts +0 -2
  10. package/src/change/lifecycle.ts +53 -94
  11. package/src/config/changeId.ts +0 -2
  12. package/src/config/load.ts +0 -4
  13. package/src/config/schema.ts +24 -13
  14. package/src/config/surface.ts +2 -12
  15. package/src/context/sddState.ts +23 -18
  16. package/src/git/spawnGit.ts +0 -3
  17. package/src/hints/jitHints.ts +82 -0
  18. package/src/index.ts +462 -39
  19. package/src/init/defaultConfig.ts +4 -13
  20. package/src/init/init.ts +108 -36
  21. package/src/init/skillCheck.ts +60 -0
  22. package/src/init/uncommentConfig.ts +909 -0
  23. package/src/locale.ts +0 -2
  24. package/src/project/migrateNotes.ts +0 -9
  25. package/src/project/migrations.ts +151 -9
  26. package/src/report/graph/analysis.ts +0 -4
  27. package/src/report/graph/nodes.ts +0 -6
  28. package/src/report/show.ts +7 -23
  29. package/src/report/specHelpers.ts +10 -14
  30. package/src/review/review.ts +0 -12
  31. package/src/spec/assignSpecIds.ts +0 -3
  32. package/src/spec/authoring.ts +16 -24
  33. package/src/spec/ir.ts +14 -5
  34. package/src/spec/keywords.ts +0 -2
  35. package/src/spec/machineKey.ts +49 -0
  36. package/src/spec/migrateNative.ts +4 -18
  37. package/src/spec/parser.ts +10 -19
  38. package/src/spec/reqRef.ts +135 -0
  39. package/src/studio/changeScope.ts +50 -0
  40. package/src/studio/changeScopeDiff.ts +195 -0
  41. package/src/studio/contracts.ts +493 -0
  42. package/src/studio/decisionTree.ts +206 -0
  43. package/src/studio/deeplink.ts +116 -0
  44. package/src/studio/demos.ts +167 -0
  45. package/src/studio/diff.ts +494 -0
  46. package/src/studio/drift.ts +738 -0
  47. package/src/studio/extract.ts +360 -0
  48. package/src/studio/featureSync.ts +592 -0
  49. package/src/studio/forest.ts +570 -0
  50. package/src/studio/index.ts +32 -0
  51. package/src/studio/model.ts +254 -0
  52. package/src/studio/revisions.ts +476 -0
  53. package/src/studio/search.ts +337 -0
  54. package/src/studio/store.ts +811 -0
  55. package/src/studio/sync.ts +912 -0
  56. package/src/studio/textfold.ts +72 -0
  57. package/src/studio/time.ts +107 -0
  58. package/src/studio/validate.ts +363 -0
  59. package/src/templates/embedded.ts +4 -6
  60. package/src/templates/engine.ts +1 -1
  61. package/src/templates/skills.ts +76 -51
  62. package/src/theorems/guard.ts +52 -0
  63. package/src/theorems/index.ts +56 -0
  64. package/src/theorems/migrate.ts +133 -0
  65. package/src/theorems/schema.ts +67 -0
  66. package/src/theorems/scope.ts +68 -0
  67. package/src/theorems/serialize.ts +60 -0
  68. package/src/theorems/transactionMachine.ts +247 -0
  69. package/src/theorems/validate.ts +141 -0
  70. package/src/util/nextNumber.ts +0 -2
  71. package/src/validation/changeCheck.ts +0 -24
  72. package/src/validation/flowAndNesting.ts +434 -0
  73. package/src/validation/harness.ts +108 -65
  74. package/src/validation/validate.ts +26 -12
  75. package/src/validation/xstateTransitions.ts +483 -184
  76. package/templates/zh-Hans/llmanspec-agents-stub.md +17 -2
  77. package/templates/zh-Hans/skills/llman-sdd-autopilot/SKILL.md +34 -0
  78. package/templates/zh-Hans/skills/llman-sdd-change/SKILL.md +44 -0
  79. package/templates/zh-Hans/skills/llman-sdd-change/playbooks/archive.md +15 -0
  80. package/templates/zh-Hans/skills/llman-sdd-change/playbooks/draft.md +9 -0
  81. package/templates/zh-Hans/skills/llman-sdd-review/SKILL.md +71 -0
  82. package/templates/zh-Hans/skills/llman-sdd-specs/SKILL.md +70 -0
  83. package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/compact.md +12 -0
  84. package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/doctor.md +26 -0
  85. package/templates/zh-Hans/skills/llman-sdd-specs/references/graph-dsl.md +33 -0
  86. package/templates/zh-Hans/skills/llman-sdd-studio/SKILL.md +33 -0
  87. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/collab.md +20 -0
  88. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/drift.md +52 -0
  89. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/onboard.md +33 -0
  90. package/templates/zh-Hans/units/skills/cli-footer.md +2 -2
  91. package/src/context/indexStore.ts +0 -171
  92. package/src/context/retrieve.ts +0 -332
  93. package/src/context/tree.ts +0 -112
  94. package/templates/zh-Hans/agents-root-stub.md +0 -9
  95. package/templates/zh-Hans/skills/llman-sdd-apply-cycle.md +0 -69
  96. package/templates/zh-Hans/skills/llman-sdd-apply.md +0 -117
  97. package/templates/zh-Hans/skills/llman-sdd-arch-review.md +0 -58
  98. package/templates/zh-Hans/skills/llman-sdd-archive.md +0 -79
  99. package/templates/zh-Hans/skills/llman-sdd-continue.md +0 -34
  100. package/templates/zh-Hans/skills/llman-sdd-draft.md +0 -53
  101. package/templates/zh-Hans/skills/llman-sdd-explore.md +0 -64
  102. package/templates/zh-Hans/skills/llman-sdd-ff.md +0 -33
  103. package/templates/zh-Hans/skills/llman-sdd-graph.md +0 -56
  104. package/templates/zh-Hans/skills/llman-sdd-propose.md +0 -107
  105. package/templates/zh-Hans/skills/llman-sdd-quick.md +0 -41
  106. package/templates/zh-Hans/skills/llman-sdd-research.md +0 -35
  107. package/templates/zh-Hans/skills/llman-sdd-specs-compact.md +0 -41
  108. package/templates/zh-Hans/skills/llman-sdd-validate.md +0 -28
  109. package/templates/zh-Hans/skills/llman-sdd-verify.md +0 -77
  110. package/templates/zh-Hans/skills/llman-sdd-wayfinder.md +0 -83
  111. package/templates/zh-Hans/units/skills/ethics-governance.md +0 -6
  112. package/templates/zh-Hans/units/skills/git-native-flow.md +0 -56
  113. package/templates/zh-Hans/units/skills/human-readable-summary.md +0 -9
  114. package/templates/zh-Hans/units/skills/index-fallback.md +0 -1
  115. package/templates/zh-Hans/units/skills/stage-guard.md +0 -17
  116. package/templates/zh-Hans/units/skills/structured-protocol.md +0 -19
  117. package/templates/zh-Hans/units/skills/validation-hints.md +0 -20
  118. package/templates/zh-Hans/units/skills/version-drift.md +0 -3
  119. package/templates/zh-Hans/units/spec/feature-contract.md +0 -8
@@ -6,40 +6,43 @@ import type { SddConfig } from '../config/schema.ts';
6
6
  import { localeFallbacks } from '../locale.ts';
7
7
  import { renderTemplate, type UnitRegistry } from './engine.ts';
8
8
 
9
- export const DEFAULT_SKILL_FILES: readonly string[] = [
10
- 'llman-sdd-explore.md',
11
- 'llman-sdd-propose.md',
12
- 'llman-sdd-draft.md',
13
- 'llman-sdd-apply.md',
14
- 'llman-sdd-verify.md',
15
- 'llman-sdd-quick.md',
16
- 'llman-sdd-specs-compact.md',
17
- 'llman-sdd-archive.md',
18
- 'llman-sdd-graph.md',
19
- 'llman-sdd-apply-cycle.md',
20
- ];
9
+ export interface SkillPackageSpec {
10
+ readonly name: string;
11
+ /** Relative paths under `skills/<name>/` (always includes `SKILL.md`). */
12
+ readonly files: readonly string[];
13
+ /** True for skills that must not be auto-invoked by the model. */
14
+ readonly manualOnly?: boolean;
15
+ }
21
16
 
22
- export const OPTIONAL_SKILL_FILES: readonly string[] = [
23
- 'llman-sdd-continue.md',
24
- 'llman-sdd-ff.md',
25
- 'llman-sdd-validate.md',
26
- 'llman-sdd-arch-review.md',
27
- 'llman-sdd-wayfinder.md',
28
- 'llman-sdd-research.md',
17
+ export const SKILL_PACKAGES: readonly SkillPackageSpec[] = [
18
+ {
19
+ name: 'llman-sdd-specs',
20
+ files: ['SKILL.md', 'references/graph-dsl.md', 'playbooks/doctor.md', 'playbooks/compact.md'],
21
+ },
22
+ {
23
+ name: 'llman-sdd-studio',
24
+ files: ['SKILL.md', 'playbooks/onboard.md', 'playbooks/collab.md', 'playbooks/drift.md'],
25
+ },
26
+ {
27
+ name: 'llman-sdd-change',
28
+ files: ['SKILL.md', 'playbooks/draft.md', 'playbooks/archive.md'],
29
+ },
30
+ {
31
+ name: 'llman-sdd-review',
32
+ files: ['SKILL.md'],
33
+ },
34
+ {
35
+ name: 'llman-sdd-autopilot',
36
+ files: ['SKILL.md'],
37
+ manualOnly: true,
38
+ },
29
39
  ];
30
40
 
31
- export const UNIT_FILES: readonly string[] = [
32
- 'skills/index-fallback.md',
33
- 'skills/validation-hints.md',
34
- 'skills/human-readable-summary.md',
35
- 'skills/git-native-flow.md',
36
- 'skills/stage-guard.md',
37
- 'skills/ethics-governance.md',
38
- 'skills/version-drift.md',
39
- 'spec/feature-contract.md',
40
- 'skills/structured-protocol.md',
41
- 'skills/cli-footer.md',
42
- ];
41
+ export const DEFAULT_SKILL_FILES: readonly string[] = SKILL_PACKAGES.map((p) => p.name);
42
+
43
+ export const OPTIONAL_SKILL_FILES: readonly string[] = [];
44
+
45
+ export const UNIT_FILES: readonly string[] = ['skills/cli-footer.md'];
43
46
 
44
47
  export const ETHICS_KEYS: readonly string[] = [
45
48
  'ethics.risk_level',
@@ -49,18 +52,24 @@ export const ETHICS_KEYS: readonly string[] = [
49
52
  'ethics.escalation_policy',
50
53
  ];
51
54
 
52
- /** All-string globals (predecessor BTreeMap<String, String> semantics). */
55
+ /** Skills the model must not load on its own. Init writes the Codex policy file for these. */
56
+ export const MANUAL_INVOCATION_SKILLS: readonly string[] = SKILL_PACKAGES.filter(
57
+ (p) => p.manualOnly === true,
58
+ ).map((p) => p.name);
59
+
60
+ export const OPENAI_EXPLICIT_POLICY = `policy:\n allow_implicit_invocation: false\n`;
61
+
53
62
  export function buildTemplateVars(config: SddConfig, version: string): Record<string, string> {
54
63
  const vars: Record<string, string> = { llman_version: version };
55
64
  if (config.specs) {
56
65
  vars['specs_enabled'] = 'true';
57
66
  if (config.specs.verify_prompt) vars['specs_verify_prompt'] = config.specs.verify_prompt;
58
67
  }
59
- const extras = new Set<string>(config.extra_skills ?? []);
60
- for (const name of OPTIONAL_SKILL_FILES) {
61
- const stem = name.replace(/\.md$/u, '');
62
- const key = `extra_skill_${stem.replace(/^llman-sdd-/u, '').replaceAll('-', '_')}`;
63
- if (extras.has(stem)) vars[key] = 'true';
68
+ if (config.review?.handoff_mode) {
69
+ vars['review_handoff_mode'] = config.review.handoff_mode;
70
+ }
71
+ if (config.review?.handoff_file) {
72
+ vars['review_handoff_file'] = config.review.handoff_file;
64
73
  }
65
74
  return vars;
66
75
  }
@@ -98,20 +107,23 @@ export function loadUnitRegistry(
98
107
  return units;
99
108
  }
100
109
 
110
+ export interface SkillTemplateFile {
111
+ /** Relative path inside the skill directory, e.g. 'playbooks/doctor.md'. */
112
+ relativePath: string;
113
+ content: string;
114
+ }
115
+
101
116
  export interface SkillTemplate {
117
+ /** Skill directory name, e.g. 'llman-sdd-specs'. */
102
118
  name: string;
119
+ /** Rendered top-level SKILL.md content. */
103
120
  content: string;
121
+ /** Rendered nested files inside the skill directory (excluding SKILL.md). */
122
+ files: SkillTemplateFile[];
104
123
  }
105
124
 
106
- export function skillCandidates(config: SddConfig): string[] {
107
- const extras: readonly string[] = config.extra_skills ?? [];
108
- return [
109
- ...DEFAULT_SKILL_FILES,
110
- ...OPTIONAL_SKILL_FILES.filter((f) => {
111
- const stem = f.replace(/\.md$/u, '');
112
- return extras.includes(stem);
113
- }),
114
- ];
125
+ export function skillCandidates(_config: SddConfig): string[] {
126
+ return SKILL_PACKAGES.map((p) => p.name);
115
127
  }
116
128
 
117
129
  export function loadSkillTemplates(
@@ -123,12 +135,25 @@ export function loadSkillTemplates(
123
135
  const locales = localeFallbacks(config.locale);
124
136
  const units = loadUnitRegistry(io, templatesRoot, locales);
125
137
  const templates: SkillTemplate[] = [];
126
- for (const skillFile of skillCandidates(config)) {
127
- const raw = loadLocaleResource(io, templatesRoot, locales, `skills/${skillFile}`);
128
- if (raw === null) {
129
- throw new Error(`template not found: skills/${skillFile}`);
138
+ for (const pkg of SKILL_PACKAGES) {
139
+ const mainRaw = loadLocaleResource(io, templatesRoot, locales, `skills/${pkg.name}/SKILL.md`);
140
+ if (mainRaw === null) {
141
+ throw new Error(`template not found: skills/${pkg.name}/SKILL.md`);
142
+ }
143
+ const nested: SkillTemplateFile[] = [];
144
+ for (const rel of pkg.files) {
145
+ if (rel === 'SKILL.md') continue;
146
+ const raw = loadLocaleResource(io, templatesRoot, locales, `skills/${pkg.name}/${rel}`);
147
+ if (raw === null) {
148
+ throw new Error(`template not found: skills/${pkg.name}/${rel}`);
149
+ }
150
+ nested.push({ relativePath: rel, content: renderTemplate(raw, units, vars) });
130
151
  }
131
- templates.push({ name: skillFile, content: renderTemplate(raw, units, vars) });
152
+ templates.push({
153
+ name: pkg.name,
154
+ content: renderTemplate(mainRaw, units, vars),
155
+ files: nested,
156
+ });
132
157
  }
133
158
  return templates;
134
159
  }
@@ -0,0 +1,52 @@
1
+ import type { TheoremSeverity } from './schema.ts';
2
+
3
+ export type TheoremGuardScenario = 'conflict' | 'write';
4
+
5
+ export type TheoremGuardDecision =
6
+ | 'agent-stop-and-escalate'
7
+ | 'allow-with-documented-deviation'
8
+ | 'reject-write-ask-human'
9
+ | 'enter-human-transaction';
10
+
11
+ export interface TheoremGuardInput {
12
+ scenario: TheoremGuardScenario;
13
+ severity: TheoremSeverity;
14
+ humanTty: boolean;
15
+ }
16
+
17
+ export interface TheoremGuardVerdict {
18
+ decision: TheoremGuardDecision;
19
+ rationale: string;
20
+ }
21
+
22
+ function decideConflict(severity: TheoremSeverity): TheoremGuardVerdict {
23
+ if (severity === 'hard') {
24
+ return {
25
+ decision: 'agent-stop-and-escalate',
26
+ rationale: 'hard theorem conflict: stop and escalate to the human',
27
+ };
28
+ }
29
+ return {
30
+ decision: 'allow-with-documented-deviation',
31
+ rationale: 'advisory theorem conflict: deviation allowed with an explicit rationale',
32
+ };
33
+ }
34
+
35
+ function decideWrite(humanTty: boolean): TheoremGuardVerdict {
36
+ if (!humanTty) {
37
+ return {
38
+ decision: 'reject-write-ask-human',
39
+ rationale: 'CLI, OS lock and gates reject theorem writes without a human TTY',
40
+ };
41
+ }
42
+ return {
43
+ decision: 'enter-human-transaction',
44
+ rationale: 'human TTY: enter the copy-edit transaction and relock after Diff confirmation',
45
+ };
46
+ }
47
+
48
+ export function evaluateTheoremGuard(input: TheoremGuardInput): TheoremGuardVerdict {
49
+ return input.scenario === 'conflict'
50
+ ? decideConflict(input.severity)
51
+ : decideWrite(input.humanTty);
52
+ }
@@ -0,0 +1,56 @@
1
+ export {
2
+ THEOREM_ID_RE,
3
+ THEOREM_LEGACY_LOCK_FILE,
4
+ THEOREM_LOCK_STRENGTHS,
5
+ THEOREMS_DIR_REL,
6
+ TheoremDocumentSchema,
7
+ TheoremSeveritySchema,
8
+ TheoremStatusSchema,
9
+ TheoremVerifySchema,
10
+ type TheoremDocument,
11
+ type TheoremEntry,
12
+ type TheoremIssue,
13
+ type TheoremLockStrength,
14
+ type TheoremSeverity,
15
+ type TheoremSourceFile,
16
+ type TheoremStatus,
17
+ type TheoremValidationResult,
18
+ type TheoremVerify,
19
+ } from './schema.ts';
20
+ export {
21
+ discoverTheoremFiles,
22
+ findLegacyTheoremFiles,
23
+ validateTheoremSet,
24
+ type TheoremDiscoverIo,
25
+ } from './validate.ts';
26
+ export {
27
+ compileScopeGlob,
28
+ normalizeTheoremPath,
29
+ selectTheoremsByTag,
30
+ selectTheoremsForPaths,
31
+ theoremMatchesPath,
32
+ } from './scope.ts';
33
+ export {
34
+ isSingleTheoremDocument,
35
+ migrateLegacyTheoremMarkdown,
36
+ type MigratedTheorem,
37
+ type TheoremMigrationResult,
38
+ } from './migrate.ts';
39
+ export { renderTheoremUnifiedDiff, renderTheoremYaml, yamlBlock, yamlScalar } from './serialize.ts';
40
+ export {
41
+ THEOREM_CONFIRM_STATE,
42
+ THEOREM_TRANSACTION_FINAL_STATES,
43
+ THEOREM_TRANSACTION_SPEC_STATES,
44
+ theoremTransactionMachine,
45
+ type TheoremTransactionActors,
46
+ type TheoremTransactionContext,
47
+ type TheoremTransactionEvent,
48
+ type TheoremTransactionSpecState,
49
+ } from './transactionMachine.ts';
50
+ export {
51
+ evaluateTheoremGuard,
52
+ type TheoremGuardDecision,
53
+ type TheoremGuardInput,
54
+ type TheoremGuardScenario,
55
+ type TheoremGuardVerdict,
56
+ } from './guard.ts';
@@ -0,0 +1,133 @@
1
+ import { parse as parseYaml } from 'yaml';
2
+
3
+ import { renderTheoremYaml } from './serialize.ts';
4
+
5
+ export interface MigratedTheorem {
6
+ id: string;
7
+ filePath: string;
8
+ yaml: string;
9
+ }
10
+
11
+ export interface TheoremMigrationResult {
12
+ ok: boolean;
13
+ theorems: MigratedTheorem[];
14
+ issues: string[];
15
+ }
16
+
17
+ const HEADING_RE = /^##\s+theorem:([a-z0-9][a-z0-9-]*)(?:\s*[—–-]+\s*(.+))?$/iu;
18
+ const BULLET_RE = /^[-*]\s+\*\*([a-zA-Z_]+)\*\*\s*:\s*(.*)$/u;
19
+
20
+ interface Draft {
21
+ id: string;
22
+ title: string;
23
+ statement: string;
24
+ rationale: string;
25
+ gate: string;
26
+ scope: string[];
27
+ tags: string[];
28
+ }
29
+
30
+ function stripBulletValue(value: string): string {
31
+ const ticked = /^`(.*)`$/u.exec(value.trim());
32
+ return (ticked?.[1] ?? value).trim();
33
+ }
34
+
35
+ function splitList(value: string): string[] {
36
+ return value
37
+ .split(',')
38
+ .map((item) => stripBulletValue(item))
39
+ .filter((item) => item !== '');
40
+ }
41
+
42
+ function renderTheorem(draft: Draft): string {
43
+ return renderTheoremYaml({
44
+ id: draft.id,
45
+ title: draft.title === '' ? draft.id : draft.title,
46
+ statement: draft.statement,
47
+ rationale: draft.rationale,
48
+ severity: 'hard',
49
+ status: 'active',
50
+ ...(draft.scope.length > 0 ? { scope: draft.scope } : {}),
51
+ ...(draft.tags.length > 0 ? { tags: draft.tags } : {}),
52
+ ...(draft.gate !== '' ? { verify: { command: draft.gate, timeout_sec: 60 } } : {}),
53
+ });
54
+ }
55
+
56
+ function finishDraft(draft: Draft, issues: string[], filePath: string): MigratedTheorem | null {
57
+ if (draft.statement === '') {
58
+ issues.push(filePath + ': theorem:' + draft.id + ' missing required statement');
59
+ return null;
60
+ }
61
+ if (draft.rationale === '') {
62
+ issues.push(filePath + ': theorem:' + draft.id + ' missing required rationale');
63
+ return null;
64
+ }
65
+ return {
66
+ id: draft.id,
67
+ filePath: 'llmanspec/theorems/' + draft.id + '.yaml',
68
+ yaml: renderTheorem(draft),
69
+ };
70
+ }
71
+
72
+ export function migrateLegacyTheoremMarkdown(
73
+ filePath: string,
74
+ content: string,
75
+ ): TheoremMigrationResult {
76
+ const theorems: MigratedTheorem[] = [];
77
+ const issues: string[] = [];
78
+ let draft: Draft | null = null;
79
+
80
+ const flush = (): void => {
81
+ if (draft === null) return;
82
+ const done = finishDraft(draft, issues, filePath);
83
+ if (done !== null) theorems.push(done);
84
+ draft = null;
85
+ };
86
+
87
+ for (const rawLine of content.split('\n')) {
88
+ const line = rawLine.trimEnd();
89
+ const heading = HEADING_RE.exec(line);
90
+ if (heading !== null) {
91
+ flush();
92
+ draft = {
93
+ id: heading[1] ?? '',
94
+ title: (heading[2] ?? '').trim(),
95
+ statement: '',
96
+ rationale: '',
97
+ gate: '',
98
+ scope: [],
99
+ tags: [],
100
+ };
101
+ continue;
102
+ }
103
+ const bullet = BULLET_RE.exec(line.trim());
104
+ if (bullet !== null && draft !== null) {
105
+ const key = (bullet[1] ?? '').toLowerCase();
106
+ const value = bullet[2] ?? '';
107
+ if (key === 'statement') draft.statement = stripBulletValue(value);
108
+ else if (key === 'rationale') draft.rationale = stripBulletValue(value);
109
+ else if (key === 'gate') draft.gate = stripBulletValue(value);
110
+ else if (key === 'scope') draft.scope = splitList(value);
111
+ else if (key === 'tags') draft.tags = splitList(value);
112
+ continue;
113
+ }
114
+ }
115
+ flush();
116
+
117
+ if (theorems.length === 0 && issues.length === 0) {
118
+ issues.push(filePath + ': no theorem declaration found');
119
+ }
120
+ for (const theorem of theorems) {
121
+ if (theorem.id === '') issues.push(filePath + ': theorem with empty id');
122
+ }
123
+ return { ok: issues.length === 0, theorems, issues };
124
+ }
125
+
126
+ export function isSingleTheoremDocument(yamlText: string): boolean {
127
+ try {
128
+ const parsed: unknown = parseYaml(yamlText);
129
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed);
130
+ } catch {
131
+ return false;
132
+ }
133
+ }
@@ -0,0 +1,67 @@
1
+ // - status: `deprecated` is hidden from `list` unless `--include-deprecated`.
2
+ import { z } from 'zod';
3
+
4
+ export const THEOREMS_DIR_REL = 'llmanspec/theorems';
5
+ export const THEOREM_LEGACY_LOCK_FILE = '.theorems.lock.json';
6
+
7
+ export const THEOREM_LOCK_STRENGTHS = ['strong', 'weak', 'none'] as const;
8
+ export type TheoremLockStrength = (typeof THEOREM_LOCK_STRENGTHS)[number];
9
+
10
+ export const TheoremSeveritySchema = z.enum(['hard', 'advisory']);
11
+ export type TheoremSeverity = z.infer<typeof TheoremSeveritySchema>;
12
+
13
+ export const TheoremStatusSchema = z.enum(['active', 'deprecated']);
14
+ export type TheoremStatus = z.infer<typeof TheoremStatusSchema>;
15
+
16
+ export const THEOREM_ID_RE = /^[a-z0-9][a-z0-9-]*$/u;
17
+
18
+ export const TheoremVerifySchema = z.object({
19
+ command: z.string().trim().min(1),
20
+ timeout_sec: z.number().int().min(1).max(600).default(60),
21
+ });
22
+ export type TheoremVerify = z.infer<typeof TheoremVerifySchema>;
23
+
24
+ export const TheoremDocumentSchema = z.object({
25
+ id: z.string().regex(THEOREM_ID_RE),
26
+ title: z.string().trim().min(1).max(160),
27
+ statement: z.string().trim().min(1),
28
+ rationale: z.string().trim().min(1),
29
+ severity: TheoremSeveritySchema.default('hard'),
30
+ status: TheoremStatusSchema.default('active'),
31
+ scope: z.array(z.string().trim().min(1)).optional(),
32
+ tags: z.array(z.string().trim().min(1)).optional(),
33
+ verify: TheoremVerifySchema.optional(),
34
+ });
35
+ export type TheoremDocument = z.infer<typeof TheoremDocumentSchema>;
36
+
37
+ export interface TheoremEntry {
38
+ id: string;
39
+ title: string;
40
+ statement: string;
41
+ rationale: string;
42
+ severity: TheoremSeverity;
43
+ status: TheoremStatus;
44
+ scope?: string[];
45
+ tags: string[];
46
+ verify?: TheoremVerify;
47
+ filePath: string;
48
+ }
49
+
50
+ export interface TheoremIssue {
51
+ code: 'yaml-parse' | 'schema' | 'id-mismatch' | 'duplicate-id' | 'legacy-conflict';
52
+ filePath: string;
53
+ message: string;
54
+ }
55
+
56
+ export interface TheoremSourceFile {
57
+ /** Instance-relative POSIX path. */
58
+ filePath: string;
59
+ content: string;
60
+ }
61
+
62
+ export interface TheoremValidationResult {
63
+ ok: boolean;
64
+ theorems: TheoremEntry[];
65
+ issues: TheoremIssue[];
66
+ legacyFiles: string[];
67
+ }
@@ -0,0 +1,68 @@
1
+ import type { TheoremEntry } from './schema.ts';
2
+
3
+ /** Normalize a candidate path to POSIX, no leading ./ and no trailing slash. */
4
+ export function normalizeTheoremPath(path: string): string {
5
+ const posix = path.replace(/\\/gu, '/').trim();
6
+ return posix.replace(/^\.\//u, '').replace(/\/+$/u, '');
7
+ }
8
+
9
+ function escapeRegExp(text: string): string {
10
+ return text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
11
+ }
12
+
13
+ export function compileScopeGlob(glob: string): RegExp {
14
+ const norm = normalizeTheoremPath(glob);
15
+ let out = '';
16
+ let i = 0;
17
+ while (i < norm.length) {
18
+ const ch = norm[i];
19
+ if (ch === '*') {
20
+ if (norm[i + 1] === '*') {
21
+ if (norm[i + 2] === '/') {
22
+ out += '(?:.*/)?';
23
+ i += 3;
24
+ continue;
25
+ }
26
+ out += '.*';
27
+ i += 2;
28
+ continue;
29
+ }
30
+ out += '[^/]*';
31
+ i += 1;
32
+ continue;
33
+ }
34
+ if (ch === '?') {
35
+ out += '[^/]';
36
+ i += 1;
37
+ continue;
38
+ }
39
+ out += escapeRegExp(ch ?? '');
40
+ i += 1;
41
+ }
42
+ return new RegExp(`^${out}$`, 'u');
43
+ }
44
+
45
+ /** Whether one theorem's scope covers targetPath (no scope = global). */
46
+ export function theoremMatchesPath(theorem: TheoremEntry, targetPath: string): boolean {
47
+ const scope = theorem.scope;
48
+ if (scope === undefined || scope.length === 0) return true;
49
+ const target = normalizeTheoremPath(targetPath);
50
+ return scope.some((glob) => compileScopeGlob(glob).test(target));
51
+ }
52
+
53
+ /** Recall theorems covering at least one of the queried paths. */
54
+ export function selectTheoremsForPaths(
55
+ theorems: readonly TheoremEntry[],
56
+ paths: readonly string[],
57
+ ): TheoremEntry[] {
58
+ if (paths.length === 0) return [...theorems];
59
+ return theorems.filter((theorem) => paths.some((path) => theoremMatchesPath(theorem, path)));
60
+ }
61
+
62
+ /** Recall theorems carrying a tag. */
63
+ export function selectTheoremsByTag(
64
+ theorems: readonly TheoremEntry[],
65
+ tag: string,
66
+ ): TheoremEntry[] {
67
+ return theorems.filter((theorem) => theorem.tags.includes(tag));
68
+ }
@@ -0,0 +1,60 @@
1
+ import { createTwoFilesPatch } from 'diff';
2
+
3
+ import type { TheoremDocument } from './schema.ts';
4
+
5
+ const PLAIN_SCALAR_RE = /^[A-Za-z0-9_./-]+$/u;
6
+ const RESERVED_SCALAR_RE = /^(true|false|null|yes|no|on|off)$/iu;
7
+
8
+ export function yamlScalar(value: string): string {
9
+ if (value === '') return '""';
10
+ if (PLAIN_SCALAR_RE.test(value) && !RESERVED_SCALAR_RE.test(value)) return value;
11
+ return JSON.stringify(value);
12
+ }
13
+
14
+ export function yamlBlock(field: string, value: string): string[] {
15
+ const out = [field + ': |-'];
16
+ for (const line of value.split('\n')) out.push(' ' + line);
17
+ return out;
18
+ }
19
+
20
+ export function renderTheoremYaml(doc: TheoremDocument): string {
21
+ const out: string[] = [];
22
+ out.push('id: ' + doc.id);
23
+ out.push('title: ' + yamlScalar(doc.title));
24
+ out.push(...yamlBlock('statement', doc.statement));
25
+ out.push(...yamlBlock('rationale', doc.rationale));
26
+ out.push('severity: ' + doc.severity);
27
+ out.push('status: ' + doc.status);
28
+ if (doc.scope !== undefined && doc.scope.length > 0) {
29
+ out.push('scope:');
30
+ for (const entry of doc.scope) out.push(' - ' + yamlScalar(entry));
31
+ }
32
+ if (doc.tags !== undefined && doc.tags.length > 0) {
33
+ out.push('tags:');
34
+ for (const entry of doc.tags) out.push(' - ' + yamlScalar(entry));
35
+ }
36
+ if (doc.verify !== undefined) {
37
+ out.push('verify:');
38
+ out.push(' command: ' + yamlScalar(doc.verify.command));
39
+ out.push(' timeout_sec: ' + String(doc.verify.timeout_sec));
40
+ }
41
+ return out.join('\n') + '\n';
42
+ }
43
+
44
+ export function renderTheoremUnifiedDiff(input: {
45
+ filePath: string;
46
+ before: string;
47
+ after: string;
48
+ }): string {
49
+ if (input.before === input.after) return '';
50
+ const patch = createTwoFilesPatch(
51
+ 'a/' + input.filePath,
52
+ 'b/' + input.filePath,
53
+ input.before,
54
+ input.after,
55
+ 'before',
56
+ 'after',
57
+ { context: 3 },
58
+ );
59
+ return patch;
60
+ }