agentfootprint 6.24.0 → 6.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +31 -0
  2. package/bin/agentfootprint-lint-tools.mjs +14 -0
  3. package/dist/esm/lib/tool-lint/analyze.js +235 -0
  4. package/dist/esm/lib/tool-lint/analyze.js.map +1 -0
  5. package/dist/esm/lib/tool-lint/cli.js +198 -0
  6. package/dist/esm/lib/tool-lint/cli.js.map +1 -0
  7. package/dist/esm/lib/tool-lint/format.js +61 -0
  8. package/dist/esm/lib/tool-lint/format.js.map +1 -0
  9. package/dist/esm/lib/tool-lint/index.js +23 -0
  10. package/dist/esm/lib/tool-lint/index.js.map +1 -0
  11. package/dist/esm/lib/tool-lint/rules.js +249 -0
  12. package/dist/esm/lib/tool-lint/rules.js.map +1 -0
  13. package/dist/esm/lib/tool-lint/types.js +25 -0
  14. package/dist/esm/lib/tool-lint/types.js.map +1 -0
  15. package/dist/esm/observe.js +13 -0
  16. package/dist/esm/observe.js.map +1 -1
  17. package/dist/esm/recorders/observability/ToolChoiceRecorder.js +261 -0
  18. package/dist/esm/recorders/observability/ToolChoiceRecorder.js.map +1 -0
  19. package/dist/lib/tool-lint/analyze.js +242 -0
  20. package/dist/lib/tool-lint/analyze.js.map +1 -0
  21. package/dist/lib/tool-lint/cli.js +203 -0
  22. package/dist/lib/tool-lint/cli.js.map +1 -0
  23. package/dist/lib/tool-lint/format.js +65 -0
  24. package/dist/lib/tool-lint/format.js.map +1 -0
  25. package/dist/lib/tool-lint/index.js +43 -0
  26. package/dist/lib/tool-lint/index.js.map +1 -0
  27. package/dist/lib/tool-lint/rules.js +256 -0
  28. package/dist/lib/tool-lint/rules.js.map +1 -0
  29. package/dist/lib/tool-lint/types.js +26 -0
  30. package/dist/lib/tool-lint/types.js.map +1 -0
  31. package/dist/observe.js +34 -1
  32. package/dist/observe.js.map +1 -1
  33. package/dist/recorders/observability/ToolChoiceRecorder.js +266 -0
  34. package/dist/recorders/observability/ToolChoiceRecorder.js.map +1 -0
  35. package/dist/types/lib/tool-lint/analyze.d.ts +84 -0
  36. package/dist/types/lib/tool-lint/analyze.d.ts.map +1 -0
  37. package/dist/types/lib/tool-lint/cli.d.ts +44 -0
  38. package/dist/types/lib/tool-lint/cli.d.ts.map +1 -0
  39. package/dist/types/lib/tool-lint/format.d.ts +19 -0
  40. package/dist/types/lib/tool-lint/format.d.ts.map +1 -0
  41. package/dist/types/lib/tool-lint/index.d.ts +24 -0
  42. package/dist/types/lib/tool-lint/index.d.ts.map +1 -0
  43. package/dist/types/lib/tool-lint/rules.d.ts +86 -0
  44. package/dist/types/lib/tool-lint/rules.d.ts.map +1 -0
  45. package/dist/types/lib/tool-lint/types.d.ts +156 -0
  46. package/dist/types/lib/tool-lint/types.d.ts.map +1 -0
  47. package/dist/types/observe.d.ts +2 -0
  48. package/dist/types/observe.d.ts.map +1 -1
  49. package/dist/types/recorders/observability/ToolChoiceRecorder.d.ts +165 -0
  50. package/dist/types/recorders/observability/ToolChoiceRecorder.d.ts.map +1 -0
  51. package/package.json +4 -2
@@ -0,0 +1,84 @@
1
+ /**
2
+ * analyzeToolCatalog — the tool-catalog confusability lint
3
+ * (RFC-002 block C1, the adoption front door).
4
+ *
5
+ * Pattern: policy layer over `pairwiseSimilarity` (influence-core) — the
6
+ * geometry is computed there; thresholds, verdicts, hints and
7
+ * the structural rule pack live here. Everything is consumer-
8
+ * injectable with our defaults (the plug-and-play meta-pattern).
9
+ * Role: `src/lib/tool-lint/`. ZERO stack buy-in — plain
10
+ * `{ name, description?, inputSchema? }[]` in, report out.
11
+ * `catalogFromTools` adapts the library's own `Tool[]`;
12
+ * `coerceCatalog` (cli.ts) normalizes OpenAI/Anthropic/MCP
13
+ * shapes.
14
+ *
15
+ * ## What is embedded (and why)
16
+ *
17
+ * `confusabilityText(tool)` = tokenized name + ': ' + description. The
18
+ * model differentiates tools by name AND description together, so two
19
+ * tools with near-identical names and overlapping descriptions ARE the
20
+ * confusability case (`get_fcns_database` vs `influx_get_fcns_database`)
21
+ * — embedding only the prose would miss the name signal.
22
+ *
23
+ * ## Calibration (RFC-002 §3 — read this before trusting verdicts)
24
+ *
25
+ * Absolute cosine ranges are PER-EMBEDDER. The default threshold (0.85)
26
+ * is a starting point for real sentence embedders. The test/demo
27
+ * `mockEmbedder` (character-frequency) compresses unrelated prose into
28
+ * ~0.85–0.97 — with it, use `MOCK_EMBEDDER_CALIBRATION` and trust only
29
+ * the RELATIVE ordering in `report.similarity.ranked` (the acceptance
30
+ * fixtures assert ordering, never absolute scores).
31
+ */
32
+ import type { Tool } from '../../core/tools.js';
33
+ import type { AnalyzeToolCatalogOptions, CatalogTool, ToolCatalogReport } from './types.js';
34
+ /** Default `confusabilityThreshold` — a starting point for REAL sentence
35
+ * embedders (unrelated tool descriptions typically land 0.3–0.7).
36
+ * Calibrate per embedder; meaningless for the mock (see below). */
37
+ export declare const DEFAULT_CONFUSABILITY_THRESHOLD = 0.85;
38
+ /** Default `watchBand` below the threshold. */
39
+ export declare const DEFAULT_WATCH_BAND = 0.05;
40
+ /**
41
+ * Threshold/band calibrated for the char-frequency `mockEmbedder` on
42
+ * realistic tool prose (seed corpus: the Neo SAN catalog). The mock
43
+ * compresses unrelated descriptions into ~0.85–0.97 cosine, so expect
44
+ * false positives even at 0.94 — with the mock, the RELATIVE ordering
45
+ * of `report.similarity.ranked` is the trustworthy signal; absolute
46
+ * verdicts are only honest with a real embedder + per-embedder
47
+ * calibration.
48
+ */
49
+ export declare const MOCK_EMBEDDER_CALIBRATION: Readonly<{
50
+ confusabilityThreshold: 0.94;
51
+ watchBand: 0.02;
52
+ }>;
53
+ /**
54
+ * Adapt the library's `Tool[]` (from `defineTool` / `Agent.tool`) to the
55
+ * lint's plain catalog shape. Trivial on purpose: `Tool.schema` already
56
+ * IS `{ name, description, inputSchema }`.
57
+ */
58
+ export declare function catalogFromTools(tools: readonly Tool[]): readonly CatalogTool[];
59
+ /**
60
+ * The text the confusability analysis embeds for one tool: the name with
61
+ * `_`/`-`/camelCase boundaries opened into words, then the description.
62
+ * Exported so consumers can reproduce or replace the construction.
63
+ */
64
+ export declare function confusabilityText(tool: CatalogTool): string;
65
+ /**
66
+ * Lint a tool catalog: pairwise confusability over what the model reads
67
+ * (when an embedder is supplied) + the structural rule pack. Returns a
68
+ * report whose `ok` is the CI gate.
69
+ *
70
+ * Duplicate tool names are themselves reported as structural errors
71
+ * (rule `duplicate-name`, built-in precondition — a catalog where two
72
+ * tools share a name is broken before any similarity question); the
73
+ * duplicates are dropped from the similarity analysis (first one wins).
74
+ */
75
+ export declare function analyzeToolCatalog(tools: readonly CatalogTool[], options?: AnalyzeToolCatalogOptions): Promise<ToolCatalogReport>;
76
+ /**
77
+ * Suggest the DIFFERENTIATING AXIS for a flagged pair. Heuristic: when
78
+ * the names are near-twins (≤2 distinct tokens), the qualifier IS the
79
+ * axis — the descriptions must say when to choose each variant. When the
80
+ * names differ, surface the few description terms each tool does NOT
81
+ * share, as the place to anchor an explicit choice condition.
82
+ */
83
+ export declare function differentiationHint(a: CatalogTool, b: CatalogTool): string;
84
+ //# sourceMappingURL=analyze.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analyze.d.ts","sourceRoot":"","sources":["../../../../src/lib/tool-lint/analyze.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAGhD,OAAO,KAAK,EACV,yBAAyB,EACzB,WAAW,EAGX,iBAAiB,EAClB,MAAM,YAAY,CAAC;AAEpB;;oEAEoE;AACpE,eAAO,MAAM,+BAA+B,OAAO,CAAC;AAEpD,+CAA+C;AAC/C,eAAO,MAAM,kBAAkB,OAAO,CAAC;AAEvC;;;;;;;;GAQG;AACH,eAAO,MAAM,yBAAyB;;;EAGpC,CAAC;AAEH;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,SAAS,WAAW,EAAE,CAM/E;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM,CAO3D;AAED;;;;;;;;;GASG;AACH,wBAAsB,kBAAkB,CACtC,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,GAAE,yBAA8B,GACtC,OAAO,CAAC,iBAAiB,CAAC,CAyF5B;AA4CD;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,EAAE,WAAW,GAAG,MAAM,CA6B1E"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Tool-lint CLI core (RFC-002 block C3 — the CI gate).
3
+ *
4
+ * Pattern: humble shell — `bin/agentfootprint-lint-tools.mjs` is a
5
+ * 3-line wrapper; ALL behavior (arg parsing, catalog coercion,
6
+ * report, exit code) lives here so it is unit-testable without
7
+ * spawning a process.
8
+ * Role: `src/lib/tool-lint/`. Reads ONE JSON file of tools, prints a
9
+ * report, returns the process exit code:
10
+ * 0 — report.ok
11
+ * 1 — findings failed the gate (!ok)
12
+ * 2 — usage / input error (bad flags, unreadable file,
13
+ * unrecognized JSON shape)
14
+ *
15
+ * ## Embedder & gating honesty
16
+ *
17
+ * The CLI has no way to receive a consumer embedder, so it uses the
18
+ * built-in deterministic mock (char-frequency, offline, dependency-free)
19
+ * for the similarity RANKING — and, by default, does NOT gate on it:
20
+ * without `--threshold`, similarity is report-only (relative ordering +
21
+ * watch hints) and the exit code reflects structural findings alone.
22
+ * Pass `--threshold` to make confusable pairs fail the gate — you own
23
+ * the calibration at that point (start from
24
+ * `MOCK_EMBEDDER_CALIBRATION.confusabilityThreshold` = 0.94). For real
25
+ * embedder gating, use `analyzeToolCatalog` from
26
+ * `agentfootprint/observe` in a small script instead.
27
+ */
28
+ import type { CatalogTool } from './types.js';
29
+ export interface ToolLintCliIO {
30
+ readonly stdout: (line: string) => void;
31
+ readonly stderr: (line: string) => void;
32
+ }
33
+ /**
34
+ * Normalize any of the recognized tool-list JSON shapes to the lint's
35
+ * plain catalog. Throws (with a shape description) on unrecognized
36
+ * input — the CLI maps that to exit code 2.
37
+ */
38
+ export declare function coerceCatalog(json: unknown): readonly CatalogTool[];
39
+ /**
40
+ * Run the lint CLI. Returns the exit code (never calls `process.exit` —
41
+ * the bin wrapper assigns it to `process.exitCode`).
42
+ */
43
+ export declare function runToolLintCli(argv: readonly string[], io?: ToolLintCliIO): Promise<number>;
44
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../../../src/lib/tool-lint/cli.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAMH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACxC,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC;AAqBD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,OAAO,GAAG,SAAS,WAAW,EAAE,CAuCnE;AAmDD;;;GAGG;AACH,wBAAsB,cAAc,CAClC,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,EAAE,GAAE,aAKH,GACA,OAAO,CAAC,MAAM,CAAC,CAkDjB"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * formatToolCatalogReport — human-readable rendering of a lint report.
3
+ *
4
+ * Pattern: pure presenter. One report → one string; used verbatim by the
5
+ * CLI (`agentfootprint-lint-tools`) and the examples so output
6
+ * stays byte-identical across surfaces.
7
+ * Role: `src/lib/tool-lint/` leaf. No I/O.
8
+ */
9
+ import type { ToolCatalogReport } from './types.js';
10
+ export interface FormatReportOptions {
11
+ /** How many ranked pairs to show in the relative-ordering section.
12
+ * Default 10. 0 hides the section. */
13
+ readonly topPairs?: number;
14
+ /** How many WATCH pairs to print before eliding the rest (the report
15
+ * object always carries all of them). Default 10. */
16
+ readonly maxWatch?: number;
17
+ }
18
+ export declare function formatToolCatalogReport(report: ToolCatalogReport, options?: FormatReportOptions): string;
19
+ //# sourceMappingURL=format.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../../../src/lib/tool-lint/format.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,MAAM,WAAW,mBAAmB;IAClC;2CACuC;IACvC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B;0DACsD;IACtD,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,iBAAiB,EACzB,OAAO,GAAE,mBAAwB,GAChC,MAAM,CA6DR"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * tool-lint — the tool-catalog confusability lint (RFC-002 tier 1,
3
+ * blocks C1–C3).
4
+ *
5
+ * Build-time, CI-gateable, framework-agnostic: a plain
6
+ * `{ name, description?, inputSchema? }[]` in (any OpenAI / Anthropic /
7
+ * LangChain / MCP tool list coerces to it), a report with a CI-gateable
8
+ * `ok` out. The embedding geometry comes from influence-core
9
+ * (`pairwiseSimilarity`); this module is the policy layer — thresholds,
10
+ * verdicts, hints, and the pluggable structural rule pack.
11
+ *
12
+ * Surfaces:
13
+ * - `analyzeToolCatalog(tools, opts)` — the API (C1)
14
+ * - `defaultStructuralRules` + rule factories — the rule pack (C2)
15
+ * - `runToolLintCli` / bin `agentfootprint-lint-tools` — the gate (C3)
16
+ *
17
+ * Front-door guide: docs/guides/tool-catalog-lint.md
18
+ */
19
+ export type { AnalyzeToolCatalogOptions, CatalogTool, ConfusablePairFinding, LintRule, LintSeverity, PairVerdict, SimilarityReport, StructuralFinding, ToolCatalogReport, } from './types.js';
20
+ export { analyzeToolCatalog, catalogFromTools, confusabilityText, differentiationHint, DEFAULT_CONFUSABILITY_THRESHOLD, DEFAULT_WATCH_BAND, MOCK_EMBEDDER_CALIBRATION, } from './analyze.js';
21
+ export { defaultStructuralRules, descriptionRule, enumInProseRule, optionalParamRule, saysWhatNotWhenRule, DEFAULT_OMISSION_CUES, DEFAULT_WHEN_CUES, type DescriptionRuleOptions, type OptionalParamRuleOptions, type SaysWhatNotWhenRuleOptions, } from './rules.js';
22
+ export { formatToolCatalogReport, type FormatReportOptions } from './format.js';
23
+ export { coerceCatalog, runToolLintCli, type ToolLintCliIO } from './cli.js';
24
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/lib/tool-lint/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,YAAY,EACV,yBAAyB,EACzB,WAAW,EACX,qBAAqB,EACrB,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,iBAAiB,EACjB,mBAAmB,EACnB,+BAA+B,EAC/B,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,sBAAsB,EACtB,eAAe,EACf,eAAe,EACf,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,iBAAiB,EACjB,KAAK,sBAAsB,EAC3B,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,GAChC,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,uBAAuB,EAAE,KAAK,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEhF,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,KAAK,aAAa,EAAE,MAAM,UAAU,CAAC"}
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Structural lint rules (RFC-002 block C2) — the PLUGGABLE RULE PACK.
3
+ *
4
+ * Pattern: Strategy list — each rule is a plain `{ id, check }` object;
5
+ * `defaultStructuralRules` is OUR pack, and consumers add /
6
+ * remove / replace freely via `AnalyzeToolCatalogOptions.rules`.
7
+ * Parameterizable rules ship as FACTORIES (`descriptionRule`,
8
+ * `saysWhatNotWhenRule`, …) returning a configured `LintRule`.
9
+ * Role: `src/lib/tool-lint/` leaf. Pure functions over `CatalogTool`;
10
+ * no embedder, no I/O.
11
+ *
12
+ * Every rule encodes a FIELD FINDING from real catalogs (the Neo SAN
13
+ * triage agent's 29-tool catalog was the seed corpus):
14
+ *
15
+ * 1. description-missing-or-short — the model can only guess from a name.
16
+ * 2. says-what-not-when — describes WHAT the tool returns but gives the
17
+ * model no cue for WHEN to pick it over a sibling (the #1 cause of
18
+ * twin-tool confusion: 'get_fcns_database' vs 'influx_get_fcns_database').
19
+ * 3. enum-in-prose — string params whose legal values are listed in prose
20
+ * ("avg_iops | peak_iops | mbps") instead of a JSON-Schema `enum` the
21
+ * model (and validators, see #9 tool-args validation) can act on.
22
+ * 4. optional-param-undocumented — optional params whose omission has
23
+ * meaning (fabric-wide sweep vs one switch) but whose schema never
24
+ * says so; the model can't reason about leaving them out.
25
+ *
26
+ * Honest claim: these are token/regex HEURISTICS. They flag review
27
+ * prompts, not certainties — expect (rare) false positives and tune via
28
+ * the factory options instead of deleting the rule.
29
+ */
30
+ import type { LintRule } from './types.js';
31
+ export interface DescriptionRuleOptions {
32
+ /** Descriptions shorter than this (in chars) get a `warn`. Default 40. */
33
+ readonly minChars?: number;
34
+ }
35
+ /**
36
+ * Missing description → `error` (the model can only guess from the
37
+ * name). Present but shorter than `minChars` → `warn` (too short to
38
+ * differentiate from siblings).
39
+ */
40
+ export declare function descriptionRule(options?: DescriptionRuleOptions): LintRule;
41
+ /** RFC-002 C2 heuristic cue list — temporal/conditional words whose
42
+ * presence suggests the description says WHEN to use the tool. */
43
+ export declare const DEFAULT_WHEN_CUES: readonly string[];
44
+ export interface SaysWhatNotWhenRuleOptions {
45
+ /** Cue tokens (whole-word, case-insensitive). Default `DEFAULT_WHEN_CUES`. */
46
+ readonly cueTokens?: readonly string[];
47
+ }
48
+ /**
49
+ * A description with NO temporal/conditional cue token usually describes
50
+ * WHAT the tool returns but never WHEN to pick it — the #1 cause of
51
+ * twin-tool confusion. Heuristic by design: tune `cueTokens` rather than
52
+ * dropping the rule. Skips tools with no description (rule 1's finding).
53
+ */
54
+ export declare function saysWhatNotWhenRule(options?: SaysWhatNotWhenRuleOptions): LintRule;
55
+ /**
56
+ * A string param whose description enumerates its legal values in prose
57
+ * (pipe-separated literals, or comma lists behind "one of"/"allowed
58
+ * values") should declare a JSON-Schema `enum` instead — the model picks
59
+ * reliably from enums, and arg validators (#9) can enforce them. The
60
+ * field case: Neo's `influx_get_port_ranking.metric` =
61
+ * `"avg_iops | peak_iops | mbps"`.
62
+ */
63
+ export declare function enumInProseRule(): LintRule;
64
+ /** Words that signal the description DOES say what omission means. */
65
+ export declare const DEFAULT_OMISSION_CUES: readonly string[];
66
+ export interface OptionalParamRuleOptions {
67
+ /** Cue tokens that satisfy the rule. Default `DEFAULT_OMISSION_CUES`. */
68
+ readonly omissionCues?: readonly string[];
69
+ }
70
+ /**
71
+ * An optional param's omission usually MEANS something (Neo:
72
+ * `influx_get_interface_counters` without `switch_name` = fabric-wide
73
+ * sweep) — but the model can only reason about leaving a param out if
74
+ * the description says so. No description at all, or one with no
75
+ * omission cue, gets a `warn`.
76
+ */
77
+ export declare function optionalParamRule(options?: OptionalParamRuleOptions): LintRule;
78
+ /**
79
+ * OUR rule pack, built with default options. Compose your own:
80
+ *
81
+ * rules: [...defaultStructuralRules, myRule] // add
82
+ * rules: defaultStructuralRules.filter(r => r.id !== '…') // remove
83
+ * rules: [descriptionRule({ minChars: 80 }), …] // re-tune
84
+ */
85
+ export declare const defaultStructuralRules: readonly LintRule[];
86
+ //# sourceMappingURL=rules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../../../src/lib/tool-lint/rules.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,KAAK,EAAe,QAAQ,EAAqB,MAAM,YAAY,CAAC;AA2C3E,MAAM,WAAW,sBAAsB;IACrC,0EAA0E;IAC1E,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,QAAQ,CA6B9E;AAID;mEACmE;AACnE,eAAO,MAAM,iBAAiB,EAAE,SAAS,MAAM,EAO9C,CAAC;AAEF,MAAM,WAAW,0BAA0B;IACzC,8EAA8E;IAC9E,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACxC;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,0BAA+B,GAAG,QAAQ,CAqBtF;AAcD;;;;;;;GAOG;AACH,wBAAgB,eAAe,IAAI,QAAQ,CA4B1C;AAgBD,sEAAsE;AACtE,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAalD,CAAC;AAEF,MAAM,WAAW,wBAAwB;IACvC,yEAAyE;IACzE,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3C;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,GAAG,QAAQ,CA+BlF;AAID;;;;;;GAMG;AACH,eAAO,MAAM,sBAAsB,EAAE,SAAS,QAAQ,EAKrD,CAAC"}
@@ -0,0 +1,156 @@
1
+ /**
2
+ * tool-lint types — the tool-catalog confusability lint contract
3
+ * (RFC-002 tier 1, blocks C1–C3).
4
+ *
5
+ * Pattern: Strategy seam (the plug-and-play meta-pattern) — the frame
6
+ * and rule engine are the library's; the embedder, thresholds,
7
+ * and structural rule pack are all consumer-injected, with our
8
+ * defaults. Exactly like NarrativeFormatter / reliability /
9
+ * permission / commentary strategies.
10
+ * Role: `src/lib/` leaf module. ZERO stack buy-in: input is a plain
11
+ * `{ name, description?, inputSchema? }[]` — any OpenAI /
12
+ * Anthropic / LangChain / MCP tool list normalizes to it
13
+ * (see `coerceCatalog`). The library's own `Tool[]` adapts via
14
+ * `catalogFromTools`.
15
+ *
16
+ * ## Honest claim (RFC-002 §2)
17
+ *
18
+ * Confusability here is embedding geometry over what the model READS
19
+ * (tool name + description) — a deterministic heuristic for "could the
20
+ * model mix these up", never a measurement of any model's actual
21
+ * selection function. Tier 3 (choice-entropy sampling) validates the
22
+ * proxy; until then treat verdicts as review prompts, not ground truth.
23
+ */
24
+ import type { Embedder, SimilarityPair } from '../influence-core/index.js';
25
+ /**
26
+ * One tool as the lint sees it — the minimal, framework-agnostic shape.
27
+ * `inputSchema` is a JSON Schema object (the same one the LLM sees);
28
+ * structural rules read `properties` / `required` / `enum` from it.
29
+ */
30
+ export interface CatalogTool {
31
+ readonly name: string;
32
+ readonly description?: string;
33
+ /** JSON Schema for the tool's arguments (`type: 'object'` shape). */
34
+ readonly inputSchema?: Readonly<Record<string, unknown>>;
35
+ }
36
+ /** Verdict for one description pair from the similarity analysis. */
37
+ export type PairVerdict = 'confusable' | 'watch';
38
+ /** One flagged pair: two tools the model could plausibly mix up. */
39
+ export interface ConfusablePairFinding {
40
+ readonly kind: PairVerdict;
41
+ /** Tool names (input order: `a` has the lower catalog index). */
42
+ readonly a: string;
43
+ readonly b: string;
44
+ /** cosine(embed(a), embed(b)) over `confusabilityText` of each tool. */
45
+ readonly similarity: number;
46
+ /**
47
+ * Heuristic suggestion for the DIFFERENTIATING AXIS — what to make
48
+ * explicit in the descriptions so the model can tell them apart
49
+ * (e.g. "names differ only by 'influx' — say WHEN to use each").
50
+ */
51
+ readonly hint: string;
52
+ }
53
+ /** Severity of a structural finding. `error` fails the gate by default. */
54
+ export type LintSeverity = 'error' | 'warn';
55
+ /** One structural finding from a `LintRule`. */
56
+ export interface StructuralFinding {
57
+ /** Id of the rule that produced this finding. */
58
+ readonly rule: string;
59
+ /** Name of the offending tool. */
60
+ readonly tool: string;
61
+ readonly severity: LintSeverity;
62
+ readonly message: string;
63
+ /** Offending parameter name, when the finding is param-scoped. */
64
+ readonly param?: string;
65
+ /** Concrete fix suggestion (e.g. the JSON-Schema `enum` to add). */
66
+ readonly suggestion?: string;
67
+ }
68
+ /**
69
+ * One pluggable structural rule. Rules are plain objects — add your own
70
+ * to `rules` in `analyzeToolCatalog` options, or filter the exported
71
+ * `defaultStructuralRules` to remove ours.
72
+ */
73
+ export interface LintRule {
74
+ /** Stable id, kebab-case (shows on findings + CLI output). */
75
+ readonly id: string;
76
+ /** Inspect ONE tool (with the whole catalog for context) and return
77
+ * zero or more findings. Must not throw on weird-but-valid input. */
78
+ check(tool: CatalogTool, catalog: readonly CatalogTool[]): readonly StructuralFinding[];
79
+ }
80
+ export interface AnalyzeToolCatalogOptions {
81
+ /**
82
+ * Injected embedder for the confusability analysis. OMITTED → the
83
+ * similarity analysis is skipped (structural rules still run) and
84
+ * `report.similarity.analyzed` is false.
85
+ *
86
+ * Wrap in an `EmbeddingCache` (from `agentfootprint/observe`) so
87
+ * catalog descriptions embed once across lint runs — keyed by content
88
+ * hash, so unchanged descriptions cost nothing on re-lint.
89
+ */
90
+ readonly embedder?: Embedder;
91
+ /**
92
+ * Pairs with similarity ≥ this are `confusable`. Default 0.85 — a
93
+ * STARTING point calibrated for real sentence embedders (where
94
+ * unrelated tool descriptions typically land 0.3–0.7).
95
+ *
96
+ * ⚠ Per-embedder calibration is REQUIRED (RFC-002 §3): absolute
97
+ * cosine ranges differ by embedder. The test/demo `mockEmbedder`
98
+ * (character-frequency) compresses unrelated prose into ~0.85–0.97,
99
+ * so with the mock use `MOCK_EMBEDDER_CALIBRATION` and trust only
100
+ * RELATIVE ordering of pairs, never absolute verdicts.
101
+ */
102
+ readonly confusabilityThreshold?: number;
103
+ /**
104
+ * Pairs within this band BELOW the threshold are `watch` (advisory —
105
+ * never fail the gate). Default 0.05.
106
+ */
107
+ readonly watchBand?: number;
108
+ /**
109
+ * The structural rule pack. Default `defaultStructuralRules`.
110
+ * Add/remove freely — rules are plain `{ id, check }` objects.
111
+ */
112
+ readonly rules?: readonly LintRule[];
113
+ /**
114
+ * Which structural severity fails the gate (`report.ok`).
115
+ * Default 'error' — warnings are advisory. 'warn' = strict mode.
116
+ */
117
+ readonly failOn?: LintSeverity;
118
+ /** Abort signal threaded to the embedder (network backends). */
119
+ readonly signal?: AbortSignal;
120
+ }
121
+ /** The similarity section of a report. */
122
+ export interface SimilarityReport {
123
+ /** False when no embedder was supplied — similarity was skipped. */
124
+ readonly analyzed: boolean;
125
+ readonly confusable: readonly ConfusablePairFinding[];
126
+ readonly watch: readonly ConfusablePairFinding[];
127
+ /**
128
+ * EVERY pair ranked by similarity, descending — the relative-ordering
129
+ * view that stays meaningful under ANY embedder (including the mock).
130
+ * Empty when `analyzed` is false.
131
+ */
132
+ readonly ranked: readonly SimilarityPair[];
133
+ readonly thresholds: {
134
+ readonly confusabilityThreshold: number;
135
+ readonly watchBand: number;
136
+ };
137
+ }
138
+ /** The lint report — `ok` is the CI-gateable verdict. */
139
+ export interface ToolCatalogReport {
140
+ /**
141
+ * True when there are no confusable pairs AND no structural findings
142
+ * at/above `failOn` severity. The CI gate: exit non-zero on `!ok`.
143
+ */
144
+ readonly ok: boolean;
145
+ readonly toolCount: number;
146
+ readonly similarity: SimilarityReport;
147
+ readonly structural: readonly StructuralFinding[];
148
+ readonly summary: {
149
+ readonly confusable: number;
150
+ readonly watch: number;
151
+ readonly errors: number;
152
+ readonly warnings: number;
153
+ };
154
+ }
155
+ export type { Embedder, SimilarityPair };
156
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":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AAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,UAAU,EAAE,gBAAgB,CAAC;IACtC,QAAQ,CAAC,UAAU,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAClD,QAAQ,CAAC,OAAO,EAAE;QAChB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;QAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;QACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;KAC3B,CAAC;CACH;AAED,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC"}
@@ -52,4 +52,6 @@ export { agentThinkingTrace, type AgentThinkingTraceHandle, type AgentThinkingTr
52
52
  export { typedEmit } from './recorders/core/typedEmit.js';
53
53
  export { adaptWeights, averageRelevancy, compositeScore, contentHash, DEFAULT_INFLUENCE_WEIGHTS, DEFAULT_MARGIN_THRESHOLD, DEFAULT_PERSISTENCE_THRESHOLD, EmbeddingCache, embeddingCache, finalAnswerSimilarity, pairwiseSimilarity, persistence, scoreInfluence, scoreMargin, structuralProximity, type CandidateScore, type Embedder, type EmbeddingCacheOptions, type EmbeddingCacheStats, type EvidenceInput, type InfluenceScore, type InfluenceWeights, type MarginCandidate, type MarginResult, type PairwiseSimilarityArgs, type PairwiseSimilarityResult, type ScoreInfluenceArgs, type ScoreMarginArgs, type SignalScores, type SimilarityItem, type SimilarityPair, } from './lib/influence-core/index.js';
54
54
  export { callTraceTool, TOOLPACK_HARD_CAPS, traceToolpack, type TraceToolpackArtifacts, type TraceToolpackOptions, } from './lib/trace-toolpack/index.js';
55
+ export { analyzeToolCatalog, catalogFromTools, coerceCatalog, confusabilityText, DEFAULT_CONFUSABILITY_THRESHOLD, DEFAULT_OMISSION_CUES, DEFAULT_WATCH_BAND, DEFAULT_WHEN_CUES, defaultStructuralRules, descriptionRule, differentiationHint, enumInProseRule, formatToolCatalogReport, MOCK_EMBEDDER_CALIBRATION, optionalParamRule, runToolLintCli, saysWhatNotWhenRule, type AnalyzeToolCatalogOptions, type CatalogTool, type ConfusablePairFinding, type DescriptionRuleOptions, type FormatReportOptions, type LintRule, type LintSeverity, type OptionalParamRuleOptions, type PairVerdict, type SaysWhatNotWhenRuleOptions, type SimilarityReport, type StructuralFinding, type ToolCatalogReport, type ToolLintCliIO, } from './lib/tool-lint/index.js';
56
+ export { buildChoiceContext, toolChoiceRecorder, type OfferedTool, type ToolChoiceCall, type ToolChoiceRecorderHandle, type ToolChoiceRecorderOptions, type ToolChoiceSkipReason, type ToolChoiceSummary, } from './recorders/observability/ToolChoiceRecorder.js';
55
57
  //# sourceMappingURL=observe.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"observe.d.ts","sourceRoot":"","sources":["../../src/observe.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAGH,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AACnG,OAAO,EAAE,cAAc,EAAE,KAAK,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAGhG,OAAO,EACL,mBAAmB,EACnB,KAAK,0BAA0B,GAChC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAC7F,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,KAAK,UAAU,EACf,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,EACvB,KAAK,0BAA0B,EAC/B,KAAK,yBAAyB,EAC9B,KAAK,WAAW,EAChB,KAAK,qBAAqB,EAC1B,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACxB,KAAK,wBAAwB,EAC7B,KAAK,cAAc,EACnB,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,GACxB,MAAM,+CAA+C,CAAC;AACvD,OAAO,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165 @@
1
+ /**
2
+ * toolChoiceRecorder — runtime tool-choice margins (RFC-002 tier 2,
3
+ * blocks C4–C6).
4
+ *
5
+ * Per LLM call that OFFERED tools, this recorder captures the menu the
6
+ * model saw (`stream.llm_start.tools`), what it actually invoked
7
+ * (`stream.tool_start`), and the choice context — then, LAZILY on first
8
+ * read, ranks the offered candidates against that context via
9
+ * influence-core's `scoreMargin` (C4):
10
+ *
11
+ * margin = score(best chosen) − score(best non-chosen)
12
+ *
13
+ * Small margin (`narrow`, < `marginThreshold`, default 0.05) = the
14
+ * choice was a close call under the proxy. Top-scored candidate not
15
+ * among the chosen (`proxyDisagreement`) is ALWAYS flagged — either a
16
+ * proxy miss or a genuinely surprising model choice; both are exactly
17
+ * what a debugger wants surfaced.
18
+ *
19
+ * ## The choice context (C4 — what is embedded, precisely)
20
+ *
21
+ * `buildChoiceContext` assembles the SAME two slots the model's
22
+ * tool-selection reasoning ran on:
23
+ *
24
+ * INCLUDED
25
+ * 1. the user message of the current turn (`agent.turn_start.userPrompt`)
26
+ * — the task the model is choosing a tool FOR (first
27
+ * `maxSlotChars` chars: the head states the task);
28
+ * 2. the latest assistant reasoning text — the most recent
29
+ * `stream.llm_end.content` of this turn, when present (last
30
+ * `maxSlotChars` chars: the tail is where "what next" lives).
31
+ * Iteration 1 has no assistant text; the slot is omitted.
32
+ *
33
+ * EXCLUDED (deliberately)
34
+ * - the system prompt: constant across every call of the run — zero
35
+ * per-call discrimination, it only dilutes the embedding;
36
+ * - older history turns: recency dominates tool choice, and the full
37
+ * transcript grows the embedding cost linearly with run length;
38
+ * - raw tool results: the model reads them, but their distilled
39
+ * effect on the NEXT choice is the assistant's own reasoning text,
40
+ * which IS included; raw payloads skew the embedding toward data
41
+ * vocabulary (the honest-proxy discipline: mirror the
42
+ * decision-relevant text, not every visible byte);
43
+ * - tool schemas: those are the CANDIDATES being ranked, not context.
44
+ *
45
+ * Candidate text per offered tool = `confusabilityText` (tokenized name
46
+ * + description) — the SAME construction the catalog lint (C1) embeds,
47
+ * so build-time confusability and runtime margins measure one geometry.
48
+ *
49
+ * ## Laziness (C5)
50
+ *
51
+ * Event hooks only RECORD (string copies into a KeyedStore). The
52
+ * embedder runs on the first `getCalls()` / `getFlagged()` /
53
+ * `getSummary()` — embedding I/O NEVER rides the hot path, even when
54
+ * the recorder is attached inline. Scores memoize per entry. Attach
55
+ * with `{ delivery: 'deferred' }` (footprintjs RFC-001) to move the
56
+ * bookkeeping off the hot path too — it is a normal CombinedRecorder.
57
+ *
58
+ * Pattern: CombinedRecorder (Convention 1 — single purpose: tool-choice
59
+ * margin evidence). Owns a `KeyedStore<ToolChoiceEntry>` keyed
60
+ * by the LLM call's `runtimeStageId`. Convention 4: resets on a
61
+ * new `runId` via `FlowRecorder.onRunStart`.
62
+ * Role: Tier-3 /observe recorder. Attach via `Agent.create(...)
63
+ * .recorder(handle)` or `executor.attachCombinedRecorder`.
64
+ *
65
+ * Honest claim (RFC-002 §2): margins are embedding geometry between the
66
+ * context and tool descriptions — a deterministic PROXY for the model's
67
+ * selection function, never "the model chose because". Tier 3
68
+ * (choice-entropy sampling) validates the proxy.
69
+ */
70
+ import type { EmitEvent } from 'footprintjs';
71
+ import { type Embedder, type MarginResult } from '../../lib/influence-core/index.js';
72
+ /** Minimal structural slice of footprintjs's FlowRunEvent (runId is all
73
+ * we read — Convention 4). */
74
+ interface RunBoundaryEvent {
75
+ readonly traversalContext?: {
76
+ readonly runId?: string;
77
+ };
78
+ }
79
+ /** One offered tool, as the model saw it on `llm_start`. */
80
+ export interface OfferedTool {
81
+ readonly name: string;
82
+ readonly description?: string;
83
+ }
84
+ /** Why an entry has no margin. */
85
+ export type ToolChoiceSkipReason =
86
+ /** The model answered without invoking any tool — no choice to score. */
87
+ 'nothing-chosen'
88
+ /** A chosen tool name was not in the offered catalog (wiring anomaly —
89
+ * surfaced, not silently massaged). */
90
+ | 'chosen-not-offered';
91
+ /** One LLM call that offered tools — the recorder's public row shape. */
92
+ export interface ToolChoiceCall {
93
+ /** runtimeStageId of the LLM-call stage (the KeyedStore key). */
94
+ readonly runtimeStageId: string;
95
+ readonly iteration: number;
96
+ /** The catalog the model saw, in request order. */
97
+ readonly offered: readonly OfferedTool[];
98
+ /** Unique tool names actually invoked, in first-call order. */
99
+ readonly chosen: readonly string[];
100
+ /** Every invocation (parallel calls + repeat calls of one tool visible). */
101
+ readonly toolCallIds: readonly string[];
102
+ /** The choice context that was (or will be) embedded. */
103
+ readonly contextText: string;
104
+ /** Ranked scores + margin + flags. Undefined until scored, or when
105
+ * `skipped` says why it never will be. */
106
+ readonly margin?: MarginResult;
107
+ readonly skipped?: ToolChoiceSkipReason;
108
+ }
109
+ /** Run-summary counts (C6). */
110
+ export interface ToolChoiceSummary {
111
+ /** LLM calls that offered tools (= recorded entries). */
112
+ readonly llmCallsWithTools: number;
113
+ /** Entries where the model invoked at least one tool. */
114
+ readonly choices: number;
115
+ /** Entries with a computed `margin`. */
116
+ readonly scored: number;
117
+ /** narrow OR proxy-disagreement. */
118
+ readonly flagged: number;
119
+ readonly narrow: number;
120
+ readonly proxyDisagreement: number;
121
+ /** Entries that will never score (`skipped` set). */
122
+ readonly skipped: number;
123
+ }
124
+ export interface ToolChoiceRecorderOptions {
125
+ /**
126
+ * Injected embedder — runs ONLY on first read (lazy). Wrap in
127
+ * `embeddingCache(...)` (agentfootprint/observe) so repeated tool
128
+ * descriptions embed once across calls and runs.
129
+ */
130
+ readonly embedder: Embedder;
131
+ /** Margins below this flag `narrow`. Default 0.05 (RFC-002 §4). */
132
+ readonly marginThreshold?: number;
133
+ /** Per-slot cap for the choice context. Default 2000 chars. */
134
+ readonly maxSlotChars?: number;
135
+ /** Recorder id (default 'tool-choice'). */
136
+ readonly id?: string;
137
+ }
138
+ export interface ToolChoiceRecorderHandle {
139
+ readonly id: string;
140
+ /** All recorded LLM calls (scored on demand — first call runs the
141
+ * embedder; results memoize). Entries still open mid-run stay
142
+ * unscored until they close. */
143
+ getCalls(): Promise<readonly ToolChoiceCall[]>;
144
+ /** Calls whose choice was fragile: `narrow` margin OR
145
+ * `proxyDisagreement` (always flagged) — C6. */
146
+ getFlagged(): Promise<readonly ToolChoiceCall[]>;
147
+ /** Run-summary counts (C6). Scores pending entries first. */
148
+ getSummary(): Promise<ToolChoiceSummary>;
149
+ clear(): void;
150
+ onEmit(event: EmitEvent): void;
151
+ onRunStart(event: RunBoundaryEvent): void;
152
+ onRunEnd(event: RunBoundaryEvent): void;
153
+ onRunFailed(event: RunBoundaryEvent): void;
154
+ }
155
+ /** C4: the precise choice-context construction (see module JSDoc for the
156
+ * include/exclude rationale). Exported so consumers can reproduce it. */
157
+ export declare function buildChoiceContext(args: {
158
+ readonly userPrompt: string;
159
+ readonly latestAssistantText?: string;
160
+ readonly maxSlotChars?: number;
161
+ }): string;
162
+ /** Build the tool-choice margin recorder (C5). */
163
+ export declare function toolChoiceRecorder(options: ToolChoiceRecorderOptions): ToolChoiceRecorderHandle;
164
+ export {};
165
+ //# sourceMappingURL=ToolChoiceRecorder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ToolChoiceRecorder.d.ts","sourceRoot":"","sources":["../../../../src/recorders/observability/ToolChoiceRecorder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C,OAAO,EAGL,KAAK,QAAQ,EACb,KAAK,YAAY,EAClB,MAAM,mCAAmC,CAAC;AAG3C;+BAC+B;AAC/B,UAAU,gBAAgB;IACxB,QAAQ,CAAC,gBAAgB,CAAC,EAAE;QAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACzD;AAED,4DAA4D;AAC5D,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,WAAW,CAA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