@mcoda/codali 0.1.135-codali.42 → 0.1.135-codali.47

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 (93) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/config/deterministic/node-worker.mjs +15 -2
  3. package/config/skills/code-implementation/SKILL.md +1 -1
  4. package/config/skills/planning/SKILL.md +1 -1
  5. package/config/skills/ui-ux-design/SKILL.md +1 -1
  6. package/config/skills/webapp-testing/SKILL.md +2 -11
  7. package/config/skills/webapp-testing/journey-driver.mjs +104 -3
  8. package/dist/eval/fixtures/ContractReviewProvider.d.ts +5 -0
  9. package/dist/eval/fixtures/ContractReviewProvider.d.ts.map +1 -1
  10. package/dist/eval/fixtures/ContractReviewProvider.js +63 -0
  11. package/dist/eval/fixtures/MixedMediaRecoveryJourney.js +2 -2
  12. package/dist/eval/fixtures/TerminalRecoveryJourney.js +2 -2
  13. package/dist/permissions/PermissionGate.js +1 -1
  14. package/dist/providers/ClaudeCliProvider.d.ts.map +1 -1
  15. package/dist/providers/ClaudeCliProvider.js +1 -0
  16. package/dist/providers/CodexCliProvider.d.ts.map +1 -1
  17. package/dist/providers/CodexCliProvider.js +1 -0
  18. package/dist/providers/ModelServiceError.d.ts +14 -0
  19. package/dist/providers/ModelServiceError.d.ts.map +1 -1
  20. package/dist/providers/ModelServiceError.js +15 -2
  21. package/dist/providers/OllamaRemoteProvider.d.ts.map +1 -1
  22. package/dist/providers/OllamaRemoteProvider.js +1 -0
  23. package/dist/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  24. package/dist/providers/OpenAiCompatibleProvider.js +4 -0
  25. package/dist/providers/ProviderTypes.d.ts +4 -0
  26. package/dist/providers/ProviderTypes.d.ts.map +1 -1
  27. package/dist/runtime/AnswerEdits.d.ts +39 -0
  28. package/dist/runtime/AnswerEdits.d.ts.map +1 -0
  29. package/dist/runtime/AnswerEdits.js +134 -0
  30. package/dist/runtime/AnswerVerification.d.ts.map +1 -1
  31. package/dist/runtime/AnswerVerification.js +4 -2
  32. package/dist/runtime/AuditGuards.d.ts +41 -0
  33. package/dist/runtime/AuditGuards.d.ts.map +1 -0
  34. package/dist/runtime/AuditGuards.js +81 -0
  35. package/dist/runtime/CompletionReport.d.ts +4 -2
  36. package/dist/runtime/CompletionReport.d.ts.map +1 -1
  37. package/dist/runtime/CompletionReport.js +8 -3
  38. package/dist/runtime/DeliveryDocs.d.ts +21 -0
  39. package/dist/runtime/DeliveryDocs.d.ts.map +1 -0
  40. package/dist/runtime/DeliveryDocs.js +148 -0
  41. package/dist/runtime/FigureCheck.d.ts +61 -2
  42. package/dist/runtime/FigureCheck.d.ts.map +1 -1
  43. package/dist/runtime/FigureCheck.js +210 -14
  44. package/dist/runtime/GatewayRequest.d.ts +13 -0
  45. package/dist/runtime/GatewayRequest.d.ts.map +1 -1
  46. package/dist/runtime/GatewayRequest.js +54 -1
  47. package/dist/runtime/InspectionConvergence.d.ts +4 -0
  48. package/dist/runtime/InspectionConvergence.d.ts.map +1 -1
  49. package/dist/runtime/InspectionConvergence.js +24 -1
  50. package/dist/runtime/NumericProvenance.d.ts +102 -0
  51. package/dist/runtime/NumericProvenance.d.ts.map +1 -0
  52. package/dist/runtime/NumericProvenance.js +411 -0
  53. package/dist/runtime/OutageWait.d.ts +13 -0
  54. package/dist/runtime/OutageWait.d.ts.map +1 -1
  55. package/dist/runtime/OutageWait.js +13 -0
  56. package/dist/runtime/ResearchEvidence.d.ts.map +1 -1
  57. package/dist/runtime/ResearchEvidence.js +79 -3
  58. package/dist/runtime/ReviewCoordinator.d.ts +22 -0
  59. package/dist/runtime/ReviewCoordinator.d.ts.map +1 -1
  60. package/dist/runtime/ReviewCoordinator.js +201 -24
  61. package/dist/runtime/SessionController.d.ts +31 -22
  62. package/dist/runtime/SessionController.d.ts.map +1 -1
  63. package/dist/runtime/SessionController.js +592 -176
  64. package/dist/runtime/StructuralEvidence.d.ts +10 -0
  65. package/dist/runtime/StructuralEvidence.d.ts.map +1 -1
  66. package/dist/runtime/StructuralEvidence.js +10 -0
  67. package/dist/runtime/TaskReview.d.ts +10 -0
  68. package/dist/runtime/TaskReview.d.ts.map +1 -1
  69. package/dist/runtime/TaskReview.js +14 -1
  70. package/dist/tools/ToolRegistry.d.ts.map +1 -1
  71. package/dist/tools/ToolRegistry.js +11 -2
  72. package/dist/tools/browser/BrowserWorker.js +142 -2
  73. package/dist/tools/calculation/CalculatorTool.d.ts +1 -1
  74. package/dist/tools/calculation/CalculatorTool.d.ts.map +1 -1
  75. package/dist/tools/calculation/CalculatorTool.js +209 -41
  76. package/dist/tools/deterministic/DeterministicTools.js +1 -1
  77. package/dist/tools/deterministic/node-worker.cjs +10 -10
  78. package/dist/tools/shell/AsyncProcess.d.ts +2 -0
  79. package/dist/tools/shell/AsyncProcess.d.ts.map +1 -1
  80. package/dist/tools/shell/AsyncProcess.js +32 -5
  81. package/dist/tools/shell/IsolatedExecutor.d.ts +29 -1
  82. package/dist/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  83. package/dist/tools/shell/IsolatedExecutor.js +169 -7
  84. package/dist/tools/shell/ShellTool.js +1 -1
  85. package/dist/tools/verification/CodeRunTool.d.ts +19 -0
  86. package/dist/tools/verification/CodeRunTool.d.ts.map +1 -0
  87. package/dist/tools/verification/CodeRunTool.js +104 -0
  88. package/dist/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -1
  89. package/dist/tools/verification/JavaScriptVerificationTool.js +21 -10
  90. package/dist/tools/verification/VitestTool.d.ts +27 -0
  91. package/dist/tools/verification/VitestTool.d.ts.map +1 -1
  92. package/dist/tools/verification/VitestTool.js +160 -16
  93. package/package.json +3 -3
@@ -0,0 +1,39 @@
1
+ /** Audits that return edits instead of a rewritten answer. A rewrite has to
2
+ * reproduce the whole answer to change one sentence, and in cycle 7 that went
3
+ * wrong both ways: a research rewrite came back at half the length, cut off
4
+ * inside a link, and replaced the complete answer; a design rewrite that fixed
5
+ * a figure was discarded only because it was longer. An edit names the text it
6
+ * replaces, so the rest of the answer cannot be lost, each edit can be judged
7
+ * and refused on its own, and the length of the reply does not matter. */
8
+ export interface AnswerEdit {
9
+ find: string;
10
+ replace: string;
11
+ reason?: string;
12
+ }
13
+ export interface AppliedEdits {
14
+ text: string;
15
+ applied: AnswerEdit[];
16
+ skipped: Array<{
17
+ edit: AnswerEdit;
18
+ reason: string;
19
+ }>;
20
+ }
21
+ export declare const EDIT_FORMAT_RULE = "Return only JSON: {\"edits\":[{\"find\":\"...\",\"replace\":\"...\",\"reason\":\"...\"}]}. Each \"find\" is a passage copied character for character from the draft, long enough to occur only once (a sentence, a table row or a heading line), and an edit never changes a link address or inline code unless that is the defect, in which case its find includes the whole link; \"replace\" is the text that goes in its place, in the draft's own format; \"reason\" names the defect in a few words. Correct every place a changed value or claim is used, each with its own edit. To add text, find the sentence or line it follows and replace it with that line plus the addition. To delete text, replace it with \"\". Do not edit passages that are correct and do not restate the draft. Return {\"edits\":[]} when there is no demonstrable defect.";
22
+ /** The edits in an audit reply, or undefined when the reply is not an edit list
23
+ * (then it is read as a full rewritten answer). */
24
+ export declare function parseAnswerEdits(text: string): AnswerEdit[] | undefined;
25
+ /** Apply edits in order. An edit is placed only where its passage occurs
26
+ * exactly once outside link targets, URLs and inline code; otherwise it is
27
+ * skipped (not_found, inside_link_or_code, ambiguous). `refuse` may veto an
28
+ * edit with a reason. `allowShrink` admits an edit that removes most of the
29
+ * answer, for a request with an explicit length limit. */
30
+ export declare function applyAnswerEdits(draft: string, edits: AnswerEdit[], refuse?: (edit: AnswerEdit, text: string) => string | undefined, allowShrink?: boolean): AppliedEdits;
31
+ /** An answer that stops inside markup: an open link, bracket or code span on
32
+ * its last line. Seen in cycle 7 at 4,044 output tokens, a count no cap check
33
+ * would flag, with the server reporting a normal finish. */
34
+ export declare const endsInsideMarkup: (text: string) => boolean;
35
+ /** What a revised answer lost of the draft's structure, if it lost much: most
36
+ * of its section headings, or most of its distinct links (only the links
37
+ * `countLink` accepts, so removing links that were never retrieved is not a loss). */
38
+ export declare const structureLoss: (draft: string, revised: string, countLink?: (url: string) => boolean) => "lost_sections" | "lost_links" | undefined;
39
+ //# sourceMappingURL=AnswerEdits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AnswerEdits.d.ts","sourceRoot":"","sources":["../../src/runtime/AnswerEdits.ts"],"names":[],"mappings":"AAAA;;;;;;0EAM0E;AAC1E,MAAM,WAAW,UAAU;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAAE;AAC/E,MAAM,WAAW,YAAY;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,UAAU,EAAE,CAAC;IAAC,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAAE;AAE5H,eAAO,MAAM,gBAAgB,s0BAA8yB,CAAC;AAE50B;mDACmD;AACnD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,EAAE,GAAG,SAAS,CAavE;AA2CD;;;;0DAI0D;AAC1D,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,EAAE,WAAW,UAAQ,GAAG,YAAY,CAkBvK;AAKD;;4DAE4D;AAC5D,eAAO,MAAM,gBAAgB,GAAI,MAAM,MAAM,KAAG,OAM/C,CAAC;AAEF;;sFAEsF;AACtF,eAAO,MAAM,aAAa,GAAI,OAAO,MAAM,EAAE,SAAS,MAAM,EAAE,YAAW,CAAC,GAAG,EAAE,MAAM,KAAK,OAAoB,KAAG,eAAe,GAAG,YAAY,GAAG,SASjJ,CAAC"}
@@ -0,0 +1,134 @@
1
+ export const EDIT_FORMAT_RULE = `Return only JSON: {"edits":[{"find":"...","replace":"...","reason":"..."}]}. Each "find" is a passage copied character for character from the draft, long enough to occur only once (a sentence, a table row or a heading line), and an edit never changes a link address or inline code unless that is the defect, in which case its find includes the whole link; "replace" is the text that goes in its place, in the draft's own format; "reason" names the defect in a few words. Correct every place a changed value or claim is used, each with its own edit. To add text, find the sentence or line it follows and replace it with that line plus the addition. To delete text, replace it with "". Do not edit passages that are correct and do not restate the draft. Return {"edits":[]} when there is no demonstrable defect.`;
2
+ /** The edits in an audit reply, or undefined when the reply is not an edit list
3
+ * (then it is read as a full rewritten answer). */
4
+ export function parseAnswerEdits(text) {
5
+ const body = text.trim().replace(/^```(?:json)?\s*/u, "").replace(/\s*```$/u, "");
6
+ if (!/^\{\s*"edits"\s*:/u.test(body))
7
+ return undefined;
8
+ let data;
9
+ try {
10
+ data = JSON.parse(body);
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ const list = data && typeof data === "object" ? data.edits : undefined;
16
+ if (!Array.isArray(list))
17
+ return undefined;
18
+ return list.flatMap(item => {
19
+ if (!item || typeof item !== "object")
20
+ return [];
21
+ const { find, replace, reason } = item;
22
+ if (typeof find !== "string" || !find.trim() || typeof replace !== "string" || find === replace)
23
+ return [];
24
+ return [{ find, replace, ...(typeof reason === "string" ? { reason: reason.slice(0, 300) } : {}) }];
25
+ }).slice(0, 200);
26
+ }
27
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
28
+ /** The same passage with any run of whitespace matching any other run: models
29
+ * often copy a passage with a line break turned into a space. */
30
+ const loosePattern = (find) => new RegExp(find.trim().split(/\s+/u).map(escape).join("\\s+"), "gu");
31
+ /** Spans an edit may not touch: link targets, bare URLs and inline code. A
32
+ * figure edit (v2024 -> v2025) that also rewrote a link's address broke the link. */
33
+ const maskedSpans = (text) => {
34
+ const spans = [];
35
+ for (const pattern of [/\]\([^)\s]*\)/gu, /https?:\/\/[^\s<>()\[\]"'`\\]+/gu, /`[^`\n]+`/gu]) {
36
+ for (const match of text.matchAll(pattern))
37
+ spans.push([match.index, match.index + match[0].length]);
38
+ }
39
+ return spans;
40
+ };
41
+ const occurrences = (text, find) => {
42
+ const found = [];
43
+ for (let at = text.indexOf(find); at >= 0; at = text.indexOf(find, at + 1))
44
+ found.push([at, at + find.length]);
45
+ if (found.length)
46
+ return found;
47
+ return [...text.matchAll(loosePattern(find))].map(match => [match.index, match.index + match[0].length]);
48
+ };
49
+ const headingLines = (text) => text.match(/^ {0,3}(?:#{1,6}[ \t]+\S.*|\*\*[^*\n]{2,120}\*\*:?[ \t]*)$/gmu) ?? [];
50
+ /** A heading's kind: its level ("#", "##", ...) or "bold" for a bold-only line. */
51
+ const headingKind = (line) => /^\s*(#{1,6})[ \t]/u.exec(line)?.[1] ?? "bold";
52
+ /** Why one edit must not apply as a deletion: it removes a section heading, or
53
+ * most of the answer. Other large deletions are judged edit by edit and stand.
54
+ * A heading counts as removed only when the replacement has fewer headings of
55
+ * its kind than the passage it replaces: renaming a heading or correcting a
56
+ * figure in it ("**Total cost: $243**" to "$324") is an ordinary edit. */
57
+ const deletionDefect = (edit, text, allowShrink) => {
58
+ const before = headingLines(edit.find), after = headingLines(edit.replace);
59
+ const lines = (value) => value.split("\n").filter(line => line.trim()).length;
60
+ for (const kind of new Set(before.map(headingKind))) {
61
+ const lost = before.filter(line => headingKind(line) === kind).length - after.filter(line => headingKind(line) === kind).length;
62
+ // A bold line is lost only when the line itself goes, not when it is reworded or unbolded.
63
+ if (lost > 0 && (kind !== "bold" || lines(edit.find) - lines(edit.replace) >= lost))
64
+ return "removes_section";
65
+ }
66
+ if (!allowShrink && edit.find.length - edit.replace.length > text.length * 0.5)
67
+ return "removes_most_of_answer";
68
+ return undefined;
69
+ };
70
+ /** Apply edits in order. An edit is placed only where its passage occurs
71
+ * exactly once outside link targets, URLs and inline code; otherwise it is
72
+ * skipped (not_found, inside_link_or_code, ambiguous). `refuse` may veto an
73
+ * edit with a reason. `allowShrink` admits an edit that removes most of the
74
+ * answer, for a request with an explicit length limit. */
75
+ export function applyAnswerEdits(draft, edits, refuse, allowShrink = false) {
76
+ let text = draft;
77
+ const applied = [], skipped = [];
78
+ for (const edit of edits) {
79
+ const vetoed = refuse?.(edit, text) ?? deletionDefect(edit, text, allowShrink);
80
+ if (vetoed) {
81
+ skipped.push({ edit, reason: vetoed });
82
+ continue;
83
+ }
84
+ const masked = maskedSpans(text);
85
+ const all = occurrences(text, edit.find);
86
+ const free = all.filter(([start, end]) => !masked.some(([from, to]) => start < to && end > from && !(start <= from && end >= to)));
87
+ if (!all.length) {
88
+ skipped.push({ edit, reason: "not_found" });
89
+ continue;
90
+ }
91
+ if (!free.length) {
92
+ skipped.push({ edit, reason: "inside_link_or_code" });
93
+ continue;
94
+ }
95
+ // The same passage in several places is not a place: "243" could be any of them.
96
+ if (free.length > 1) {
97
+ skipped.push({ edit, reason: "ambiguous" });
98
+ continue;
99
+ }
100
+ const [[start, end]] = free;
101
+ text = text.slice(0, start) + edit.replace + text.slice(end);
102
+ applied.push(edit);
103
+ }
104
+ return { text, applied, skipped };
105
+ }
106
+ const headings = (text) => (text.match(/^ {0,3}(?:#{1,6}[ \t]+\S.*|\*\*[^*\n]{2,120}\*\*:?[ \t]*)$/gmu) ?? []).length;
107
+ const distinctLinks = (text) => new Set((text.match(/https?:\/\/[^\s<>()\[\]"'`\\]+/gu) ?? []).map(url => url.replace(/[.,;:!?*]+$/u, "").replace(/\/+$/u, "")));
108
+ /** An answer that stops inside markup: an open link, bracket or code span on
109
+ * its last line. Seen in cycle 7 at 4,044 output tokens, a count no cap check
110
+ * would flag, with the server reporting a normal finish. */
111
+ export const endsInsideMarkup = (text) => {
112
+ const last = text.trimEnd().split("\n").pop() ?? "";
113
+ if (/\]\([^)\s]*$/u.test(last))
114
+ return true;
115
+ const opened = (last.match(/\[/gu) ?? []).length, closed = (last.match(/\]/gu) ?? []).length;
116
+ if (opened > closed)
117
+ return true;
118
+ return (last.match(/`/gu) ?? []).length % 2 === 1;
119
+ };
120
+ /** What a revised answer lost of the draft's structure, if it lost much: most
121
+ * of its section headings, or most of its distinct links (only the links
122
+ * `countLink` accepts, so removing links that were never retrieved is not a loss). */
123
+ export const structureLoss = (draft, revised, countLink = () => true) => {
124
+ const before = headings(draft), after = headings(revised);
125
+ if (before >= 3 && after < Math.ceil(before * 0.75))
126
+ return "lost_sections";
127
+ const links = new Set([...distinctLinks(draft)].filter(countLink));
128
+ if (links.size >= 4) {
129
+ const kept = distinctLinks(revised);
130
+ if ([...links].filter(link => kept.has(link)).length * 2 < links.size)
131
+ return "lost_links";
132
+ }
133
+ return undefined;
134
+ };
@@ -1 +1 @@
1
- {"version":3,"file":"AnswerVerification.d.ts","sourceRoot":"","sources":["../../src/runtime/AnswerVerification.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,kBAAkB;IAAG,QAAQ,EAAE,KAAK,GAAG,YAAY,GAAG,YAAY,GAAG,QAAQ,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;CAAE;AAElH;kFACkF;AAClF,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,kBAAkB,EAAE,GAAG,MAAM,EAAE,CAU5F;AAED,MAAM,WAAW,OAAO;IAAG,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAAE;AAI9F;;;;;6EAK6E;AAC7E,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,CAY3F;AAED;8EAC8E;AAC9E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,MAAM,EAAE,MAAM,GAAG,QAAQ,CAAC;IAAC,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE,GAAG,SAAS,CAmBzI"}
1
+ {"version":3,"file":"AnswerVerification.d.ts","sourceRoot":"","sources":["../../src/runtime/AnswerVerification.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,kBAAkB;IAAG,QAAQ,EAAE,KAAK,GAAG,YAAY,GAAG,YAAY,GAAG,QAAQ,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;CAAE;AAElH;kFACkF;AAClF,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,kBAAkB,EAAE,GAAG,MAAM,EAAE,CAU5F;AAED,MAAM,WAAW,OAAO;IAAG,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAAE;AAK9F;;;;;6EAK6E;AAC7E,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,CAY3F;AAED;8EAC8E;AAC9E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,MAAM,EAAE,MAAM,GAAG,QAAQ,CAAC;IAAC,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE,GAAG,SAAS,CAmBzI"}
@@ -1,3 +1,4 @@
1
+ import { isTestFile } from "../tools/verification/VitestTool.js";
1
2
  /** Detect presentation drift, not semantic correctness. A passing execution
2
3
  * says nothing about code the model subsequently rewrites in its final answer. */
3
4
  export function unmatchedExecutedCode(text, executed) {
@@ -12,7 +13,8 @@ export function unmatchedExecutedCode(text, executed) {
12
13
  }
13
14
  return [...unmatched];
14
15
  }
15
- const TEST_PATH = /(^|\/)(test_[^/]*\.py|[^/]*_test\.py|[^/]*\.(test|spec)\.[cm]?[jt]s)$/;
16
+ // The same test-file rule verify_tests applies (test_x.js, x.test.js, ...).
17
+ const isTest = (file, runner) => isTestFile(file, runner === "python" || runner === "node" ? runner : file.path.endsWith(".py") ? "python" : "vitest");
16
18
  const LANGUAGE_OF = (path) => path.endsWith(".py") ? "python" : /\.[cm]?[jt]s$/.test(path) ? "code-js" : undefined;
17
19
  /** The session's last test run with the final answer's code in place of its
18
20
  * source file. Cycle 5 case 28 (.41 regression pack): every verify_tests run
@@ -23,7 +25,7 @@ const LANGUAGE_OF = (path) => path.endsWith(".py") ? "python" : /\.[cm]?[jt]s$/.
23
25
  export function finalCodeRerun(text, last) {
24
26
  if (!last?.files?.length)
25
27
  return;
26
- const sources = last.files.filter(file => !TEST_PATH.test(file.path));
28
+ const sources = last.files.filter(file => !isTest(file, last.runner));
27
29
  if (sources.length !== 1 || sources.length === last.files.length)
28
30
  return;
29
31
  const language = LANGUAGE_OF(sources[0].path);
@@ -0,0 +1,41 @@
1
+ import { type AnswerCheck, type FigureResult } from "./FigureCheck.js";
2
+ import type { AnswerEdit } from "./AnswerEdits.js";
3
+ /** Figures in a mismatch the audit should resolve: not those whose expression
4
+ * uses numbers the draft and request never state. A difference of exactly a
5
+ * unit factor stays flagged, marked as a possible slip: it may be the
6
+ * expression's slip or a real unit error in the draft, and the audit judges which. */
7
+ export declare const flaggedFigures: (check: AnswerCheck | undefined) => FigureResult[];
8
+ /** Values the calculator confirmed and the text states, which an edit may not
9
+ * change. A confirmed figure that uses a flagged figure as an input is not
10
+ * protected: correcting the input must be able to carry through. */
11
+ export declare const protectedFigures: (check: AnswerCheck | undefined, text: string) => FigureResult[];
12
+ /** The protected figures that stay protected under a set of edits. When an
13
+ * edit changes an input of a protected figure (3 shifts become 4), that figure
14
+ * must be free to change with it, and so must every figure built on it, or the
15
+ * answer is left saying 4 x 81 = 243. The new values are then judged by the
16
+ * re-check, not by the protection. */
17
+ export declare const stillProtected: (guarded: FigureResult[], edits: AnswerEdit[]) => FigureResult[];
18
+ /** Why an edit must be refused: it removes a protected value from the passage it replaces. */
19
+ export declare const editChangesProtected: (edit: AnswerEdit, guarded: FigureResult[]) => string | undefined;
20
+ /** Protected values that a full rewrite dropped. */
21
+ export declare const droppedProtected: (guarded: FigureResult[], revised: string) => number[];
22
+ /** Failures in the re-check of a revised text that the revision introduced: a
23
+ * mismatched figure whose stated value the previous text did not contain or
24
+ * the previous check had confirmed (an input changed, its result did not), or
25
+ * a target the previous check found met (or did not list) and the new one
26
+ * finds missed. `inputs` are the input numbers of those figures. */
27
+ export declare const introducedFailures: (after: AnswerCheck, previousText: string, previous: AnswerCheck | undefined) => {
28
+ values: number[];
29
+ inputs: number[];
30
+ targets: string[];
31
+ };
32
+ /** The edits to undo for introduced failures: those whose new text carries an
33
+ * introduced value, an input of a newly broken figure, or an achieved claim. */
34
+ export declare const editsToRevert: (edits: AnswerEdit[], failures: {
35
+ values: number[];
36
+ inputs?: number[];
37
+ targets: string[];
38
+ }, after: AnswerCheck) => AnswerEdit[];
39
+ /** Open problems a check hands to the audit: flagged figures, missed targets, conflicts. */
40
+ export declare const openIssues: (check: AnswerCheck | undefined) => number;
41
+ //# sourceMappingURL=AuditGuards.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AuditGuards.d.ts","sourceRoot":"","sources":["../../src/runtime/AuditGuards.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACrF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAenD;;;sFAGsF;AACtF,eAAO,MAAM,cAAc,GAAI,OAAO,WAAW,GAAG,SAAS,KAAG,YAAY,EAC0C,CAAC;AAIvH;;oEAEoE;AACpE,eAAO,MAAM,gBAAgB,GAAI,OAAO,WAAW,GAAG,SAAS,EAAE,MAAM,MAAM,KAAG,YAAY,EAI3F,CAAC;AAEF;;;;sCAIsC;AACtC,eAAO,MAAM,cAAc,GAAI,SAAS,YAAY,EAAE,EAAE,OAAO,UAAU,EAAE,KAAG,YAAY,EAWzF,CAAC;AAEF,8FAA8F;AAC9F,eAAO,MAAM,oBAAoB,GAAI,MAAM,UAAU,EAAE,SAAS,YAAY,EAAE,KAAG,MAAM,GAAG,SAIzF,CAAC;AAEF,oDAAoD;AACpD,eAAO,MAAM,gBAAgB,GAAI,SAAS,YAAY,EAAE,EAAE,SAAS,MAAM,KAAG,MAAM,EAGjF,CAAC;AAEF;;;;oEAIoE;AACpE,eAAO,MAAM,kBAAkB,GAAI,OAAO,WAAW,EAAE,cAAc,MAAM,EAAE,UAAU,WAAW,GAAG,SAAS,KAAG;IAAE,MAAM,EAAE,MAAM,EAAE,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAQvK,CAAC;AAEF;gFACgF;AAChF,eAAO,MAAM,aAAa,GAAI,OAAO,UAAU,EAAE,EAAE,UAAU;IAAE,MAAM,EAAE,MAAM,EAAE,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,EAAE,OAAO,WAAW,KAAG,UAAU,EAOvJ,CAAC;AAEF,4FAA4F;AAC5F,eAAO,MAAM,UAAU,GAAI,OAAO,WAAW,GAAG,SAAS,KAAG,MACkF,CAAC"}
@@ -0,0 +1,81 @@
1
+ import { numberValues } from "./FigureCheck.js";
2
+ /** Guards around a consistency audit, decided from calculator results rather
3
+ * than from the audit's own judgement. In cycle 7 the audit doubled figures
4
+ * the calculator had just confirmed (243 cartridges a year became 486) and
5
+ * "corrected" a right figure into a tenfold error, and nothing checked its
6
+ * output. */
7
+ const same = (a, b) => Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
8
+ const contains = (values, value) => values.some(other => same(other, value));
9
+ /** Kept, allowing for the rounding of a restated value (233.28 written as 233.3). */
10
+ const keeps = (values, value) => values.some(other => Math.abs(other - value) <= 0.01 * Math.abs(value));
11
+ /** Small whole numbers occur everywhere; protecting them would refuse ordinary edits. */
12
+ const distinctive = (value) => !(Number.isInteger(value) && Math.abs(value) < 10);
13
+ /** Figures in a mismatch the audit should resolve: not those whose expression
14
+ * uses numbers the draft and request never state. A difference of exactly a
15
+ * unit factor stays flagged, marked as a possible slip: it may be the
16
+ * expression's slip or a real unit error in the draft, and the audit judges which. */
17
+ export const flaggedFigures = (check) => (check?.figures ?? []).filter(figure => !figure.error && !figure.matches && figure.suspect !== "inputs_not_in_text");
18
+ const inputsOf = (figure) => numberValues(figure.expression.replace(/\[[^\]]*\]/gu, " "));
19
+ /** Values the calculator confirmed and the text states, which an edit may not
20
+ * change. A confirmed figure that uses a flagged figure as an input is not
21
+ * protected: correcting the input must be able to carry through. */
22
+ export const protectedFigures = (check, text) => {
23
+ const flagged = flaggedFigures(check).map(figure => figure.stated), stated = numberValues(text);
24
+ return (check?.figures ?? []).filter(figure => figure.matches && !figure.error && figure.computed !== undefined && distinctive(figure.stated)
25
+ && contains(stated, figure.stated) && !inputsOf(figure).some(input => contains(flagged, input)));
26
+ };
27
+ /** The protected figures that stay protected under a set of edits. When an
28
+ * edit changes an input of a protected figure (3 shifts become 4), that figure
29
+ * must be free to change with it, and so must every figure built on it, or the
30
+ * answer is left saying 4 x 81 = 243. The new values are then judged by the
31
+ * re-check, not by the protection. */
32
+ export const stillProtected = (guarded, edits) => {
33
+ const removed = edits.flatMap(edit => { const after = numberValues(edit.replace); return numberValues(edit.find).filter(value => !keeps(after, value)); });
34
+ const freed = new Set();
35
+ // Inputs changed directly (not themselves protected results), then whatever depends on a freed result.
36
+ let changed = removed.filter(value => !guarded.some(figure => same(figure.stated, value)));
37
+ while (changed.length) {
38
+ const next = guarded.filter(figure => !freed.has(figure) && inputsOf(figure).some(input => contains(changed, input)));
39
+ for (const figure of next)
40
+ freed.add(figure);
41
+ changed = next.map(figure => figure.stated).filter(value => contains(removed, value));
42
+ }
43
+ return guarded.filter(figure => !freed.has(figure));
44
+ };
45
+ /** Why an edit must be refused: it removes a protected value from the passage it replaces. */
46
+ export const editChangesProtected = (edit, guarded) => {
47
+ const before = numberValues(edit.find), after = numberValues(edit.replace);
48
+ const hit = guarded.find(figure => contains(before, figure.stated) && !keeps(after, figure.stated));
49
+ return hit ? `confirmed_figure:${hit.stated}` : undefined;
50
+ };
51
+ /** Protected values that a full rewrite dropped. */
52
+ export const droppedProtected = (guarded, revised) => {
53
+ const after = numberValues(revised);
54
+ return guarded.filter(figure => !keeps(after, figure.stated)).map(figure => figure.stated);
55
+ };
56
+ /** Failures in the re-check of a revised text that the revision introduced: a
57
+ * mismatched figure whose stated value the previous text did not contain or
58
+ * the previous check had confirmed (an input changed, its result did not), or
59
+ * a target the previous check found met (or did not list) and the new one
60
+ * finds missed. `inputs` are the input numbers of those figures. */
61
+ export const introducedFailures = (after, previousText, previous) => {
62
+ const earlier = numberValues(previousText);
63
+ const confirmed = (previous?.figures ?? []).filter(figure => figure.matches && !figure.error && figure.computed !== undefined).map(figure => figure.stated);
64
+ const broken = flaggedFigures(after).filter(figure => !contains(earlier, figure.stated) || contains(confirmed, figure.stated));
65
+ const missedBefore = new Set((previous?.targets ?? []).filter(target => !target.met && !target.error).map(target => target.requirement.trim().toLowerCase()));
66
+ const targets = after.targets.filter(target => !target.met && !target.error && !missedBefore.has(target.requirement.trim().toLowerCase()))
67
+ .filter(target => target.achievedClaim === undefined || !previousText.includes(target.achievedClaim)).map(target => target.requirement);
68
+ return { values: broken.map(figure => figure.stated), inputs: broken.flatMap(inputsOf), targets };
69
+ };
70
+ /** The edits to undo for introduced failures: those whose new text carries an
71
+ * introduced value, an input of a newly broken figure, or an achieved claim. */
72
+ export const editsToRevert = (edits, failures, after) => {
73
+ const claims = after.targets.filter(target => failures.targets.includes(target.requirement)).map(target => target.achievedClaim ?? "").filter(Boolean);
74
+ const suspects = [...failures.values, ...(failures.inputs ?? [])];
75
+ return edits.filter(edit => {
76
+ const added = numberValues(edit.replace).filter(value => !contains(numberValues(edit.find), value));
77
+ return suspects.some(value => contains(added, value)) || claims.some(claim => edit.replace.includes(claim) && !edit.find.includes(claim));
78
+ });
79
+ };
80
+ /** Open problems a check hands to the audit: flagged figures, missed targets, conflicts. */
81
+ export const openIssues = (check) => flaggedFigures(check).length + (check?.targets ?? []).filter(target => !target.met && !target.error).length + (check?.conflicts.length ?? 0);
@@ -1,6 +1,8 @@
1
1
  import type { WorkState } from "../session/WorkTypes.js";
2
2
  /** A stopped turn is not a delivery. Summarize only durable state, without inference. */
3
- export declare function interruptedReport(state: WorkState, sessionId: string, touched: string[], uncertain: string[]): string;
3
+ /** Files changed during a call that failed on a workspace conflict and not read or written since. */
4
+ export declare const unreconciledNote: (files: string[]) => string;
5
+ export declare function interruptedReport(state: WorkState, sessionId: string, touched: string[], uncertain: string[], unreconciled?: string[]): string;
4
6
  /** What a turn that ran out of time hands back: recorded state only, with the
5
7
  * latest check as it was observed. */
6
8
  export declare function deadlineReport(handoff: string, latestCheck?: {
@@ -9,5 +11,5 @@ export declare function deadlineReport(handoff: string, latestCheck?: {
9
11
  }): string;
10
12
  /** Delivery repeats accepted evidence instead of asking the model to introduce
11
13
  * new factual claims after the goal has already passed review. */
12
- export declare function completionReport(state: WorkState, budgetExhausted?: boolean): string;
14
+ export declare function completionReport(state: WorkState, budgetExhausted?: boolean, unreconciled?: string[]): string;
13
15
  //# sourceMappingURL=CompletionReport.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"CompletionReport.d.ts","sourceRoot":"","sources":["../../src/runtime/CompletionReport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEzD,yFAAyF;AACzF,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAYrH;AAED;sCACsC;AACtC,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAKzG;AAED;kEACkE;AAClE,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,SAAS,EAAE,eAAe,UAAQ,GAAG,MAAM,CASlF"}
1
+ {"version":3,"file":"CompletionReport.d.ts","sourceRoot":"","sources":["../../src/runtime/CompletionReport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEzD,yFAAyF;AACzF,qGAAqG;AACrG,eAAO,MAAM,gBAAgB,GAAI,OAAO,MAAM,EAAE,KAAG,MAAuP,CAAC;AAE3S,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,YAAY,GAAE,MAAM,EAAO,GAAG,MAAM,CAalJ;AAED;sCACsC;AACtC,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAKzG;AAED;kEACkE;AAClE,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,SAAS,EAAE,eAAe,UAAQ,EAAE,YAAY,GAAE,MAAM,EAAO,GAAG,MAAM,CAU/G"}
@@ -1,5 +1,7 @@
1
1
  /** A stopped turn is not a delivery. Summarize only durable state, without inference. */
2
- export function interruptedReport(state, sessionId, touched, uncertain) {
2
+ /** Files changed during a call that failed on a workspace conflict and not read or written since. */
3
+ export const unreconciledNote = (files) => `Files changed during a failed tool call and not inspected since (they may hold another process's edits): ${files.slice(0, 8).join(", ")}${files.length > 8 ? `; ${files.length - 8} more` : ""}. Review them before relying on this result.`;
4
+ export function interruptedReport(state, sessionId, touched, uncertain, unreconciled = []) {
3
5
  const pending = state.tasks.filter(task => !["verified", "cancelled", "superseded"].includes(task.status));
4
6
  const verified = state.tasks.filter(task => task.status === "verified").length;
5
7
  const short = (text) => text.replace(/\s+/g, " ").slice(0, 180);
@@ -12,6 +14,8 @@ export function interruptedReport(state, sessionId, touched, uncertain) {
12
14
  lines.push(`Changed files (not a completion claim): ${touched.slice(0, 8).map(short).join(", ")}${touched.length > 8 ? `; ${touched.length - 8} more` : ""}.`);
13
15
  if (uncertain.length)
14
16
  lines.push(`${uncertain.length} operation outcome(s) need reconciliation before retrying.`);
17
+ if (unreconciled.length)
18
+ lines.push(unreconciledNote(unreconciled));
15
19
  lines.push(`Resume this session with /resume ${sessionId}, then /continue. Inspect /status and /usage for details.`);
16
20
  return lines.join("\n");
17
21
  }
@@ -25,7 +29,7 @@ export function deadlineReport(handoff, latestCheck) {
25
29
  }
26
30
  /** Delivery repeats accepted evidence instead of asking the model to introduce
27
31
  * new factual claims after the goal has already passed review. */
28
- export function completionReport(state, budgetExhausted = false) {
32
+ export function completionReport(state, budgetExhausted = false, unreconciled = []) {
29
33
  const accepted = new Set(state.tasks.filter(task => task.status === "verified").flatMap(task => task.evidenceIds));
30
34
  const summaries = [...new Set(state.evidence.filter(item => accepted.has(item.id) && item.kind === "review" && item.ok)
31
35
  .map(item => item.summary.trim()).filter(Boolean))];
@@ -33,5 +37,6 @@ export function completionReport(state, budgetExhausted = false) {
33
37
  const selected = summaries.slice(-5).map(summary => summary.length <= 2000 ? summary : summary.slice(0, 2000) + "\n[Summary shortened; full evidence is retained in the session.]");
34
38
  const more = summaries.length > selected.length ? `\n\n${summaries.length - selected.length} additional accepted task summaries are retained in the session.` : "";
35
39
  return heading + (selected.length ? "\n\n" + selected.join("\n\n") : "") + more
36
- + (budgetExhausted ? "\n\nThe model budget was exhausted; this report uses the recorded verification evidence." : "");
40
+ + (budgetExhausted ? "\n\nThe model budget was exhausted; this report uses the recorded verification evidence." : "")
41
+ + (unreconciled.length ? `\n\n${unreconciledNote(unreconciled)}` : "");
37
42
  }
@@ -0,0 +1,21 @@
1
+ /** Delivery documents (README, delivery notes, guides) the session wrote. Cycle 7
2
+ * left them to the last task (a crash left neither) and stated a session
3
+ * lifetime the code did not have; cycle 5 claimed a logout that failed. */
4
+ export declare const isDeliveryDocument: (file: string) => boolean;
5
+ /** Markdown files the request asks to be delivered that do not exist yet.
6
+ * Inputs and files the request only refers to are excluded. */
7
+ export declare function missingDeliveryDocuments(requestTexts: readonly string[], existingPaths: readonly string[], inputPaths: readonly string[]): string[];
8
+ /** Statements in a delivered document worth checking: prose lines and list
9
+ * items, without headings, fences, table rules or very short fragments. */
10
+ export declare function deliveryClaims(text: string): string[];
11
+ /** Durations a delivered document states for a setting (a session lifetime, a
12
+ * timeout, a lockout window) that no source setting and no receipt output has.
13
+ * Each finding names the document line and the settings the code does have. */
14
+ export declare function ungroundedDurations(docs: readonly {
15
+ path: string;
16
+ text: string;
17
+ }[], sources: readonly {
18
+ path: string;
19
+ text: string;
20
+ }[], receiptOutputs: readonly string[]): string[];
21
+ //# sourceMappingURL=DeliveryDocs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DeliveryDocs.d.ts","sourceRoot":"","sources":["../../src/runtime/DeliveryDocs.ts"],"names":[],"mappings":"AAGA;;2EAE2E;AAC3E,eAAO,MAAM,kBAAkB,GAAI,MAAM,MAAM,KAAG,OACuF,CAAC;AAU1I;+DAC+D;AAC/D,wBAAgB,wBAAwB,CAAC,YAAY,EAAE,SAAS,MAAM,EAAE,EAAE,aAAa,EAAE,SAAS,MAAM,EAAE,EAAE,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAuBnJ;AAED;2EAC2E;AAC3E,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAYrD;AAyDD;;+EAE+E;AAC/E,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,EAAE,OAAO,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,EACrI,cAAc,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAuB7C"}
@@ -0,0 +1,148 @@
1
+ import { isDependencyArtifact } from "./StructuralEvidence.js";
2
+ import { isTestSourcePath } from "./RequestedTestEvidence.js";
3
+ /** Delivery documents (README, delivery notes, guides) the session wrote. Cycle 7
4
+ * left them to the last task (a crash left neither) and stated a session
5
+ * lifetime the code did not have; cycle 5 claimed a logout that failed. */
6
+ export const isDeliveryDocument = (file) => /\.(?:md|markdown|mdx|rst)$/i.test(file)
7
+ && !isDependencyArtifact(file) && !/^(?:build|dist|out|coverage)\//.test(file) && !/(?:^|\/)(?:CHANGELOG|LICEN[CS]E)[^/]*$/i.test(file);
8
+ // A sentence that asks for a document to be delivered, and a mention that only
9
+ // refers to one ("see the upstream CONTRIBUTING.md", "described in BRIEF.md").
10
+ // "The repo should contain a README.md", "a README.md must explain …" and a list
11
+ // under a "Deliverables:" line ask for one too.
12
+ const DELIVER = /\b(?:deliver(?:able)?s?|deliver\w*|write|writes|written|create|creates|provide|provides|include|includes|add|adds|produce|ship|prepare|supply|document|update|maintain|keep|contain|contains|explain|explains|describe|describes|cover|covers|outputs?|artifacts?|should|must|shall|needs?|requires?|required)\b/i;
13
+ const REFERENCE = /\b(?:see|read|reads|reading|refer(?:s|ring)? to|per|from|according to|(?:described|specified|defined|listed|given) in|as in|upstream|existing|like)\s+(?:the\s+|an?\s+)?(?:[\w-]+\s+)?[`'"(\[*]?$/i;
14
+ const LIST_ITEM = /^\s*(?:[-*+]|\d+[.)])\s+/;
15
+ /** Markdown files the request asks to be delivered that do not exist yet.
16
+ * Inputs and files the request only refers to are excluded. */
17
+ export function missingDeliveryDocuments(requestTexts, existingPaths, inputPaths) {
18
+ const existing = new Set(existingPaths.map(file => file.toLowerCase()));
19
+ const inputs = new Set(inputPaths.map(file => file.toLowerCase()));
20
+ const named = new Set();
21
+ for (const text of requestTexts) {
22
+ let context = "";
23
+ for (const line of text.split(/\r?\n/)) {
24
+ if (!line.trim())
25
+ continue;
26
+ const item = LIST_ITEM.test(line);
27
+ if (!item)
28
+ context = line;
29
+ // A list item reads with the line that introduces it ("Deliverables:").
30
+ for (const sentence of line.split(/(?<=[.!?])\s+/)) {
31
+ const gate = item ? `${context} ${sentence}` : sentence;
32
+ if (!DELIVER.test(gate))
33
+ continue;
34
+ for (const match of sentence.matchAll(/(?:^|[\s`'"(\[*])((?:[\w-]+\/)*[\w.-]*[\w-]\.md)\b/gi)) {
35
+ const file = match[1].replace(/^\.\//, "");
36
+ if (REFERENCE.test(sentence.slice(0, match.index + match[0].length - match[1].length)))
37
+ continue;
38
+ if (!existing.has(file.toLowerCase()) && !inputs.has(file.toLowerCase()))
39
+ named.add(file);
40
+ }
41
+ }
42
+ }
43
+ }
44
+ return [...named];
45
+ }
46
+ /** Statements in a delivered document worth checking: prose lines and list
47
+ * items, without headings, fences, table rules or very short fragments. */
48
+ export function deliveryClaims(text) {
49
+ const claims = [];
50
+ let fenced = false;
51
+ for (const raw of text.split(/\r?\n/)) {
52
+ const line = raw.trim();
53
+ if (/^(?:```|~~~)/.test(line)) {
54
+ fenced = !fenced;
55
+ continue;
56
+ }
57
+ if (fenced || !line || /^#/.test(line) || /^\|?[\s:|-]+\|?$/.test(line))
58
+ continue;
59
+ const statement = line.replace(/^(?:[-*+]|\d+[.)])\s+/, "").replace(/^\[[ xX]\]\s+/, "").trim();
60
+ if (statement.split(/\s+/).length < 4 || statement.length > 2000)
61
+ continue;
62
+ claims.push(statement);
63
+ }
64
+ return [...new Set(claims)];
65
+ }
66
+ const SECONDS = { ms: 0.001, millisecond: 0.001, milliseconds: 0.001, s: 1, sec: 1, secs: 1, second: 1, seconds: 1,
67
+ m: 60, min: 60, mins: 60, minute: 60, minutes: 60, h: 3600, hr: 3600, hrs: 3600, hour: 3600, hours: 3600,
68
+ d: 86400, day: 86400, days: 86400, week: 604800, weeks: 604800 };
69
+ // Single-letter s, m and d count only when attached to the number (15m, 30s, 7d).
70
+ const DURATION = /(\d+(?:\.\d+)?)(?:\s*(milliseconds?|ms|secs?|seconds?|mins?|minutes?|hrs?|hours?|h|days?|weeks?)|(s|m|d))\b/gi;
71
+ // Lines that state a setting, not an incidental time ("tests take 2 minutes").
72
+ const SETTING = /(?:^|[^a-z])(ttl|timeouts?|expir\w*|lifetime|sessions?|idle|lock\w*|limits?|max\w*|min(?:imum)?|intervals?|retention|cache\w*|window|throttl\w*|rate|debounce|poll\w*|refresh\w*|cookies?|tokens?|retr(?:y|ies)|backoff|delay|duration|age|valid\w*)(?![a-z])/i;
73
+ const UNIT_HINT = /(?:^|[^a-z])(ms|millis\w*|secs?|seconds?|mins?|minutes?|hours?|hrs?|days?|weeks?|ttl|timeout|expir\w*|age|interval|delay|duration|window)(?![a-z])/i;
74
+ const words = (line) => line.replace(/([a-z0-9])([A-Z])/g, "$1_$2");
75
+ // A grounding setting must be about the same thing as the document line: one
76
+ // topic in common, or one content word. "MAX_RETRIES = 8; // per hour" does not
77
+ // ground "sessions last 8 hours".
78
+ const TOPICS = [/ttl|expir|lifetime|session|valid|(?:^|_|\b)age|idle|inactiv|cookie|token|logout|sign.?out/,
79
+ /lock|throttl|rate|attempt|brute|window|limit/, /retr|backoff|delay|attempt/, /timeout|deadline|wait/,
80
+ /interval|poll|refresh|cache|retention|debounce|schedule|cron|every|purge|cleanup/];
81
+ const IGNORED_WORDS = new Set("milli millis second seconds minute minutes hour hours days week weeks after every about with from that this than then into only each once must will const export default value values setting settings config".split(" "));
82
+ const topicWords = (text) => new Set(words(text).toLowerCase().split(/[^a-z]+/)
83
+ .filter(word => word.length >= 4 && !IGNORED_WORDS.has(word)).map(word => word.replace(/(?:es|s)$/, "").slice(0, 5)));
84
+ const sameSubject = (doc, source) => {
85
+ const a = words(doc).toLowerCase(), b = words(source).toLowerCase();
86
+ if (TOPICS.some(topic => topic.test(a) && topic.test(b)))
87
+ return true;
88
+ const shared = topicWords(source);
89
+ return [...topicWords(doc)].some(word => shared.has(word));
90
+ };
91
+ // Lines about how long a run takes, or a named library's own default.
92
+ const RUN_TIME = /\b(?:takes?|took|lasts?|runs?|finish(?:es)?|completes?)\b[^.]*\b(?:about|around|roughly|approximately|under|less than|up to)\b|\b(?:tests?|suite|build|install(?:ation)?|ci|npm|pnpm|yarn|journey|script|command)\b[^.]*\b(?:takes?|took|runs? (?:in|for)|finish(?:es)? in|completes? in)\b/i;
93
+ const LIBRARY_DEFAULT = /\b(?:library|driver|framework|browser|package|module|upstream|sdk|client|engine|runtime)(?:'s)?\b[^.]*\bdefaults?\b|\bdefaults?\b[^.]*\bof (?:the )?(?:library|driver|framework|browser|package|module)\b/i;
94
+ function durations(line) {
95
+ return [...line.matchAll(DURATION)].map(match => ({ text: match[0], seconds: Number(match[1]) * SECONDS[(match[2] ?? match[3]).toLowerCase()] }));
96
+ }
97
+ /** Values a source line gives: products and unit strings are durations already
98
+ * (in the unit the code uses), plain literals may be in any unit. */
99
+ function sourceValues(line) {
100
+ const values = [];
101
+ let rest = line;
102
+ for (const match of line.matchAll(/\d[\d_]*(?:\.\d+)?(?:\s*\*\s*\d[\d_]*(?:\.\d+)?)+/g)) {
103
+ values.push(match[0].split("*").reduce((product, part) => product * Number(part.replace(/[_\s]/g, "")), 1));
104
+ rest = rest.replace(match[0], " ");
105
+ }
106
+ for (const match of rest.matchAll(/(?:hours|minutes|seconds|days|weeks|milliseconds)\s*[=:]\s*(\d+(?:\.\d+)?)/gi)) {
107
+ values.push(Number(match[1]) * SECONDS[match[0].split(/\s*[=:]/)[0].toLowerCase()] / 0.001);
108
+ }
109
+ for (const match of rest.matchAll(/['"`](\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w)['"`]/gi)) {
110
+ values.push(Number(match[1]) * { ms: 0.001, s: 1, m: 60, h: 3600, d: 86400, w: 604800 }[match[2].toLowerCase()] / 0.001);
111
+ }
112
+ for (const match of rest.replace(/['"`]\d+(?:\.\d+)?\s*(?:ms|s|m|h|d|w)['"`]/gi, " ").matchAll(/(?<![\w.])\d[\d_]*(?:\.\d+)?(?![\w.])/g))
113
+ values.push(Number(match[0].replace(/_/g, "")));
114
+ return values;
115
+ }
116
+ const same = (a, b) => Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
117
+ // A source number counts in any unit code commonly uses for durations.
118
+ const matches = (value, seconds) => [0.001, 1, 60, 3600, 86400, 604800].some(unit => same(value * unit, seconds));
119
+ /** Durations a delivered document states for a setting (a session lifetime, a
120
+ * timeout, a lockout window) that no source setting and no receipt output has.
121
+ * Each finding names the document line and the settings the code does have. */
122
+ export function ungroundedDurations(docs, sources, receiptOutputs) {
123
+ const settings = sources.filter(source => !isDeliveryDocument(source.path) && !isTestSourcePath(source.path))
124
+ .flatMap(source => source.text.split(/\r?\n/).map((text, index) => ({ path: source.path, line: index + 1, text: text.trim() })))
125
+ .filter(line => line.text.length <= 400 && UNIT_HINT.test(words(line.text)) && /\d/.test(line.text));
126
+ const observed = receiptOutputs.flatMap(output => durations(output).map(value => value.seconds));
127
+ const findings = [];
128
+ for (const doc of docs) {
129
+ for (const [index, raw] of doc.text.split(/\r?\n/).entries()) {
130
+ const line = raw.trim();
131
+ if (!SETTING.test(words(line)) || RUN_TIME.test(line) || LIBRARY_DEFAULT.test(line))
132
+ continue;
133
+ for (const stated of durations(line)) {
134
+ if (observed.some(value => same(value, stated.seconds)))
135
+ continue;
136
+ if (settings.some(setting => sameSubject(line, setting.text) && sourceValues(setting.text).some(value => matches(value, stated.seconds))))
137
+ continue;
138
+ const keywords = [...words(line).toLowerCase().matchAll(new RegExp(SETTING.source, "gi"))].map(match => match[1]);
139
+ const sharing = settings.filter(setting => sameSubject(line, setting.text) || keywords.some(keyword => words(setting.text).toLowerCase().includes(keyword)));
140
+ const related = (sharing.length ? sharing : settings).slice(0, 3).map(setting => `${setting.path}:${setting.line} ${setting.text.slice(0, 120)}`);
141
+ findings.push(`${doc.path}:${index + 1} states ${stated.text} ("${line.slice(0, 160)}"), but no source setting has that duration and no receipt shows it.`
142
+ + (related.length ? ` Related settings in the code: ${related.join(" | ")}.` : "")
143
+ + " Make the document state what the code does (or change the code if the requirement says so), then verify again.");
144
+ }
145
+ }
146
+ }
147
+ return findings;
148
+ }