@plune-ai/cairn 0.7.0 → 0.8.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 (101) hide show
  1. package/README.md +3 -1
  2. package/dist/agent/graph.d.ts +9 -0
  3. package/dist/agent/graph.d.ts.map +1 -1
  4. package/dist/agent/graph.js +9 -1
  5. package/dist/agent/graph.js.map +1 -1
  6. package/dist/agent/index.d.ts +9 -0
  7. package/dist/agent/index.d.ts.map +1 -1
  8. package/dist/agent/index.js +87 -34
  9. package/dist/agent/index.js.map +1 -1
  10. package/dist/agent/repair-loop.d.ts +17 -1
  11. package/dist/agent/repair-loop.d.ts.map +1 -1
  12. package/dist/agent/repair-loop.js +88 -5
  13. package/dist/agent/repair-loop.js.map +1 -1
  14. package/dist/artifacts/report.d.ts +9 -0
  15. package/dist/artifacts/report.d.ts.map +1 -1
  16. package/dist/artifacts/report.js +26 -0
  17. package/dist/artifacts/report.js.map +1 -1
  18. package/dist/cli/index.d.ts.map +1 -1
  19. package/dist/cli/index.js +35 -4
  20. package/dist/cli/index.js.map +1 -1
  21. package/dist/config/index.d.ts +10 -0
  22. package/dist/config/index.d.ts.map +1 -1
  23. package/dist/config/index.js +101 -1
  24. package/dist/config/index.js.map +1 -1
  25. package/dist/config/schema.d.ts +10 -0
  26. package/dist/config/schema.d.ts.map +1 -1
  27. package/dist/config/schema.js +2 -0
  28. package/dist/config/schema.js.map +1 -1
  29. package/dist/core/config.d.ts +7 -0
  30. package/dist/core/config.d.ts.map +1 -1
  31. package/dist/core/config.js +4 -0
  32. package/dist/core/config.js.map +1 -1
  33. package/dist/core/modalities/explore.d.ts.map +1 -1
  34. package/dist/core/modalities/explore.js +7 -1
  35. package/dist/core/modalities/explore.js.map +1 -1
  36. package/dist/decider/capabilities.d.ts +15 -0
  37. package/dist/decider/capabilities.d.ts.map +1 -0
  38. package/dist/decider/capabilities.js +87 -0
  39. package/dist/decider/capabilities.js.map +1 -0
  40. package/dist/decider/client-http.d.ts +27 -0
  41. package/dist/decider/client-http.d.ts.map +1 -0
  42. package/dist/decider/client-http.js +134 -0
  43. package/dist/decider/client-http.js.map +1 -0
  44. package/dist/decider/guarded.d.ts +18 -0
  45. package/dist/decider/guarded.d.ts.map +1 -0
  46. package/dist/decider/guarded.js +48 -0
  47. package/dist/decider/guarded.js.map +1 -0
  48. package/dist/decider/index.d.ts +61 -0
  49. package/dist/decider/index.d.ts.map +1 -0
  50. package/dist/decider/index.js +191 -0
  51. package/dist/decider/index.js.map +1 -0
  52. package/dist/decider/redact.d.ts +6 -0
  53. package/dist/decider/redact.d.ts.map +1 -0
  54. package/dist/decider/redact.js +265 -0
  55. package/dist/decider/redact.js.map +1 -0
  56. package/dist/decider/types.d.ts +139 -0
  57. package/dist/decider/types.d.ts.map +1 -0
  58. package/dist/decider/types.js +21 -0
  59. package/dist/decider/types.js.map +1 -0
  60. package/dist/decider/uses/coverage.d.ts +37 -0
  61. package/dist/decider/uses/coverage.d.ts.map +1 -0
  62. package/dist/decider/uses/coverage.js +63 -0
  63. package/dist/decider/uses/coverage.js.map +1 -0
  64. package/dist/decider/uses/locator-heal.d.ts +69 -0
  65. package/dist/decider/uses/locator-heal.d.ts.map +1 -0
  66. package/dist/decider/uses/locator-heal.js +216 -0
  67. package/dist/decider/uses/locator-heal.js.map +1 -0
  68. package/dist/decider/uses/repair-triage.d.ts +40 -0
  69. package/dist/decider/uses/repair-triage.d.ts.map +1 -0
  70. package/dist/decider/uses/repair-triage.js +94 -0
  71. package/dist/decider/uses/repair-triage.js.map +1 -0
  72. package/dist/eval/judge.d.ts +12 -0
  73. package/dist/eval/judge.d.ts.map +1 -1
  74. package/dist/eval/judge.js +51 -0
  75. package/dist/eval/judge.js.map +1 -1
  76. package/dist/flow/crawl.d.ts +5 -0
  77. package/dist/flow/crawl.d.ts.map +1 -1
  78. package/dist/flow/crawl.js +0 -0
  79. package/dist/flow/crawl.js.map +1 -1
  80. package/dist/llm/cost.d.ts +2 -1
  81. package/dist/llm/cost.d.ts.map +1 -1
  82. package/dist/llm/cost.js +3 -2
  83. package/dist/llm/cost.js.map +1 -1
  84. package/dist/mcp/server.d.ts.map +1 -1
  85. package/dist/mcp/server.js +2 -1
  86. package/dist/mcp/server.js.map +1 -1
  87. package/dist/mcp/tools.d.ts +8 -7
  88. package/dist/mcp/tools.d.ts.map +1 -1
  89. package/dist/mcp/tools.js +9 -2
  90. package/dist/mcp/tools.js.map +1 -1
  91. package/dist/telemetry/index.d.ts +23 -0
  92. package/dist/telemetry/index.d.ts.map +1 -1
  93. package/dist/telemetry/index.js +44 -1
  94. package/dist/telemetry/index.js.map +1 -1
  95. package/dist/tui/screens/summary-screen.d.ts.map +1 -1
  96. package/dist/tui/screens/summary-screen.js +10 -1
  97. package/dist/tui/screens/summary-screen.js.map +1 -1
  98. package/dist/validate/runner.d.ts.map +1 -1
  99. package/dist/validate/runner.js +19 -1
  100. package/dist/validate/runner.js.map +1 -1
  101. package/package.json +5 -5
@@ -0,0 +1,18 @@
1
+ export interface GuardOptions {
2
+ timeoutMs: number;
3
+ /** Per-run ceiling on decide() calls (DECIDER_MAX_CALLS). A retry is part of its call, not a new one. */
4
+ maxCalls: number;
5
+ /** Pause before the single retry on 429/5xx. */
6
+ retryDelayMs?: number;
7
+ }
8
+ /**
9
+ * The layer's bounds (ADR-0022, spec §3.6): a per-run call ceiling, ONE timeout over the whole call
10
+ * (retry included), exactly one retry on 429/5xx. Everything that goes wrong surfaces as
11
+ * DeciderUnavailable, so a call site has one thing to catch.
12
+ * ponytail: fixed retry delay; honour `retry-after` if Jev's 429s turn out to need it.
13
+ */
14
+ export declare function guarded(opts: GuardOptions): {
15
+ readonly calls: number;
16
+ run<T>(attempt: (signal: AbortSignal) => Promise<T>): Promise<T>;
17
+ };
18
+ //# sourceMappingURL=guarded.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guarded.d.ts","sourceRoot":"","sources":["../../src/decider/guarded.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,yGAAyG;IACzG,QAAQ,EAAE,MAAM,CAAC;IACjB,gDAAgD;IAChD,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAKD;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,YAAY;oBAGzB,MAAM;QAGT,CAAC,WAAW,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;EA4BzE"}
@@ -0,0 +1,48 @@
1
+ import { DeciderUnavailable } from "./types.js";
2
+ const retryable = (e) => e instanceof DeciderUnavailable && e.status !== undefined && (e.status === 429 || e.status >= 500);
3
+ /**
4
+ * The layer's bounds (ADR-0022, spec §3.6): a per-run call ceiling, ONE timeout over the whole call
5
+ * (retry included), exactly one retry on 429/5xx. Everything that goes wrong surfaces as
6
+ * DeciderUnavailable, so a call site has one thing to catch.
7
+ * ponytail: fixed retry delay; honour `retry-after` if Jev's 429s turn out to need it.
8
+ */
9
+ export function guarded(opts) {
10
+ let calls = 0;
11
+ return {
12
+ get calls() {
13
+ return calls;
14
+ },
15
+ async run(attempt) {
16
+ if (calls >= opts.maxCalls)
17
+ throw new DeciderUnavailable(`call ceiling reached (${opts.maxCalls} per run)`);
18
+ calls += 1;
19
+ const ctl = new AbortController();
20
+ let timer;
21
+ const timeout = new Promise((_, reject) => {
22
+ timer = setTimeout(() => {
23
+ ctl.abort();
24
+ reject(new DeciderUnavailable(`timeout after ${opts.timeoutMs} ms`));
25
+ }, opts.timeoutMs);
26
+ });
27
+ const work = (async () => {
28
+ try {
29
+ return await attempt(ctl.signal);
30
+ }
31
+ catch (e) {
32
+ if (!retryable(e) || ctl.signal.aborted)
33
+ throw e;
34
+ await new Promise((r) => setTimeout(r, opts.retryDelayMs ?? 250));
35
+ return attempt(ctl.signal);
36
+ }
37
+ })();
38
+ try {
39
+ // A request that rejects after the timeout won is still handled: race subscribed to it.
40
+ return await Promise.race([work, timeout]);
41
+ }
42
+ finally {
43
+ clearTimeout(timer);
44
+ }
45
+ },
46
+ };
47
+ }
48
+ //# sourceMappingURL=guarded.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guarded.js","sourceRoot":"","sources":["../../src/decider/guarded.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAUhD,MAAM,SAAS,GAAG,CAAC,CAAU,EAAW,EAAE,CACxC,CAAC,YAAY,kBAAkB,IAAI,CAAC,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC;AAErG;;;;;GAKG;AACH,MAAM,UAAU,OAAO,CAAC,IAAkB;IACxC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,OAAO;QACL,IAAI,KAAK;YACP,OAAO,KAAK,CAAC;QACf,CAAC;QACD,KAAK,CAAC,GAAG,CAAI,OAA4C;YACvD,IAAI,KAAK,IAAI,IAAI,CAAC,QAAQ;gBAAE,MAAM,IAAI,kBAAkB,CAAC,yBAAyB,IAAI,CAAC,QAAQ,WAAW,CAAC,CAAC;YAC5G,KAAK,IAAI,CAAC,CAAC;YACX,MAAM,GAAG,GAAG,IAAI,eAAe,EAAE,CAAC;YAClC,IAAI,KAAgD,CAAC;YACrD,MAAM,OAAO,GAAG,IAAI,OAAO,CAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;gBAC/C,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;oBACtB,GAAG,CAAC,KAAK,EAAE,CAAC;oBACZ,MAAM,CAAC,IAAI,kBAAkB,CAAC,iBAAiB,IAAI,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC;gBACvE,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;YACrB,CAAC,CAAC,CAAC;YACH,MAAM,IAAI,GAAG,CAAC,KAAK,IAAgB,EAAE;gBACnC,IAAI,CAAC;oBACH,OAAO,MAAM,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;gBACnC,CAAC;gBAAC,OAAO,CAAC,EAAE,CAAC;oBACX,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO;wBAAE,MAAM,CAAC,CAAC;oBACjD,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,EAAE,IAAI,CAAC,YAAY,IAAI,GAAG,CAAC,CAAC,CAAC;oBAClE,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;gBAC7B,CAAC;YACH,CAAC,CAAC,EAAE,CAAC;YACL,IAAI,CAAC;gBACH,wFAAwF;gBACxF,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YAC7C,CAAC;oBAAS,CAAC;gBACT,YAAY,CAAC,KAAK,CAAC,CAAC;YACtB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,61 @@
1
+ import { CostLedger } from "../llm/cost.js";
2
+ import type { Telemetry } from "../telemetry/index.js";
3
+ import { type HttpTarget } from "./client-http.js";
4
+ import type { TriageResult } from "./uses/repair-triage.js";
5
+ import type { HealRecord } from "./uses/locator-heal.js";
6
+ import { type Decider, type DeciderConfig, type DeciderSummary } from "./types.js";
7
+ export { DeciderUnavailable, DECIDER_USES, DECIDER_PROVIDERS } from "./types.js";
8
+ export type { Answer, Decider, DeciderCaps, DeciderConfig, DeciderProvider, DeciderSummary, DeciderUse, Question, ShadowEntry, ShadowLog, } from "./types.js";
9
+ export { secretValues } from "./redact.js";
10
+ export interface DeciderDeps {
11
+ /**
12
+ * Where decider tokens and cost land (spec §5.5: a `decider` row, only when the decider is on). In shadow
13
+ * mode the decider meters into a private ledger instead, so the run's `report.json` cost is untouched.
14
+ */
15
+ ledger: CostLedger;
16
+ telemetry?: Pick<Telemetry, "recordDecision" | "recordScore">;
17
+ /** Scrubbed from every state before it leaves the process (redact.ts). */
18
+ secrets?: readonly string[];
19
+ /** One-line notices (where the data goes). Default: stderr. */
20
+ warn?: (msg: string) => void;
21
+ fetchFn?: typeof fetch;
22
+ }
23
+ export declare function httpTarget(cfg: DeciderConfig): HttpTarget;
24
+ /** Where requests to `baseUrl` physically go — for the start-up notice and `cairn doctor`. */
25
+ export declare function dataDestination(baseUrl: string): {
26
+ local: boolean;
27
+ label: string;
28
+ };
29
+ /**
30
+ * Whether any enabled use point can fire in this run: repair-triage needs a validate ⇄ repair loop, coverage a
31
+ * checklist. A run that can use none builds no decider — no data notice, no empty shadow file, no report key.
32
+ */
33
+ export declare function deciderReaches(cfg: DeciderConfig | undefined, run: {
34
+ repair: boolean;
35
+ checklist: boolean;
36
+ }): cfg is DeciderConfig;
37
+ /**
38
+ * The decision layer (ADR-0022) — or `undefined` when DECIDER is off, which is what keeps a run without
39
+ * the flag byte-identical: every use point is gated on this value, and there is no other switch.
40
+ */
41
+ export declare function makeDecider(cfg: DeciderConfig | undefined, deps: DeciderDeps): Decider | undefined;
42
+ /**
43
+ * The report keys an opted-in run adds — `{}` otherwise, so a run without the flag writes the very same
44
+ * files. Shadow mode adds nothing here either: its only artifact is decider-shadow.json.
45
+ */
46
+ export declare function deciderReportKeys(d: Decider | undefined, notRepaired?: TriageResult[], healed?: HealRecord[]): {
47
+ decider?: DeciderSummary;
48
+ notRepaired?: TriageResult[];
49
+ healed?: HealRecord[];
50
+ };
51
+ /**
52
+ * Shadow mode's only artifact (spec §7): `runs/<id>/decider-shadow.json`. A no-op for an active decider or
53
+ * none, so every other file of the run stays what it would have been without the flag.
54
+ */
55
+ export declare function writeShadowFile(runDir: string, decider: Decider | undefined, file?: string): Promise<void>;
56
+ /**
57
+ * `cairn doctor` (spec §4): the provider, where the data goes, and ONE real `noul` call with its latency.
58
+ * `[]` when DECIDER is off. Never throws — a misconfiguration or a dead server is a finding, not a crash.
59
+ */
60
+ export declare function deciderDoctorReport(env: Record<string, string | undefined>, fetchFn?: typeof fetch): Promise<string[]>;
61
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/decider/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,KAAK,EAAiB,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAItE,OAAO,EAAiB,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAGlE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAEL,KAAK,OAAO,EACZ,KAAK,aAAa,EAClB,KAAK,cAAc,EAIpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACjF,YAAY,EACV,MAAM,EACN,OAAO,EACP,WAAW,EACX,aAAa,EACb,eAAe,EACf,cAAc,EACd,UAAU,EACV,QAAQ,EACR,WAAW,EACX,SAAS,GACV,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,MAAM,EAAE,UAAU,CAAC;IACnB,SAAS,CAAC,EAAE,IAAI,CAAC,SAAS,EAAE,gBAAgB,GAAG,aAAa,CAAC,CAAC;IAC9D,0EAA0E;IAC1E,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,+DAA+D;IAC/D,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7B,OAAO,CAAC,EAAE,OAAO,KAAK,CAAC;CACxB;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,UAAU,CAEzD;AAED,8FAA8F;AAC9F,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAMlF;AASD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,aAAa,GAAG,SAAS,EAAE,GAAG,EAAE;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,GAAG,GAAG,IAAI,aAAa,CAEjI;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,aAAa,GAAG,SAAS,EAAE,IAAI,EAAE,WAAW,GAAG,OAAO,GAAG,SAAS,CAiElG;AAsBD;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,CAAC,EAAE,OAAO,GAAG,SAAS,EACtB,WAAW,CAAC,EAAE,YAAY,EAAE,EAC5B,MAAM,CAAC,EAAE,UAAU,EAAE,GACpB;IAAE,OAAO,CAAC,EAAE,cAAc,CAAC;IAAC,WAAW,CAAC,EAAE,YAAY,EAAE,CAAC;IAAC,MAAM,CAAC,EAAE,UAAU,EAAE,CAAA;CAAE,CAMnF;AAED;;;GAGG;AACH,wBAAsB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,SAAS,EAAE,IAAI,SAAwB,GAAG,OAAO,CAAC,IAAI,CAAC,CAK/H;AAQD;;;GAGG;AACH,wBAAsB,mBAAmB,CACvC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,EACvC,OAAO,GAAE,OAAO,KAAa,GAC5B,OAAO,CAAC,MAAM,EAAE,CAAC,CA6BnB"}
@@ -0,0 +1,191 @@
1
+ import { writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { CostLedger } from "../llm/cost.js";
4
+ import { createEnvReader } from "../config/env.js";
5
+ import { parseDeciderConfig, TYPESAFE_HOST } from "../config/index.js";
6
+ import { CAPS, checkCaps } from "./capabilities.js";
7
+ import { postSystemOne } from "./client-http.js";
8
+ import { guarded } from "./guarded.js";
9
+ import { redact, redactQuestion } from "./redact.js";
10
+ import { DeciderUnavailable, } from "./types.js";
11
+ export { DeciderUnavailable, DECIDER_USES, DECIDER_PROVIDERS } from "./types.js";
12
+ export { secretValues } from "./redact.js";
13
+ export function httpTarget(cfg) {
14
+ return { provider: cfg.provider, baseUrl: cfg.baseUrl, model: cfg.model, ...(cfg.apiKey ? { apiKey: cfg.apiKey } : {}) };
15
+ }
16
+ /** Where requests to `baseUrl` physically go — for the start-up notice and `cairn doctor`. */
17
+ export function dataDestination(baseUrl) {
18
+ const host = new URL(baseUrl).hostname.replace(/^\[|\]$/g, "");
19
+ // A dotted quad only: `127.evil.com` is a DNS name like any other.
20
+ if (host === "localhost" || host === "::1" || /^127(\.\d{1,3}){3}$/.test(host))
21
+ return { local: true, label: "this machine (localhost)" };
22
+ if (TYPESAFE_HOST.test(host))
23
+ return { local: false, label: `TypeSafe cloud (${host})` };
24
+ return { local: false, label: `a remote server (${host})` };
25
+ }
26
+ let warnedRemote = false; // once per process, like the env deprecation notices
27
+ /** ~4 chars per token over the state and the questions — only when a server reports no usage. */
28
+ function estimateUsage(state, questions) {
29
+ return { inputTokens: Math.ceil((state.length + JSON.stringify(questions).length) / 4), outputTokens: 0 };
30
+ }
31
+ /**
32
+ * Whether any enabled use point can fire in this run: repair-triage needs a validate ⇄ repair loop, coverage a
33
+ * checklist. A run that can use none builds no decider — no data notice, no empty shadow file, no report key.
34
+ */
35
+ export function deciderReaches(cfg, run) {
36
+ return !!cfg && ((run.repair && cfg.uses.includes("repair-triage")) || (run.checklist && cfg.uses.includes("coverage")));
37
+ }
38
+ /**
39
+ * The decision layer (ADR-0022) — or `undefined` when DECIDER is off, which is what keeps a run without
40
+ * the flag byte-identical: every use point is gated on this value, and there is no other switch.
41
+ */
42
+ export function makeDecider(cfg, deps) {
43
+ if (!cfg)
44
+ return undefined;
45
+ const caps = CAPS[cfg.provider];
46
+ const target = httpTarget(cfg);
47
+ const guard = guarded({ timeoutMs: cfg.timeoutMs, maxCalls: cfg.maxCalls });
48
+ const dest = dataDestination(cfg.baseUrl);
49
+ const ledger = cfg.shadow ? new CostLedger() : deps.ledger;
50
+ let calls = 0;
51
+ const fallbacks = [];
52
+ if (!dest.local && !warnedRemote) {
53
+ warnedRemote = true;
54
+ (deps.warn ?? ((m) => void process.stderr.write(`${m}\n`)))(`[cairn] DECIDER=${cfg.provider} sends ARIA fragments, case texts and test errors to ${dest.label}. ` +
55
+ "For an app behind a login, prefer DECIDER=laya (runs locally) — see docs/decider.md.");
56
+ }
57
+ return {
58
+ provider: cfg.provider,
59
+ model: cfg.model,
60
+ caps,
61
+ uses: new Set(cfg.uses),
62
+ minConfidence: cfg.minConfidence,
63
+ ...(cfg.shadow ? { shadow: shadowLog(deps.telemetry, deps.secrets ?? []) } : {}),
64
+ scrub: (text) => redact(text, deps.secrets ?? []),
65
+ summary: () => ({
66
+ provider: cfg.provider,
67
+ model: cfg.model,
68
+ calls,
69
+ fallbacks: [...fallbacks],
70
+ ...(cfg.shadow ? { cost: ledger.report() } : {}),
71
+ }),
72
+ async decide(use, rawState, rawQuestions) {
73
+ calls += 1;
74
+ // state/questions are filled only once scrubbed: a trace never carries the raw text.
75
+ const trace = { use, provider: cfg.provider, startTime: new Date(), state: "", questions: {}, minConfidence: cfg.minConfidence };
76
+ const record = (t) => {
77
+ try {
78
+ deps.telemetry?.recordDecision?.(t);
79
+ }
80
+ catch {
81
+ // tracing never touches the answer
82
+ }
83
+ };
84
+ try {
85
+ // Inside the try: a scrubbing failure is a fallback like any other.
86
+ const secrets = deps.secrets ?? [];
87
+ const state = redact(rawState, secrets);
88
+ const questions = (secrets.length
89
+ ? Object.fromEntries(Object.entries(rawQuestions).map(([k, q]) => [k, redactQuestion(q, secrets)]))
90
+ : rawQuestions);
91
+ Object.assign(trace, { state, questions });
92
+ checkCaps(caps, state, questions);
93
+ const res = await guard.run((signal) => postSystemOne(target, state, questions, signal, deps.fetchFn));
94
+ ledger.record("decider", cfg.model, res.usage ?? estimateUsage(state, questions), caps.price);
95
+ record({ ...trace, model: res.model ?? cfg.model, endTime: new Date(), answers: res.answers, fallback: false });
96
+ return res.answers;
97
+ }
98
+ catch (e) {
99
+ const err = e instanceof DeciderUnavailable ? e : new DeciderUnavailable(e instanceof Error ? e.message : String(e));
100
+ fallbacks.push({ use, reason: err.message });
101
+ record({ ...trace, model: cfg.model, endTime: new Date(), fallback: true, reason: err.message });
102
+ throw err;
103
+ }
104
+ },
105
+ };
106
+ }
107
+ /** Every string of a value, scrubbed like a state. */
108
+ function scrubDeep(v, secrets) {
109
+ if (typeof v === "string")
110
+ return redact(v, secrets);
111
+ if (Array.isArray(v))
112
+ return v.map((x) => scrubDeep(x, secrets));
113
+ if (v && typeof v === "object")
114
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, scrubDeep(x, secrets)]));
115
+ return v;
116
+ }
117
+ function shadowLog(telemetry, secrets) {
118
+ const entries = [];
119
+ return {
120
+ entries,
121
+ record(e) {
122
+ // decider-shadow.json is the file a pilot collects across apps: it holds what was SENT, never the raw text.
123
+ entries.push(secrets.length ? scrubDeep(e, secrets) : e);
124
+ if (e.agreement !== undefined)
125
+ telemetry?.recordScore?.(`decider.${e.use}.agreement`, e.agreement);
126
+ },
127
+ };
128
+ }
129
+ /**
130
+ * The report keys an opted-in run adds — `{}` otherwise, so a run without the flag writes the very same
131
+ * files. Shadow mode adds nothing here either: its only artifact is decider-shadow.json.
132
+ */
133
+ export function deciderReportKeys(d, notRepaired, healed) {
134
+ return {
135
+ ...(d && !d.shadow ? { decider: d.summary() } : {}),
136
+ ...(notRepaired?.length ? { notRepaired } : {}),
137
+ ...(healed?.length ? { healed } : {}),
138
+ };
139
+ }
140
+ /**
141
+ * Shadow mode's only artifact (spec §7): `runs/<id>/decider-shadow.json`. A no-op for an active decider or
142
+ * none, so every other file of the run stays what it would have been without the flag.
143
+ */
144
+ export async function writeShadowFile(runDir, decider, file = "decider-shadow.json") {
145
+ if (!decider?.shadow)
146
+ return;
147
+ const { provider, model, calls, fallbacks, cost } = decider.summary();
148
+ const payload = { provider, model, minConfidence: decider.minConfidence, calls, fallbacks, cost, entries: decider.shadow.entries };
149
+ await writeFile(join(runDir, file), `${JSON.stringify(payload, null, 2)}\n`, "utf8");
150
+ }
151
+ const DOCTOR_QUESTION = {
152
+ type: "noul",
153
+ instructions: "Is this text a connectivity check?",
154
+ criteria: { true: "The text says it is a connectivity check", false: "The text is about something else" },
155
+ };
156
+ /**
157
+ * `cairn doctor` (spec §4): the provider, where the data goes, and ONE real `noul` call with its latency.
158
+ * `[]` when DECIDER is off. Never throws — a misconfiguration or a dead server is a finding, not a crash.
159
+ */
160
+ export async function deciderDoctorReport(env, fetchFn = fetch) {
161
+ const head = ["", "Cairn decision layer (DECIDER — ADR-0022)"];
162
+ let cfg;
163
+ try {
164
+ cfg = parseDeciderConfig(createEnvReader(env, () => undefined));
165
+ }
166
+ catch (e) {
167
+ return [...head, ` ✗ ${e.message}`];
168
+ }
169
+ if (!cfg)
170
+ return [];
171
+ const dest = dataDestination(cfg.baseUrl);
172
+ const lines = [
173
+ ...head,
174
+ ` Provider: ${cfg.provider} · model: ${cfg.model}`,
175
+ ` Base URL: ${cfg.baseUrl}`,
176
+ ` Data goes to: ${dest.label}${dest.local ? "" : " — ARIA fragments, case texts and test errors leave this machine"}`,
177
+ ` Uses: ${cfg.uses.join(", ")} · min confidence ${cfg.minConfidence} · timeout ${cfg.timeoutMs} ms · ≤ ${cfg.maxCalls} decisions/run`,
178
+ ...(cfg.shadow ? [" Mode: shadow mode — answers are recorded, never acted on (runs/<id>/decider-shadow.json)"] : []),
179
+ ];
180
+ const target = httpTarget(cfg);
181
+ const t0 = Date.now();
182
+ try {
183
+ const r = await guarded({ timeoutMs: cfg.timeoutMs, maxCalls: 1 }).run((signal) => postSystemOne(target, "Cairn doctor connectivity check.", { q: DOCTOR_QUESTION }, signal, fetchFn));
184
+ lines.push(` ✓ Test call (noul): ${Date.now() - t0} ms · answered by ${r.model ?? cfg.model}`);
185
+ }
186
+ catch (e) {
187
+ lines.push(` ✗ Test call failed: ${e.message}`);
188
+ }
189
+ return lines;
190
+ }
191
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/decider/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACvE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAmB,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAGrD,OAAO,EACL,kBAAkB,GAOnB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAajF,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAgB3C,MAAM,UAAU,UAAU,CAAC,GAAkB;IAC3C,OAAO,EAAE,QAAQ,EAAE,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,C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AAa,cAAc,GAAG,CAAC,SAAS,WAAW,GAAG,CAAC,QAAQ,gBAAgB;QACtI,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,4FAA4F,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;KACtH,CAAC;IACF,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;IAC/B,MAAM,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACtB,IAAI,CAAC;QACH,MAAM,CAAC,GAAG,MAAM,OAAO,CAAC,EAAE,SAAS,EAAE,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAChF,aAAa,CAAC,MAAM,EAAE,kCAAkC,EAAE,EAAE,CAAC,EAAE,eAAe,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,CACnG,CAAC;QACF,KAAK,CAAC,IAAI,CAAC,yBAAyB,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,qBAAqB,CAAC,CAAC,KAAK,IAAI,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC;IAClG,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,KAAK,CAAC,IAAI,CAAC,yBAA0B,CAAW,CAAC,OAAO,EAAE,CAAC,CAAC;IAC9D,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { Question } from "./types.js";
2
+ export declare function secretValues(knowledgeText: string, env: Record<string, string | undefined>): string[];
3
+ export declare function redact(text: string, secrets: readonly string[]): string;
4
+ /** The question's texts are scrubbed too; its option LABELS are the answer contract and stay as they are. */
5
+ export declare function redactQuestion(q: Question, secrets: readonly string[]): Question;
6
+ //# sourceMappingURL=redact.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact.d.ts","sourceRoot":"","sources":["../../src/decider/redact.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAkK3C,wBAAgB,YAAY,CAAC,aAAa,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,MAAM,EAAE,CAyErG;AAID,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAUvE;AAED,6GAA6G;AAC7G,wBAAgB,cAAc,CAAC,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,QAAQ,CAchF"}
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Values that must never reach a decider (spec §3.7). Cairn never PUTS knowledge, storageState, screenshots
3
+ * or env into a state — but a designed case can ECHO a credential it read in a knowledge file ("type
4
+ * Sup3rS3cret! into Password"), and a test error can echo a typed value. So every state and every question
5
+ * is scrubbed of the values that look like secrets in this run's knowledge and environment.
6
+ *
7
+ * BEST-EFFORT, weighed by what a wrong guess costs: a missed secret leaves the machine; a word scrubbed by
8
+ * mistake damages every input it appears in. So a secret word anywhere on a line only POINTS at values, and
9
+ * of those only credential-shaped ones are taken (`Qwerty123!`, `sk_live_…`, `admin@test`) — never a plain word
10
+ * like `required` or `name` — unless a label whose head word names the secret says the value IS one
11
+ * (`Password: qwerty`). A credential-shaped secret is scrubbed wherever it appears (`Qwerty123!x` included); a
12
+ * plain one only as a whole token, so it can never eat into a longer word.
13
+ */
14
+ // A secret word, anywhere on a line, as a whole word.
15
+ const SECRET_WORD = /(?<![\p{L}\p{N}])(?:pass(?:words?|wd|phrase|code)?|pwd|secrets?|tokens?|(?:api)?keys?|otp|pin|пін|пин|credentials?|creds|парол\p{L}*|токен\p{L}*|секрет\p{L}*|ключ\p{L}*|креденшел\p{L}*|облікові\s+дані|учетные\s+данные)(?![\p{L}\p{N}])/iu;
16
+ // A label whose HEAD word is a secret word names the secret itself. English puts the head last ("Admin
17
+ // password", "Stripe key", "PIN code"); Ukrainian/Russian first or last, in the nominative ("Пароль
18
+ // адміністратора", "Тестовий пароль", "ПІН-код") — "Password rules" and "Правила пароля" only talk about one.
19
+ const EN_SECRET_HEAD = /(?:^|[^\p{L}\p{N}])(?:pass(?:words?|wd|phrase|code)?|pwd|secrets?|tokens?|keys?|(?:otp|pin)(?:[\s-]?code)?|credentials?|creds)$/iu;
20
+ const SLAVIC_HEAD = "(?:парол[ьіи]|токен[иы]?|секрет[иы]?|ключ[іи]?|креденшел[иі]|облікові\\s+дані|учетные\\s+данные|(?:otp|pin|пін|пин)(?:-?код)?)";
21
+ const SLAVIC_SECRET_HEAD = new RegExp(`^${SLAVIC_HEAD}(?![\\p{L}\\p{N}])|(?<![\\p{L}\\p{N}])${SLAVIC_HEAD}$`, "iu");
22
+ /**
23
+ * "Forgot password", "Change password", "Змінити пароль" name a feature or a link; "Empty password", "Wrong
24
+ * password", "Порожній пароль" a test condition (`Empty password: "Password is required"` quotes a message) —
25
+ * none of them the secret.
26
+ */
27
+ const ACTION_HEAD = /(?:^|[^\p{L}\p{N}])(?:forgot(?:ten)?|reset|change|recover|restore|update|show|hide|toggle|remember|manage|edit|empty|blank|wrong|invalid|incorrect|short|weak|missing|забули|змінити|скинути|відновити|показати|сховати|приховати|порожн\p{L}*|невірн\p{L}*|неправильн\p{L}*|коротк\p{L}*|слаб\p{L}*|изменить|сменить|поменять|сбросить|восстановить|забыли|показать|скрыть|пуст\p{L}*|неверн\p{L}*)(?:\s+(?:your|the|my|свій|ваш|свой))?\s+\S+$/iu;
28
+ /** Env names that end in a secret word (`DB_PASS`, `GITHUB_TOKEN`, `STRIPE_KEY`) or carry SECRET / PASSWORD
29
+ * anywhere (`SECRET_KEY_BASE`) — not `TOKEN_TTL`, not a public key. */
30
+ const SECRET_ENV = /(?:^|_)(?:PASS(?:WORDS?|WD|PHRASE|CODE)?|PWD|SECRETS?|TOKENS?|KEYS?|OTP|PIN|CREDENTIALS?|CREDS)$|SECRET|PASSWORD/i;
31
+ /** …of which a password variable counts whatever its value looks like (`DB_PASSWORD=postgres`). */
32
+ const PASSWORD_ENV = /(?:^|_)(?:PASS(?:WORDS?|WD|PHRASE|CODE)?|PWD)$/i;
33
+ const PUBLIC_ENV = /(?:^|_)(?:PUBLIC|PUBLISHABLE)_KEYS?$/i;
34
+ /** Never a secret: flags, and the words a field list puts after "Password:". */
35
+ const TRIVIAL = /^(?:true|false|yes|no|on|off|null|none|undefined|empty|blank|enabled|disabled|required|optional|hidden|visible|masked|mandatory|обов['’]язков\p{L}*|необов['’]язков\p{L}*|порожн\p{L}*|пуст\p{L}*|немає|нема)$/iu;
36
+ /** Drops trailing characters of a class — a loop, not a `[…]+$` pattern, which rescans a long run from every position. */
37
+ const trimEnd = (s, cls) => {
38
+ let end = s.length;
39
+ while (end > 0 && cls.test(s[end - 1]))
40
+ end -= 1;
41
+ return s.slice(0, end);
42
+ };
43
+ /** Markdown, quotes and punctuation around a label or a value: `**Password:**`, `` `sk-…` ``, `«…»`, `(admin)`. */
44
+ const strip = (s) => trimEnd(s.trim().replace(/^[\s*_`"'([«“„‘]+/u, ""), /[\s*_`"')\].,;:»”’]/u);
45
+ /** A value written in quotes is meant literally (single quotes excluded: they are apostrophes too). */
46
+ const QUOTED = /[`"«“„]([^`"«»“”„\n]{4,})[`"»”“]/gu;
47
+ /** …and a value that STARTS with a quote is that quote, spaces and all: `Password: "correct horse battery"`. */
48
+ const QUOTED_VALUE = /^[`"«“„]([^`"«»“”„\n]{4,})[`"»”“]/u;
49
+ /** A column that describes a field or records a result rather than holding its value: `| Field | Type |`,
50
+ * `| Поле | Роль |`, `| Status |`, `| Min |` — from a word start, so `Information` is not `format`, and a bound as a
51
+ * whole word (`Minimum`, `Мінімальне значення`), so `Maxim` stays a name. */
52
+ const SPEC_COLUMN = /(?<![\p{L}\p{N}])(?:type|role|kind|format|rule|validat|constraint|selector|locator|element|widget|controls?(?!\p{L})|descri|note|comment|behavio|expect|status|result|actual|length|тип|роль|формат|правил|валідац|валидац|опис|примітк|примечан|очікуван|ожидаем|селектор|локатор|елемент|элемент|статус|результат|фактичн|довжин|длин|(?:(?:min|max)(?:imum|imal)?|мін(?:імум|імальн\p{L}*)?|мин(?:имум|имальн\p{L}*)?|макс(?:имум|имальн\p{L}*)?)(?!\p{L}))/iu;
53
+ /** A type word describes a field and is never a secret: `| Password | textbox |`, `Password: password` — a password
54
+ * `password` protects nothing, and taking it would cut the word out of every state. */
55
+ const SPEC_WORD = /^(?:password|text|textbox|textarea|string|email|e-mail|number|numeric|integer|int|boolean|bool|checkbox|radio|input|field|button|select|combobox|date|datetime|tel|url|search|пароль|текст|рядок|строка|число)$/iu;
56
+ /** A first header cell that makes every column an instance: `| | Staging | Production |`, `| Role | Admin | Viewer |`. */
57
+ const MATRIX_HEAD = /(?<![\p{L}\p{N}])(?:environment|env(?!\p{L})|account|role|user|середовищ|оточенн|окружени|акаунт|роль|користувач)/iu;
58
+ /** …as do columns that all name an environment: `| Parameter | Staging | Production |`, `| QA1 | QA2 |`,
59
+ * `| Staging EU | Prod (US) |`. */
60
+ const ENV_NAME = /^(?:staging|stage|stg|prod|production|dev|development|qa|test|testing|uat|local|demo|sandbox|pre-?prod|beta|integration|live|тест|прод|дев|стейдж\p{L}*)(?:[\s_-]*(?:\d+|[a-z]{2}|\([^)]*\)?))?$/iu;
61
+ /** Outside a matrix, a column named for the value holds it — the header's last word, and not a default, invalid or
62
+ * old value: `| Field | Required | Value |`, `| Test data |`, `| Тестове значення |`; not `| Data source |`. */
63
+ const VALUE_COLUMN = /(?<![\p{L}\p{N}])(?<!(?:default|invalid|wrong|old|initial|(?:невалідн|неправильн|невірн|некоректн|стар|початков|невалидн|неверн|некорректн|начальн)\p{L}*)\s+)(?:values?|examples?|data|значення|значение|приклад|пример|дані|данные)$/iu;
64
+ /** A key–value table's layout, read once from its header: which columns describe the field, whether every other
65
+ * column holds a value (a matrix), and the column named for the value. */
66
+ const tableLayout = (header) => {
67
+ const spec = header.map((h) => SPEC_COLUMN.test(h));
68
+ const values = header.flatMap((h, i) => (i > 0 && !spec[i] ? [i] : []));
69
+ const matrix = !header[0] || MATRIX_HEAD.test(header[0]) || values.every((i) => ENV_NAME.test(strip(header[i])));
70
+ return { spec, matrix, named: values.find((i) => VALUE_COLUMN.test(strip(header[i]))) };
71
+ };
72
+ /**
73
+ * Shaped like a credential rather than a word: letters mixed with digits (not "6-digit"), or a symbol other
74
+ * than a word's own hyphen, apostrophe or dot, or a closing "?"/"!" (not "e-mail", "one-time", "password?");
75
+ * all digits (a PIN) only when asked.
76
+ */
77
+ function credentialShaped(t, digitsOnly = false) {
78
+ if (t.length < 4 || TRIVIAL.test(t))
79
+ return false;
80
+ if (/^\p{N}+$/u.test(t))
81
+ return digitsOnly;
82
+ if (/\p{L}/u.test(t) && /\p{N}/u.test(t))
83
+ return !/^\p{N}+[-‑–]\p{L}+$/u.test(t);
84
+ return /[^\p{L}\p{N}\-‑–'’ʼ.]/u.test(trimEnd(t, /[?!]/u));
85
+ }
86
+ /** Parenthesised commentary out: "Password (admin)", "(the admin's)". `[^()]` keeps an unclosed "(" run linear. */
87
+ const dropParens = (s) => s.replace(/\([^()]*\)/g, " ");
88
+ function secretHead(rawLabel) {
89
+ const label = strip(dropParens(rawLabel)).replace(/\s+(?:for|of)\s.*$/i, ""); // "… for the admin"
90
+ const m = EN_SECRET_HEAD.exec(label) ?? SLAVIC_SECRET_HEAD.exec(label);
91
+ if (!m)
92
+ return undefined;
93
+ const w = m[0].toLowerCase();
94
+ const head = /phrase/.test(w)
95
+ ? "passphrase"
96
+ : /otp|pin|пін|пин|код|code/.test(w)
97
+ ? "code"
98
+ : /pass|pwd|парол/.test(w)
99
+ ? "password"
100
+ : /cred|креденшел|дані|данные/.test(w)
101
+ ? "credentials"
102
+ : "other";
103
+ // "Forgot password: /forgot-password", "Empty password: "…"" — but "Reset PIN: 4711" is still a code (digits only)
104
+ return head !== "code" && ACTION_HEAD.test(label) ? undefined : head;
105
+ }
106
+ /** What a value under a secret head adds, whatever the rest of the line says. */
107
+ function headValues(head, value) {
108
+ const quoted = QUOTED_VALUE.exec(value.trim())?.[1];
109
+ const v = quoted ?? strip(dropParens(value));
110
+ if (head !== "passphrase" && /^\/|:\/\//.test(v))
111
+ return []; // a path or a URL names a page, not a secret
112
+ const first = strip(v.split(/[\s,;]+/)[0] ?? "");
113
+ const pair = v.split("/").map((p) => p.trim()); // "login / password"
114
+ switch (head) {
115
+ case "passphrase":
116
+ return [v]; // spaces are part of it
117
+ case "password":
118
+ case "credentials":
119
+ if (pair.length === 2)
120
+ return [strip(pair[1])]; // "Email / password: qa@acme.test / qwerty"
121
+ if (head === "credentials")
122
+ return [];
123
+ return quoted !== undefined || !/\s/.test(v) ? [v] : []; // a weak password is still one — but "required, 8-64 characters" is prose
124
+ case "code":
125
+ return credentialShaped(first, true) ? [first] : []; // "PIN: 4711, same for all" — not "6-digit code…"
126
+ case "other":
127
+ // "Key: abcd-1234", "API key = `sk-live-abcdef`" — not "Sort key: name", nor `Sort key: "name"`
128
+ if (quoted !== undefined && !/\s/.test(v) && /[-_]/.test(v))
129
+ return [v];
130
+ return credentialShaped(first) ? [first] : [];
131
+ }
132
+ }
133
+ /** `label: value`, `label = value` or `label — value` / `label - value`; bullets and quotes tolerated. */
134
+ const LINE = /^\s*(?:>\s*)?(?:[-*+]\s+|\d+[.)]\s+)?(.{1,60}?)(?:\s*[:=:]|\s+[—–]|\s+-(?=\s))\s*(.+)$/u;
135
+ /**
136
+ * A login written next to its credential with no label at all: "Test account: qa@acme.test / Qwerty123!". The
137
+ * lookbehind starts a match only at a token's first character — without it a long run of word characters is
138
+ * rescanned from every position.
139
+ */
140
+ const LOGIN_PAIR = /(?<![\p{L}\p{N}._%+-])[\p{L}\p{N}._%+-]+@[\p{L}\p{N}.-]+\s*\/\s*(\S+)/gu;
141
+ /**
142
+ * "Login: admin / Password: qwerty", "User: qa@acme.test, Password: qwerty", "Admin - Password: qwerty" — one label
143
+ * per segment; a dash only splits before another "label:".
144
+ */
145
+ const SEGMENT = /(?:[,;]|\s[/|—–-])\s+(?=[^,;:]{1,40}[:=:])/;
146
+ export function secretValues(knowledgeText, env) {
147
+ const out = new Set();
148
+ const add = (v) => {
149
+ const s = strip(v);
150
+ if (s.length >= 4 && !TRIVIAL.test(s) && !SPEC_WORD.test(s))
151
+ out.add(s);
152
+ };
153
+ // A Markdown table: the row above its |---| rule is the header; a header cell naming a secret marks a column.
154
+ let above = [];
155
+ let table; // undefined until the rule: a row above it may be the header
156
+ let columns = [];
157
+ for (const line of knowledgeText.split(/\r?\n/)) {
158
+ for (const p of line.matchAll(LOGIN_PAIR)) {
159
+ const v = strip(p[1] ?? "");
160
+ // Not a second login ("viewer@… / editor@…"), not a phone number ("qa@… / +380 44 …").
161
+ if (!v.includes("@") && !/^\+?[\d()-]+$/.test(v) && credentialShaped(v))
162
+ add(v);
163
+ }
164
+ if (/^\s*\|/.test(line)) {
165
+ const cells = line.split("|").slice(1, -1).map((c) => c.trim());
166
+ if (cells.length > 0 && cells.every((c) => /^:?-+:?$/.test(c))) {
167
+ columns = above.flatMap((c, at) => (SECRET_WORD.test(c) ? [{ at, head: secretHead(c) }] : []));
168
+ table = tableLayout(above);
169
+ continue;
170
+ }
171
+ above = cells;
172
+ for (const { at, head } of columns) {
173
+ const cell = cells[at] ?? ""; // | admin | admin@acme.test | Adm1n!2024 |
174
+ for (const v of head ? headValues(head, cell) : [])
175
+ add(v);
176
+ for (const t of cell.split(/[\s,;/]+/))
177
+ if (credentialShaped(strip(t)))
178
+ add(t);
179
+ }
180
+ // A key–value row — | Password | qwerty | — holds one value: in the column named for it (| Value |, | Test data |),
181
+ // else in the first that neither describes the field (| Type |, | Status |) nor holds a flag (| yes |, | ✓ |) or
182
+ // nothing. The columns past it hold results or translations (| error |, | Passwort |); a matrix holds one per column.
183
+ const rowHead = table && cells[0] ? secretHead(cells[0]) : undefined;
184
+ if (table && rowHead) {
185
+ const { spec, matrix, named } = table;
186
+ const values = cells.flatMap((_, i) => (i > 0 && !spec[i] ? [i] : []));
187
+ const holds = (i) => {
188
+ const s = strip(cells[i] ?? "");
189
+ return s.length >= 4 && !TRIVIAL.test(s);
190
+ };
191
+ const at = matrix ? values : [named ?? values.find(holds)];
192
+ for (const i of at)
193
+ if (i !== undefined)
194
+ for (const v of headValues(rowHead, cells[i] ?? ""))
195
+ add(v);
196
+ }
197
+ }
198
+ else {
199
+ above = [];
200
+ table = undefined;
201
+ columns = [];
202
+ }
203
+ const at = line.search(SECRET_WORD);
204
+ if (at < 0)
205
+ continue;
206
+ // Everything after the secret word may hold it — "(password: Adm1n!2024)" included.
207
+ const after = line.slice(at);
208
+ for (const t of after.split(/[\s,;|/:]+/))
209
+ if (credentialShaped(strip(t)))
210
+ add(t);
211
+ // A Markdown heading is a title, not "label: value" — "## Passwords - staging" names a section.
212
+ for (const seg of /^\s*#/.test(line) ? [] : line.split(SEGMENT)) {
213
+ const m = LINE.exec(seg);
214
+ const head = m?.[1] && m[2] ? secretHead(m[1]) : undefined;
215
+ if (head)
216
+ for (const v of headValues(head, m[2]))
217
+ add(v);
218
+ }
219
+ // Any other quote on the line counts only when it looks like a credential — "Forgot password?" does not.
220
+ for (const q of after.matchAll(QUOTED)) {
221
+ const v = q[1] ?? "";
222
+ if (v.split(/\s+/).some((w) => credentialShaped(strip(w))))
223
+ add(v);
224
+ }
225
+ }
226
+ for (const [k, v] of Object.entries(env)) {
227
+ // PWD is the working directory, not a password.
228
+ if (!v || k === "PWD" || !SECRET_ENV.test(k) || PUBLIC_ENV.test(k))
229
+ continue;
230
+ const t = v.trim();
231
+ // An env value is not prose: API_TOKEN=Welcome! is the token, closing "!" and all — VITE_STORAGE_KEY=user is not.
232
+ if (PASSWORD_ENV.test(k) || credentialShaped(t, true) || /[?!]$/.test(t))
233
+ add(v);
234
+ }
235
+ return [...out].sort((a, b) => b.length - a.length); // longest first: a secret containing another is scrubbed whole
236
+ }
237
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
238
+ export function redact(text, secrets) {
239
+ let out = text;
240
+ for (const s of secrets) {
241
+ // A credential-shaped secret anywhere — a negative case's "Qwerty123!x" still carries it; a plain word or a
242
+ // PIN only as a whole token, so a scrubbed "qwerty" never eats into "qwertyuiop", nor "4711" into "14711".
243
+ out = credentialShaped(s)
244
+ ? out.split(s).join("‹redacted›")
245
+ : out.replace(new RegExp(`(?<![\\p{L}\\p{N}])${escapeRe(s)}(?![\\p{L}\\p{N}])`, "gu"), "‹redacted›");
246
+ }
247
+ return out;
248
+ }
249
+ /** The question's texts are scrubbed too; its option LABELS are the answer contract and stay as they are. */
250
+ export function redactQuestion(q, secrets) {
251
+ const r = (t) => redact(t, secrets);
252
+ switch (q.type) {
253
+ case "noul":
254
+ return { ...q, instructions: r(q.instructions), criteria: { true: r(q.criteria.true), false: r(q.criteria.false) } };
255
+ case "choice":
256
+ return {
257
+ ...q,
258
+ instructions: r(q.instructions),
259
+ options: Object.fromEntries(Object.entries(q.options).map(([k, d]) => [k, d === null ? null : r(d)])),
260
+ };
261
+ case "score":
262
+ return { ...q, instructions: r(q.instructions), levels: q.levels.map(r) };
263
+ }
264
+ }
265
+ //# sourceMappingURL=redact.js.map