@stalfh233/omc-cli 0.6.44 → 0.6.49

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 (43) hide show
  1. package/dist/capability-overview.js +113 -0
  2. package/dist/cli-stdout.js +3 -0
  3. package/dist/cli.js +255 -60
  4. package/dist/command-transport.js +5 -1
  5. package/dist/discovery.js +193 -75
  6. package/dist/goal-plan.js +1244 -0
  7. package/dist/goal-routes.js +78 -3
  8. package/dist/graph.js +264 -38
  9. package/dist/lanes/app.js +4 -0
  10. package/dist/lanes/apply-changes.js +1 -0
  11. package/dist/lanes/b2-registration.js +24 -0
  12. package/dist/lanes/businessrule.js +5 -0
  13. package/dist/lanes/custom-page.js +8 -0
  14. package/dist/lanes/datarule.js +4 -0
  15. package/dist/lanes/dictionary.js +13 -0
  16. package/dist/lanes/environment.js +2 -0
  17. package/dist/lanes/field.js +14 -0
  18. package/dist/lanes/folder.js +4 -0
  19. package/dist/lanes/form.js +5 -0
  20. package/dist/lanes/list-view.js +5 -0
  21. package/dist/lanes/meta.js +5 -0
  22. package/dist/lanes/model.js +9 -0
  23. package/dist/lanes/online-js.js +2 -0
  24. package/dist/lanes/organization.js +20 -0
  25. package/dist/lanes/perm.js +5 -5
  26. package/dist/lanes/programming.js +6 -0
  27. package/dist/lanes/report.js +9 -0
  28. package/dist/lanes/rule-lifecycle.js +6 -0
  29. package/dist/lanes/rulelog.js +1 -0
  30. package/dist/lanes/runtime-data.js +6 -0
  31. package/dist/lanes/workflow.js +18 -0
  32. package/dist/mcp-graph.js +180 -41
  33. package/dist/package-tool.js +1 -0
  34. package/dist/search-index.js +137 -0
  35. package/dist/tool-search.js +647 -0
  36. package/dist/tools.js +1 -0
  37. package/dist/write.js +2 -1
  38. package/docs/omc-introduction.md +5 -7
  39. package/package.json +6 -5
  40. package/skills/omc-business-configuration.md +2 -1
  41. package/skills/omc-capabilities.md +3 -2
  42. package/skills/omc-start-here.md +21 -7
  43. package/skills/omc-tool-selection.md +7 -15
@@ -0,0 +1,1244 @@
1
+ import { createHash } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { goalRoute } from "./goal-routes.js";
4
+ import { capabilityRouteIndex } from "./capability-overview.js";
5
+ import { paramFillRuleFor } from "./search-index.js";
6
+ import { scoreTools } from "./tool-search.js";
7
+ const AUTHORED_KEYS = new Set([
8
+ "nodeGraph", "template", "source", "methodConfig", "serviceConfig",
9
+ "methodInputParameters", "methodOutputParameters", "draftViewJson", "draftAttributesJson",
10
+ "records", "fields", "subFields",
11
+ ]);
12
+ /**
13
+ * Read asks (M6): rank read tools with the M1 search face, resolve the model the
14
+ * ask names, and hand back ONE runnable read step + what is still needed.
15
+ *
16
+ * The distinction that matters: `needs-input` here is about the QUERY SEMANTICS
17
+ * (which rows), not about which tool or which model — those two are answered.
18
+ */
19
+ async function planReadAsk(registry, goal, environment, options, base, match, capability, lane) {
20
+ const hits = scoreTools(registry, goal).filter((hit) => registry.find((tool) => tool.name === hit.name)?.kind === "read");
21
+ const primary = hits[0]?.name;
22
+ const tool = primary === undefined ? undefined : registry.find((entry) => entry.name === primary);
23
+ const ambiguities = [];
24
+ const missing = {};
25
+ const warnings = [];
26
+ const probes = [];
27
+ const steps = [];
28
+ const blockers = [];
29
+ let probeFailure;
30
+ if (tool === undefined) {
31
+ return {
32
+ ...base,
33
+ ready: false,
34
+ level: 2,
35
+ ...(match !== undefined ? { match } : {}),
36
+ blockers: [{ type: "needs-input", reason: "读路径没能定位到一个具体读工具", hint: "换更具体的业务说法,或 omc commands --filter <词>" }],
37
+ planHash: planHash({ goal, environment, level: 2 }),
38
+ next: ["omc commands --filter <关键词>", "omc capabilities"],
39
+ };
40
+ }
41
+ // Fill what the read tool needs, from the ask + one probe.
42
+ const args = {};
43
+ if (environment !== null)
44
+ args.environment = environment;
45
+ const shape = tool.inputSchema;
46
+ const requiredKeys = Object.entries(shape)
47
+ .filter(([, node]) => typeof node?.isOptional !== "function" || node.isOptional() === false)
48
+ .map(([key]) => key)
49
+ .filter((key) => key !== "environment");
50
+ for (const key of requiredKeys) {
51
+ if (key === "schemaCode") {
52
+ const hint = hintFromGoal(goal, {});
53
+ if (options.offline === true || options.probe === undefined) {
54
+ probes.push(`omc call model.list --env ${environment ?? "<env>"} --args '{}'`);
55
+ missing[key] = { reason: "需 model.list 解析目标模型", source: "model.list → models[].schemaCode" };
56
+ continue;
57
+ }
58
+ const probed = await probeReadOnly(options.probe, "model.list");
59
+ if (probed.state === "uncertain") {
60
+ probeFailure = `model.list 探测失败:${probed.reason ?? "未返回可判定结果"}`;
61
+ continue;
62
+ }
63
+ const rows = probed.rows ?? [];
64
+ const resolved = resolveModelCandidate(hint, rows, goal);
65
+ if (resolved.state === "needs-input") {
66
+ ambiguities.push({ param: key, candidates: resolved.candidates ?? [], question: "目标模型有多个候选,选中哪一个?" });
67
+ continue;
68
+ }
69
+ if (resolved.state === "blocked" || resolved.code === undefined) {
70
+ // Zero rows is NOT "pick one from this list" — it is a scope answer, and
71
+ // `model.list` already explains it (the scan is clipped to one app). Asking
72
+ // the user to choose from an empty list is the kind of non-answer that
73
+ // costs a round.
74
+ if (rows.length === 0) {
75
+ blockers.push({
76
+ type: "blocked",
77
+ param: key,
78
+ reason: "model.list 在当前应用里没有返回任何模型(扫描被应用边界裁剪,不代表租户全集)",
79
+ next: environment === null
80
+ ? "omc call app.list --env <env> --args '{}'"
81
+ : `omc call app.list --env ${environment} --args '{}'`,
82
+ });
83
+ continue;
84
+ }
85
+ ambiguities.push({ param: key, candidates: rows.slice(0, 10), question: "目标句里没有能对上平台的模型,选哪个?" });
86
+ continue;
87
+ }
88
+ args[key] = resolved.code;
89
+ if (resolved.warning !== undefined)
90
+ warnings.push(`${key}: ${resolved.warning}`);
91
+ continue;
92
+ }
93
+ missing[key] = {
94
+ reason: "查询条件/范围需明确(本计划只读,不替你猜语义)",
95
+ source: `omc describe ${tool.name} --param ${key}`,
96
+ };
97
+ }
98
+ // Query SEMANTICS: `data.list {schemaCode}` is schema-valid and would run, but it
99
+ // returns the whole table — not what 「金额大于一万」 asked for. `ready=true` must
100
+ // not overclaim, so a stated condition with no filter set is a missing input.
101
+ const statesCondition = /大于|小于|等于|超过|低于|介于|不等|包含|开头|结尾|为空|不为空|等于|是\s|不是|>|<|>=|<=|=/.test(goal);
102
+ const hasFilterValue = ["filter", "filters", "filterGroup", "query", "rawCondition"].some((key) => args[key] !== undefined);
103
+ if (statesCondition && !hasFilterValue) {
104
+ const target = ["filter", "filters", "filterGroup"].find((key) => key in tool.inputSchema);
105
+ if (target !== undefined) {
106
+ missing[target] = {
107
+ reason: "问句里有筛选条件,但 filter DSL 需要把「金额大于一万」翻译成 {op,field,value};本计划不替你猜字段 code 与取值语义",
108
+ source: `omc describe ${tool.name} --example ${tool.executionMetadata?.recipes[0]?.id ?? "<recipe>"}`,
109
+ };
110
+ }
111
+ }
112
+ const uncertain = probeFailure !== undefined;
113
+ const pending = new Set(Object.keys(missing));
114
+ const validated = validateStep(tool, args, pending);
115
+ const step = {
116
+ id: "s1",
117
+ tool: tool.name,
118
+ kind: "read",
119
+ purpose: `读:${summarizeForPlan(tool.description)}`,
120
+ args,
121
+ dependsOn: [],
122
+ validated,
123
+ dryRun: { supported: false, notes: "只读步骤没有 dry-run 语义(它本身不写)" },
124
+ };
125
+ if (!uncertain)
126
+ steps.push(step);
127
+ const ready = !uncertain && Object.keys(missing).length === 0 && ambiguities.length === 0 && validated.ok;
128
+ return {
129
+ status: "ok",
130
+ goal,
131
+ environment,
132
+ ready,
133
+ level: uncertain ? 3 : ready ? 1 : 2,
134
+ ...(match !== undefined ? { match } : {}),
135
+ ...(capability !== undefined ? { capability } : {}),
136
+ ...(lane !== undefined ? { lane } : {}),
137
+ steps,
138
+ missing,
139
+ unverified: {},
140
+ warnings,
141
+ ambiguities,
142
+ blockers: uncertain ? [{ type: "uncertain", reason: probeFailure }] : blockers,
143
+ probes,
144
+ planHash: planHash({ goal, environment, tool: tool.name, args, ready }),
145
+ next: ready
146
+ ? [`omc call ${tool.name} --env ${environment ?? "<env>"} --args '<上面的 args>'`]
147
+ : [
148
+ ...(probes.length > 0 ? probes : []),
149
+ ...(tool.executionMetadata?.recipes[0] !== undefined ? [`omc describe ${tool.name} --example ${tool.executionMetadata.recipes[0].id}`] : [`omc describe ${tool.name}`]),
150
+ ],
151
+ note: `读路径:${tool.name}(按业务说法排序命中)`,
152
+ };
153
+ }
154
+ /** First sentence of a description, bounded — a purpose line, not prose. */
155
+ function summarizeForPlan(description) {
156
+ const collapsed = description.replace(/\s+/g, " ").trim();
157
+ const stop = collapsed.search(/[。;;!!??]|\.(?=\s|$)/);
158
+ const sentence = stop >= 0 ? collapsed.slice(0, stop) : collapsed;
159
+ return sentence.length > 60 ? `${sentence.slice(0, 59)}…` : sentence;
160
+ }
161
+ /** Which read tool answers each registry-resolvable placeholder (§search-index KEY_RULES). */
162
+ const RESOLVERS = Object.freeze({
163
+ schemaCode: "model.list",
164
+ propertyCode: "field.list",
165
+ workflowCode: "workflow.get_published",
166
+ serviceCode: "service.list",
167
+ sheetCode: "form.get",
168
+ applicationCode: "discover_environment",
169
+ });
170
+ function canonical(value) {
171
+ const sort = (input) => {
172
+ if (Array.isArray(input))
173
+ return input.map(sort);
174
+ if (input !== null && typeof input === "object") {
175
+ return Object.fromEntries(Object.entries(input).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, sort(v)]));
176
+ }
177
+ return input;
178
+ };
179
+ return JSON.stringify(sort(value));
180
+ }
181
+ /** Every string leaf that still looks like a template placeholder. */
182
+ function collectPlaceholders(value, path = "") {
183
+ const out = [];
184
+ const walk = (node, at) => {
185
+ if (typeof node === "string") {
186
+ if (/^<[^<>]+>$/.test(node) || node.includes("omc_recipe_"))
187
+ out.push({ path: at, key: at.split(".")[0] ?? at });
188
+ return;
189
+ }
190
+ if (Array.isArray(node)) {
191
+ node.forEach((entry, index) => walk(entry, `${at}[${index}]`));
192
+ return;
193
+ }
194
+ if (node !== null && typeof node === "object") {
195
+ for (const [key, entry] of Object.entries(node))
196
+ walk(entry, at === "" ? key : `${at}.${key}`);
197
+ }
198
+ };
199
+ walk(value, path);
200
+ return out;
201
+ }
202
+ /**
203
+ * Type-appropriate sample for a placeholder, used ONLY to run the local schema
204
+ * gate: the plan must prove the shape is otherwise valid, without pretending the
205
+ * placeholder is a real value. Never emitted as a step argument.
206
+ */
207
+ function sampleFor(node) {
208
+ if (node === null || node === undefined)
209
+ return "<value>";
210
+ const shape = node;
211
+ const typeName = shape._def?.typeName;
212
+ if (typeName === "ZodString")
213
+ return "<value>";
214
+ if (typeName === "ZodNumber")
215
+ return 0;
216
+ if (typeName === "ZodBoolean")
217
+ return false;
218
+ if (typeName === "ZodEnum")
219
+ return shape.options?.[0] ?? "<value>";
220
+ if (typeName === "ZodArray")
221
+ return [];
222
+ if (typeName === "ZodObject") {
223
+ // Zod exposes the shape BOTH as `shape` (property) and `_def.shape()` (fn);
224
+ // calling the property blindly throws "shape.shape is not a function".
225
+ const fields = typeof shape.shape === "function"
226
+ ? shape.shape()
227
+ : (shape.shape ?? {});
228
+ return Object.fromEntries(Object.entries(fields).map(([key, child]) => [key, sampleFor(child)]));
229
+ }
230
+ return "<value>";
231
+ }
232
+ /**
233
+ * Local schema gate (M3-6). The Zod schema is authoritative, but a placeholder is
234
+ * by definition not a legal value; validate the SHAPE against Zod itself with a
235
+ * typed sample substituted for the pending slots, so an impossible step (wrong
236
+ * enum, wrong shape) is caught here instead of costing a wire round.
237
+ */
238
+ function validateStep(tool, args, pending) {
239
+ const issues = [];
240
+ const schemaKeys = new Set(Object.keys(tool.inputSchema));
241
+ for (const key of Object.keys(args))
242
+ if (!schemaKeys.has(key))
243
+ issues.push(`未知参数 ${key}(omc describe ${tool.name} 看合法参数)`);
244
+ const shape = tool.inputSchema;
245
+ for (const [key, node] of Object.entries(shape)) {
246
+ if (typeof node?.isOptional === "function" && node.isOptional())
247
+ continue;
248
+ if (!(key in args))
249
+ issues.push(`缺必填 ${key}`);
250
+ }
251
+ if (issues.length > 0)
252
+ return { ok: false, issues };
253
+ const filled = {};
254
+ for (const [key, entry] of Object.entries(args))
255
+ filled[key] = pending.has(key) ? sampleFor(shape[key]) : entry;
256
+ const parsed = z.object(tool.inputSchema).safeParse(filled);
257
+ if (!parsed.success) {
258
+ for (const issue of parsed.error.issues.slice(0, 5)) {
259
+ issues.push(`${issue.path.join(".") || "(root)"}: ${issue.message}`);
260
+ }
261
+ }
262
+ return { ok: issues.length === 0, issues };
263
+ }
264
+ /**
265
+ * M4-2: a placeholder that names an earlier step's readback
266
+ * (`<data.save.performed.bizObjectId>`) becomes a cross-step reference.
267
+ *
268
+ * The reference is a plain string (`$s1.performed.bizObjectId`) so it survives
269
+ * JSON, is visible in the plan, and cannot be mistaken for a legal id — the
270
+ * caller substitutes it after that step succeeds.
271
+ */
272
+ function crossStepProducer(value, byTool) {
273
+ if (typeof value !== "string")
274
+ return undefined;
275
+ // The authored placeholder already names the producer: `<data.save.performed.bizObjectId>`.
276
+ const match = /^<([A-Za-z][\w.]*)\.performed\.([A-Za-z][\w]*)[^>]*>$/.exec(value);
277
+ if (match === null)
278
+ return undefined;
279
+ const producer = byTool.get(match[1]);
280
+ if (producer === undefined)
281
+ return undefined;
282
+ return { stepId: producer.stepId, reference: `$${producer.stepId}.performed.${match[2]}` };
283
+ }
284
+ /** Replace `$<stepid>.performed.<var>` leaves after that step reports its readback. */
285
+ export function resolveStepReferences(args, values) {
286
+ const walk = (node) => {
287
+ if (typeof node === "string") {
288
+ const match = /^\$(s\d+)\.performed\.([A-Za-z][\w]*)$/.exec(node);
289
+ return match === null ? node : (values[`$${match[1]}.performed.${match[2]}`] ?? node);
290
+ }
291
+ if (Array.isArray(node))
292
+ return node.map(walk);
293
+ if (node !== null && typeof node === "object") {
294
+ return Object.fromEntries(Object.entries(node).map(([key, entry]) => [key, walk(entry)]));
295
+ }
296
+ return node;
297
+ };
298
+ return walk(args);
299
+ }
300
+ /**
301
+ * M4-3: which read tool proves a write landed.
302
+ *
303
+ * Explicit where the relationship is not mechanical (`rule.save` → `rule.get`,
304
+ * `data.save` → `data.load`, `programming.publish` → `programming.get`), and a
305
+ * mechanical `X.create → X.get|X.list` / `X.publish → X.get_published` fallback
306
+ * otherwise. A missing read tool yields NO verify block — an invented readback
307
+ * command is worse than none, because it looks like evidence.
308
+ */
309
+ const READBACK_TOOL = Object.freeze({
310
+ "rule.save": "rule.get",
311
+ "data.save": "data.load",
312
+ "data.update": "data.load",
313
+ "data.submit": "data.load",
314
+ "data.delete": "data.list",
315
+ "field.create": "field.list",
316
+ "field.update": "field.list",
317
+ "field.delete": "field.list",
318
+ "field.publish": "field.list",
319
+ "form.publish": "form.get",
320
+ "form.draft": "form.get",
321
+ "workflow.publish": "workflow.get_published",
322
+ "workflow.create": "workflow.get_draft",
323
+ "workflow.update": "workflow.get_draft",
324
+ "listview.configure": "listview.get",
325
+ "listview.create": "listview.list",
326
+ "onlinejs.compose": "onlinejs.get",
327
+ "datarule.create": "datarule.list",
328
+ "datarule.update": "datarule.list",
329
+ "datarule.delete": "datarule.list",
330
+ "dictionary.save": "dictionary.get",
331
+ "dictionary.class.save": "dictionary.classes",
332
+ "service.register": "service.get",
333
+ "service.update": "service.get",
334
+ "method.create": "method.get",
335
+ "method.update": "method.get",
336
+ "programming.publish": "programming.get",
337
+ "programming.save": "programming.get",
338
+ "perm.assign": "perm.groups",
339
+ "perm.auth": "perm.user",
340
+ "perm.group": "perm.groups",
341
+ "rule.enable": "rule.get",
342
+ "rule.disable": "rule.get",
343
+ "model.create": "model.list",
344
+ "model.update": "model.list",
345
+ "app.create": "app.list",
346
+ "app.update": "app.list",
347
+ "folder.create": "folder.tree",
348
+ "folder.update": "folder.tree",
349
+ });
350
+ /** Mechanical fallback for a write tool with no explicit readback mapping. */
351
+ function mechanicalReadback(toolName) {
352
+ const [family, action] = toolName.split(".");
353
+ if (family === undefined || action === undefined)
354
+ return undefined;
355
+ if (action === "publish")
356
+ return `${family}.get_published`;
357
+ if (["create", "update", "save", "delete", "configure", "compose", "enable", "disable", "run"].includes(action))
358
+ return `${family}.get`;
359
+ return undefined;
360
+ }
361
+ /**
362
+ * M4-3: build the verify block for one step. The read command reuses only the
363
+ * identifiers the read tool actually requires (from ITS inputSchema), so the
364
+ * predicate is runnable rather than aspirational.
365
+ */
366
+ function verifyFor(registry, step, expects) {
367
+ if (expects === undefined || Object.keys(expects).length === 0)
368
+ return undefined;
369
+ const readerName = READBACK_TOOL[step.tool] ?? mechanicalReadback(step.tool);
370
+ if (readerName === undefined)
371
+ return undefined;
372
+ const reader = registry.find((entry) => entry.name === readerName);
373
+ if (reader === undefined)
374
+ return undefined;
375
+ const readerArgs = {};
376
+ for (const key of Object.keys(reader.inputSchema)) {
377
+ if (key in step.args && step.args[key] !== undefined)
378
+ readerArgs[key] = step.args[key];
379
+ }
380
+ const required = Object.entries(reader.inputSchema)
381
+ .filter(([, node]) => typeof node?.isOptional !== "function" || node.isOptional() === false)
382
+ .map(([key]) => key)
383
+ // `environment` is filled by the CLI flag, not authored into the read args.
384
+ .filter((key) => key !== "environment");
385
+ const missing = required.filter((key) => !(key in readerArgs));
386
+ const note = missing.length === 0
387
+ ? `读回:${readerName};把结果与 expects 对齐(字段缺失即写入未生效)`
388
+ : `读回:${readerName},但它还需要 ${missing.join("/")}(由前序步骤或调用方补)`;
389
+ const predicate = (expects.readback !== undefined && typeof expects.readback === "object"
390
+ ? expects.readback
391
+ : expects);
392
+ return {
393
+ tool: readerName,
394
+ args: readerArgs,
395
+ expects: predicate,
396
+ note,
397
+ };
398
+ }
399
+ /**
400
+ * M4-1/M4-2: compile the authored `priorToolReferences` into real steps.
401
+ *
402
+ * They are not all "read confirmations": `workflow-backed-data-submit` names
403
+ * `data.save` as the step that PRODUCES bizObjectId/workflowInstanceId/
404
+ * workItemId. A plan that flattened them all to reads would hide a write.
405
+ *
406
+ * `captures` come from the recipe's `expectedReadback.performed.captures`, which
407
+ * is the only authored statement of "which values this step yields".
408
+ */
409
+ function compilePriorSteps(registry, recipe, environment, startIndex) {
410
+ const captures = (recipe.expectedReadback?.performed?.captures) ?? [];
411
+ const steps = [];
412
+ const byTool = new Map();
413
+ const capturesByTool = new Map();
414
+ const priors = recipe.priorToolReferences ?? [];
415
+ priors.forEach((prior, offset) => {
416
+ const id = `s${startIndex + offset}`;
417
+ const tool = registry.find((entry) => entry.name === prior.tool);
418
+ const args = {};
419
+ for (const [key, value] of Object.entries(prior.args)) {
420
+ args[key] = value === "<environment>" ? (environment ?? "<environment>") : value;
421
+ }
422
+ const isWriter = tool?.kind === "write";
423
+ // The authored `captures` belong to the step that PRODUCES them: the first
424
+ // writing prerequisite (data.save before data.submit). A recipe whose priors
425
+ // are all reads (field.list) has no producing step, so no captures.
426
+ const produces = captureVarsFor(prior.tool, offset, priors, captures);
427
+ steps.push({
428
+ id,
429
+ tool: prior.tool,
430
+ kind: isWriter ? "write" : "read",
431
+ purpose: prior.purpose,
432
+ args,
433
+ dependsOn: [],
434
+ ...(produces.length > 0 ? { captures: produces } : {}),
435
+ validated: tool === undefined
436
+ ? { ok: false, issues: [`未知工具 ${prior.tool}`] }
437
+ : validateStep(tool, args, new Set(Object.keys(args).filter((key) => typeof args[key] === "string" && String(args[key]).includes("<")))),
438
+ dryRun: dryRunFor(prior.tool, args, tool),
439
+ ...(() => {
440
+ const verify = verifyFor(registry, { tool: prior.tool, args }, undefined);
441
+ return verify === undefined ? {} : { verify };
442
+ })(),
443
+ });
444
+ byTool.set(prior.tool, { stepId: id, kind: isWriter ? "write" : "read" });
445
+ if (produces.length > 0)
446
+ capturesByTool.set(prior.tool, { stepId: id, vars: produces });
447
+ });
448
+ return { steps, byTool, capturesByTool };
449
+ }
450
+ /**
451
+ * Which variables a prior step yields. The recipe declares them once
452
+ * (`expectedReadback.performed.captures`); a step owns them when it is the
453
+ * AUTHORED producer — i.e. the prior that writes, or the one named in the
454
+ * placeholder path (`<data.save.performed.bizObjectId>` → tool `data.save`).
455
+ */
456
+ function captureVarsFor(priorTool, offset, priors, captures) {
457
+ if (captures.length === 0)
458
+ return [];
459
+ // Ownership rule: the first prior whose action creates/saves/produces a row.
460
+ const producerIndex = priors.findIndex((entry) => /^(data\.save|data\.update|data\.submit|rule\.save|field\.create|field\.update|.*\.create|.*\.update|.*\.save|.*\.register|.*\.compose)$/.test(entry.tool));
461
+ // No producing prior: don't invent one — the captures stay unowned.
462
+ return producerIndex === offset && priors[offset]?.tool === priorTool ? captures : [];
463
+ }
464
+ /** M4-4: the dry-run form of one step (no wire side effects). */
465
+ function dryRunFor(toolName, args, tool) {
466
+ if (tool === undefined)
467
+ return { supported: false, notes: "工具不在注册表里,无法判定 dry-run" };
468
+ if (tool.kind !== "write")
469
+ return { supported: false, notes: "只读步骤没有 dry-run 语义(它本身不写)" };
470
+ const envFlag = typeof args.environment === "string" ? ` --env ${args.environment}` : "";
471
+ const payload = JSON.stringify(args);
472
+ // A single quote cannot ride inside `--args '<json>'`; name the safe transport.
473
+ const transport = payload.includes("'") ? "--args -(stdin,本步 args 含单引号)" : `--args '${payload}'`;
474
+ return {
475
+ supported: true,
476
+ command: `omc call ${toolName}${envFlag} --dry-run ${transport}`,
477
+ notes: "dry-run 只校验输入与治理,不写环境;真实结果仍需执行后读回",
478
+ };
479
+ }
480
+ /**
481
+ * Ladder merging: give one segment's steps a namespace (`p1-s2`) and rewrite its
482
+ * internal references, so two segments never collide on `s1`.
483
+ */
484
+ function prefixPlanSteps(plan, prefix) {
485
+ const rewrite = (value) => {
486
+ if (typeof value === "string")
487
+ return value.replace(/\$s(\d+)\.performed\./g, `$${prefix}-s$1.performed.`);
488
+ if (Array.isArray(value))
489
+ return value.map(rewrite);
490
+ if (value !== null && typeof value === "object") {
491
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, rewrite(entry)]));
492
+ }
493
+ return value;
494
+ };
495
+ const steps = plan.steps.map((step) => ({
496
+ ...step,
497
+ id: `${prefix}-${step.id}`,
498
+ dependsOn: step.dependsOn.map((id) => `${prefix}-${id}`),
499
+ args: rewrite(step.args),
500
+ ...(step.verify !== undefined ? { verify: { ...step.verify, args: rewrite(step.verify.args) } } : {}),
501
+ }));
502
+ return { ...plan, steps };
503
+ }
504
+ /**
505
+ * M4-2: re-derive `captures` from what the plan actually REFERENCES.
506
+ *
507
+ * The recipe's own `expectedReadback.performed.captures` describes its own
508
+ * readback; a downstream recipe (`data.submit`) holds `<data.save.performed.*>`
509
+ * instead. Deriving captures from those references keeps both honest without
510
+ * cross-reading another recipe's metadata.
511
+ */
512
+ function attachCaptures(steps) {
513
+ const referenced = new Map();
514
+ const scan = (node) => {
515
+ if (typeof node === "string") {
516
+ const match = /^\$(s\d+)\.performed\.([A-Za-z][\w]*)$/.exec(node);
517
+ if (match !== null) {
518
+ const set = referenced.get(match[1]) ?? new Set();
519
+ set.add(match[2]);
520
+ referenced.set(match[1], set);
521
+ }
522
+ return;
523
+ }
524
+ if (Array.isArray(node)) {
525
+ for (const entry of node)
526
+ scan(entry);
527
+ return;
528
+ }
529
+ if (node !== null && typeof node === "object")
530
+ for (const entry of Object.values(node))
531
+ scan(entry);
532
+ };
533
+ for (const step of steps)
534
+ scan(step.args);
535
+ return steps.map((step) => {
536
+ const vars = referenced.get(step.id);
537
+ if (vars === undefined || vars.size === 0)
538
+ return step;
539
+ const merged = new Set([...(step.captures ?? []), ...vars]);
540
+ return { ...step, captures: [...merged] };
541
+ });
542
+ }
543
+ /**
544
+ * M4-2: topological order with cycle detection. Steps come in authored order;
545
+ * the sort makes dependencies explicit so a caller (or `omc script`) can run the
546
+ * list top to bottom without reasoning about it.
547
+ */
548
+ export function topoSort(steps) {
549
+ const byId = new Map(steps.map((step) => [step.id, step]));
550
+ const ordered = [];
551
+ const state = new Map();
552
+ const path = [];
553
+ const visit = (id) => {
554
+ const mark = state.get(id);
555
+ if (mark === "done")
556
+ return true;
557
+ if (mark === "visiting") {
558
+ path.push(id);
559
+ return false;
560
+ }
561
+ const step = byId.get(id);
562
+ if (step === undefined)
563
+ return true;
564
+ state.set(id, "visiting");
565
+ for (const dependency of step.dependsOn) {
566
+ if (!visit(dependency)) {
567
+ path.unshift(id);
568
+ return false;
569
+ }
570
+ }
571
+ state.set(id, "done");
572
+ ordered.push(step);
573
+ return true;
574
+ };
575
+ for (const step of steps) {
576
+ if (!visit(step.id))
577
+ return { ordered: [], cycle: path };
578
+ }
579
+ return { ordered };
580
+ }
581
+ /** Step ids that cannot run standalone (cross-step refs or failed local gate). */
582
+ export function selfContainedSteps(steps) {
583
+ return steps.filter((step) => step.dependsOn.length === 0 && step.validated.ok
584
+ && JSON.stringify(step.args).includes("<") === false);
585
+ }
586
+ function planHash(parts) {
587
+ return createHash("sha256").update(canonical(parts)).digest("hex");
588
+ }
589
+ /** `model.list` rows → the model candidate list used by the schemaCode state machine. */
590
+ function modelsOf(result) {
591
+ const rows = Array.isArray(result?.models) ? result.models : [];
592
+ return rows
593
+ .filter((row) => typeof row.code === "string" || typeof row.schemaCode === "string")
594
+ .map((row) => ({ code: String(row.schemaCode ?? row.code), name: String(row.name ?? row.schemaCode ?? row.code) }));
595
+ }
596
+ /**
597
+ * schemaCode state machine (BIG-REFACTOR-PLAN-V2 §4.2):
598
+ * zero rows → blocked / one → resolved / one fuzzy → warning / many → needs-input
599
+ * It never guesses among candidates — that is the whole point.
600
+ *
601
+ * `goal` is used for the strongest hint a human actually gives: naming the object
602
+ * in the sentence («给**采购合同**加两位小数»). A candidate whose NAME or CODE
603
+ * appears verbatim in the goal beats any fuzzy string distance, and the longest
604
+ * such name wins («采购合同台账» must not be shadowed by a shorter «合同» row).
605
+ */
606
+ export function resolveModelCandidate(hint, models, goal = "") {
607
+ if (models.length === 0)
608
+ return { state: "blocked", reason: "model-not-found" };
609
+ const needle = hint.trim();
610
+ const exact = needle === "" ? [] : models.filter((model) => model.code === needle);
611
+ if (exact.length === 1)
612
+ return { state: "resolved", code: exact[0].code };
613
+ const byName = needle === "" ? [] : models.filter((model) => model.name === needle);
614
+ if (byName.length === 1)
615
+ return { state: "resolved-with-warning", code: byName[0].code, warning: `按名称「${needle}」唯一匹配 ${byName[0].code}` };
616
+ // Named in the sentence: match the model's own strings against the goal text.
617
+ const mentioned = models
618
+ .map((model) => {
619
+ const hits = [model.name, model.code].filter((text) => text.length >= 2 && goal.includes(text));
620
+ const longest = hits.reduce((best, text) => (text.length > best.length ? text : best), "");
621
+ return { model, longest };
622
+ })
623
+ .filter((entry) => entry.longest !== "")
624
+ // Longest mention wins; a row whose name is a substring of another matched
625
+ // row's name is the container, not the target.
626
+ .filter((entry, _index, all) => !all.some((other) => other !== entry && other.longest.length > entry.longest.length && other.longest.includes(entry.longest)));
627
+ if (mentioned.length === 1) {
628
+ return { state: "resolved-with-warning", code: mentioned[0].model.code, warning: `目标句提到「${mentioned[0].longest}」,据此选中 ${mentioned[0].model.code}` };
629
+ }
630
+ if (mentioned.length > 1) {
631
+ return { state: "needs-input", candidates: mentioned.map((entry) => entry.model).slice(0, 10) };
632
+ }
633
+ // Nothing named anywhere: that is a question with the full shortlist, not a
634
+ // model-not-found (the difference decides whether the agent asks or gives up).
635
+ if (needle === "")
636
+ return { state: "needs-input", candidates: models.slice(0, 10) };
637
+ const fuzzy = models.filter((model) => model.code.includes(needle) || String(model.name).includes(needle));
638
+ if (exact.length > 1 || byName.length > 1 || fuzzy.length > 1) {
639
+ return { state: "needs-input", candidates: (exact.length > 1 ? exact : byName.length > 1 ? byName : fuzzy).slice(0, 10) };
640
+ }
641
+ if (fuzzy.length === 1)
642
+ return { state: "resolved-with-warning", code: fuzzy[0].code, warning: `「${needle}」模糊匹配到 ${fuzzy[0].code}(${fuzzy[0].name}),请核对` };
643
+ return { state: "blocked", reason: "model-not-found" };
644
+ }
645
+ /**
646
+ * Build a plan. PURE except for the injected probe runner — no writes, ever.
647
+ */
648
+ export async function planGoal(registry, goal, options = {}) {
649
+ const explicit = options.target;
650
+ const route = explicit === undefined
651
+ ? goalRoute(registry, goal)
652
+ : {
653
+ status: "ok",
654
+ goal,
655
+ confident: true,
656
+ mode: "build",
657
+ write: true,
658
+ match: { kind: "recipe", ref: explicit.recipe, tool: explicit.tool, recipe: explicit.recipe },
659
+ route: { capability: undefined, lane: undefined, firstCommands: [] },
660
+ };
661
+ const environment = options.environment ?? null;
662
+ const base = {
663
+ status: "ok",
664
+ goal,
665
+ environment,
666
+ missing: {},
667
+ unverified: {},
668
+ warnings: [],
669
+ ambiguities: [],
670
+ blockers: [],
671
+ probes: [],
672
+ steps: [],
673
+ };
674
+ // Level 4: the goal did not route. Hand back the routing faces, not a guess.
675
+ if (route.confident !== true || route.route === null) {
676
+ const plan = {
677
+ ...base,
678
+ ready: false,
679
+ level: 4,
680
+ ...(route.match !== undefined ? { match: route.match } : {}),
681
+ blockers: [{ type: "route-uncertain", reason: "目标未命中任何能力/配方", hint: route.fallback ?? "换能力词或先 omc next 看路线" }],
682
+ planHash: planHash({ goal, environment, level: 4 }),
683
+ next: [`omc next "${goal}"`, "omc capabilities", "omc commands --filter <关键词>"],
684
+ };
685
+ return plan;
686
+ }
687
+ const lane = typeof route.route.lane === "string" ? route.route.lane : undefined;
688
+ const capability = typeof route.route.capability === "string" ? route.route.capability : undefined;
689
+ const intentPrimary = route.route.primary === "intent" || route.mode === "whole-package";
690
+ // Level 5: the ask is a whole configuration package. The declarative intent
691
+ // compiler owns that; an atomic call chain would be strictly worse.
692
+ if (intentPrimary) {
693
+ return {
694
+ ...base,
695
+ ready: false,
696
+ level: 5,
697
+ ...(route.match !== undefined ? { match: route.match } : {}),
698
+ ...(capability !== undefined ? { capability } : {}),
699
+ ...(lane !== undefined ? { lane } : {}),
700
+ blockers: [{ type: "declarative-face", reason: "整包需求由 intent 编译器承接(模型/字段/规则/流程按依赖排序、可 readback 对账)", why: "原子 call 链无法保证顺序与幂等" }],
701
+ planHash: planHash({ goal, environment, level: 5 }),
702
+ next: ["omc intent schema", "omc intent validate <file>", "omc intent plan <file> --env <env>"],
703
+ };
704
+ }
705
+ const match = route.match;
706
+ // Composer: a CLI management face (form-default / field-add / model-scaffold …).
707
+ // It has no registry recipe to fill, so a plan cannot hand out copyable args —
708
+ // say so and hand back the composer's own `--help` instead of pretending.
709
+ if (match?.kind === "composer") {
710
+ return {
711
+ ...base,
712
+ ready: false,
713
+ level: 2,
714
+ match,
715
+ ...(capability !== undefined ? { capability } : {}),
716
+ ...(lane !== undefined ? { lane } : {}),
717
+ blockers: [{
718
+ type: "composer",
719
+ composer: match.ref,
720
+ reason: "该目标由拼装器(CLI 管理面)承接,不是 call 工具:参数由它自己的 --help 定义",
721
+ ...(match.command !== undefined ? { command: match.command } : {}),
722
+ ...(route.firstAnswer?.question !== undefined ? { hint: route.firstAnswer.question } : {}),
723
+ }],
724
+ planHash: planHash({ goal, environment, level: 2, composer: match.ref }),
725
+ next: [
726
+ ...(match.command !== undefined ? [match.command] : []),
727
+ `omc ${match.ref ?? "<composer>"} --help`,
728
+ ],
729
+ };
730
+ }
731
+ const toolName = match?.tool;
732
+ const recipeId = match?.recipe;
733
+ // Ladder: the goal spans capabilities and the route is an ORDERED list of
734
+ // segments. M4 compiles every segment into its own steps and concatenates them
735
+ // in the authored order — the dependency order IS the ladder order.
736
+ if (match?.kind === "ladder" && Array.isArray(route.route.ladder)) {
737
+ const ladder = route.route.ladder;
738
+ const segments = ladder.filter((step) => step.recipe?.tool !== undefined && step.recipe.id !== undefined);
739
+ if (segments.length === 0) {
740
+ return {
741
+ ...base,
742
+ ready: false,
743
+ level: 2,
744
+ match,
745
+ blockers: [{ type: "blocked", reason: "阶梯里没有可编译的配方" }],
746
+ planHash: planHash({ goal, environment, level: 2 }),
747
+ next: ["omc capabilities"],
748
+ };
749
+ }
750
+ // One probe cache: every segment asks `model.list`; asking per segment would
751
+ // multiply the wire cost without changing the answer.
752
+ const memo = new Map();
753
+ const cachedProbe = options.probe === undefined ? undefined : (tool, args) => {
754
+ const key = `${tool}:${JSON.stringify(args)}`;
755
+ const hit = memo.get(key);
756
+ if (hit !== undefined)
757
+ return hit;
758
+ const started = options.probe(tool, args);
759
+ memo.set(key, started);
760
+ return started;
761
+ };
762
+ const children = [];
763
+ for (const [index, segment] of segments.entries()) {
764
+ const child = await planGoal(registry, goal, {
765
+ ...options,
766
+ ...(cachedProbe !== undefined ? { probe: cachedProbe } : {}),
767
+ target: { tool: segment.recipe.tool, recipe: segment.recipe.id },
768
+ });
769
+ children.push(prefixPlanSteps(child, `p${index + 1}`));
770
+ }
771
+ const steps = children.flatMap((child) => child.steps);
772
+ const ready = children.length > 0 && children.every((child) => child.ready);
773
+ // M4-7 at ladder level: the declaration face is the better compiler for a
774
+ // multi-capability package whenever any segment needs authored payload.
775
+ const authoredSegments = segments
776
+ .map((segment, index) => ({ capability: segment.capability, index }))
777
+ .filter((entry) => entry.capability !== undefined
778
+ && children[entry.index].blockers.some((blocker) => blocker.type === "needs-authoring")
779
+ && capabilityHasDeclarativeFace(registry, entry.capability));
780
+ const intentAlternative = authoredSegments.length > 0
781
+ ? {
782
+ available: true,
783
+ why: `${authoredSegments.map((entry) => entry.capability).join("、")} 有声明式面:整段配置写成 intent 文件后由编译器排序并 readback 对账,不必逐段手拼载荷`,
784
+ commands: ["omc intent schema", "omc intent validate <file>", "omc intent plan <file> --env <env>"],
785
+ }
786
+ : undefined;
787
+ const level = ready ? 1 : (children.some((child) => child.level === 3) ? 3 : 2);
788
+ return {
789
+ status: "ok",
790
+ goal,
791
+ environment,
792
+ ready,
793
+ level,
794
+ match,
795
+ ...(capability !== undefined ? { capability } : {}),
796
+ ...(lane !== undefined ? { lane } : {}),
797
+ ...(intentAlternative !== undefined ? { intentAlternative } : {}),
798
+ steps,
799
+ // Segment-qualified so two segments that both need `code` stay distinguishable.
800
+ missing: Object.fromEntries(children.flatMap((child, index) => Object.entries(child.missing).map(([key, value]) => [`p${index + 1}.${key}`, value]))),
801
+ unverified: Object.fromEntries(children.flatMap((child, index) => Object.entries(child.unverified).map(([key, value]) => [`p${index + 1}.${key}`, value]))),
802
+ warnings: children.flatMap((child) => child.warnings),
803
+ ambiguities: children.flatMap((child, index) => child.ambiguities.map((entry) => ({ ...entry, param: `p${index + 1}.${entry.param}` }))),
804
+ blockers: children.flatMap((child) => child.blockers),
805
+ probes: [...new Set(children.flatMap((child) => child.probes))],
806
+ planHash: planHash({ goal, environment, ladder: segments.map((segment) => segment.recipe.id), steps: steps.map((step) => ({ id: step.id, tool: step.tool, args: step.args })) }),
807
+ next: ready
808
+ ? [`omc plan "${goal}" --env ${environment ?? "<env>"} --ndjson`]
809
+ : [...new Set([...(intentAlternative !== undefined ? intentAlternative.commands : []), ...children.flatMap((child) => child.next)])],
810
+ note: `阶梯 ${segments.length} 段已按依赖顺序编译(${segments.map((segment) => segment.recipe.id).join(" → ")})`,
811
+ };
812
+ }
813
+ if (toolName === undefined || recipeId === undefined) {
814
+ // READ ask (M6): the route only says "this is a read across these
815
+ // capabilities" — it does not pick the tool. Ranking the registry with the
816
+ // M1 search face answers "which read tool", and resolving the model the ask
817
+ // names turns that into a runnable step. Returning just "give me a
818
+ // schemaCode" would be smaller and useless: bytes bought with rounds.
819
+ if (route.mode === "read" || Array.isArray(route.route.readTools)) {
820
+ return await planReadAsk(registry, goal, environment, options, base, match, capability, lane);
821
+ }
822
+ return {
823
+ ...base,
824
+ ready: false,
825
+ level: 2,
826
+ ...(match !== undefined ? { match } : {}),
827
+ ...(capability !== undefined ? { capability } : {}),
828
+ ...(lane !== undefined ? { lane } : {}),
829
+ blockers: [{ type: "needs-input", reason: "该能力没有命中配方", hint: route.firstAnswer?.question ?? "给我 schemaCode(或模型业务名,我列清单核对)" }],
830
+ probes: ["omc call model.list --env <env> --args '{}'"],
831
+ planHash: planHash({ goal, environment, level: 2 }),
832
+ next: ["omc call model.list --env <env> --args '{}'", ...(capability !== undefined ? [`omc capability ${capability}`] : [])],
833
+ };
834
+ }
835
+ const tool = registry.find((entry) => entry.name === toolName);
836
+ const recipe = tool?.executionMetadata?.recipes.find((entry) => entry.id === recipeId);
837
+ if (tool === undefined || recipe === undefined) {
838
+ return {
839
+ ...base,
840
+ ready: false,
841
+ level: 4,
842
+ blockers: [{ type: "blocked", reason: `路由指向的配方不存在:${toolName}/${recipeId}` }],
843
+ planHash: planHash({ goal, environment, level: 4 }),
844
+ next: ["omc capabilities", `omc describe ${toolName}`],
845
+ };
846
+ }
847
+ const rawArgs = recipe.args;
848
+ // M4-1: authored prerequisites become real steps (`data.save` before
849
+ // `data.submit`, `field.list` before a datarule). Without this the plan called
850
+ // a step "blocked" merely because its identity comes from an earlier step.
851
+ const priorCompiled = compilePriorSteps(registry, recipe, environment, 1);
852
+ const mainStepId = `s${priorCompiled.steps.length + 1}`;
853
+ // `dependsOn` means DATA dependency (a value flows in), not sequence. Prior
854
+ // read confirmations are ordered by the step array; only a step that PRODUCES a
855
+ // referenced value is a dependency — otherwise NDJSON would drop every step
856
+ // that happens to follow a confirmation read.
857
+ const dependencies = new Set();
858
+ const args = {};
859
+ const pending = new Set();
860
+ const missing = {};
861
+ const unverified = {};
862
+ const warnings = [];
863
+ const ambiguities = [];
864
+ const blockers = [];
865
+ const probes = [];
866
+ let probeFailure;
867
+ // ---- resolve one slot at a time -------------------------------------------------
868
+ for (const [key, value] of Object.entries(rawArgs)) {
869
+ // The environment is never a probe: `--env` already is the answer, and the
870
+ // recipe's `<environment>` stand-in must not survive into a step.
871
+ if (key === "environment") {
872
+ if (environment !== null)
873
+ args.environment = environment;
874
+ else
875
+ pending.add(key);
876
+ continue;
877
+ }
878
+ const rule = paramFillRuleFor(tool.name, recipe.id, key);
879
+ const placeholders = collectPlaceholders(value, key);
880
+ const needsValue = placeholders.length > 0;
881
+ args[key] = value;
882
+ // A concrete value can still be WRONG for this environment: every recipe was
883
+ // authored against an example tenant (`schemaCode: "crm_contract"`). Registry
884
+ // ids are therefore verified even when they look filled.
885
+ if (!needsValue && rule.cls !== "registry")
886
+ continue;
887
+ // A: authored payload — the asker must design it. Never a "few params".
888
+ if (AUTHORED_KEYS.has(key) || (rule.cls === "user" && rule.user === "utterance" && Buffer.byteLength(JSON.stringify(value)) > 400)) {
889
+ if (AUTHORED_KEYS.has(key)) {
890
+ blockers.push({
891
+ type: "needs-authoring",
892
+ param: key,
893
+ reason: `${key} 是需求本体(规则图/流程拓扑/脚本/接口契约/字段清单),不是可由探测补全的参数`,
894
+ why: rule.source,
895
+ ...(key === "nodeGraph" ? { next: `omc describe ${tool.name} --example <id>` } : {}),
896
+ });
897
+ }
898
+ else {
899
+ missing[key] = { reason: "需求话语需给出该配置", source: rule.source };
900
+ }
901
+ pending.add(key);
902
+ continue;
903
+ }
904
+ // B: registry-resolvable id — one read probe, then the state machine.
905
+ if (rule.cls === "registry") {
906
+ const resolver = RESOLVERS[key];
907
+ // No resolver registered for this id: keep the authored value but say it is
908
+ // unverified. `ready=true` is earned, never assumed.
909
+ if (resolver === undefined) {
910
+ if (needsValue) {
911
+ missing[key] = { reason: "需先读平台确认该标识", source: rule.source };
912
+ pending.add(key);
913
+ }
914
+ else {
915
+ unverified[key] = { reason: "沿用配方示例值,未在本环境核对", source: rule.source };
916
+ }
917
+ continue;
918
+ }
919
+ // Which value are we looking for? A placeholder means "whatever the ask
920
+ // names"; a concrete authored id means "confirm this one exists".
921
+ const hints = needsValue ? hintCandidates(goal) : [typeof value === "string" ? value : ""];
922
+ if (options.offline === true || options.probe === undefined) {
923
+ probes.push(`omc call ${resolver} --env ${environment ?? "<env>"} --args '{}'`);
924
+ if (needsValue) {
925
+ missing[key] = { reason: `需 ${resolver} 解析`, source: rule.source };
926
+ pending.add(key);
927
+ }
928
+ else {
929
+ unverified[key] = { reason: `需 ${resolver} 核对示例值 ${String(value)} 是否存在于本环境`, source: rule.source };
930
+ }
931
+ continue;
932
+ }
933
+ const probed = await probeReadOnly(options.probe, resolver);
934
+ if (probed.state === "uncertain") {
935
+ probeFailure = `${resolver} 探测失败:${probed.reason ?? "未返回可判定结果"}`;
936
+ pending.add(key);
937
+ continue;
938
+ }
939
+ const rows = probed.rows ?? [];
940
+ // Every candidate is tried, then the DISTINCT resolved models are compared.
941
+ // "First hit wins" silently picks one when the ask names two objects
942
+ // (「把采购合同和销售合同的金额…」) — the exact guess §4.2 forbids.
943
+ const resolvedByCodes = new Map();
944
+ let fallback = resolveModelCandidate(hints[0] ?? "", rows, goal);
945
+ for (const candidate of hints) {
946
+ const attempt = resolveModelCandidate(candidate, rows, goal);
947
+ if ((attempt.state === "resolved" || attempt.state === "resolved-with-warning") && attempt.code !== undefined) {
948
+ const row = rows.find((entry) => entry.code === attempt.code);
949
+ resolvedByCodes.set(attempt.code, row ?? { code: attempt.code, name: attempt.code });
950
+ }
951
+ else if (attempt.state === "needs-input" && fallback.state !== "needs-input") {
952
+ fallback = attempt;
953
+ }
954
+ }
955
+ const outcome = resolvedByCodes.size === 1
956
+ ? { state: "resolved-with-warning", code: [...resolvedByCodes.keys()][0], warning: `目标句指向 ${[...resolvedByCodes.keys()][0]}` }
957
+ : resolvedByCodes.size > 1
958
+ ? { state: "needs-input", candidates: [...resolvedByCodes.values()].slice(0, 10) }
959
+ : fallback;
960
+ if (outcome.state === "needs-input") {
961
+ ambiguities.push({
962
+ param: key,
963
+ candidates: outcome.candidates ?? [],
964
+ question: needsValue ? `${key} 有多个候选,选中哪一个?` : `示例值「${hints[0]}」不唯一,选中哪一个?`,
965
+ });
966
+ pending.add(key);
967
+ continue;
968
+ }
969
+ if (outcome.state === "blocked") {
970
+ // A concrete authored id that is absent here is NOT "the platform has no
971
+ // model": it is a plan that must ask. Fabricating it is the failure §4.2 bans.
972
+ if (!needsValue) {
973
+ ambiguities.push({ param: key, candidates: rows.slice(0, 10), question: `配方示例值「${hints[0]}」在本环境不存在,选哪个 ${key}?` });
974
+ }
975
+ else {
976
+ blockers.push({ type: "blocked", param: key, reason: outcome.reason ?? "平台无匹配" });
977
+ }
978
+ pending.add(key);
979
+ continue;
980
+ }
981
+ if (outcome.code === undefined) {
982
+ missing[key] = { reason: `需 ${resolver} 解析`, source: rule.source };
983
+ pending.add(key);
984
+ continue;
985
+ }
986
+ // A concrete authored scalar is REPLACED by the resolved code; a template
987
+ // gets every placeholder leaf rewritten. Mixing these up ships the example
988
+ // tenant's code into a plan against another environment.
989
+ args[key] = needsValue ? substitutePlaceholders(value, outcome.code) : outcome.code;
990
+ // A unique fuzzy match is an INFERENCE, not a doubt: §4.1 requires "无歧义"
991
+ // (unique), and this is unique. It is reported so the caller can check, but
992
+ // it must not make `ready` unreachable.
993
+ if (outcome.state === "resolved-with-warning" && outcome.warning !== undefined)
994
+ warnings.push(`${key}: ${outcome.warning}`);
995
+ continue;
996
+ }
997
+ // C: probe-produced ids (bizObjectId / workItemId).
998
+ if (rule.cls === "probe") {
999
+ // M4-2: if an authored prerequisite PRODUCES this value, wire a cross-step
1000
+ // reference instead of blocking. That is the difference between "you must
1001
+ // run data.save first (this plan says which step)" and "go away and replan".
1002
+ const producedBy = crossStepProducer(value, priorCompiled.byTool);
1003
+ if (producedBy !== undefined) {
1004
+ args[key] = producedBy.reference;
1005
+ dependencies.add(producedBy.stepId);
1006
+ continue;
1007
+ }
1008
+ blockers.push({
1009
+ type: "needs-input",
1010
+ param: key,
1011
+ reason: `${key} 由前序写回执产生,但本配方没有声明产出它的前置步骤`,
1012
+ why: rule.source,
1013
+ next: `先执行产生该标识的步骤,再 omc plan 重新规划`,
1014
+ });
1015
+ pending.add(key);
1016
+ continue;
1017
+ }
1018
+ // D: user-supplied but the asker can just say it.
1019
+ if (rule.cls === "user") {
1020
+ missing[key] = { reason: rule.user === "ask" ? "无法推断,需明确" : "需求话语需给出,或可提议后确认", source: rule.source, ...(rule.user !== undefined ? { why: rule.user } : {}) };
1021
+ pending.add(key);
1022
+ continue;
1023
+ }
1024
+ // E: unclassified — exposed as a gap, never guessed.
1025
+ missing[key] = { reason: "未分类参数(宁可暴露缺口,不猜)", source: rule.source };
1026
+ pending.add(key);
1027
+ }
1028
+ // ---- schema gate + uncertainty rule --------------------------------------------
1029
+ const validated = validateStep(tool, args, pending);
1030
+ const mainStep = {
1031
+ id: mainStepId,
1032
+ tool: tool.name,
1033
+ kind: tool.kind === "write" ? "write" : "read",
1034
+ purpose: recipe.title,
1035
+ args,
1036
+ dependsOn: [...dependencies],
1037
+ validated,
1038
+ dryRun: dryRunFor(tool.name, args, tool),
1039
+ ...(() => {
1040
+ const verify = verifyFor(registry, { tool: tool.name, args }, recipe.expectedReadback);
1041
+ return verify === undefined ? {} : { verify };
1042
+ })(),
1043
+ // A hand-authored recipe in a test may omit authored recovery; absent is
1044
+ // "nothing authored", never "no refusals exist".
1045
+ ...((recipe.refusalRecovery ?? []).length > 0
1046
+ ? { onFailure: recipe.refusalRecovery.map((entry) => ({ code: String(entry.code ?? ""), action: String(entry.action ?? "") })) }
1047
+ : {}),
1048
+ };
1049
+ const uncertain = probeFailure !== undefined;
1050
+ // Uncertain ⇒ NOTHING executable. The risk the review called out: a plan that
1051
+ // half-resolved ids still looks runnable, and a write lands against the wrong model.
1052
+ const compiled = uncertain ? [] : [...priorCompiled.steps, mainStep];
1053
+ // M4-2: dependencies are declared, so the order must be PROVEN, not assumed.
1054
+ const sorted = topoSort(compiled);
1055
+ if (sorted.cycle !== undefined) {
1056
+ return {
1057
+ ...base,
1058
+ ready: false,
1059
+ level: 2,
1060
+ ...(match !== undefined ? { match } : {}),
1061
+ ...(capability !== undefined ? { capability } : {}),
1062
+ ...(lane !== undefined ? { lane } : {}),
1063
+ blockers: [{ type: "blocked", reason: `步骤依赖成环:${sorted.cycle.join(" → ")}` }],
1064
+ planHash: planHash({ goal, environment, level: 2, cycle: sorted.cycle }),
1065
+ next: [`omc describe ${tool.name} --example ${recipe.id}`],
1066
+ };
1067
+ }
1068
+ const steps = attachCaptures(sorted.ordered);
1069
+ const ready = !uncertain
1070
+ && Object.keys(missing).length === 0
1071
+ && Object.keys(unverified).length === 0
1072
+ && ambiguities.length === 0
1073
+ && blockers.length === 0
1074
+ && validated.ok
1075
+ && steps.every((step) => step.validated.ok);
1076
+ const level = uncertain ? 3 : ready ? 1 : 2;
1077
+ // M4-7: when the ATOMIC path is blocked on an authored payload, name the
1078
+ // declarative face — but only if that capability actually has one. Otherwise
1079
+ // the pointer is noise (and worse, it reads as "there is an easier way").
1080
+ const needsAuthoring = blockers.some((entry) => entry.type === "needs-authoring");
1081
+ const intentAlternative = needsAuthoring && capability !== undefined && capabilityHasDeclarativeFace(registry, capability)
1082
+ ? {
1083
+ available: true,
1084
+ why: `${capability} 有声明式面:整段配置可写成 intent 文件,由编译器按依赖排序并 readback 对账,不必手拼 ${blockers.filter((entry) => entry.type === "needs-authoring").map((entry) => entry.param).join("/")}`,
1085
+ commands: ["omc intent schema", "omc intent validate <file>", "omc intent plan <file> --env <env>"],
1086
+ }
1087
+ : undefined;
1088
+ return {
1089
+ status: "ok",
1090
+ goal,
1091
+ environment,
1092
+ ready,
1093
+ level,
1094
+ ...(match !== undefined ? { match } : {}),
1095
+ ...(capability !== undefined ? { capability } : {}),
1096
+ ...(lane !== undefined ? { lane } : {}),
1097
+ ...(intentAlternative !== undefined ? { intentAlternative } : {}),
1098
+ steps,
1099
+ missing,
1100
+ unverified,
1101
+ warnings,
1102
+ ambiguities,
1103
+ blockers: uncertain ? [...blockers, { type: "uncertain", reason: probeFailure }] : blockers,
1104
+ probes,
1105
+ planHash: planHash({ goal, environment, tool: tool.name, recipe: recipe.id, args, ready, level }),
1106
+ next: ready
1107
+ ? [`omc call ${tool.name} --env ${environment ?? "<env>"} --args '<上面的 args>'`, `omc describe ${tool.name}`]
1108
+ : [
1109
+ ...(probes.length > 0 ? probes : []),
1110
+ ...(intentAlternative !== undefined ? intentAlternative.commands : []),
1111
+ `omc describe ${tool.name} --example ${recipe.id}`,
1112
+ `omc describe ${tool.name}`,
1113
+ ],
1114
+ ...(recipe.requiresEnvironmentDerivedIds ? { note: "该配方需要环境读回派生标识;前置步骤已按配方声明编入计划" } : {}),
1115
+ };
1116
+ }
1117
+ /**
1118
+ * M4-7: does this capability have a declarative (intent) face?
1119
+ *
1120
+ * `intent.level !== "none"` is the registry's own answer — the same field
1121
+ * `omc capabilities` prints — so the plan never claims a declarative route the
1122
+ * compiler cannot take.
1123
+ */
1124
+ export function capabilityHasDeclarativeFace(registry, capabilityId) {
1125
+ return capabilityRouteIndex(registry).nodeById.get(capabilityId)?.intent.level !== undefined
1126
+ && capabilityRouteIndex(registry).nodeById.get(capabilityId).intent.level !== "none";
1127
+ }
1128
+ /** Replace every `<placeholder>` leaf with one resolved value; keeps nested shapes. */
1129
+ function substitutePlaceholders(value, code) {
1130
+ if (typeof value === "string")
1131
+ return /^<[^<>]+>$/.test(value) || value.includes("omc_recipe_") ? code : value;
1132
+ if (Array.isArray(value))
1133
+ return value.map((entry) => substitutePlaceholders(entry, code));
1134
+ if (value !== null && typeof value === "object") {
1135
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, substitutePlaceholders(entry, code)]));
1136
+ }
1137
+ return value;
1138
+ }
1139
+ /**
1140
+ * Run one read-only resolver tool and lift its rows into the candidate shape.
1141
+ *
1142
+ * Only `model.list` is wired: it is the one probe every recipe needs and the one
1143
+ * the review named (schemaCode ambiguity). Other registry ids keep their authored
1144
+ * value and are reported as `unverified` — an honest gap, not a fabricated id.
1145
+ */
1146
+ async function probeReadOnly(probe, resolver) {
1147
+ const outcome = await probe(resolver, {});
1148
+ if (!outcome.ok)
1149
+ return { state: "uncertain", reason: outcome.error ?? "probe failed" };
1150
+ return { state: "ok", rows: modelsOf(outcome.result) };
1151
+ }
1152
+ /**
1153
+ * The target object the ask names — the ONLY source of a schemaCode. Deliberately
1154
+ * dumb: a plan must not invent a model from a vague verb.
1155
+ */
1156
+ function hintFromGoal(goal, rawArgs) {
1157
+ // An authored Latin identifier is the strongest hint there is.
1158
+ for (const value of Object.values(rawArgs)) {
1159
+ if (typeof value === "string" && !/^<[^<>]+>$/.test(value) && !value.includes("omc_recipe_") && /^[A-Za-z][\w.]*$/.test(value) && value.length >= 4)
1160
+ return value;
1161
+ }
1162
+ return hintCandidates(goal)[0] ?? "";
1163
+ }
1164
+ /**
1165
+ * Ordered model-name candidates from a Chinese ask.
1166
+ *
1167
+ * CJK has no spaces, so "the longest run" is the WHOLE sentence — useless as a
1168
+ * model name (「查采购申请里金额大于一万的单据」 has no terminator to split on).
1169
+ * This strips the leading verb, cuts at container markers (里/的/中/上) and at
1170
+ * punctuation/conjunctions, then trims trailing structural nouns (模型/字段/表单…).
1171
+ * Several candidates are returned because the ask may name the object loosely;
1172
+ * the caller tries each against the platform's rows and takes the first unique hit.
1173
+ */
1174
+ export function hintCandidates(goal) {
1175
+ const quoted = goal.match(/[「"]([^」"]{2,20})[」"]/);
1176
+ const out = [];
1177
+ const push = (value) => {
1178
+ const trimmed = value.trim();
1179
+ if (trimmed.length >= 2 && trimmed.length <= 20 && !out.includes(trimmed))
1180
+ out.push(trimmed);
1181
+ };
1182
+ if (quoted)
1183
+ push(quoted[1]);
1184
+ // Longest alternatives FIRST: 「新建一个」 must be consumed before 「新建」,
1185
+ // otherwise the leftover 「一个」 survives into the model name.
1186
+ const LEADING_VERBS = /^(?:请|帮我|麻烦)?(?:查一下|查一查|查询一下|查询|查|看一下|看看|看下|看|列出|列一下|列|搜一下|搜|找一下|找|盘点|清点|统计|汇总|导出|给我一份|新建一个|创建一个|搭建一个|建一个|加一个|新建|创建|搭建|建|增加|新增|添加|加|给|把|为|在|一个|一套)/;
1187
+ const TRAILING_NOUNS = /(?:的)?(?:数据|记录|单据|列表|清单|模型|字段|表单|视图|规则|流程|页面|报表|字典|应用|目录|分组|服务|接口|方法|角色|部门|用户|员工|账号|权限|权限组|字段校验规则|校验规则|业务规则|列表视图|自定义页面|工作流|审批流)$/;
1188
+ const strip = (value) => {
1189
+ let current = value.trim();
1190
+ for (let i = 0; i < 4; i += 1) {
1191
+ const before = current;
1192
+ current = current.replace(LEADING_VERBS, "").replace(TRAILING_NOUNS, "").trim();
1193
+ if (current === before)
1194
+ break;
1195
+ }
1196
+ return current;
1197
+ };
1198
+ // Cut at container markers and at punctuation/conjunctions — the segment BEFORE
1199
+ // the marker is the object ("采购申请里金额…" → 采购申请; "差旅申请模型,带…" → 差旅申请).
1200
+ const segments = goal.split(/[里中的上下内,,、。;;::和与及或]|带|包含|要有|需要/);
1201
+ push(strip(goal));
1202
+ for (const segment of segments)
1203
+ push(strip(segment));
1204
+ // Two-to-four character prefixes of the first meaningful segment catch nouns
1205
+ // that carry a verb-like prefix the regex list missed.
1206
+ const first = strip(segments[0] ?? goal);
1207
+ for (const length of [4, 3, 2])
1208
+ if (first.length > length)
1209
+ push(first.slice(0, length));
1210
+ return out;
1211
+ }
1212
+ /**
1213
+ * M4-5: the NDJSON that `omc script` consumes.
1214
+ *
1215
+ * Only self-contained steps go in: a step that still holds `<…>` placeholders or
1216
+ * waits on an earlier step's readback cannot be expressed in NDJSON (the script
1217
+ * runner does no variable interpolation), and emitting it would hand the runner
1218
+ * a guaranteed failure. `planToNdjsonSkipped` names what was left out and why,
1219
+ * so the caller can chain manually instead of wondering where steps went.
1220
+ */
1221
+ export function planToNdjson(plan) {
1222
+ return selfContainedSteps(plan.steps).map((step) => JSON.stringify({
1223
+ tool: step.tool,
1224
+ args: step.args,
1225
+ ...(plan.environment !== null ? { env: plan.environment } : {}),
1226
+ dryRun: true,
1227
+ }));
1228
+ }
1229
+ /** Steps withheld from NDJSON, with the reason (M4-5). */
1230
+ export function planToNdjsonSkipped(plan) {
1231
+ const included = new Set(selfContainedSteps(plan.steps).map((step) => step.id));
1232
+ return plan.steps
1233
+ .filter((step) => !included.has(step.id))
1234
+ .map((step) => ({
1235
+ id: step.id,
1236
+ tool: step.tool,
1237
+ reason: !step.validated.ok
1238
+ ? `本地 schema 未通过(${step.validated.issues.slice(0, 2).join(";")})`
1239
+ : step.dependsOn.length > 0
1240
+ ? `依赖 ${step.dependsOn.join("、")} 的读回值(NDJSON 不做变量插值)`
1241
+ : "参数里仍有未解析的 <占位符>",
1242
+ }));
1243
+ }
1244
+ //# sourceMappingURL=goal-plan.js.map