@llman-sdd/core 0.11.0 → 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.
- package/package.json +6 -3
- package/src/archive/freeze.ts +0 -13
- package/src/archive/frozenCard.ts +1 -10
- package/src/archive/ignoreChain.ts +2 -6
- package/src/archive/sevenzip.ts +0 -1
- package/src/change/closeOutHarness.ts +17 -0
- package/src/change/collect.ts +0 -5
- package/src/change/frontmatter.ts +15 -7
- package/src/change/id.ts +0 -2
- package/src/change/lifecycle.ts +1 -38
- package/src/config/changeId.ts +0 -2
- package/src/config/load.ts +0 -4
- package/src/config/schema.ts +24 -0
- package/src/git/spawnGit.ts +0 -3
- package/src/hints/jitHints.ts +82 -0
- package/src/index.ts +455 -3
- package/src/init/defaultConfig.ts +2 -0
- package/src/init/init.ts +61 -20
- package/src/init/uncommentConfig.ts +909 -0
- package/src/locale.ts +0 -2
- package/src/project/migrateNotes.ts +0 -9
- package/src/project/migrations.ts +70 -0
- package/src/report/graph/analysis.ts +0 -4
- package/src/report/graph/nodes.ts +0 -6
- package/src/report/show.ts +7 -23
- package/src/report/specHelpers.ts +10 -14
- package/src/review/review.ts +0 -12
- package/src/spec/assignSpecIds.ts +0 -3
- package/src/spec/authoring.ts +14 -26
- package/src/spec/ir.ts +14 -5
- package/src/spec/keywords.ts +0 -2
- package/src/spec/machineKey.ts +49 -0
- package/src/spec/migrateNative.ts +4 -18
- package/src/spec/parser.ts +10 -19
- package/src/spec/reqRef.ts +135 -0
- package/src/studio/changeScope.ts +50 -0
- package/src/studio/changeScopeDiff.ts +195 -0
- package/src/studio/contracts.ts +493 -0
- package/src/studio/decisionTree.ts +206 -0
- package/src/studio/deeplink.ts +116 -0
- package/src/studio/demos.ts +167 -0
- package/src/studio/diff.ts +494 -0
- package/src/studio/drift.ts +738 -0
- package/src/studio/extract.ts +360 -0
- package/src/studio/featureSync.ts +592 -0
- package/src/studio/forest.ts +570 -0
- package/src/studio/index.ts +32 -0
- package/src/studio/model.ts +254 -0
- package/src/studio/revisions.ts +476 -0
- package/src/studio/search.ts +337 -0
- package/src/studio/store.ts +811 -0
- package/src/studio/sync.ts +912 -0
- package/src/studio/textfold.ts +72 -0
- package/src/studio/time.ts +107 -0
- package/src/studio/validate.ts +363 -0
- package/src/templates/embedded.ts +4 -6
- package/src/templates/engine.ts +1 -1
- package/src/templates/skills.ts +71 -49
- package/src/theorems/guard.ts +52 -0
- package/src/theorems/index.ts +56 -0
- package/src/theorems/migrate.ts +133 -0
- package/src/theorems/schema.ts +67 -0
- package/src/theorems/scope.ts +68 -0
- package/src/theorems/serialize.ts +60 -0
- package/src/theorems/transactionMachine.ts +247 -0
- package/src/theorems/validate.ts +141 -0
- package/src/util/nextNumber.ts +0 -2
- package/src/validation/changeCheck.ts +0 -24
- package/src/validation/flowAndNesting.ts +434 -0
- package/src/validation/harness.ts +108 -65
- package/src/validation/validate.ts +26 -12
- package/src/validation/xstateTransitions.ts +483 -184
- package/templates/zh-Hans/llmanspec-agents-stub.md +17 -2
- package/templates/zh-Hans/skills/llman-sdd-autopilot/SKILL.md +34 -0
- package/templates/zh-Hans/skills/llman-sdd-change/SKILL.md +44 -0
- package/templates/zh-Hans/skills/llman-sdd-change/playbooks/archive.md +15 -0
- package/templates/zh-Hans/skills/llman-sdd-change/playbooks/draft.md +9 -0
- package/templates/zh-Hans/skills/llman-sdd-review/SKILL.md +71 -0
- package/templates/zh-Hans/skills/llman-sdd-specs/SKILL.md +70 -0
- package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/compact.md +12 -0
- package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/doctor.md +26 -0
- package/templates/zh-Hans/skills/llman-sdd-specs/references/graph-dsl.md +33 -0
- package/templates/zh-Hans/skills/llman-sdd-studio/SKILL.md +33 -0
- package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/collab.md +20 -0
- package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/drift.md +52 -0
- package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/onboard.md +33 -0
- package/templates/zh-Hans/units/skills/cli-footer.md +2 -2
- package/templates/zh-Hans/agents-root-stub.md +0 -9
- package/templates/zh-Hans/skills/llman-sdd-apply-cycle.md +0 -69
- package/templates/zh-Hans/skills/llman-sdd-apply.md +0 -116
- package/templates/zh-Hans/skills/llman-sdd-arch-review.md +0 -58
- package/templates/zh-Hans/skills/llman-sdd-archive.md +0 -78
- package/templates/zh-Hans/skills/llman-sdd-continue.md +0 -34
- package/templates/zh-Hans/skills/llman-sdd-draft.md +0 -53
- package/templates/zh-Hans/skills/llman-sdd-explore.md +0 -63
- package/templates/zh-Hans/skills/llman-sdd-ff.md +0 -34
- package/templates/zh-Hans/skills/llman-sdd-graph.md +0 -56
- package/templates/zh-Hans/skills/llman-sdd-propose.md +0 -106
- package/templates/zh-Hans/skills/llman-sdd-quick.md +0 -40
- package/templates/zh-Hans/skills/llman-sdd-research.md +0 -35
- package/templates/zh-Hans/skills/llman-sdd-specs-compact.md +0 -42
- package/templates/zh-Hans/skills/llman-sdd-validate.md +0 -28
- package/templates/zh-Hans/skills/llman-sdd-verify.md +0 -77
- package/templates/zh-Hans/skills/llman-sdd-wayfinder.md +0 -83
- package/templates/zh-Hans/units/skills/ethics-governance.md +0 -6
- package/templates/zh-Hans/units/skills/git-native-flow.md +0 -56
- package/templates/zh-Hans/units/skills/human-readable-summary.md +0 -9
- package/templates/zh-Hans/units/skills/stage-guard.md +0 -17
- package/templates/zh-Hans/units/skills/structured-protocol.md +0 -19
- package/templates/zh-Hans/units/skills/validation-hints.md +0 -20
- package/templates/zh-Hans/units/skills/version-drift.md +0 -3
- package/templates/zh-Hans/units/spec/feature-contract.md +0 -8
|
@@ -0,0 +1,738 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 0-Token Cross-Language Runtime Trace Reconciliation & `@llmanspec:` Anchor Slice Engine (studio-core r149).
|
|
3
|
+
* 100% offline deterministic pure domain module — zero filesystem I/O, zero network, zero LLM calls.
|
|
4
|
+
*/
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
|
|
7
|
+
import { specIdOf } from '../spec/ir.ts';
|
|
8
|
+
import { parseReqRef } from '../spec/reqRef.ts';
|
|
9
|
+
import { buildReqRegistry } from '../spec/reqRegistry.ts';
|
|
10
|
+
import type { SpecEntry } from '../validation/validate.ts';
|
|
11
|
+
import { extractStudioMachines } from './extract.ts';
|
|
12
|
+
import type { RevisionOp, StudioMachineIR, StudioStateDoc } from './model.ts';
|
|
13
|
+
import { proposeRevision } from './revisions.ts';
|
|
14
|
+
|
|
15
|
+
export const runtimeTraceEventSchema = z.object({
|
|
16
|
+
machine: z.string().trim().min(1, 'machine must be a non-empty string'),
|
|
17
|
+
from: z.string().trim().min(1, 'from must be a non-empty string'),
|
|
18
|
+
event: z.string().trim().min(1, 'event must be a non-empty string'),
|
|
19
|
+
condition: z.string().optional(),
|
|
20
|
+
to: z.string().trim().min(1, 'to must be a non-empty string'),
|
|
21
|
+
ts: z.string().optional(),
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
export type RuntimeTraceEvent = z.infer<typeof runtimeTraceEventSchema>;
|
|
25
|
+
|
|
26
|
+
export interface ParsedRuntimeTraceEvent extends RuntimeTraceEvent {
|
|
27
|
+
line: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface RuntimeTraceParseError {
|
|
31
|
+
line: number;
|
|
32
|
+
raw: string;
|
|
33
|
+
message: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ParseRuntimeTraceResult {
|
|
37
|
+
events: ParsedRuntimeTraceEvent[];
|
|
38
|
+
errors: RuntimeTraceParseError[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface ShadowTransitionFinding {
|
|
42
|
+
machineKey: string;
|
|
43
|
+
from: string;
|
|
44
|
+
event: string;
|
|
45
|
+
condition?: string;
|
|
46
|
+
to: string;
|
|
47
|
+
count: number;
|
|
48
|
+
sampleLines: number[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface UncoveredTransitionFinding {
|
|
52
|
+
machineKey: string;
|
|
53
|
+
transitionUid: string;
|
|
54
|
+
from: string;
|
|
55
|
+
event: string;
|
|
56
|
+
condition?: string;
|
|
57
|
+
to: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface UnknownMachineFinding {
|
|
61
|
+
machine: string;
|
|
62
|
+
count: number;
|
|
63
|
+
sampleLines: number[];
|
|
64
|
+
reason: 'not_found' | 'ambiguous';
|
|
65
|
+
candidates?: string[];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface RuntimeTraceReconcileResult {
|
|
69
|
+
totalEvents: number;
|
|
70
|
+
matchedEvents: number;
|
|
71
|
+
shadowTransitions: ShadowTransitionFinding[];
|
|
72
|
+
uncoveredTransitions: UncoveredTransitionFinding[];
|
|
73
|
+
unknownMachines: UnknownMachineFinding[];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface DriftRevisionProposalDraft {
|
|
77
|
+
machineKey: string;
|
|
78
|
+
rationale: string;
|
|
79
|
+
ops: RevisionOp[];
|
|
80
|
+
shadowCount: number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface LlmanspecAnchorMatch {
|
|
84
|
+
file: string;
|
|
85
|
+
line: number;
|
|
86
|
+
/** `req` pins a rule; `scenario` pins a graph, plain scenario or decision table. */
|
|
87
|
+
kind: 'req' | 'scenario';
|
|
88
|
+
target: string;
|
|
89
|
+
rawLine: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface UnifiedDiffHunk {
|
|
93
|
+
oldStart: number;
|
|
94
|
+
oldLines: number;
|
|
95
|
+
newStart: number;
|
|
96
|
+
newLines: number;
|
|
97
|
+
header: string;
|
|
98
|
+
lines: string[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface ParsedDiffFile {
|
|
102
|
+
file: string;
|
|
103
|
+
hunks: UnifiedDiffHunk[];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface DriftDiffFileInput {
|
|
107
|
+
file: string;
|
|
108
|
+
content: string;
|
|
109
|
+
hunks: readonly UnifiedDiffHunk[];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface DriftImpactedSpec {
|
|
113
|
+
kind: 'rule' | 'machine' | 'scenario';
|
|
114
|
+
capability: string;
|
|
115
|
+
reqId: string | null;
|
|
116
|
+
machineKey?: string;
|
|
117
|
+
title: string;
|
|
118
|
+
sourceFile: string;
|
|
119
|
+
excerpt: string;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface DriftMatchedFileSlice {
|
|
123
|
+
file: string;
|
|
124
|
+
anchors: LlmanspecAnchorMatch[];
|
|
125
|
+
hunks: UnifiedDiffHunk[];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface DriftSlicePacket {
|
|
129
|
+
sinceRef?: string;
|
|
130
|
+
changedFileCount: number;
|
|
131
|
+
matchedFiles: DriftMatchedFileSlice[];
|
|
132
|
+
impactedSpecs: DriftImpactedSpec[];
|
|
133
|
+
unanchoredFiles: string[];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function normGuard(g?: string): string {
|
|
137
|
+
return (g ?? '').trim();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function transitionSignature(
|
|
141
|
+
from: string,
|
|
142
|
+
event: string,
|
|
143
|
+
condition: string | undefined,
|
|
144
|
+
to: string,
|
|
145
|
+
): string {
|
|
146
|
+
return `${from.trim()}\u0000${event.trim()}\u0000${normGuard(condition)}\u0000${to.trim()}`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Parse a cross-language JSONL runtime trace string with strict per-line Zod validation.
|
|
151
|
+
* Malformed JSON or missing required fields are reported with exact 1-based line numbers.
|
|
152
|
+
*/
|
|
153
|
+
export function parseRuntimeTraceJsonl(rawText: string): ParseRuntimeTraceResult {
|
|
154
|
+
const events: ParsedRuntimeTraceEvent[] = [];
|
|
155
|
+
const errors: RuntimeTraceParseError[] = [];
|
|
156
|
+
const lines = rawText.split(/\r?\n/u);
|
|
157
|
+
|
|
158
|
+
for (let idx = 0; idx < lines.length; idx += 1) {
|
|
159
|
+
const raw = lines[idx] ?? '';
|
|
160
|
+
const trimmed = raw.trim();
|
|
161
|
+
if (trimmed === '') continue;
|
|
162
|
+
const line = idx + 1;
|
|
163
|
+
|
|
164
|
+
let parsed: unknown;
|
|
165
|
+
try {
|
|
166
|
+
parsed = JSON.parse(trimmed);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
errors.push({
|
|
169
|
+
line,
|
|
170
|
+
raw,
|
|
171
|
+
message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`,
|
|
172
|
+
});
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const checked = runtimeTraceEventSchema.safeParse(parsed);
|
|
177
|
+
if (!checked.success) {
|
|
178
|
+
const issue = checked.error.issues[0];
|
|
179
|
+
const field = issue?.path.join('.') || '<root>';
|
|
180
|
+
errors.push({
|
|
181
|
+
line,
|
|
182
|
+
raw,
|
|
183
|
+
message: `schema error at ${field}: ${issue?.message ?? 'invalid trace event'}`,
|
|
184
|
+
});
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const g = normGuard(checked.data.condition);
|
|
189
|
+
events.push({
|
|
190
|
+
line,
|
|
191
|
+
machine: checked.data.machine,
|
|
192
|
+
from: checked.data.from,
|
|
193
|
+
event: checked.data.event,
|
|
194
|
+
...(g !== '' ? { condition: g } : {}),
|
|
195
|
+
to: checked.data.to,
|
|
196
|
+
...(checked.data.ts !== undefined ? { ts: checked.data.ts } : {}),
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return { events, errors };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function resolveTraceMachine(
|
|
204
|
+
identifier: string,
|
|
205
|
+
machines: readonly StudioMachineIR[],
|
|
206
|
+
): { machine: StudioMachineIR } | { reason: 'not_found' | 'ambiguous'; candidates?: string[] } {
|
|
207
|
+
const target = identifier.trim();
|
|
208
|
+
const exact = machines.find((m) => m.machineKey === target);
|
|
209
|
+
if (exact) return { machine: exact };
|
|
210
|
+
|
|
211
|
+
const shortMatches = machines.filter((m) => {
|
|
212
|
+
const capReq = m.reqId ? `${m.capability}/${m.reqId}` : null;
|
|
213
|
+
return (
|
|
214
|
+
m.capability === target ||
|
|
215
|
+
m.scenarioName === target ||
|
|
216
|
+
m.ruleTitle === target ||
|
|
217
|
+
(m.reqId !== null && m.reqId === target) ||
|
|
218
|
+
(capReq !== null && capReq === target)
|
|
219
|
+
);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
if (shortMatches.length === 1) {
|
|
223
|
+
return { machine: shortMatches[0]! };
|
|
224
|
+
}
|
|
225
|
+
if (shortMatches.length > 1) {
|
|
226
|
+
return {
|
|
227
|
+
reason: 'ambiguous',
|
|
228
|
+
candidates: shortMatches.map((m) => m.machineKey),
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
return { reason: 'not_found' };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* 0-Token deterministic reconciliation between declared StudioMachineIR[] and observed trace events.
|
|
236
|
+
*/
|
|
237
|
+
export function reconcileRuntimeTrace(
|
|
238
|
+
machines: readonly StudioMachineIR[],
|
|
239
|
+
events: readonly ParsedRuntimeTraceEvent[],
|
|
240
|
+
): RuntimeTraceReconcileResult {
|
|
241
|
+
const declaredByMachine = new Map<string, Map<string, string>>();
|
|
242
|
+
const stateNameByMachine = new Map<string, Map<string, string>>();
|
|
243
|
+
|
|
244
|
+
for (const m of machines) {
|
|
245
|
+
const names = new Map<string, string>();
|
|
246
|
+
for (const st of m.states) names.set(st.uid, st.name);
|
|
247
|
+
stateNameByMachine.set(m.machineKey, names);
|
|
248
|
+
|
|
249
|
+
const sigs = new Map<string, string>();
|
|
250
|
+
for (const tr of m.transitions) {
|
|
251
|
+
const fromName = names.get(tr.fromUid) ?? tr.fromUid;
|
|
252
|
+
const toName = names.get(tr.toUid) ?? tr.toUid;
|
|
253
|
+
sigs.set(transitionSignature(fromName, tr.event, tr.condition, toName), tr.uid);
|
|
254
|
+
}
|
|
255
|
+
declaredByMachine.set(m.machineKey, sigs);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const coveredUids = new Set<string>();
|
|
259
|
+
const shadowMap = new Map<string, ShadowTransitionFinding>();
|
|
260
|
+
const unknownMap = new Map<string, UnknownMachineFinding>();
|
|
261
|
+
let matchedEvents = 0;
|
|
262
|
+
|
|
263
|
+
for (const ev of events) {
|
|
264
|
+
const resolved = resolveTraceMachine(ev.machine, machines);
|
|
265
|
+
if (!('machine' in resolved)) {
|
|
266
|
+
const existing = unknownMap.get(ev.machine);
|
|
267
|
+
if (existing) {
|
|
268
|
+
existing.count += 1;
|
|
269
|
+
if (existing.sampleLines.length < 5) existing.sampleLines.push(ev.line);
|
|
270
|
+
} else {
|
|
271
|
+
unknownMap.set(ev.machine, {
|
|
272
|
+
machine: ev.machine,
|
|
273
|
+
count: 1,
|
|
274
|
+
sampleLines: [ev.line],
|
|
275
|
+
reason: resolved.reason,
|
|
276
|
+
...(resolved.candidates ? { candidates: resolved.candidates } : {}),
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const machineKey = resolved.machine.machineKey;
|
|
283
|
+
const sigMap = declaredByMachine.get(machineKey)!;
|
|
284
|
+
const sig = transitionSignature(ev.from, ev.event, ev.condition, ev.to);
|
|
285
|
+
const matchedUid = sigMap.get(sig);
|
|
286
|
+
|
|
287
|
+
if (matchedUid !== undefined) {
|
|
288
|
+
matchedEvents += 1;
|
|
289
|
+
coveredUids.add(`${machineKey}\u0000${matchedUid}`);
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const shadowKey = `${machineKey}\u0000${sig}`;
|
|
294
|
+
const existingShadow = shadowMap.get(shadowKey);
|
|
295
|
+
if (existingShadow) {
|
|
296
|
+
existingShadow.count += 1;
|
|
297
|
+
if (existingShadow.sampleLines.length < 5) existingShadow.sampleLines.push(ev.line);
|
|
298
|
+
} else {
|
|
299
|
+
const g = normGuard(ev.condition);
|
|
300
|
+
shadowMap.set(shadowKey, {
|
|
301
|
+
machineKey,
|
|
302
|
+
from: ev.from,
|
|
303
|
+
event: ev.event,
|
|
304
|
+
...(g !== '' ? { condition: g } : {}),
|
|
305
|
+
to: ev.to,
|
|
306
|
+
count: 1,
|
|
307
|
+
sampleLines: [ev.line],
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const uncoveredTransitions: UncoveredTransitionFinding[] = [];
|
|
313
|
+
for (const m of machines) {
|
|
314
|
+
const names = stateNameByMachine.get(m.machineKey)!;
|
|
315
|
+
for (const tr of m.transitions) {
|
|
316
|
+
if (!coveredUids.has(`${m.machineKey}\u0000${tr.uid}`)) {
|
|
317
|
+
uncoveredTransitions.push({
|
|
318
|
+
machineKey: m.machineKey,
|
|
319
|
+
transitionUid: tr.uid,
|
|
320
|
+
from: names.get(tr.fromUid) ?? tr.fromUid,
|
|
321
|
+
event: tr.event,
|
|
322
|
+
...(tr.condition !== undefined && tr.condition.trim() !== ''
|
|
323
|
+
? { condition: tr.condition }
|
|
324
|
+
: {}),
|
|
325
|
+
to: names.get(tr.toUid) ?? tr.toUid,
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
return {
|
|
332
|
+
totalEvents: events.length,
|
|
333
|
+
matchedEvents,
|
|
334
|
+
shadowTransitions: Array.from(shadowMap.values()),
|
|
335
|
+
uncoveredTransitions,
|
|
336
|
+
unknownMachines: Array.from(unknownMap.values()),
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Convert detected shadowTransitions into structured non-destructive RevisionOp[] drafts
|
|
342
|
+
* suitable for `proposeRevision(..., { source: 'drift-trace' })`.
|
|
343
|
+
*/
|
|
344
|
+
export function buildDriftRevisionProposals(
|
|
345
|
+
machinesByKey: Readonly<Record<string, StudioMachineIR | null | undefined>>,
|
|
346
|
+
shadowTransitions: readonly ShadowTransitionFinding[],
|
|
347
|
+
): DriftRevisionProposalDraft[] {
|
|
348
|
+
const byMachine = new Map<string, ShadowTransitionFinding[]>();
|
|
349
|
+
for (const sh of shadowTransitions) {
|
|
350
|
+
const list = byMachine.get(sh.machineKey) ?? [];
|
|
351
|
+
list.push(sh);
|
|
352
|
+
byMachine.set(sh.machineKey, list);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const drafts: DriftRevisionProposalDraft[] = [];
|
|
356
|
+
for (const [machineKey, list] of byMachine.entries()) {
|
|
357
|
+
const current = machinesByKey[machineKey];
|
|
358
|
+
const existingNames = new Set((current?.states ?? []).map((s) => s.name));
|
|
359
|
+
const addedNames = new Set<string>();
|
|
360
|
+
const ops: RevisionOp[] = [];
|
|
361
|
+
const summaryParts: string[] = [];
|
|
362
|
+
|
|
363
|
+
for (const sh of list) {
|
|
364
|
+
if (!existingNames.has(sh.from) && !addedNames.has(sh.from)) {
|
|
365
|
+
addedNames.add(sh.from);
|
|
366
|
+
ops.push({ op: 'add_state', name: sh.from });
|
|
367
|
+
}
|
|
368
|
+
if (!existingNames.has(sh.to) && !addedNames.has(sh.to)) {
|
|
369
|
+
addedNames.add(sh.to);
|
|
370
|
+
ops.push({ op: 'add_state', name: sh.to });
|
|
371
|
+
}
|
|
372
|
+
ops.push({
|
|
373
|
+
op: 'add_transition',
|
|
374
|
+
from: sh.from,
|
|
375
|
+
event: sh.event,
|
|
376
|
+
...(sh.condition !== undefined && sh.condition !== '' ? { condition: sh.condition } : {}),
|
|
377
|
+
to: sh.to,
|
|
378
|
+
});
|
|
379
|
+
const conditionSuffix = sh.condition ? ` [${sh.condition}]` : '';
|
|
380
|
+
const lineStr = sh.sampleLines.map((n) => `L${String(n)}`).join(',');
|
|
381
|
+
summaryParts.push(
|
|
382
|
+
`${sh.from} --[${sh.event}${conditionSuffix}]--> ${sh.to} (x${String(sh.count)}, ${lineStr})`,
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
drafts.push({
|
|
387
|
+
machineKey,
|
|
388
|
+
shadowCount: list.length,
|
|
389
|
+
ops,
|
|
390
|
+
rationale: `逻辑漂移校准:代码运行轨迹观测到 ${String(list.length)} 条未登记状态转移:${summaryParts.join(';')}`,
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return drafts;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Append non-destructive `source: 'drift-trace'` pending revision proposals to a StudioStateDoc.
|
|
399
|
+
* Deduplicates identical pending drift-trace proposals so repeated runs stay idempotent.
|
|
400
|
+
*/
|
|
401
|
+
export function applyDriftProposalsToStateDoc(
|
|
402
|
+
doc: StudioStateDoc,
|
|
403
|
+
shadowTransitions: readonly ShadowTransitionFinding[],
|
|
404
|
+
createdAt: string,
|
|
405
|
+
): { doc: StudioStateDoc; addedProposalIds: string[] } {
|
|
406
|
+
const machinesByKey: Record<string, StudioMachineIR | null> = {};
|
|
407
|
+
for (const [k, d] of Object.entries(doc.machines)) {
|
|
408
|
+
machinesByKey[k] = d.current ?? d.baseline;
|
|
409
|
+
}
|
|
410
|
+
const proposalDrafts = buildDriftRevisionProposals(machinesByKey, shadowTransitions);
|
|
411
|
+
let nextDoc = doc;
|
|
412
|
+
const addedProposalIds: string[] = [];
|
|
413
|
+
|
|
414
|
+
for (const pd of proposalDrafts) {
|
|
415
|
+
if (!nextDoc.machines[pd.machineKey]) continue;
|
|
416
|
+
const opsKey = JSON.stringify(pd.ops);
|
|
417
|
+
const duplicate = nextDoc.revisions.find(
|
|
418
|
+
(r) =>
|
|
419
|
+
r.status === 'pending' &&
|
|
420
|
+
r.source === 'drift-trace' &&
|
|
421
|
+
r.machineKey === pd.machineKey &&
|
|
422
|
+
JSON.stringify(r.ops) === opsKey,
|
|
423
|
+
);
|
|
424
|
+
if (duplicate) continue;
|
|
425
|
+
|
|
426
|
+
nextDoc = proposeRevision(nextDoc, {
|
|
427
|
+
machineKey: pd.machineKey,
|
|
428
|
+
rationale: pd.rationale,
|
|
429
|
+
ops: pd.ops,
|
|
430
|
+
createdAt,
|
|
431
|
+
source: 'drift-trace',
|
|
432
|
+
});
|
|
433
|
+
const added = nextDoc.revisions.at(-1);
|
|
434
|
+
if (added) addedProposalIds.push(added.id);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
return { doc: nextDoc, addedProposalIds };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
const COMMENT_PREFIX_RE = /(?:\/\/|\/\*|^\s*\*|#|--|<!--)/u;
|
|
441
|
+
const ANCHOR_PREFIX = '@llmanspec:req:';
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Read one anchor target token after `@llmanspec:req:`. A quoted scenario name
|
|
445
|
+
* may contain spaces; a bare token stops at whitespace or comment terminators
|
|
446
|
+
* (`*\/`, `-->`) and must not swallow trailing punctuation (`;`, `,`, `)`, `]`, `*`).
|
|
447
|
+
*/
|
|
448
|
+
function readAnchorToken(rest: string): string {
|
|
449
|
+
let out = '';
|
|
450
|
+
let i = 0;
|
|
451
|
+
while (i < rest.length) {
|
|
452
|
+
const ch = rest[i]!;
|
|
453
|
+
if (ch === '"' && out.endsWith('#')) {
|
|
454
|
+
const close = rest.indexOf('"', i + 1);
|
|
455
|
+
if (close === -1) {
|
|
456
|
+
out += rest.slice(i);
|
|
457
|
+
break;
|
|
458
|
+
}
|
|
459
|
+
out += rest.slice(i, close + 1);
|
|
460
|
+
i = close + 1;
|
|
461
|
+
const after = rest.slice(i);
|
|
462
|
+
if (after === '' || /^(?:\s|\*\/|-->|[,;)\]])/u.test(after)) break;
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
if (/\s/u.test(ch)) break;
|
|
466
|
+
if (rest.startsWith('*/', i) || rest.startsWith('-->', i)) break;
|
|
467
|
+
out += ch;
|
|
468
|
+
i += 1;
|
|
469
|
+
}
|
|
470
|
+
if (!out.includes('"')) out = out.replace(/[*;,)\]]+$/u, '');
|
|
471
|
+
return out;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Scan cross-language comment anchors `@llmanspec:req:rN`, `@llmanspec:req:rN#<场景名>`
|
|
476
|
+
* and `@llmanspec:req:rN#"带空格 场景"` across TS/JS, Rust, Python, Shell, SQL and HTML
|
|
477
|
+
* comment styles. The whole target token is captured and then validated strictly by
|
|
478
|
+
* `parseReqRef(..., 'anchor')`: `r12-sub`, `r12abc`, `r1#`, `r1# foo` and double-prefixed
|
|
479
|
+
* `@llmanspec:req:@req:r1` yield zero anchors instead of falling back to `r12` / `r1`.
|
|
480
|
+
* Strictly ignores bare `llman` and any other namespace.
|
|
481
|
+
*/
|
|
482
|
+
export function scanLlmanspecAnchors(filePath: string, content: string): LlmanspecAnchorMatch[] {
|
|
483
|
+
const matches: LlmanspecAnchorMatch[] = [];
|
|
484
|
+
const lines = content.split(/\r?\n/u);
|
|
485
|
+
|
|
486
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
487
|
+
const rawLine = lines[i] ?? '';
|
|
488
|
+
const commentAt = COMMENT_PREFIX_RE.exec(rawLine);
|
|
489
|
+
if (commentAt === null) continue;
|
|
490
|
+
const commentSlice = rawLine.slice(commentAt.index);
|
|
491
|
+
let cursor = 0;
|
|
492
|
+
for (;;) {
|
|
493
|
+
const at = commentSlice.indexOf(ANCHOR_PREFIX, cursor);
|
|
494
|
+
if (at === -1) break;
|
|
495
|
+
cursor = at + ANCHOR_PREFIX.length;
|
|
496
|
+
const target = readAnchorToken(commentSlice.slice(cursor));
|
|
497
|
+
if (target === '') continue;
|
|
498
|
+
const ref = parseReqRef(`${ANCHOR_PREFIX}${target}`, 'anchor');
|
|
499
|
+
if (ref === null || ref.reqId === '') continue;
|
|
500
|
+
matches.push({
|
|
501
|
+
file: filePath,
|
|
502
|
+
line: i + 1,
|
|
503
|
+
kind: ref.scenarioName === null ? 'req' : 'scenario',
|
|
504
|
+
target,
|
|
505
|
+
rawLine,
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
return matches;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const HUNK_HEADER_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/u;
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Parse unified `git diff` text into structured per-file hunks (0-Token pure parser).
|
|
517
|
+
*/
|
|
518
|
+
export function parseUnifiedDiffHunks(diffText: string): ParsedDiffFile[] {
|
|
519
|
+
const files: ParsedDiffFile[] = [];
|
|
520
|
+
let currentFile: ParsedDiffFile | null = null;
|
|
521
|
+
let currentHunk: UnifiedDiffHunk | null = null;
|
|
522
|
+
|
|
523
|
+
for (const line of diffText.split(/\r?\n/u)) {
|
|
524
|
+
if (line.startsWith('diff --git ')) {
|
|
525
|
+
currentHunk = null;
|
|
526
|
+
const m = /^diff --git a\/(.+?) b\/(.+)$/u.exec(line);
|
|
527
|
+
if (m?.[2]) {
|
|
528
|
+
currentFile = { file: m[2], hunks: [] };
|
|
529
|
+
files.push(currentFile);
|
|
530
|
+
} else {
|
|
531
|
+
currentFile = null;
|
|
532
|
+
}
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
if (line.startsWith('+++ b/')) {
|
|
536
|
+
const nextName = line.slice('+++ b/'.length).trim();
|
|
537
|
+
if (currentFile) {
|
|
538
|
+
currentFile.file = nextName;
|
|
539
|
+
} else {
|
|
540
|
+
currentFile = { file: nextName, hunks: [] };
|
|
541
|
+
files.push(currentFile);
|
|
542
|
+
}
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
if (line.startsWith('@@ ')) {
|
|
546
|
+
const hm = HUNK_HEADER_RE.exec(line);
|
|
547
|
+
if (hm && currentFile) {
|
|
548
|
+
currentHunk = {
|
|
549
|
+
oldStart: Number(hm[1]),
|
|
550
|
+
oldLines: hm[2] !== undefined ? Number(hm[2]) : 1,
|
|
551
|
+
newStart: Number(hm[3]),
|
|
552
|
+
newLines: hm[4] !== undefined ? Number(hm[4]) : 1,
|
|
553
|
+
header: line,
|
|
554
|
+
lines: [line],
|
|
555
|
+
};
|
|
556
|
+
currentFile.hunks.push(currentHunk);
|
|
557
|
+
}
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
if (
|
|
561
|
+
currentHunk &&
|
|
562
|
+
(line.startsWith('+') ||
|
|
563
|
+
line.startsWith('-') ||
|
|
564
|
+
line.startsWith(' ') ||
|
|
565
|
+
line.startsWith('\\'))
|
|
566
|
+
) {
|
|
567
|
+
currentHunk.lines.push(line);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
return files;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function hunkTouchesAnchor(hunk: UnifiedDiffHunk, anchorLine: number, proximity: number): boolean {
|
|
575
|
+
const start = Math.max(1, hunk.newStart - proximity);
|
|
576
|
+
const end = hunk.newStart + Math.max(hunk.newLines, 1) - 1 + proximity;
|
|
577
|
+
return anchorLine >= start && anchorLine <= end;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** Resolve a non-graph scenario (plain steps or decision table) pinned by a scenario anchor. */
|
|
581
|
+
function findPlainScenario(
|
|
582
|
+
entries: readonly SpecEntry[],
|
|
583
|
+
reqId: string,
|
|
584
|
+
scenarioName: string,
|
|
585
|
+
): { capability: string; ruleTitle: string; sourceFile: string; excerpt: string } | null {
|
|
586
|
+
for (const entry of entries) {
|
|
587
|
+
for (const rule of entry.doc.rules) {
|
|
588
|
+
if (rule.reqId !== reqId) continue;
|
|
589
|
+
const scenario = rule.scenarios.find((sc) => sc.name === scenarioName);
|
|
590
|
+
if (!scenario) continue;
|
|
591
|
+
const tables = (scenario.examples ?? []).map((block) =>
|
|
592
|
+
[block.headers.join(' | '), ...block.rows.map((row) => row.join(' | '))].join('\n'),
|
|
593
|
+
);
|
|
594
|
+
const excerpt = [scenario.statement, ...tables].filter((part) => part !== '').join('\n');
|
|
595
|
+
return {
|
|
596
|
+
capability: specIdOf(entry),
|
|
597
|
+
ruleTitle: rule.title,
|
|
598
|
+
sourceFile: entry.fileName,
|
|
599
|
+
excerpt: excerpt === '' ? scenario.name : excerpt,
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return null;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Build a minimal, high-signal 0-Token `DriftSlicePacket` by intersecting changed diff hunks
|
|
608
|
+
* with `@llmanspec:` comment anchors and resolving ONLY the impacted rules/machines from specs.
|
|
609
|
+
*/
|
|
610
|
+
export function buildDriftSlicePacket(input: {
|
|
611
|
+
diffFiles: readonly DriftDiffFileInput[];
|
|
612
|
+
specEntries: readonly SpecEntry[];
|
|
613
|
+
sinceRef?: string;
|
|
614
|
+
proximityLines?: number;
|
|
615
|
+
}): DriftSlicePacket {
|
|
616
|
+
const proximity = input.proximityLines ?? 25;
|
|
617
|
+
const registry = buildReqRegistry(input.specEntries);
|
|
618
|
+
const extractedMachines = extractStudioMachines(input.specEntries);
|
|
619
|
+
const machines = extractedMachines.map((m) => m.machine);
|
|
620
|
+
|
|
621
|
+
const matchedFiles: DriftMatchedFileSlice[] = [];
|
|
622
|
+
const unanchoredFiles: string[] = [];
|
|
623
|
+
const impactedByKey = new Map<string, DriftImpactedSpec>();
|
|
624
|
+
|
|
625
|
+
for (const df of input.diffFiles) {
|
|
626
|
+
const fileAnchors = scanLlmanspecAnchors(df.file, df.content);
|
|
627
|
+
if (fileAnchors.length === 0) {
|
|
628
|
+
unanchoredFiles.push(df.file);
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const hitAnchors: LlmanspecAnchorMatch[] = [];
|
|
633
|
+
const hitHunks = new Set<UnifiedDiffHunk>();
|
|
634
|
+
|
|
635
|
+
for (const anchor of fileAnchors) {
|
|
636
|
+
let matchedAnyHunk = false;
|
|
637
|
+
for (const hunk of df.hunks) {
|
|
638
|
+
if (hunkTouchesAnchor(hunk, anchor.line, proximity)) {
|
|
639
|
+
matchedAnyHunk = true;
|
|
640
|
+
hitHunks.add(hunk);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
if (matchedAnyHunk) {
|
|
644
|
+
hitAnchors.push(anchor);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
if (hitAnchors.length === 0) {
|
|
649
|
+
unanchoredFiles.push(df.file);
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
matchedFiles.push({
|
|
654
|
+
file: df.file,
|
|
655
|
+
anchors: hitAnchors,
|
|
656
|
+
hunks: Array.from(hitHunks),
|
|
657
|
+
});
|
|
658
|
+
|
|
659
|
+
for (const anchor of hitAnchors) {
|
|
660
|
+
const ref = parseReqRef(anchor.target);
|
|
661
|
+
if (ref === null || ref.reqId === '') continue;
|
|
662
|
+
|
|
663
|
+
if (ref.scenarioName === null) {
|
|
664
|
+
const occs = registry.byId.get(ref.reqId) ?? [];
|
|
665
|
+
for (const occ of occs) {
|
|
666
|
+
const entry = input.specEntries.find((e) => e.fileName === occ.fileName);
|
|
667
|
+
if (!entry) continue;
|
|
668
|
+
const capId = specIdOf(entry);
|
|
669
|
+
const rule = entry.doc.rules.find((r) => r.reqId === ref.reqId);
|
|
670
|
+
if (!rule) continue;
|
|
671
|
+
const key = `rule:${capId}:${ref.reqId}`;
|
|
672
|
+
if (!impactedByKey.has(key)) {
|
|
673
|
+
impactedByKey.set(key, {
|
|
674
|
+
kind: 'rule',
|
|
675
|
+
capability: capId,
|
|
676
|
+
reqId: ref.reqId,
|
|
677
|
+
title: rule.title,
|
|
678
|
+
sourceFile: entry.fileName,
|
|
679
|
+
excerpt: `${rule.title}\n${rule.description}`.trim(),
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
continue;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const graphHits = machines.filter(
|
|
687
|
+
(m) => (m.reqId ?? '') === ref.reqId && m.scenarioName === ref.scenarioName,
|
|
688
|
+
);
|
|
689
|
+
const graph = graphHits.length === 1 ? graphHits[0] : undefined;
|
|
690
|
+
if (graph !== undefined) {
|
|
691
|
+
const draft = extractedMachines.find((x) => x.machine.machineKey === graph.machineKey);
|
|
692
|
+
const impactGroupKey = `machine:${graph.machineKey}`;
|
|
693
|
+
if (!impactedByKey.has(impactGroupKey)) {
|
|
694
|
+
const stateNames = new Map(graph.states.map((s) => [s.uid, s.name]));
|
|
695
|
+
const edgeSummary = graph.transitions
|
|
696
|
+
.map((t) => {
|
|
697
|
+
const fn = stateNames.get(t.fromUid) ?? t.fromUid;
|
|
698
|
+
const tn = stateNames.get(t.toUid) ?? t.toUid;
|
|
699
|
+
const gd = t.condition ? ` [${t.condition}]` : '';
|
|
700
|
+
return `${fn} --[${t.event}${gd}]--> ${tn}`;
|
|
701
|
+
})
|
|
702
|
+
.join('\n');
|
|
703
|
+
impactedByKey.set(impactGroupKey, {
|
|
704
|
+
kind: 'machine',
|
|
705
|
+
capability: graph.capability,
|
|
706
|
+
reqId: graph.reqId,
|
|
707
|
+
machineKey: graph.machineKey,
|
|
708
|
+
title: `${graph.ruleTitle} / ${graph.scenarioName}`,
|
|
709
|
+
sourceFile: draft?.draft.sourceFile ?? '',
|
|
710
|
+
excerpt: edgeSummary,
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
continue;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
const plain = findPlainScenario(input.specEntries, ref.reqId, ref.scenarioName);
|
|
717
|
+
if (plain === null) continue;
|
|
718
|
+
const key = `scenario:${plain.capability}:${ref.reqId}#${ref.scenarioName}`;
|
|
719
|
+
if (impactedByKey.has(key)) continue;
|
|
720
|
+
impactedByKey.set(key, {
|
|
721
|
+
kind: 'scenario',
|
|
722
|
+
capability: plain.capability,
|
|
723
|
+
reqId: ref.reqId,
|
|
724
|
+
title: `${plain.ruleTitle} / ${ref.scenarioName}`,
|
|
725
|
+
sourceFile: plain.sourceFile,
|
|
726
|
+
excerpt: plain.excerpt,
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
return {
|
|
732
|
+
...(input.sinceRef !== undefined ? { sinceRef: input.sinceRef } : {}),
|
|
733
|
+
changedFileCount: input.diffFiles.length,
|
|
734
|
+
matchedFiles,
|
|
735
|
+
impactedSpecs: Array.from(impactedByKey.values()),
|
|
736
|
+
unanchoredFiles,
|
|
737
|
+
};
|
|
738
|
+
}
|