@tikoci/centrs 0.1.9-next.22 → 0.1.9-next.24

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 (68) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/GLOSSARY.txt +38 -0
  3. package/README.md +2 -2
  4. package/commands/api/AGENTS.md +18 -1
  5. package/commands/api/README.md +10 -6
  6. package/commands/api/examples.md +1 -1
  7. package/commands/execute/README.md +26 -6
  8. package/commands/execute/examples.md +43 -5
  9. package/commands/explain/README.md +873 -182
  10. package/commands/explain/examples.md +447 -38
  11. package/commands/retrieve/README.md +13 -2
  12. package/commands/retrieve/examples.md +30 -1
  13. package/commands/transfer/README.md +8 -4
  14. package/docs/CLI.md +19 -5
  15. package/docs/CONSTITUTION.md +18 -9
  16. package/docs/MATRIX.md +51 -26
  17. package/docs/errors/cmr/caller-policy-not-enforced.md +5 -3
  18. package/docs/errors/routeros/permission-denied.md +24 -0
  19. package/docs/errors/transport/edge-auth-failed.md +22 -0
  20. package/docs/errors/transport/write-outcome-unknown.md +3 -0
  21. package/docs/errors/usage/invalid-cursor.md +20 -0
  22. package/docs/errors/validation/unknown-path.md +9 -0
  23. package/package.json +5 -2
  24. package/src/api.ts +34 -39
  25. package/src/cli/explain.ts +206 -47
  26. package/src/core/envelope.ts +10 -3
  27. package/src/core/error-catalog.ts +15 -0
  28. package/src/core/execute-command.ts +53 -0
  29. package/src/core/fanout.ts +12 -2
  30. package/src/core/inspect.ts +4 -5
  31. package/src/core/routeros-errors.ts +25 -0
  32. package/src/execute-cmr.ts +2 -8
  33. package/src/execute.ts +48 -20
  34. package/src/explain/args.ts +181 -15
  35. package/src/explain/blocks.ts +3 -4
  36. package/src/explain/brace-slots.ts +5 -0
  37. package/src/explain/catalog.ts +13 -6
  38. package/src/explain/defects.ts +1 -0
  39. package/src/explain/group-faults.ts +1060 -0
  40. package/src/explain/highlight-projection.ts +10 -8
  41. package/src/explain/operators.ts +22 -20
  42. package/src/explain/pathresolve.ts +102 -20
  43. package/src/explain/quoted-string.ts +41 -6
  44. package/src/explain/run-tokens.ts +223 -0
  45. package/src/explain/scope-brace.ts +319 -7
  46. package/src/explain/segment.ts +177 -4
  47. package/src/explain/spaced-args.ts +116 -0
  48. package/src/explain/symbols.ts +163 -7
  49. package/src/explain/transport.ts +13 -0
  50. package/src/explain/values.ts +55 -4
  51. package/src/explain/verbsplit.ts +14 -188
  52. package/src/explain/write.ts +8 -1
  53. package/src/explain-live-facets.ts +739 -0
  54. package/src/explain-live-types.ts +490 -0
  55. package/src/explain-live.ts +593 -0
  56. package/src/explain.ts +772 -60
  57. package/src/index.ts +6 -0
  58. package/src/offline-gate.ts +30 -9
  59. package/src/protocols/adapter.ts +88 -10
  60. package/src/protocols/btest-session.ts +30 -10
  61. package/src/protocols/mac-telnet-console.ts +16 -0
  62. package/src/protocols/mac-telnet.ts +38 -10
  63. package/src/protocols/native-api.ts +13 -12
  64. package/src/retrieve-follow.ts +2 -1
  65. package/src/retrieve-sample.ts +2 -1
  66. package/src/retrieve-wait.ts +10 -6
  67. package/src/retrieve.ts +77 -27
  68. package/src/transfer.ts +38 -13
package/src/explain.ts CHANGED
@@ -70,9 +70,9 @@
70
70
  * separate optional homes but no offline producer. Each fact has its own
71
71
  * provenance; no hint validates a value or becomes a diagnostic. The
72
72
  * decision and the probe matrix are #225; `op` is deliberately not a shape
73
- * hint — `(> …)` abstains offline and is reported only as a live
74
- * `observedType` because identical syntax can be `op` or `array` and
75
- * `:parse` IL cannot distinguish them (#288). This module is deliberately
73
+ * hint — `(> …)` abstains offline AND live, because identical syntax can
74
+ * be `op` or `array` and only `:typeof`, which live explain never sends,
75
+ * distinguishes them (#288, #225). This module is deliberately
76
76
  * type-blind, which is why a verdict that looks wrong around a value is a
77
77
  * type-axis question before it is a lexical one.
78
78
  * - **`runtimeAcceptance` is always `"not-proven"`**, offline and live alike.
@@ -101,7 +101,12 @@ import type {
101
101
  CommonSettingsMeta,
102
102
  EnvelopeMeta,
103
103
  } from "./core/envelope.ts";
104
- import { buildTip, type Tip, type Warning } from "./core/envelope.ts";
104
+ import {
105
+ buildTip,
106
+ type EnvelopeValidationMeta,
107
+ type Tip,
108
+ type Warning,
109
+ } from "./core/envelope.ts";
105
110
  import {
106
111
  type CanonicalExecuteCommand,
107
112
  canonicalizeExecuteCommand,
@@ -129,6 +134,7 @@ import { lookupPath } from "./explain/catalog.ts";
129
134
  import {
130
135
  analyzeCoordinates,
131
136
  type CoordinateAnalysis,
137
+ runAtByte,
132
138
  } from "./explain/coordinates.ts";
133
139
  import {
134
140
  type Defect,
@@ -136,6 +142,7 @@ import {
136
142
  isPositionalFact,
137
143
  } from "./explain/defects.ts";
138
144
  import { escapeSpans } from "./explain/escape-tokens.ts";
145
+ import { findGroupFaults, type GroupFault } from "./explain/group-faults.ts";
139
146
  import { isKnownMenuPath } from "./explain/is-known-menu.ts";
140
147
  import { operatorSpans } from "./explain/operator-tokens.ts";
141
148
  import { type PathTokenCandidate, pathSpans } from "./explain/path-tokens.ts";
@@ -157,6 +164,7 @@ import {
157
164
  findMissingSeparators,
158
165
  type MissingSeparator,
159
166
  } from "./explain/separator.ts";
167
+ import { findSpacedPairs, type SpacedPair } from "./explain/spaced-args.ts";
160
168
  import { stringSpans } from "./explain/string-tokens.ts";
161
169
  import { augmentSymbolOccurrences } from "./explain/symbol-values.ts";
162
170
  import {
@@ -169,7 +177,12 @@ import {
169
177
  type ExplainTransport,
170
178
  } from "./explain/transport.ts";
171
179
  import { valueSpans } from "./explain/value-tokens.ts";
172
- import { type ValueShape, valueShapeHints } from "./explain/values.ts";
180
+ import {
181
+ type ObservedValueType,
182
+ type SchemaValueType,
183
+ type ValueShape,
184
+ valueShapeHints,
185
+ } from "./explain/values.ts";
173
186
  import {
174
187
  type DocumentVerbSplit,
175
188
  resolveVerb,
@@ -374,7 +387,15 @@ export interface ExplainStatementFacts {
374
387
  ev: string;
375
388
  }
376
389
 
377
- export type ExplainStatement = ExplainStatementFacts & ExplainReading;
390
+ export type ExplainStatement = ExplainStatementFacts &
391
+ ExplainReading & {
392
+ /** Stable within this result: `s0`, `s1`, … in discovery order. */
393
+ id: string;
394
+ /** Owning statement's id; absent at top level. Source containment only. */
395
+ parent?: string;
396
+ /** Index of the innermost published `blocks[]` body containing this statement. */
397
+ block?: number;
398
+ };
378
399
 
379
400
  /**
380
401
  * A `[…]` command substitution, re-constituted against its enclosing menu.
@@ -394,6 +415,8 @@ export type ExplainStatement = ExplainStatementFacts & ExplainReading;
394
415
  * opinion.
395
416
  */
396
417
  export interface ExplainSubcommandFacts extends ExplainStatementFacts {
418
+ /** Id of the statement containing this substitution, including nested brackets. */
419
+ owner: string;
397
420
  /** Menu context in force at the bracket, `/` at document root. */
398
421
  context: string;
399
422
  /** Every path the inner command could resolve to, shortest first. */
@@ -406,9 +429,11 @@ export type ExplainSubcommand = ExplainSubcommandFacts & ExplainReading;
406
429
 
407
430
  /** A `{…}` scope at document level. */
408
431
  export interface ExplainBlock {
432
+ /** Owning statement's id, when the body belongs to a published statement. */
433
+ owner?: string;
409
434
  /** The argument or directive that opened it (`do`, `on-error`, …). */
410
435
  name: string;
411
- /** The BODY's span, braces excluded. */
436
+ /** The BODY's analyzed-byte span, braces excluded. */
412
437
  span: ExplainSpanRange;
413
438
  ev: string;
414
439
  }
@@ -424,10 +449,9 @@ export interface ExplainStructure {
424
449
  *
425
450
  * A `do={…}` body's statements are flattened in after their parent (which is
426
451
  * what RouterOS IL does to them), so a body statement's span is CONTAINED by
427
- * its parent's rather than following it, and spans may overlap. A consumer
428
- * that wants only the top level filters on containment; one that wants "every
429
- * command in this script" — the common case, and the reason to flatten — reads
430
- * the list as it stands.
452
+ * its parent's rather than following it, and spans may overlap. Filter on an
453
+ * absent `parent` for the top level; use `id`/`parent` for source ancestry.
454
+ * Links assert no lexical inheritance, execution order, or shared environment.
431
455
  */
432
456
  statements: ExplainStatement[];
433
457
  blocks: ExplainBlock[];
@@ -446,15 +470,21 @@ export interface ExplainStructure {
446
470
  *
447
471
  * The vocabulary is centrs-owned (the ratified decision): consumers depend on
448
472
  * it rather than on raw RouterOS `highlight` classes, so cross-version drift in
449
- * those classes is centrs's problem to absorb. For these five the two names
450
- * currently coincide, which is a convenience, not the contract.
473
+ * those classes is centrs's problem to absorb. Name-coincident classes keep
474
+ * their spelling; live classes outside this vocabulary remain unclassified
475
+ * here and are preserved in the raw highlight observation.
451
476
  */
452
477
  export type ExplainSpanClass =
453
478
  | "comment"
454
479
  | "variable-local"
455
480
  | "variable-global"
456
481
  | "variable-auto"
457
- | "variable-parameter";
482
+ | "variable-parameter"
483
+ | "dir"
484
+ | "cmd"
485
+ | "arg"
486
+ | "escaped"
487
+ | "unclassified";
458
488
 
459
489
  export interface ExplainSpan extends ExplainSpanRange {
460
490
  class: ExplainSpanClass;
@@ -606,8 +636,34 @@ export interface ExplainValueShapeFact {
606
636
  ev: string;
607
637
  }
608
638
 
639
+ /**
640
+ * A type the device's parser visibly converted a bare literal to (#225).
641
+ *
642
+ * Only a conversion is evidence: `:parse` prints a string unquoted, so an
643
+ * unchanged rendering (`123`, `1.1.1.1`, `"2.2"`) proves nothing and the fact
644
+ * is absent. See `src/explain-live-types.ts`.
645
+ */
609
646
  export interface ExplainValueTypeFact {
610
- value: string;
647
+ value: ObservedValueType;
648
+ /** The device's own rendering of the literal (`2.2` → `2.0.0.2`). */
649
+ rendered: string;
650
+ ev: string;
651
+ }
652
+
653
+ /**
654
+ * An argument's declared type, normalized from a schema source (#225).
655
+ *
656
+ * `values` are the leaf types the declaration mentions, not alternatives of
657
+ * one value: `gateway` (`Address[%Interface][@VRF]`) lists `ip`, `ip6` and
658
+ * `enum`, because inspect prints the interface names like keywords. `declared` is the source's own top-level term, verbatim,
659
+ * so a consumer can tell a live `/console/inspect` declaration from a CLI
660
+ * Reference `Type` cell by `ev` and still read the original.
661
+ */
662
+ export interface ExplainSchemaTypeFact {
663
+ values: SchemaValueType[];
664
+ /** Present only when the declaration spells a repetition; absence is not a claim. */
665
+ list?: true;
666
+ declared: string;
611
667
  ev: string;
612
668
  }
613
669
 
@@ -615,7 +671,7 @@ export interface ExplainValueTypeFact {
615
671
  export interface ExplainValueFacts {
616
672
  shapeHints?: ExplainValueShapeFact;
617
673
  observedType?: ExplainValueTypeFact;
618
- schemaType?: ExplainValueTypeFact;
674
+ schemaType?: ExplainSchemaTypeFact;
619
675
  }
620
676
 
621
677
  export interface ExplainValueOccurrence {
@@ -656,18 +712,14 @@ export interface ExplainDiagnostic {
656
712
  }
657
713
 
658
714
  /**
659
- * Where a derived fact came from — the OFFLINE SUBSET of the contract.
660
- *
661
- * The spec's evidence entry also carries `source: "live-inspect"` and a
662
- * RouterOS version stamp per probe, neither of which phase 1 can produce: no
663
- * probe runs and there is no device to stamp. The type says only what offline
664
- * emits rather than pre-declaring variants with no producer, so a consumer
665
- * cannot narrow on a `source` that never appears; phase 2 widens the union and
666
- * adds the stamp, which is an ADDITION to the shape a caller reads today.
715
+ * Where an analysis fact came from.
716
+ *
717
+ * Live probes add version, observation time, input identity and coverage. Their
718
+ * outcome describes acquisition, never runtime acceptance.
667
719
  */
668
720
  export interface ExplainEvidence {
669
721
  id: string;
670
- source: "canonicalizer";
722
+ source: "canonicalizer" | "live-inspect";
671
723
  /** The analyzer that produced the facts citing this entry. */
672
724
  probe: string;
673
725
  /**
@@ -678,7 +730,157 @@ export interface ExplainEvidence {
678
730
  * drawn from live responses.
679
731
  */
680
732
  basis: "direct" | "heuristic" | "derived";
681
- outcome: "ok" | "empty" | "timeout" | "transport-error";
733
+ outcome:
734
+ | "ok"
735
+ | "empty"
736
+ | "timeout"
737
+ | "transport-error"
738
+ | "auth-error"
739
+ | "unsupported"
740
+ | "skipped"
741
+ | "interrupted"
742
+ | "invalid-response";
743
+ /** Live observation provenance; absent on canonicalizer evidence. */
744
+ version?: string;
745
+ observedAt?: string;
746
+ statementIds?: string[];
747
+ path?: string;
748
+ coverage?: ExplainSpanRange;
749
+ inputSha256?: string;
750
+ normalization?: "original-utf8" | "sub-per-non-ascii-byte";
751
+ reason?: string;
752
+ errorCode?: CentrsError["code"];
753
+ /**
754
+ * The facet a live probe served; an `empty` facet answer is not a warning.
755
+ * `types` is the value-type probes (#225), which run on every live call.
756
+ */
757
+ facet?: "schema" | "complete" | "types";
758
+ }
759
+
760
+ /** One `request=syntax` row, verbatim: the device's declared help for one argument. */
761
+ export interface ExplainSyntaxRow {
762
+ symbol: string;
763
+ /** RouterOS `symbol-type` (`definition`, `explanation`, …). */
764
+ kind: string;
765
+ text: string;
766
+ /** RouterOS `nested` depth. */
767
+ depth: number;
768
+ }
769
+
770
+ /** A menu or verb under a described menu, with counts when it was expanded. */
771
+ export interface ExplainSchemaChild {
772
+ name: string;
773
+ verbs?: number;
774
+ menus?: number;
775
+ arguments?: number;
776
+ ev?: string;
777
+ }
778
+
779
+ export interface ExplainSchemaArgument {
780
+ name: string;
781
+ /** Argument-level `syntax` rows, present when within the probe budget. */
782
+ syntax?: ExplainSyntaxRow[];
783
+ ev?: string;
784
+ }
785
+
786
+ /**
787
+ * `--schema`: what the device declares at one path (#492). `child` decides
788
+ * the node; a menu lists verbs and submenus, a command its arguments, `print`
789
+ * also its `.proplist`. Declared facts only — never print rows or state.
790
+ */
791
+ export interface ExplainSchema {
792
+ /** The `child` probe on the described path. */
793
+ ev: string;
794
+ path: string;
795
+ statementId?: string;
796
+ node: "menu" | "command" | "argument" | "unknown";
797
+ verbs?: ExplainSchemaChild[];
798
+ menus?: ExplainSchemaChild[];
799
+ arguments?: ExplainSchemaArgument[];
800
+ /** Output-field names a `print` can show; not print rows. */
801
+ proplist?: {
802
+ ev: string;
803
+ source: "print-proplist" | "get-value-name";
804
+ names: string[];
805
+ };
806
+ /** Argument node only: its `syntax` rows. */
807
+ syntax?: ExplainSyntaxRow[];
808
+ /** Full sizes as the device reported them, before any list was cut. */
809
+ counts: {
810
+ verbs?: number;
811
+ menus?: number;
812
+ arguments?: number;
813
+ proplist?: number;
814
+ };
815
+ /** A list was cut or children were left unexpanded. */
816
+ truncated: boolean;
817
+ /** Narrower inputs that expand what this result left out. */
818
+ next: string[];
819
+ reason?: string;
820
+ }
821
+
822
+ export interface ExplainCompletionCandidate {
823
+ text: string;
824
+ /** `variable`: a name in a `where` clause, which RouterOS scopes as a variable. */
825
+ kind: "menu" | "verb" | "argument" | "variable" | "value";
826
+ /** `exact` when the typed prefix already spells the whole candidate. */
827
+ match: "partial" | "exact";
828
+ /** The input-completion probe that offered it. */
829
+ ev: string;
830
+ }
831
+
832
+ /**
833
+ * `--complete`: what may follow at the cursor (#492). Every candidate is an
834
+ * observation: the device's input completion, cited by `ev`. It is never a
835
+ * closed set, and a value may reflect configuration state (interface names).
836
+ * Declared facts (`child`, argument `syntax`) live in {@link ExplainSchema}.
837
+ */
838
+ export interface ExplainCompletion {
839
+ /** Analyzed byte offset; equals the device's UTF-8 byte offset. */
840
+ cursor: number;
841
+ /** The cursor in the original document: 0-based line, UTF-16 character. */
842
+ at: { line: number; character: number };
843
+ statementId?: string;
844
+ context: "path" | "argument-name" | "variable" | "value" | "unsupported";
845
+ /** Bytes a chosen candidate replaces; `end` is the cursor. */
846
+ replace: ExplainSpanRange;
847
+ prefix: string;
848
+ /** The command at the cursor, when known (argument-name and value contexts). */
849
+ path?: string;
850
+ /** Value context: the argument (or `where` property) whose value is being completed. */
851
+ argument?: string;
852
+ /** Exact argument name: whether the device offers `=` at the cursor. */
853
+ takesValue?: boolean;
854
+ candidates: ExplainCompletionCandidate[];
855
+ /** Argument value context: argument-level `syntax` rows (type information). */
856
+ syntax?: ExplainSyntaxRow[];
857
+ count: number;
858
+ truncated: boolean;
859
+ reason?: string;
860
+ }
861
+
862
+ export interface ExplainLiveData {
863
+ environment?: {
864
+ ev: string;
865
+ version: string;
866
+ architecture?: string;
867
+ board?: string;
868
+ };
869
+ /** Exact parse output; absent when empty, skipped or unavailable. */
870
+ parse?: {
871
+ ev: string;
872
+ output: string;
873
+ rejected: boolean;
874
+ position?: { line: number; column: number };
875
+ };
876
+ /** Raw device classes, retained separately from the centrs span vocabulary. */
877
+ highlight?: { ev: string; classes: string[] };
878
+ arguments: {
879
+ ev: string;
880
+ path: string;
881
+ statementIds: string[];
882
+ names: string[];
883
+ }[];
682
884
  }
683
885
 
684
886
  export interface ExplainData {
@@ -689,6 +891,12 @@ export interface ExplainData {
689
891
  symbols: ExplainSymbols;
690
892
  values: ExplainValues;
691
893
  spans: ExplainSpan[];
894
+ /** Read-only device observations, present only on live calls. */
895
+ live?: ExplainLiveData;
896
+ /** Live `--schema` only. */
897
+ schema?: ExplainSchema;
898
+ /** Live `--complete` only. */
899
+ completion?: ExplainCompletion;
692
900
  /**
693
901
  * Total, gapless token partition of `[0, input.bytes)`.
694
902
  *
@@ -711,8 +919,8 @@ export interface ExplainData {
711
919
 
712
920
  export interface ExplainOperationMeta {
713
921
  command: "explain";
714
- /** `offline` is the only mode phase 1 has; live evidence is phase 2. */
715
- mode: "offline";
922
+ /** Whether a target was consulted for read-only evidence. */
923
+ mode: "offline" | "live";
716
924
  statementCount: number;
717
925
  verdict: ExplainVerdict;
718
926
  }
@@ -750,6 +958,8 @@ const EV = {
750
958
  braces: "e14",
751
959
  separators: "e15",
752
960
  escapes: "e16",
961
+ spaced: "e17",
962
+ groups: "e18",
753
963
  } as const;
754
964
 
755
965
  type EvidenceKey = keyof typeof EV;
@@ -904,6 +1114,33 @@ const EVIDENCE: Record<EvidenceKey, ExplainEvidence> = {
904
1114
  basis: "heuristic",
905
1115
  outcome: "ok",
906
1116
  },
1117
+ /**
1118
+ * `heuristic`: which adjacent operands could be the spaced spelling is read
1119
+ * from the token shapes alone. That the device pairs them, and marks the gap
1120
+ * `syntax-obsolete`, is grounded (`src/explain/spaced-args.ts`); which pairs
1121
+ * it pairs is per-command schema.
1122
+ */
1123
+ spaced: {
1124
+ id: EV.spaced,
1125
+ source: "canonicalizer",
1126
+ probe: "findSpacedPairs",
1127
+ basis: "heuristic",
1128
+ outcome: "ok",
1129
+ },
1130
+ /**
1131
+ * `heuristic`: every rejection it reports is a `:parse` answer
1132
+ * (`src/explain/group-faults.ts`), but which group is an array, an
1133
+ * expression or a query, and which token a property's parser would read
1134
+ * instead, rests on the brace-role and `where` readings a live probe could
1135
+ * overturn.
1136
+ */
1137
+ groups: {
1138
+ id: EV.groups,
1139
+ source: "canonicalizer",
1140
+ probe: "findGroupFaults",
1141
+ basis: "heuristic",
1142
+ outcome: "ok",
1143
+ },
907
1144
  };
908
1145
 
909
1146
  /** Diagnostic rendering for each defect class. */
@@ -933,6 +1170,13 @@ const DEFECT_DIAGNOSTICS: Record<
933
1170
  message: () =>
934
1171
  'invalid escape in string: unknown escape, truncated hex, or lowercase hex digit — use \\n \\r \\t \\" \\\\ \\$ \\_ \\? \\a \\b \\f \\v, \\XX with uppercase hex, or \\ before whitespace to continue the line',
935
1172
  },
1173
+ // #506. The device's answer for every follower but a name, `"`, `(` and
1174
+ // `[` (`src/explain/quoted-string.ts`); the span is the `$` and that byte.
1175
+ "bad-string-variable": {
1176
+ severity: "error",
1177
+ message: () =>
1178
+ `\`$\` in a string must start a variable name (\`$v\`, \`$"v"\`), \`$(…)\` or \`$[…]\`, and RouterOS rejects it (\`syntax error\`) — write \`\\$\` for a literal dollar`,
1179
+ },
936
1180
  "bad-sigil": {
937
1181
  severity: "error",
938
1182
  message: () => "invalid sigil: the run must be zero or one character",
@@ -1221,11 +1465,24 @@ export function buildTokens(
1221
1465
  return out;
1222
1466
  }
1223
1467
 
1468
+ /** Source order, with the most severe finding first at the same byte. */
1469
+ export function compareExplainDiagnostics(
1470
+ a: ExplainDiagnostic,
1471
+ b: ExplainDiagnostic,
1472
+ ): number {
1473
+ return (
1474
+ a.span.start - b.span.start ||
1475
+ severityRank(b.severity) - severityRank(a.severity)
1476
+ );
1477
+ }
1478
+
1224
1479
  function severityRank(s: ExplainSeverity): number {
1225
1480
  return s === "error" ? 2 : s === "warning" ? 1 : 0;
1226
1481
  }
1227
1482
 
1228
- function verdictOf(diagnostics: readonly ExplainDiagnostic[]): ExplainVerdict {
1483
+ export function verdictOf(
1484
+ diagnostics: readonly ExplainDiagnostic[],
1485
+ ): ExplainVerdict {
1229
1486
  let worst = 0;
1230
1487
  for (const d of diagnostics)
1231
1488
  worst = Math.max(worst, severityRank(d.severity));
@@ -1284,6 +1541,18 @@ export function explainCommand(
1284
1541
  // `analyzed` is ASCII by construction, so the offsets need no coordinate test.
1285
1542
  const analyzedRange = documentRange(analyzed, coordinates.ascii);
1286
1543
  const segmented = segmentStatements(input);
1544
+ if (segmented.discardFrom !== undefined)
1545
+ return withDiscardedTail(
1546
+ explainCommand(
1547
+ input.slice(
1548
+ 0,
1549
+ runAtByte(coordinates, segmented.discardFrom).utf16Start,
1550
+ ),
1551
+ options,
1552
+ ),
1553
+ coordinates,
1554
+ segmented.discardFrom,
1555
+ );
1287
1556
  const statementAnalysis = resolveStatements(input);
1288
1557
  const sourceRange = coordinates.ascii ? analyzedRange : undefined;
1289
1558
  const verbs = resolveVerbsFromStatements(statementAnalysis, sourceRange);
@@ -1341,8 +1610,14 @@ export function explainCommand(
1341
1610
  // segments and pairing the two by index attaches the wrong span to every statement after
1342
1611
  // the first block. Each split carries its own document-space span.
1343
1612
  //
1344
- const readStatements: ExplainStatement[] = verbs.splits.map((split) =>
1345
- statementOf(split, analyzed, analyzedRange),
1613
+ const readStatements: ExplainStatement[] = verbs.splits.map((split, index) =>
1614
+ statementOf(
1615
+ split,
1616
+ analyzed,
1617
+ analyzedRange,
1618
+ index,
1619
+ statementAnalysis.statements[index]?.ownership?.parent,
1620
+ ),
1346
1621
  );
1347
1622
  const canonical = canonicalizeExecuteCommand(input);
1348
1623
  // The skip-tolerant token stream every TOKEN-LEVEL rule reads (#316), one
@@ -1366,17 +1641,38 @@ export function explainCommand(
1366
1641
  ? findMissingSeparators(argumentTokens[index] ?? [])
1367
1642
  : [],
1368
1643
  );
1644
+ // #350: the same order for the space-for-`=` spelling. Root directives are
1645
+ // excluded because their operands are positional by grammar
1646
+ // (`src/explain/spaced-args.ts`).
1647
+ const spaced = readStatements.map((statement, index) =>
1648
+ statement.resolution === "resolved" &&
1649
+ statement.kind === "command" &&
1650
+ statement.command.path !== "/"
1651
+ ? findSpacedPairs(argumentTokens[index] ?? [])
1652
+ : [],
1653
+ );
1369
1654
  const gated = enforceGateParity(readStatements, canonical);
1370
1655
  const statements = gated.map((statement, index) => {
1371
1656
  const runs = separators[index] ?? [];
1657
+ const pairs = spaced[index] ?? [];
1658
+ const separated = withoutSeparatedArguments(statement, runs);
1659
+ const unpaired = withoutSpacedArguments(separated, pairs);
1372
1660
  return withStatementTransport(
1373
- withoutSeparatedArguments(statement, runs),
1661
+ unpaired,
1374
1662
  verbs.splits[index]?.text ?? "",
1375
1663
  options,
1376
1664
  runs.length === 0 ? undefined : rejectedBySeparator(runs),
1665
+ // Only a reading this step withdrew. One the lexer already refused
1666
+ // (`source {…}`, `[find]`) keeps the `execute` line it had.
1667
+ unpaired === separated ? undefined : unpairedBySpacing(pairs),
1377
1668
  );
1378
1669
  });
1379
1670
 
1671
+ const braceDiagnostics = invalidCommandBraceDiagnostics(
1672
+ verbs.splits,
1673
+ analyzed,
1674
+ analyzedRange,
1675
+ );
1380
1676
  const diagnostics: ExplainDiagnostic[] = [
1381
1677
  ...defects.map(({ defect: d, ev }) => {
1382
1678
  const render = DEFECT_DIAGNOSTICS[d.code];
@@ -1388,14 +1684,21 @@ export function explainCommand(
1388
1684
  ev,
1389
1685
  };
1390
1686
  }),
1391
- ...invalidCommandBraceDiagnostics(verbs.splits, analyzed, analyzedRange),
1687
+ ...braceDiagnostics,
1688
+ ...groupFaultDiagnostics(
1689
+ findGroupFaults(
1690
+ analyzed,
1691
+ analyzedRange.masked,
1692
+ defects.find(({ defect }) => defect.code === "bom")?.defect.end,
1693
+ ),
1694
+ braceDiagnostics,
1695
+ ),
1392
1696
  ...separators.flatMap((runs) => runs.map(missingSeparatorDiagnostic)),
1697
+ ...spaced.flatMap((pairs) =>
1698
+ pairs.filter((pair) => pair.valueShaped).map(spacedArgumentDiagnostic),
1699
+ ),
1393
1700
  ...statements.flatMap((s) => diagnosticsForStatement(s)),
1394
- ].sort(
1395
- (a, b) =>
1396
- a.span.start - b.span.start ||
1397
- severityRank(b.severity) - severityRank(a.severity),
1398
- );
1701
+ ].sort(compareExplainDiagnostics);
1399
1702
 
1400
1703
  const valueFacts = valuesOf(
1401
1704
  verbs.splits,
@@ -1428,14 +1731,73 @@ export function explainCommand(
1428
1731
  ),
1429
1732
  };
1430
1733
 
1734
+ const blocks: ExplainBlock[] = scopeBlocks(input).map((b) => ({
1735
+ name: b.name,
1736
+ span: { start: b.start, end: b.start + b.body.length },
1737
+ ev: EV.blocks,
1738
+ }));
1739
+ // Link the existing outer-block inventory in UTF-16 source coordinates.
1740
+ // Q4's traversal supplies parentage even when Unicode widened descendant spans.
1741
+ const sourceOffset = (byte: number): number =>
1742
+ coordinates.ascii
1743
+ ? byte
1744
+ : byte === coordinates.analyzed.length
1745
+ ? input.length
1746
+ : runAtByte(coordinates, byte).utf16Start;
1747
+ const roots = statements.filter(
1748
+ (statement) => statement.parent === undefined,
1749
+ );
1750
+ let rootAt = 0;
1751
+ const blockIndexes = new Map<number, number>();
1752
+ for (const [index, block] of blocks.entries()) {
1753
+ blockIndexes.set(block.span.start, index);
1754
+ while (
1755
+ roots[rootAt] !== undefined &&
1756
+ sourceOffset((roots[rootAt] as ExplainStatement).span.end) <
1757
+ block.span.start
1758
+ )
1759
+ rootAt++;
1760
+ const owner = roots[rootAt];
1761
+ if (
1762
+ owner !== undefined &&
1763
+ sourceOffset(owner.span.start) <= block.span.start &&
1764
+ sourceOffset(owner.span.end) >= block.span.end
1765
+ )
1766
+ block.owner = owner.id;
1767
+ }
1768
+ for (const [index, statement] of statements.entries()) {
1769
+ const ownership = statementAnalysis.statements[index]?.ownership;
1770
+ if (ownership === undefined) continue;
1771
+ const parent = statements[ownership.parent] as ExplainStatement;
1772
+ const block =
1773
+ parent.block ??
1774
+ (parent.parent === undefined
1775
+ ? blockIndexes.get(
1776
+ sourceOffset(parent.span.start) + ownership.bodyStart,
1777
+ )
1778
+ : undefined);
1779
+ if (block !== undefined) statement.block = block;
1780
+ }
1781
+ // Publish analyzed-byte spans only after ownership has used source offsets.
1782
+ // Shallow blocks are disjoint and ordered, so one forward walk maps both
1783
+ // boundaries without scanning or encoding a source prefix for every body.
1784
+ if (!coordinates.ascii) {
1785
+ let runAt = 0;
1786
+ const byteOffset = (offset: number): number => {
1787
+ while ((coordinates.runs[runAt]?.utf16Start ?? Infinity) < offset)
1788
+ runAt++;
1789
+ return coordinates.runs[runAt]?.byteStart ?? coordinates.analyzed.length;
1790
+ };
1791
+ for (const block of blocks)
1792
+ block.span = {
1793
+ start: byteOffset(block.span.start),
1794
+ end: byteOffset(block.span.end),
1795
+ };
1796
+ }
1431
1797
  const structure: ExplainStructure = {
1432
1798
  statementCount: statements.length,
1433
1799
  statements,
1434
- blocks: scopeBlocks(input).map((b) => ({
1435
- name: b.name,
1436
- span: { start: b.start, end: b.start + b.body.length },
1437
- ev: EV.blocks,
1438
- })),
1800
+ blocks,
1439
1801
  containsWrite: renderWriteVerdict(write.verdict),
1440
1802
  subcommands: brackets.resolutions.map(subcommandOf),
1441
1803
  // `containsWrite` is the fact `structure` itself asserts; the statements
@@ -1604,12 +1966,83 @@ export function explainCommand(
1604
1966
  };
1605
1967
  }
1606
1968
 
1969
+ /** The code the execute gate refuses although it is a warning (#504). */
1970
+ export const DISCARDED_CLOSE_CODE = "explain/canonicalizer/discarded-close";
1971
+
1972
+ /**
1973
+ * The reading of a script RouterOS stops reading early (#504).
1974
+ *
1975
+ * A `}` or `]` that closes nothing at the top level ends the program on the
1976
+ * device: it accepts the script and silently discards that byte and everything
1977
+ * after it (`segment.ts` → `discardFrom`). So `read` is the analysis of the
1978
+ * prefix the device runs. What is added back is the whole input's coordinate
1979
+ * facts, the tail's one `unclassified` token, and a `warning` that spans the
1980
+ * discarded bytes. It is a warning because nothing was rejected; it is refused
1981
+ * by the execute gate all the same, because running a script that is not the
1982
+ * one the operator wrote is what validation exists to stop.
1983
+ */
1984
+ function withDiscardedTail(
1985
+ read: ExplainData,
1986
+ coordinates: CoordinateAnalysis,
1987
+ from: number,
1988
+ ): ExplainData {
1989
+ const bytes = coordinates.analyzed.length;
1990
+ const close = String.fromCharCode(coordinates.analyzed[from] as number);
1991
+ const diagnostics = [
1992
+ ...read.diagnostics,
1993
+ {
1994
+ code: DISCARDED_CLOSE_CODE,
1995
+ severity: "warning" as const,
1996
+ message: `stray \`${close}\` closes nothing: RouterOS accepts the script but stops reading here, silently discarding the \`${close}\` and everything after it — remove it, or add the opener it was meant to close`,
1997
+ span: { start: from, end: bytes },
1998
+ ev: EV.segment,
1999
+ },
2000
+ ];
2001
+ let tokens = read.tokens;
2002
+ if (tokens !== undefined) {
2003
+ const last = tokens.at(-1);
2004
+ tokens =
2005
+ last?.class === "unclassified" && last.end === from
2006
+ ? [...tokens.slice(0, -1), { ...last, end: bytes }]
2007
+ : [
2008
+ ...tokens,
2009
+ {
2010
+ start: from,
2011
+ end: bytes,
2012
+ class: "unclassified",
2013
+ ev: EV.coordinates,
2014
+ },
2015
+ ];
2016
+ }
2017
+ return {
2018
+ ...read,
2019
+ input: {
2020
+ bytes,
2021
+ normalized: !coordinates.ascii,
2022
+ truncated: false,
2023
+ positionMap: positionMap(coordinates),
2024
+ },
2025
+ verdict: verdictOf(diagnostics),
2026
+ ...(tokens === undefined ? {} : { tokens }),
2027
+ diagnostics,
2028
+ evidence: citedEvidence(
2029
+ read.structure,
2030
+ diagnostics,
2031
+ read.spans,
2032
+ read.symbols,
2033
+ read.values,
2034
+ tokens,
2035
+ ),
2036
+ };
2037
+ }
2038
+
1607
2039
  /** Attach transport only after the gate-parity guard has had the final word. */
1608
2040
  function withStatementTransport(
1609
2041
  statement: ExplainStatement,
1610
2042
  source: string,
1611
2043
  options: ExplainCommandOptions,
1612
2044
  rejected?: string,
2045
+ unpaired?: string,
1613
2046
  ): ExplainStatement {
1614
2047
  if (statement.kind !== "command" || statement.arguments === undefined)
1615
2048
  return statement;
@@ -1621,6 +2054,7 @@ function withStatementTransport(
1621
2054
  arguments: statement.arguments,
1622
2055
  source,
1623
2056
  ...(rejected === undefined ? {} : { rejected }),
2057
+ ...(unpaired === undefined ? {} : { unpaired }),
1624
2058
  },
1625
2059
  { renderCurl: options.curl, evidenceId: EV.transport },
1626
2060
  ),
@@ -1646,9 +2080,13 @@ function statementOf(
1646
2080
  split: DocumentVerbSplit,
1647
2081
  analyzed: string,
1648
2082
  analyzedRange: MaskedRange,
2083
+ index: number,
2084
+ parent?: number,
1649
2085
  ): ExplainStatement {
1650
2086
  const reading = readingOf(split);
1651
2087
  return {
2088
+ id: `s${index}`,
2089
+ ...(parent === undefined ? {} : { parent: `s${parent}` }),
1652
2090
  span: { start: split.span.start, end: split.span.end },
1653
2091
  ...(reading.kind === "command"
1654
2092
  ? withArguments(reading, split, analyzed, analyzedRange)
@@ -1851,6 +2289,163 @@ function rejectedBySeparator(runs: readonly MissingSeparator[]): string {
1851
2289
  return `a second command-shaped run (\`${first?.path} ${first?.verb}\`) sits in this operand stream with no \`;\` or newline before it, so this is not one accepted statement`;
1852
2290
  }
1853
2291
 
2292
+ /**
2293
+ * Withdraw an argument reading that may be the spaced spelling (#350).
2294
+ *
2295
+ * `read: true` with `args: {}` and the operands as positionals is an
2296
+ * affirmative claim that the list was read and names no argument, and the
2297
+ * device contradicts it: `comment "something" regexp 1.1` is
2298
+ * `comment=something;regexp=1.1`. Which adjacent words pair is per-command
2299
+ * schema, so neither reading is published. The statement stays `resolved`;
2300
+ * only the argument list is withdrawn, as #311 does.
2301
+ */
2302
+ function withoutSpacedArguments(
2303
+ statement: ExplainStatement,
2304
+ pairs: readonly SpacedPair[],
2305
+ ): ExplainStatement {
2306
+ if (pairs.length === 0 || statement.kind !== "command") return statement;
2307
+ if (statement.arguments?.read !== true) return statement;
2308
+ const { args: _dropped, ...command } = statement.command;
2309
+ return {
2310
+ ...statement,
2311
+ command,
2312
+ arguments: { read: false, why: unpairedBySpacing(pairs) },
2313
+ };
2314
+ }
2315
+
2316
+ /** The one sentence both the withdrawn argument list and transport give. */
2317
+ function unpairedBySpacing(pairs: readonly SpacedPair[]): string {
2318
+ const first = pairs[0];
2319
+ return `\`${first?.name} ${first?.value}\` may be an argument and its value with the \`=\` left out, which RouterOS accepts; offline has no per-command argument list to tell an argument name from a positional operand or a value-less flag`;
2320
+ }
2321
+
2322
+ /**
2323
+ * The spaced spelling, said out loud where the value proves it is not a flag.
2324
+ *
2325
+ * `warning`, not `error`: RouterOS accepts the form, but its own highlighter
2326
+ * marks the gap `syntax-obsolete`, which is RouterOS calling the spelling
2327
+ * deprecated. "Possible" because the name is unconfirmed offline;
2328
+ * `/system/script add zzznotanarg "beep"` is the same shape and the device
2329
+ * rejects it. A live `request=child` probe (#491) confirms the name.
2330
+ */
2331
+ function spacedArgumentDiagnostic(pair: SpacedPair): ExplainDiagnostic {
2332
+ return {
2333
+ code: "explain/canonicalizer/possible-spaced-argument",
2334
+ severity: "warning",
2335
+ message: `possible obsolete spelling: \`${pair.name} ${pair.value}\` reads as \`${pair.name}=${pair.value}\` if \`${pair.name}\` is an argument of this command — RouterOS accepts a space for the \`=\` but marks it obsolete; write \`${pair.name}=${pair.value}\``,
2336
+ span: { start: pair.span.start, end: pair.span.end },
2337
+ ev: EV.spaced,
2338
+ };
2339
+ }
2340
+
2341
+ const INVALID_COMMAND_BRACE =
2342
+ "brace arrays are not valid in command arguments — use a parenthesized comma list such as `(1,2)`, or a bare comma list where the argument schema accepts one";
2343
+
2344
+ /**
2345
+ * A `name={` with a script-like body that is not a proven script slot (#525).
2346
+ *
2347
+ * `warning`, not `error`: `down={ :beep }` lowers to `down-script=` on CHR
2348
+ * 7.24.5 and 7.23.8, while `comment={ :beep }` is a `syntax error` there, and
2349
+ * telling them apart needs the command's argument list, which is schema. The
2350
+ * brace is read as a body; the device decides the slot.
2351
+ */
2352
+ function possibleScriptBodyMessage(name: string): string {
2353
+ return `possible script-body abbreviation: \`${name}=\` with a \`{…}\` body may be a script-valued argument or abbreviate one; offline has no per-command argument list to confirm the slot, so the brace is read as a script body — device validation decides`;
2354
+ }
2355
+
2356
+ /**
2357
+ * The group faults as diagnostics (#505, #509, #511, #512).
2358
+ *
2359
+ * All `error`: each is a `:parse` rejection on CHR 7.24.5 and 7.23.8. An
2360
+ * empty `{}` that `invalidCommandBraceDiagnostics` already rejects as a brace
2361
+ * array in a command argument is one defect, so it is reported once, as that.
2362
+ * The span is the token the fault is about (the operator, the separator, the
2363
+ * `@`, or the whole empty group); the device's column is the byte after an
2364
+ * empty group or a dangling operator.
2365
+ */
2366
+ function groupFaultDiagnostics(
2367
+ faults: readonly GroupFault[],
2368
+ braces: readonly ExplainDiagnostic[],
2369
+ ): ExplainDiagnostic[] {
2370
+ const braceAt = new Set(braces.map((d) => d.span.start));
2371
+ return faults
2372
+ .filter(
2373
+ (f) =>
2374
+ !(
2375
+ f.code === "empty-group" &&
2376
+ f.detail === "{" &&
2377
+ braceAt.has(f.start)
2378
+ ) &&
2379
+ !(
2380
+ (f.code === "named-value-brace" || f.code === "glued-token") &&
2381
+ braceAt.has(f.start)
2382
+ ),
2383
+ )
2384
+ .map((f) => ({
2385
+ code:
2386
+ f.code === "named-value-brace"
2387
+ ? "explain/canonicalizer/invalid-command-brace"
2388
+ : `explain/canonicalizer/${f.code}`,
2389
+ severity: "error",
2390
+ message: groupFaultMessage(f),
2391
+ span: { start: f.start, end: f.end },
2392
+ ev: f.code === "named-value-brace" ? EV.values : EV.groups,
2393
+ }));
2394
+ }
2395
+
2396
+ function groupFaultMessage(f: GroupFault): string {
2397
+ switch (f.code) {
2398
+ case "empty-group":
2399
+ return f.detail === "("
2400
+ ? "empty expression: `()` has nothing to evaluate, and RouterOS rejects it (`syntax error`)"
2401
+ : "empty array: RouterOS rejects a `{}` that is the whole value of a statement or an argument (`syntax error`); a nested `{}` (`{1;{}}`) or one in parentheses (`({})`) parses";
2402
+ case "misplaced-separator":
2403
+ if (f.group === "{")
2404
+ return "`;` with no array element before it on its line: RouterOS rejects it (`syntax error`) — a `;` must follow an element, and a newline already separates elements";
2405
+ return f.detail === ";"
2406
+ ? "`;` inside `( … )`: an expression cannot hold a statement separator, and RouterOS rejects it (`syntax error`)"
2407
+ : "a newline inside `( … )` ends the statement in the middle of the expression, and RouterOS rejects it (`syntax error`) — join the lines, or end the line with `\\` to continue it";
2408
+ case "missing-operand":
2409
+ return `operator \`${f.detail}\` is missing an operand, and RouterOS rejects it (\`syntax error\`) — only \`-\`, \`!\`, \`>\`, \`~\` and \`any\` take a single operand after them; every other operator needs one on each side`;
2410
+ case "invalid-at-sign":
2411
+ return "unquoted `@` is a syntax error in a command word, an array or an expression — RouterOS accepts it only inside an argument value (`comment=a@b`); quote it, and drop a pasted console prompt such as `[admin@MikroTik] >`";
2412
+ case "named-value-brace":
2413
+ return INVALID_COMMAND_BRACE;
2414
+ case "glued-token":
2415
+ return 'nothing may follow a closed string, `$name` or group in the same token, and a bare word may not run into a `"`, `$` or bracket: RouterOS rejects it (`expected end of command`) — put a space between the two arguments, or join them inside an expression such as `("a" . $v)`';
2416
+ case "invalid-variable":
2417
+ return '`$` must be followed by a variable name (letters and digits) or `"name"`, and RouterOS rejects it here (`syntax error`) — quote a literal dollar (`"\\$"`)';
2418
+ case "invalid-name":
2419
+ return 'a variable name is letters and digits only, and RouterOS rejects any other byte in it (`expected end of command`) — quote the name (`:local "a_b"`) to use other characters';
2420
+ case "unquoted-non-ascii":
2421
+ case "unquoted-reserved-byte":
2422
+ return unquotedByteMessage(f);
2423
+ }
2424
+ }
2425
+
2426
+ /**
2427
+ * The unquoted-byte faults (#358, #371). The remedy follows the site: a value
2428
+ * can be quoted, an argument name must be corrected, and a path, command or
2429
+ * `$name` must lose the byte (a variable name may be quoted, `$"café"`).
2430
+ */
2431
+ function unquotedByteMessage(f: GroupFault): string {
2432
+ const what =
2433
+ f.code === "unquoted-non-ascii"
2434
+ ? "a non-ASCII character outside a string"
2435
+ : f.detail === "="
2436
+ ? "a second `=` in a bare argument"
2437
+ : `an unquoted \`${f.detail}\``;
2438
+ if (f.site === "argument-name")
2439
+ return `${what} in an argument name: RouterOS rejects the name at its first byte (\`expected end of command\`) — correct the argument name; no RouterOS argument name holds this byte`;
2440
+ if (f.site === "head-word")
2441
+ return `${what} in a path or command word: RouterOS rejects it (\`expected command name\` or \`expected end of command\`) — remove or retype the byte (a \`?\` is the console's help key, and a pasted non-breaking space or curly quote only looks like ASCII); a variable name may be quoted (\`$"café"\`)`;
2442
+ if (f.code === "unquoted-non-ascii")
2443
+ return `${what}: RouterOS reads only ASCII in a bare word, name or value, and rejects it (\`expected end of command\`) — quote it (\`name="café"\`, \`$"café"\`), or retype a pasted non-breaking space, curly quote or ellipsis`;
2444
+ return f.detail === "="
2445
+ ? `${what} value: RouterOS rejects it (\`expected end of command\`) — quote the value (\`comment="a=b"\`), as a base64 key ending in \`=\` needs`
2446
+ : `${what} is never part of a bare word, and RouterOS rejects it (\`expected end of command\`) — quote the value (\`url="http://x/a?b"\`)`;
2447
+ }
2448
+
1854
2449
  function invalidCommandBraceDiagnostics(
1855
2450
  splits: readonly DocumentVerbSplit[],
1856
2451
  analyzed: string,
@@ -1862,16 +2457,28 @@ function invalidCommandBraceDiagnostics(
1862
2457
  const { start, end } = split.span;
1863
2458
  const text = analyzed.slice(start, end);
1864
2459
  if (text !== split.text) continue;
1865
- // The verb splitter cannot yet flatten every relative nested menu block.
1866
- // Do not reinterpret a known submenu's leading `{` as an argument value,
1867
- // but retain diagnostics for rejected braces later in the same split.
1868
- // Require evidence that the brace actually opens a menu container
1869
- // (body starts with a submenu name), so `/ip/route/print {1;2}` and
1870
- // `/ip { firewall/filter/print {1;2} }` still diagnose the `{1;2}` array.
2460
+ // The segmenter flattens a relative submenu block only where the source
2461
+ // alone names the menu (#351, `menuBlockPath`): not after a navigation
2462
+ // statement (`/ip⏎address { … }`), and not for an abbreviated or
2463
+ // digit-led menu word. Those still reach here as one split. Do not
2464
+ // reinterpret a known submenu's leading `{` as an argument value, but
2465
+ // retain diagnostics for rejected braces later in the same split.
2466
+ // Require evidence that the brace actually opens a menu container, so
2467
+ // `/ip/route/print {1;2}` and `/ip { firewall/filter/print {1;2} }` still
2468
+ // diagnose the `{1;2}` array.
2469
+ //
2470
+ // A verb the vocabulary or the catalog names is no menu, so its leading
2471
+ // brace is a positional operand: `/system/script add { :beep }` and
2472
+ // `/system/reboot { :beep }` are rejected on CHR 7.24.5 (#496).
1871
2473
  const argsText = text.slice(split.argsAt);
1872
2474
  const leadingBraceAt = argsText.search(/\S/);
2475
+ const verbIsCommand =
2476
+ VERBS.has(split.verb) ||
2477
+ lookupPath([...split.path.split("/").filter(Boolean), split.verb])
2478
+ ?.kind === "command";
1873
2479
  let menuBraceAt: number | null = null;
1874
2480
  if (
2481
+ !verbIsCommand &&
1875
2482
  leadingBraceAt >= 0 &&
1876
2483
  argsText[leadingBraceAt] === "{" &&
1877
2484
  split.candidates.some((candidate) =>
@@ -1887,7 +2494,8 @@ function invalidCommandBraceDiagnostics(
1887
2494
  // A menu block body is a statement list, and a statement may be a
1888
2495
  // scripting directive or an ABSOLUTE command — neither of which the
1889
2496
  // enclosing menu can vouch for, and neither of which any array literal
1890
- // can start with. `/interface { ethernet { :put x } }` is corpus 521,
2497
+ // can start with. `/interface { ethernet { :put x } }` is the shape of
2498
+ // corpus script `forum/amm0/topic-184067-routeros-lsp-for-better-syntax-checking-command-completion-in-editors-like-vscod/post-0014-snippet-02.rsc`,
1891
2499
  // accepted on 7.21.5/7.23.5/7.24.2/7.25beta3 as
1892
2500
  // `(evl /interface/ethernet/ (evl /putmessage=…))` — #348.
1893
2501
  menuBraceAt = braceAt;
@@ -1924,19 +2532,28 @@ function invalidCommandBraceDiagnostics(
1924
2532
  }
1925
2533
  }
1926
2534
  }
1927
- for (const at of invalidCommandBraceOffsets(
2535
+ for (const finding of invalidCommandBraceOffsets(
1928
2536
  text,
1929
2537
  split.argsAt,
1930
2538
  split.path === "/" ? split.verb : undefined,
1931
2539
  nestedRange(analyzedRange, start, end),
1932
2540
  )) {
1933
- if (at === menuBraceAt) continue;
2541
+ if (finding.at === menuBraceAt) continue;
2542
+ if (finding.ambiguous) {
2543
+ out.push({
2544
+ code: "explain/canonicalizer/possible-script-body-abbreviation",
2545
+ severity: "warning",
2546
+ message: possibleScriptBodyMessage(finding.name ?? "name"),
2547
+ span: { start: start + finding.at, end: start + finding.at + 1 },
2548
+ ev: EV.values,
2549
+ });
2550
+ continue;
2551
+ }
1934
2552
  out.push({
1935
2553
  code: "explain/canonicalizer/invalid-command-brace",
1936
2554
  severity: "error",
1937
- message:
1938
- "brace arrays are not valid in command arguments — use a parenthesized comma list such as `(1,2)`, or a bare comma list where the argument schema accepts one",
1939
- span: { start: start + at, end: start + at + 1 },
2555
+ message: INVALID_COMMAND_BRACE,
2556
+ span: { start: start + finding.at, end: start + finding.at + 1 },
1940
2557
  ev: EV.values,
1941
2558
  });
1942
2559
  }
@@ -2107,6 +2724,7 @@ function subcommandOf(r: Resolution): ExplainSubcommand {
2107
2724
  ),
2108
2725
  );
2109
2726
  return {
2727
+ owner: `s${r.owner}`,
2110
2728
  span: { start: r.span.start, end: r.span.end },
2111
2729
  context: r.context,
2112
2730
  ...reading,
@@ -2251,7 +2869,7 @@ export function explainEnvelope(
2251
2869
  buildTip(
2252
2870
  "tip/explain-offline-only",
2253
2871
  "No router was given, so this is the canonicalizer's reading alone.",
2254
- "Completion, schema, and `:parse` evidence come from a live target (`centrs explain <router> '<input>'`), which is phase 2 and not accepted yet.",
2872
+ "Add a router (`centrs explain <router> '<input>'`) for read-only parse, highlight and argument-name evidence; `--schema` and `--complete` then describe paths and complete at the cursor.",
2255
2873
  ),
2256
2874
  ...(options.tips ?? []),
2257
2875
  ];
@@ -2260,7 +2878,7 @@ export function explainEnvelope(
2260
2878
  target: {},
2261
2879
  via: null,
2262
2880
  settings: settingsMeta(options.format),
2263
- validation: { enabled: false, result: "skipped" },
2881
+ validation: explainValidationMeta(),
2264
2882
  operation: {
2265
2883
  command: "explain",
2266
2884
  mode: "offline",
@@ -2285,7 +2903,7 @@ export function buildExplainFacetTip(facets: readonly string[]): Tip {
2285
2903
  return buildTip(
2286
2904
  "tip/explain-live-facets",
2287
2905
  `${named} enumerate what a device accepts, and no router was given — so nothing is enumerated here.`,
2288
- "Name a router once live evidence lands (phase 2); until then use `rosetta` for documented RouterOS schema facts.",
2906
+ "Name a router (`centrs explain <router> '<input>' --schema`) to ask the device; use `rosetta` for documented RouterOS schema facts.",
2289
2907
  );
2290
2908
  }
2291
2909
 
@@ -2419,10 +3037,23 @@ export function buildExplainErrorEnvelope(
2419
3037
  error: serializeCentrsError(centrs),
2420
3038
  warnings: [],
2421
3039
  tips,
2422
- meta: { target: {}, via: null, settings: settingsMeta(format) },
3040
+ meta: {
3041
+ target: {},
3042
+ via: null,
3043
+ settings: settingsMeta(format),
3044
+ validation: explainValidationMeta(),
3045
+ },
2423
3046
  };
2424
3047
  }
2425
3048
 
3049
+ /**
3050
+ * explain is not a gate: it never runs the input, so there is no gate verdict
3051
+ * to report, offline or live. Its verdict is `data.verdict` (#535).
3052
+ */
3053
+ export function explainValidationMeta(): EnvelopeValidationMeta {
3054
+ return { enabled: false };
3055
+ }
3056
+
2426
3057
  export function renderExplainEnvelope(
2427
3058
  envelope: ExplainEnvelope | ExplainErrorEnvelope,
2428
3059
  format: ExplainOutputFormat,
@@ -2484,7 +3115,85 @@ function renderValue(occurrence: ExplainValueOccurrence): string {
2484
3115
  const shapes = occurrence.facts.shapeHints?.values.join("|") ?? "unknown";
2485
3116
  const parent =
2486
3117
  occurrence.parent === undefined ? "" : ` in=${occurrence.parent}`;
2487
- return `${occurrence.kind.padEnd(10)}${name}${parent} shapes=${shapes}`;
3118
+ const observed = occurrence.facts.observedType;
3119
+ const schema = occurrence.facts.schemaType;
3120
+ const live = `${observed ? ` observed=${observed.value}(${observed.rendered})` : ""}${schema ? ` schema=${schema.values.join("|")}${schema.list ? "[list]" : ""}` : ""}`;
3121
+ return `${occurrence.kind.padEnd(10)}${name}${parent} shapes=${shapes}${live}`;
3122
+ }
3123
+
3124
+ function renderLiveSummary(live: ExplainLiveData): string {
3125
+ const device = live.environment
3126
+ ? `${live.environment.version}${live.environment.architecture ? ` ${live.environment.architecture}` : ""}`
3127
+ : "device unavailable";
3128
+ const parse = live.parse
3129
+ ? `parse ${live.parse.rejected ? "rejected" : "accepted"}${live.parse.position ? ` at ${live.parse.position.line}:${live.parse.position.column}` : ""}`
3130
+ : "parse unavailable";
3131
+ const highlight = live.highlight
3132
+ ? `highlight ${live.highlight.classes.length} byte(s)`
3133
+ : "highlight unavailable";
3134
+ const names = live.arguments.reduce(
3135
+ (total, entry) => total + entry.names.length,
3136
+ 0,
3137
+ );
3138
+ return `live: ${device} · ${parse} · ${highlight} · arguments ${live.arguments.length} path(s), ${names} name(s)`;
3139
+ }
3140
+
3141
+ /** Names only, at most a dozen per line; `--json` keeps every fact. */
3142
+ function renderSchemaSummary(schema: ExplainSchema): string[] {
3143
+ const list = (label: string, names: readonly string[], total?: number) =>
3144
+ ` ${label} (${total ?? names.length}): ${names.slice(0, 12).join(", ")}${(total ?? names.length) > Math.min(names.length, 12) ? ", …" : ""}`;
3145
+ const lines = [
3146
+ `schema: ${schema.path} is ${schema.node === "unknown" ? "unknown to the device" : `a ${schema.node}`}${schema.truncated ? " (truncated)" : ""}${schema.reason ? ` — ${schema.reason}` : ""}`,
3147
+ ];
3148
+ if (schema.verbs)
3149
+ lines.push(
3150
+ list(
3151
+ "verbs",
3152
+ schema.verbs.map((v) => v.name),
3153
+ schema.counts.verbs,
3154
+ ),
3155
+ );
3156
+ if (schema.menus?.length)
3157
+ lines.push(
3158
+ list(
3159
+ "menus",
3160
+ schema.menus.map((m) => m.name),
3161
+ schema.counts.menus,
3162
+ ),
3163
+ );
3164
+ if (schema.arguments)
3165
+ lines.push(
3166
+ list(
3167
+ "arguments",
3168
+ schema.arguments.map((a) => a.name),
3169
+ schema.counts.arguments,
3170
+ ),
3171
+ );
3172
+ if (schema.proplist)
3173
+ lines.push(list("proplist", schema.proplist.names, schema.counts.proplist));
3174
+ if (schema.syntax)
3175
+ for (const row of schema.syntax)
3176
+ lines.push(` ${row.symbol ? `${row.symbol}: ` : ""}${row.text}`);
3177
+ return lines;
3178
+ }
3179
+
3180
+ function renderCompletionSummary(completion: ExplainCompletion): string {
3181
+ const head = `complete @${completion.cursor}: ${completion.context}${completion.argument ? ` ${completion.argument}=` : ""}${completion.prefix ? ` "${completion.prefix}"` : ""}`;
3182
+ if (completion.reason && completion.candidates.length === 0)
3183
+ return `${head} — ${completion.reason}`;
3184
+ const shown = completion.candidates
3185
+ .slice(0, 12)
3186
+ .map((c) => (c.match === "exact" ? `${c.text}*` : c.text));
3187
+ const value =
3188
+ completion.takesValue === undefined
3189
+ ? ""
3190
+ : completion.takesValue
3191
+ ? " (takes a value: `=`)"
3192
+ : " (flag, no value)";
3193
+ const syntax = completion.syntax?.length
3194
+ ? ` [${completion.syntax.map((row) => row.text || row.symbol).join("; ")}]`
3195
+ : "";
3196
+ return `${head} → ${completion.count === 0 ? "no candidates" : `${shown.join(", ")}${completion.count > shown.length ? ", …" : ""}`}${value}${syntax}`;
2488
3197
  }
2489
3198
 
2490
3199
  /**
@@ -2514,6 +3223,9 @@ function renderExplainText(
2514
3223
  `gate: ${canonical.mode}${canonical.path ? ` ${canonical.path}` : ""}${canonical.verb ? ` ${canonical.verb}` : ""} · ${argCount} arg(s)${canonical.writeShaped ? " · write-shaped" : ""}`,
2515
3224
  );
2516
3225
  lines.push(`write: ${structure.containsWrite}`);
3226
+ if (data.live) lines.push(renderLiveSummary(data.live));
3227
+ if (data.schema) lines.push(...renderSchemaSummary(data.schema));
3228
+ if (data.completion) lines.push(renderCompletionSummary(data.completion));
2517
3229
  if (data.input.normalized)
2518
3230
  lines.push(
2519
3231
  `input: ${data.input.bytes} byte(s), normalized (non-ASCII stood in for one-for-one)`,