@llman-sdd/core 0.10.0 → 0.11.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.
- package/package.json +7 -6
- package/src/archive/freeze.ts +73 -11
- package/src/archive/frozenCard.ts +62 -5
- package/src/archive/ignoreChain.ts +167 -0
- package/src/archive/sevenzip.ts +17 -8
- package/src/change/lifecycle.ts +55 -59
- package/src/config/schema.ts +0 -13
- package/src/config/surface.ts +2 -12
- package/src/context/sddState.ts +23 -18
- package/src/index.ts +15 -36
- package/src/init/defaultConfig.ts +2 -13
- package/src/init/init.ts +50 -19
- package/src/init/skillCheck.ts +60 -0
- package/src/project/migrations.ts +81 -9
- package/src/spec/authoring.ts +5 -1
- package/src/templates/skills.ts +15 -12
- package/templates/zh-Hans/skills/llman-sdd-apply-cycle.md +5 -5
- package/templates/zh-Hans/skills/llman-sdd-apply.md +8 -9
- package/templates/zh-Hans/skills/llman-sdd-arch-review.md +1 -1
- package/templates/zh-Hans/skills/llman-sdd-archive.md +13 -14
- package/templates/zh-Hans/skills/llman-sdd-continue.md +3 -3
- package/templates/zh-Hans/skills/llman-sdd-draft.md +3 -3
- package/templates/zh-Hans/skills/llman-sdd-explore.md +2 -3
- package/templates/zh-Hans/skills/llman-sdd-ff.md +3 -2
- package/templates/zh-Hans/skills/llman-sdd-graph.md +1 -1
- package/templates/zh-Hans/skills/llman-sdd-propose.md +8 -9
- package/templates/zh-Hans/skills/llman-sdd-quick.md +4 -5
- package/templates/zh-Hans/skills/llman-sdd-research.md +1 -1
- package/templates/zh-Hans/skills/llman-sdd-specs-compact.md +4 -3
- package/templates/zh-Hans/skills/llman-sdd-validate.md +2 -2
- package/templates/zh-Hans/skills/llman-sdd-verify.md +3 -3
- package/templates/zh-Hans/skills/llman-sdd-wayfinder.md +2 -2
- package/templates/zh-Hans/units/skills/git-native-flow.md +8 -8
- package/templates/zh-Hans/units/skills/stage-guard.md +3 -3
- package/templates/zh-Hans/units/skills/structured-protocol.md +1 -1
- package/templates/zh-Hans/units/skills/validation-hints.md +3 -3
- package/src/context/indexStore.ts +0 -171
- package/src/context/retrieve.ts +0 -332
- package/src/context/tree.ts +0 -112
- package/templates/zh-Hans/units/skills/index-fallback.md +0 -1
|
@@ -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
|
-
}
|
package/src/context/retrieve.ts
DELETED
|
@@ -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
|
-
}
|
package/src/context/tree.ts
DELETED
|
@@ -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 +0,0 @@
|
|
|
1
|
-
context 不可用(含 `quality: "unavailable"`)→ 先 `llman-sdd index check`:stale/缺失则 `llman-sdd index rebuild`(默认 pageindex,免模型)后重试;fresh 仍不可用(`LLMAN_SDD_INDEX_CHAT_MODEL` 未设)→ 改用 `llman-sdd list --specs` + 直读 `.feature`——勿循环 rebuild。
|