@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
@@ -1,171 +0,0 @@
1
- import { type FsPort } from '../util/fsPort.ts';
2
- /**
3
- * Index orchestration (context-index capability, r26): rebuild writes the
4
- * pageindex tree under a create-new lock; check compares the stored spec_hash
5
- * against a fresh one. All paths are ROOT-RELATIVE through the injected IO.
6
- */
7
- import type { SpecEntry } from '../validation/validate.ts';
8
- import { buildTreeIndex, computeSpecHash, type SerializedTreeIndex } from './tree.ts';
9
-
10
- export const CONTEXT_DIR_REL = 'llmanspec/.context';
11
- export const PAGEINDEX_DIR_REL = `${CONTEXT_DIR_REL}/pageindex`;
12
- export const TREE_JSON_REL = `${PAGEINDEX_DIR_REL}/tree.json`;
13
- export const REBUILD_LOCK_REL = `${PAGEINDEX_DIR_REL}/.rebuild.lock`;
14
- const LOCK_MAX_AGE_MS = 6 * 60 * 60 * 1000;
15
-
16
- export type IndexIo = Pick<
17
- FsPort,
18
- | 'exists'
19
- | 'readText'
20
- | 'writeText'
21
- | 'remove'
22
- | 'isDirectory'
23
- | 'listDir'
24
- | 'mkdirp'
25
- | 'processAlive'
26
- | 'currentPid'
27
- | 'now'
28
- >;
29
-
30
- export interface RebuildOpts {
31
- chatModel: string;
32
- buildTimestamp?: string;
33
- }
34
-
35
- export interface RebuildResult {
36
- lines: string[];
37
- specCount: number;
38
- }
39
-
40
- /** Parse the minimal TOML-ish lock (pid/started_at/...). */
41
- export function parseLock(content: string): { pid: number; startedAt: string } | null {
42
- const pid = content.match(/^pid\s*=\s*(\d+)/mu)?.[1];
43
- const startedAt = content.match(/^started_at\s*=\s*"([^"]+)"/mu)?.[1];
44
- if (pid === undefined || startedAt === undefined) return null;
45
- return { pid: Number(pid), startedAt };
46
- }
47
-
48
- function acquireLock(io: IndexIo, lockPath: string): void {
49
- if (io.exists(lockPath)) {
50
- const parsed = parseLock(io.readText(lockPath));
51
- const stale =
52
- parsed === null ||
53
- io.now().getTime() - Date.parse(parsed.startedAt) > LOCK_MAX_AGE_MS ||
54
- !io.processAlive(parsed.pid);
55
- if (!stale) throw new Error(`rebuild already in progress (lock: ${lockPath})`);
56
- io.remove(lockPath);
57
- }
58
- io.writeText(
59
- lockPath,
60
- `pid = ${io.currentPid()}\nstarted_at = "${io.now().toISOString()}"\nchunks_total = 1\nchunks_done = 1\nprogress_pct = 100\n`,
61
- );
62
- }
63
-
64
- export function rebuildIndex(
65
- io: IndexIo,
66
- specsDir: string,
67
- entries: readonly SpecEntry[],
68
- opts: RebuildOpts,
69
- ): RebuildResult {
70
- const lockRel = REBUILD_LOCK_REL;
71
- acquireLock(io, lockRel);
72
- try {
73
- const specHash = computeSpecHash(specsDir, io);
74
- const tree = buildTreeIndex(entries, {
75
- specHash,
76
- buildTimestamp: opts.buildTimestamp ?? io.now().toISOString(),
77
- chatModel: opts.chatModel,
78
- });
79
- io.mkdirp(PAGEINDEX_DIR_REL);
80
- io.writeText(TREE_JSON_REL, `${JSON.stringify(tree, null, 2)}\n`);
81
- return {
82
- lines: [
83
- 'Scanning specs for pageindex tree (no LLM)...',
84
- `Building tree from ${entries.length} specs...`,
85
- `pageindex tree index rebuilt (${entries.length} specs, chat_model=${opts.chatModel === '' ? '<unset>' : opts.chatModel})`,
86
- ],
87
- specCount: entries.length,
88
- };
89
- } finally {
90
- io.remove(lockRel);
91
- }
92
- }
93
-
94
- export interface FreshnessResult {
95
- fresh: boolean;
96
- lines: string[];
97
- }
98
-
99
- export function checkIndexFreshness(io: IndexIo, specsDir: string): FreshnessResult {
100
- if (!io.exists(TREE_JSON_REL)) {
101
- return { fresh: false, lines: ['[pageindex] missing — run `index rebuild` first'] };
102
- }
103
- let tree: SerializedTreeIndex;
104
- try {
105
- tree = JSON.parse(io.readText(TREE_JSON_REL)) as SerializedTreeIndex;
106
- } catch {
107
- return { fresh: false, lines: ['[pageindex] stale (tree.json corrupted)'] };
108
- }
109
- const current = computeSpecHash(specsDir, io);
110
- const model = tree.chat_model === '' ? '<unset>' : tree.chat_model;
111
- if (tree.spec_hash === current) {
112
- return {
113
- fresh: true,
114
- lines: [
115
- `[pageindex] fresh (built ${tree.build_timestamp}, ${tree.docs.length} specs, chat model: ${model})`,
116
- ],
117
- };
118
- }
119
- return { fresh: false, lines: ['[pageindex] stale — specs changed since last rebuild'] };
120
- }
121
-
122
- /** Load the tree for retrieval (absent/corrupt → null). */
123
- export function loadTree(io: IndexIo): SerializedTreeIndex | null {
124
- if (!io.exists(TREE_JSON_REL)) return null;
125
- try {
126
- return JSON.parse(io.readText(TREE_JSON_REL)) as SerializedTreeIndex;
127
- } catch {
128
- return null;
129
- }
130
- }
131
-
132
- export interface AutoRefreshResult {
133
- tree: SerializedTreeIndex | null;
134
- rebuilt: boolean;
135
- error: string | null;
136
- }
137
-
138
- /**
139
- * r62: retrieval-side lazy refresh — a missing/corrupted/stale index is
140
- * rebuilt once (zero-LLM) before retrieval; a failed rebuild surfaces
141
- * `index_rebuild_failed` instead of a missing/stale quality note.
142
- */
143
- export function loadTreeWithAutoRebuild(
144
- io: IndexIo,
145
- specsDir: string,
146
- entries: readonly SpecEntry[],
147
- opts: RebuildOpts,
148
- ): AutoRefreshResult {
149
- const initial = loadTree(io);
150
- if (initial !== null && checkIndexFreshness(io, specsDir).fresh) {
151
- return { tree: initial, rebuilt: false, error: null };
152
- }
153
- try {
154
- rebuildIndex(io, specsDir, entries, opts);
155
- } catch (error) {
156
- return {
157
- tree: null,
158
- rebuilt: false,
159
- error: `auto-rebuild failed: ${(error as Error).message} — run \`llman-sdd index rebuild\``,
160
- };
161
- }
162
- const tree = loadTree(io);
163
- if (tree === null) {
164
- return {
165
- tree: null,
166
- rebuilt: true,
167
- error: 'auto-rebuild produced an unreadable tree.json — run `llman-sdd index rebuild`',
168
- };
169
- }
170
- return { tree, rebuilt: true, error: null };
171
- }
@@ -1,332 +0,0 @@
1
- /**
2
- * Context agentic retrieval (context-index capability, r27-r29):
3
- * OpenAI-compatible /chat/completions with tool calling — three local tools,
4
- * 12-round cap, then one forced no-tools turn. r28 dedups the model's
5
- * direct/related classification (direct wins). r29 pins the output contract:
6
- * quality ∈ {agentic, unavailable}, exhaustion degrades to agentic +
7
- * truncation note, failures emit summary {totalSpecs:0, error:true}.
8
- * Env contract mirrors predecessor: LLMAN_SDD_INDEX_CHAT_MODEL (required) /
9
- * LLMAN_SDD_INDEX_CHAT_API_HOST|KEY with LLMAN_SDD_INDEX_OPENAI_* fallbacks.
10
- */
11
- import type { SerializedTreeIndex } from './tree.ts';
12
-
13
- export const MAX_TOOL_ROUNDS = 12;
14
-
15
- export interface ChatConfig {
16
- model: string;
17
- host: string;
18
- apiKey: string;
19
- }
20
-
21
- const envOr = (env: Record<string, string | undefined>, key: string): string | null =>
22
- env[key]?.trim() || null;
23
-
24
- export function resolveChatConfig(env: Record<string, string | undefined>): ChatConfig | null {
25
- const model = envOr(env, 'LLMAN_SDD_INDEX_CHAT_MODEL');
26
- if (model === null) return null;
27
- const host = (
28
- envOr(env, 'LLMAN_SDD_INDEX_CHAT_API_HOST') ??
29
- envOr(env, 'LLMAN_SDD_INDEX_OPENAI_API_HOST') ??
30
- 'https://api.openai.com/v1'
31
- ).replace(/\/$/u, '');
32
- const apiKey =
33
- envOr(env, 'LLMAN_SDD_INDEX_CHAT_API_KEY') ??
34
- envOr(env, 'LLMAN_SDD_INDEX_OPENAI_API_KEY') ??
35
- '';
36
- return { model, host, apiKey };
37
- }
38
-
39
- export interface TierEntry {
40
- id: string;
41
- reason: string;
42
- }
43
-
44
- export interface ContextSuccessSummary {
45
- totalSpecs: number;
46
- tierDirect: number;
47
- tierRelated: number;
48
- unrelatedCount: number;
49
- toolCalls: number;
50
- staleWarnings: string[];
51
- readRecommended: string[];
52
- paths: string[];
53
- }
54
-
55
- /** r29: failures collapse to predecessor's print_err two-field error summary. */
56
- export interface ContextErrorSummary {
57
- totalSpecs: 0;
58
- error: true;
59
- }
60
-
61
- export type ContextSummary = ContextSuccessSummary | ContextErrorSummary;
62
-
63
- export interface ContextResult {
64
- status: {
65
- ok: boolean;
66
- /** r29: value domain is `agentic` (incl. degraded truncation) | `unavailable`. */
67
- quality: 'agentic' | 'unavailable';
68
- qualityNote: string;
69
- errorKind?: string;
70
- };
71
- direct: TierEntry[];
72
- related: TierEntry[];
73
- summary: ContextSummary;
74
- }
75
-
76
- const SYSTEM_PROMPT = `You are a spec retriever. Given a task, classify which capability specs MUST be read.
77
- 1. Call list_specs() to see all available spec documents and their purposes.
78
- 2. For specs whose purpose seems relevant to the task, call get_document_structure(spec_id) to see requirements.
79
- 3. For requirements that look relevant, call get_spec_content(spec_id, req_ids) to read the requirement text.
80
- Then output ONLY this JSON (no markdown fence):
81
- {\\"direct\\": [{\\"id\\": \\"<spec_id>\\", \\"reason\\": \\"<one sentence why this MUST be read>\\"}], \\"related\\": [{\\"id\\": \\"<spec_id>\\", \\"reason\\": \\"<one sentence>\\"}]}
82
- - "direct" = specs whose behavior contract (any requirement-semantics statement, command behavior) the task changes or depends on.
83
- - "related" = specs that provide useful context but whose contract won't change.
84
- - If the task changes behavior, the governing spec MUST be in "direct".
85
- - Decide based on the requirement text you read, not on the spec id alone.`;
86
-
87
- const TOOL_SCHEMAS = [
88
- {
89
- type: 'function',
90
- function: {
91
- name: 'list_specs',
92
- description: 'List all spec documents with their purposes.',
93
- parameters: { type: 'object', properties: {} },
94
- },
95
- },
96
- {
97
- type: 'function',
98
- function: {
99
- name: 'get_document_structure',
100
- description: 'List requirement ids and titles of one spec document.',
101
- parameters: {
102
- type: 'object',
103
- properties: { spec_id: { type: 'string', description: 'Spec id from list_specs()' } },
104
- required: ['spec_id'],
105
- },
106
- },
107
- },
108
- {
109
- type: 'function',
110
- function: {
111
- name: 'get_spec_content',
112
- description: 'Read requirement statements of one spec by req ids.',
113
- parameters: {
114
- type: 'object',
115
- properties: {
116
- spec_id: { type: 'string' },
117
- req_ids: { type: 'array', items: { type: 'string' }, description: 'e.g. ["r3"]' },
118
- },
119
- required: ['spec_id', 'req_ids'],
120
- },
121
- },
122
- },
123
- ];
124
-
125
- export interface TreeToolDeps {
126
- tree: SerializedTreeIndex;
127
- readFile: (path: string) => string;
128
- root: string;
129
- }
130
-
131
- function executeTool(deps: TreeToolDeps, name: string, argsJson: string): string {
132
- const args = JSON.parse(argsJson || '{}') as { spec_id?: string; req_ids?: string[] };
133
- const doc = deps.tree.docs.find((d) => d.spec_id === args.spec_id);
134
- switch (name) {
135
- case 'list_specs':
136
- return JSON.stringify(
137
- deps.tree.docs.map((d) => ({ spec_id: d.spec_id, purpose: d.purpose })),
138
- );
139
- case 'get_document_structure':
140
- if (!doc) return `unknown spec_id: ${args.spec_id}`;
141
- return JSON.stringify(doc.reqs.map((r) => ({ req_id: r.req_id, title: r.title })));
142
- case 'get_spec_content': {
143
- if (!doc) return `unknown spec_id: ${args.spec_id}`;
144
- const wanted = new Set(args.req_ids ?? []);
145
- const reqs = doc.reqs.filter((r) => wanted.has(r.req_id));
146
- if (reqs.length === 0) return `no matching req_ids in ${args.spec_id}`;
147
- return reqs.map((r) => `[${r.req_id}] ${r.title}\n${r.statement}`).join('\n\n');
148
- }
149
- default:
150
- return `unknown tool: ${name}`;
151
- }
152
- }
153
-
154
- function parseTiers(content: string): { direct: TierEntry[]; related: TierEntry[] } {
155
- const start = content.indexOf('{');
156
- const end = content.lastIndexOf('}');
157
- if (start === -1 || end === -1)
158
- throw new Error(`model output is not JSON: ${content.slice(0, 120)}`);
159
- const parsed = JSON.parse(content.slice(start, end + 1)) as {
160
- direct?: TierEntry[];
161
- related?: TierEntry[];
162
- };
163
- return { direct: parsed.direct ?? [], related: parsed.related ?? [] };
164
- }
165
-
166
- /**
167
- * r28: the model may classify one spec into both tiers (observed with real
168
- * models; predecessor passes duplicates through). Cross-tier duplicates keep the direct
169
- * entry, in-tier duplicates keep the first occurrence; summary counts are
170
- * computed after this runs.
171
- */
172
- function dedupTiers(tiers: { direct: TierEntry[]; related: TierEntry[] }): {
173
- direct: TierEntry[];
174
- related: TierEntry[];
175
- } {
176
- const seenDirect = new Set<string>();
177
- const direct: TierEntry[] = [];
178
- for (const entry of tiers.direct) {
179
- if (seenDirect.has(entry.id)) continue;
180
- seenDirect.add(entry.id);
181
- direct.push(entry);
182
- }
183
- const related: TierEntry[] = [];
184
- for (const entry of tiers.related) {
185
- if (seenDirect.has(entry.id)) continue;
186
- if (related.some((kept) => kept.id === entry.id)) continue;
187
- related.push(entry);
188
- }
189
- return { direct, related };
190
- }
191
-
192
- export interface RetrieveDeps extends TreeToolDeps {
193
- config: ChatConfig;
194
- task: string;
195
- paths?: string;
196
- top?: number;
197
- fetchImpl?: typeof fetch;
198
- }
199
-
200
- export async function runContextRetrieval(deps: RetrieveDeps): Promise<ContextResult> {
201
- const fetchImpl = deps.fetchImpl ?? fetch;
202
- const messages: Record<string, unknown>[] = [
203
- { role: 'system', content: SYSTEM_PROMPT },
204
- {
205
- role: 'user',
206
- content: `Task: ${deps.task}${deps.paths ? `\nPaths: ${deps.paths}` : ''}`,
207
- },
208
- ];
209
-
210
- let tiers: { direct: TierEntry[]; related: TierEntry[] } | null = null;
211
- let toolCalls = 0;
212
- try {
213
- for (let round = 0; round <= MAX_TOOL_ROUNDS && tiers === null; round += 1) {
214
- const forceFinal = round === MAX_TOOL_ROUNDS;
215
- const body: Record<string, unknown> = {
216
- model: deps.config.model,
217
- messages,
218
- ...(forceFinal ? {} : { tools: TOOL_SCHEMAS, tool_choice: 'auto' }),
219
- };
220
- const resp = await fetchImpl(`${deps.config.host}/chat/completions`, {
221
- method: 'POST',
222
- headers: {
223
- 'content-type': 'application/json',
224
- authorization: `Bearer ${deps.config.apiKey}`,
225
- },
226
- body: JSON.stringify(body),
227
- });
228
- if (!resp.ok) {
229
- const text = await resp.text();
230
- return errorResult(`chat API ${resp.status}: ${text.slice(0, 200)}`, 'api_error');
231
- }
232
- const data = (await resp.json()) as {
233
- choices: {
234
- message: {
235
- content: string | null;
236
- tool_calls?: {
237
- id: string;
238
- type: string;
239
- function: { name: string; arguments: string };
240
- }[];
241
- };
242
- }[];
243
- };
244
- const message = data.choices?.[0]?.message;
245
- if (!message) throw new Error('chat API returned no message');
246
-
247
- if (message.tool_calls && message.tool_calls.length > 0) {
248
- toolCalls += message.tool_calls.length;
249
- messages.push({
250
- role: 'assistant',
251
- content: message.content ?? '',
252
- tool_calls: message.tool_calls,
253
- });
254
- for (const call of message.tool_calls) {
255
- const result = executeTool(deps, call.function.name, call.function.arguments);
256
- messages.push({ role: 'tool', tool_call_id: call.id, content: result });
257
- }
258
- continue;
259
- }
260
- tiers = parseTiers(message.content ?? '');
261
- }
262
- } catch (error) {
263
- // predecessor print_err semantics: network/transport/parse failures degrade to
264
- // unavailable + api_error, never crash the CLI without JSON output.
265
- return errorResult(`retrieval failed: ${(error as Error).message}`, 'api_error');
266
- }
267
- if (tiers === null) {
268
- // r29: loop exhaustion degrades to agentic + truncation note + empty
269
- // tiers (predecessor truncated RetrievalOutput), with the success summary shape.
270
- const noTiers: TierEntry[] = [];
271
- return {
272
- status: {
273
- ok: true,
274
- quality: 'agentic',
275
- qualityNote: `agentic loop hit the ${MAX_TOOL_ROUNDS}-round tool-call limit; result may be incomplete`,
276
- },
277
- direct: noTiers,
278
- related: [],
279
- summary: successSummary(deps.tree.docs.length, noTiers, [], toolCalls, deps.paths),
280
- };
281
- }
282
- const deduped = dedupTiers(tiers);
283
- const direct = deduped.direct.slice(0, deps.top ?? 5);
284
- const related = deduped.related.slice(0, deps.top ?? 5);
285
- return {
286
- status: { ok: true, quality: 'agentic', qualityNote: 'pageindex' },
287
- direct,
288
- related,
289
- summary: successSummary(deps.tree.docs.length, direct, related, toolCalls, deps.paths),
290
- };
291
- }
292
-
293
- function successSummary(
294
- totalSpecs: number,
295
- direct: TierEntry[],
296
- related: TierEntry[],
297
- toolCalls: number,
298
- paths?: string,
299
- ): ContextSuccessSummary {
300
- const pathList = paths
301
- ? paths
302
- .split(',')
303
- .map((p) => p.trim())
304
- .filter((p) => p !== '')
305
- : [];
306
- return {
307
- totalSpecs,
308
- tierDirect: direct.length,
309
- tierRelated: related.length,
310
- unrelatedCount: Math.max(0, totalSpecs - direct.length - related.length),
311
- toolCalls,
312
- staleWarnings: [],
313
- readRecommended: direct.map((d) => d.id),
314
- paths: pathList,
315
- };
316
- }
317
-
318
- function errorResult(qualityNote: string, errorKind: string): ContextResult {
319
- return {
320
- status: { ok: false, quality: 'unavailable', qualityNote, errorKind },
321
- direct: [],
322
- related: [],
323
- summary: { totalSpecs: 0, error: true },
324
- };
325
- }
326
-
327
- export function unavailableResult(): ContextResult {
328
- return errorResult(
329
- 'LLMAN_SDD_INDEX_CHAT_MODEL unset; set a tool-calling chat model: LLMAN_SDD_INDEX_CHAT_MODEL is required for the pageindex backend (agentic retrieval needs a chat model that supports tool/function calling)',
330
- 'api_error',
331
- );
332
- }
@@ -1,112 +0,0 @@
1
- /**
2
- * Pageindex tree (context-index capability, r26): specs IR serialized as a
3
- * tree — building is LLM-free. Serialization keys are snake_case, matching
4
- * predecessor's tree.json so retrieval IDs stay comparable.
5
- */
6
- import { createHash } from 'node:crypto';
7
-
8
- import { specIdOf } from '../spec/ir.ts';
9
- import { type FsPort } from '../util/fsPort.ts';
10
- import { discoverFeatureFiles } from '../validation/discover.ts';
11
- import type { SpecEntry } from '../validation/validate.ts';
12
-
13
- export const TREE_VERSION = 1;
14
-
15
- export interface SerializedReqNode {
16
- req_id: string;
17
- title: string;
18
- statement: string;
19
- }
20
-
21
- export interface SerializedScenarioNode {
22
- req_id: string;
23
- id: string;
24
- given: string;
25
- when: string;
26
- then: string;
27
- }
28
-
29
- export interface SerializedDocNode {
30
- spec_id: string;
31
- purpose: string;
32
- reqs: SerializedReqNode[];
33
- scenarios: SerializedScenarioNode[];
34
- }
35
-
36
- export interface SerializedTreeIndex {
37
- version: number;
38
- spec_hash: string;
39
- build_timestamp: string;
40
- chat_model: string;
41
- docs: SerializedDocNode[];
42
- }
43
-
44
- function joinSteps(
45
- steps: readonly { kind: string; text: string }[],
46
- kind: 'given' | 'when' | 'then',
47
- ): string {
48
- return steps
49
- .filter((s) => s.kind === kind)
50
- .map((s) => s.text)
51
- .join('\n');
52
- }
53
-
54
- export function buildDocs(entries: readonly SpecEntry[]): SerializedDocNode[] {
55
- return entries
56
- .map((entry) => {
57
- const cap = specIdOf(entry);
58
- const reqs = entry.doc.rules.map((r) => ({
59
- req_id: r.reqId,
60
- title: r.title,
61
- statement: r.description
62
- .split('\n')
63
- .map((l) => l.replace(/^-\s+/u, ''))
64
- .join('\n'),
65
- }));
66
- const scenOf = (
67
- s: { name: string; steps: readonly { kind: string; text: string }[] },
68
- reqId: string,
69
- ): SerializedScenarioNode => ({
70
- req_id: reqId,
71
- id: s.name,
72
- given: joinSteps(s.steps, 'given'),
73
- when: joinSteps(s.steps, 'when'),
74
- // `then` is the tree.json contract key, not a thenable
75
- // oxlint-disable-next-line unicorn/no-thenable
76
- then: joinSteps(s.steps, 'then'),
77
- });
78
- const scenarios = [
79
- ...entry.doc.rules.flatMap((r) => r.scenarios.map((s) => scenOf(s, r.reqId))),
80
- ...entry.doc.orphans.map((s) => scenOf(s, '')),
81
- ];
82
- return { spec_id: cap, purpose: entry.doc.header.purpose ?? '', reqs, scenarios };
83
- })
84
- .toSorted((a, b) => a.spec_id.localeCompare(b.spec_id));
85
- }
86
-
87
- export function buildTreeIndex(
88
- entries: readonly SpecEntry[],
89
- meta: { specHash: string; buildTimestamp: string; chatModel: string },
90
- ): SerializedTreeIndex {
91
- return {
92
- version: TREE_VERSION,
93
- spec_hash: meta.specHash,
94
- build_timestamp: meta.buildTimestamp,
95
- chat_model: meta.chatModel,
96
- docs: buildDocs(entries),
97
- };
98
- }
99
-
100
- export type HashIo = Pick<FsPort, 'exists' | 'isDirectory' | 'listDir' | 'readText'>;
101
-
102
- /** sha256 over all .feature files, sorted by path (r26 freshness anchor). */
103
- export function computeSpecHash(specsDir: string, io: HashIo): string {
104
- const hash = createHash('sha256');
105
- // T24: shared discovery — the hashed path set/order is exactly the parser's,
106
- // so editing specs cannot desynchronize freshness from parse coverage.
107
- for (const full of discoverFeatureFiles(specsDir.replace(/\\/g, '/').replace(/\/$/u, ''), io)) {
108
- hash.update(full);
109
- hash.update(io.readText(full));
110
- }
111
- return hash.digest('hex');
112
- }
@@ -1,9 +0,0 @@
1
- # LLMAN 规范驱动开发
2
-
3
- 本项目使用 llman SDD。阅读 `llmanspec/config.yaml` 了解 SDD 命令行为配置,以及 `llmanspec/AGENTS.md` 获取项目附加规则。
4
-
5
- ## SDD 流水线
6
-
7
- 使用 `/llman-sdd-explore` 开始,然后按照 pipeline:`/llman-sdd-propose` → `/llman-sdd-apply` → `/llman-sdd-verify` → `/llman-sdd-archive`。
8
-
9
- 保留此托管块,便于 `llman-sdd init --update` 刷新。
@@ -1,69 +0,0 @@
1
- ---
2
- name: "llman-sdd-apply-cycle"
3
- description: "单 change 一轮到底:实施→测试→校验→verify→归档提交。仅手动触发,agent 不得自动调用。"
4
- metadata:
5
- version: "{{ llman_version }}"
6
- disable-model-invocation: true
7
- ---
8
-
9
- # LLMAN SDD Apply Cycle
10
-
11
- 单 change 一轮到底(手动)。须已绑定分支且 specs-landed 门通过(`specsLanded ∨ needsSpecsChange=false`);`readyToImplement=true`(完成信号)收拢循环。
12
-
13
- **仅手动触发**:`/skill:llman-sdd-apply-cycle <change-id>`
14
-
15
- ## 工作流
16
-
17
- ### 0) 门禁 + 状态
18
- ```bash
19
- llman-sdd show <change-id> --output json --type change
20
- ```
21
- > 阶段判定用 `stage` / `readyToImplement` 字段;完整判定表见 llman-sdd-apply。
22
-
23
- - 须在绑定的非默认分支上。
24
- - specs-landed 门未过 → STOP(先提交 specs 或 `needs_specs_change: false`)。已绿但 `readyToImplement=false` → 正常:tasks 待完成,继续实施;**仅当 `readyToImplement=true` 才 finalize**。
25
- - 进度以 `tasks.md` checkbox 为准(或 `llman-sdd list` 任务计数);实现时仍须读 `tasks.md`、proposal/design 与绑定分支上的 `llmanspec/specs/**`(唯一事实来源)。
26
-
27
- ### 1) 循环:实施 → 测试
28
- 对每个未完成 task:
29
- 1. 按 task + specs 实现(最小改动)
30
- 2. task 文本写明验证命令时运行之
31
- 3. 失败修复重试(自修复预算同 `llman-sdd-apply`:上限 8 轮)
32
- 4. 勾选 `tasks.md` 为 `[x]`
33
-
34
- ### 2) 校验
35
- ```bash
36
- llman-sdd validate <change-id> --strict
37
- ```
38
- 失败修复重试(上限 8 轮)。
39
-
40
- ### 3) Verify(推荐)
41
- 优先跑 `llman-sdd-verify`(或等效双轴自检)。有 CRITICAL → STOP,勿归档。
42
-
43
- ### 4) 归档 + 提交
44
- ```bash
45
- llman-sdd change finalize <change-id>
46
- ```
47
- 工作区可脏;自动合并(默认 squash)+ 改名 + **自动提交** `archive(sdd): <change-id>` 单进程完成。`--no-commit` 跳过自动提交(手动/CI 历史)——此时自行 `git add -A && git commit -m "archive(sdd): <change-id>"`。普通 `change archive` 保留为 fallback。
48
-
49
- ### 5) 可选清理
50
- ```bash
51
- git branch -D <feature-branch> # squash 后分支不再是 main 祖先,-d 会被拒
52
- ```
53
- push / PR 仅当用户明确要求。
54
-
55
- ## 硬约束
56
- - **不得问“是否继续”**——除非 blocker,一路到底。
57
- - **不得切换**其他 change,直到本 change 归档并提交。
58
- - **不得**写 `changes/<id>/specs/`;**不得默认 push/PR**。
59
-
60
- {{ unit("skills/ethics-governance") }}
61
-
62
- ### Ethics Governance 覆写
63
- 本技能含 finalize 合并等不可逆动作,以下键覆写共享单元:
64
-
65
- - `ethics.risk_level`: medium。
66
- - `ethics.required_evidence`: 另须 `readyToImplement=true` 与 tasks 全勾。
67
- - `ethics.escalation_policy`: 归档前暂停并请用户确认。
68
-
69
- {{ unit("skills/cli-footer") }}