@codyswann/lisa 8.0.1 → 8.1.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 (112) hide show
  1. package/all/copy-overwrite/scripts/lib/completion-authorization.mjs +28 -0
  2. package/all/copy-overwrite/scripts/lib/completion-proof-adapters.mjs +21 -0
  3. package/all/copy-overwrite/scripts/lib/completion-proof-projection.mjs +25 -41
  4. package/all/copy-overwrite/scripts/lib/completion-proof-shape.mjs +23 -0
  5. package/all/copy-overwrite/scripts/lib/npm-update-helper-inventory.mjs +6 -0
  6. package/all/copy-overwrite/scripts/lib/tracker-row-fold.mjs +48 -0
  7. package/all/copy-overwrite/scripts/lib/work-item-estimate-actual.mjs +131 -0
  8. package/all/copy-overwrite/scripts/lib/work-item-estimate-calibration.mjs +16 -33
  9. package/all/copy-overwrite/scripts/lib/work-item-estimate-check.mjs +26 -5
  10. package/all/copy-overwrite/scripts/lib/work-item-estimate-config.mjs +21 -0
  11. package/all/copy-overwrite/scripts/lib/work-item-estimate-tally.mjs +272 -0
  12. package/all/copy-overwrite/scripts/lib/work-item-estimate.mjs +60 -31
  13. package/all/copy-overwrite/scripts/lisa-estimate.mjs +60 -9
  14. package/all/copy-overwrite/scripts/npm-updater-helper-graph.json +61 -8
  15. package/dist/core/lisa-owned-hash-ledger.json +88 -4
  16. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  17. package/dist/core/upstream-evidence-manifest.json +32 -17
  18. package/dist/utils/usage-accounting-totals.d.ts.map +1 -1
  19. package/dist/utils/usage-accounting-totals.js +6 -1
  20. package/dist/utils/usage-accounting-totals.js.map +1 -1
  21. package/package.json +4 -4
  22. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  23. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  24. package/plugins/lisa/.codex-plugin/skills/lisa-tracker-evidence/SKILL.md +1 -0
  25. package/plugins/lisa/.codex-plugin/skills/lisa-usage-accounting/SKILL.md +2 -1
  26. package/plugins/lisa/.codex-plugin/skills/lisa-usage-accounting/references/estimate.md +49 -0
  27. package/plugins/lisa/rules/reference/work-item-definition-of-ready.md +5 -2
  28. package/plugins/lisa/skills/lisa-tracker-evidence/SKILL.md +1 -0
  29. package/plugins/lisa/skills/lisa-usage-accounting/SKILL.md +2 -1
  30. package/plugins/lisa/skills/lisa-usage-accounting/references/estimate.md +49 -0
  31. package/plugins/lisa-agy/plugin.json +1 -1
  32. package/plugins/lisa-agy/skills/lisa-tracker-evidence/SKILL.md +1 -0
  33. package/plugins/lisa-agy/skills/lisa-usage-accounting/SKILL.md +2 -1
  34. package/plugins/lisa-agy/skills/lisa-usage-accounting/references/estimate.md +49 -0
  35. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  36. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  37. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  38. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  39. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  40. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  41. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  42. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  43. package/plugins/lisa-copilot/rules/reference/work-item-definition-of-ready.md +5 -2
  44. package/plugins/lisa-copilot/skills/lisa-tracker-evidence/SKILL.md +1 -0
  45. package/plugins/lisa-copilot/skills/lisa-usage-accounting/SKILL.md +2 -1
  46. package/plugins/lisa-copilot/skills/lisa-usage-accounting/references/estimate.md +49 -0
  47. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  48. package/plugins/lisa-cursor/rules/work-item-definition-of-ready-reference.mdc +5 -2
  49. package/plugins/lisa-cursor/skills/lisa-tracker-evidence/SKILL.md +1 -0
  50. package/plugins/lisa-cursor/skills/lisa-usage-accounting/SKILL.md +2 -1
  51. package/plugins/lisa-cursor/skills/lisa-usage-accounting/references/estimate.md +49 -0
  52. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  53. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  54. package/plugins/lisa-devin/rules/reference/work-item-definition-of-ready.md +5 -2
  55. package/plugins/lisa-devin/skills/lisa-tracker-evidence/SKILL.md +1 -0
  56. package/plugins/lisa-devin/skills/lisa-usage-accounting/SKILL.md +2 -1
  57. package/plugins/lisa-devin/skills/lisa-usage-accounting/references/estimate.md +49 -0
  58. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  59. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  60. package/plugins/lisa-expo-agy/plugin.json +1 -1
  61. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  62. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  63. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  64. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  65. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  67. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  68. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  69. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  70. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  71. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  72. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  73. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  74. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  75. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  77. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  78. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  79. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  80. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  81. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  82. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  83. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  84. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  85. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  86. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  87. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  88. package/plugins/lisa-rails-agy/plugin.json +1 -1
  89. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  90. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  91. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  92. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  93. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  94. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  95. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  96. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  97. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  98. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  99. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  100. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  101. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  102. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  103. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  104. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  105. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  106. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  107. package/plugins/src/base/rules/reference/work-item-definition-of-ready.md +5 -2
  108. package/plugins/src/base/skills/lisa-tracker-evidence/SKILL.md +1 -0
  109. package/plugins/src/base/skills/lisa-usage-accounting/SKILL.md +2 -1
  110. package/plugins/src/base/skills/lisa-usage-accounting/references/estimate.md +49 -0
  111. package/scripts/two-channel-couplings.json +1 -1
  112. package/typescript/copy-overwrite/.prettierignore +3 -0
@@ -34,9 +34,32 @@ import {
34
34
  validateDelivery,
35
35
  } from "./completion-proof-source.mjs";
36
36
  import { validateConformance } from "./completion-proof-conformance.mjs";
37
+ import { checkEstimate } from "./work-item-estimate-check.mjs";
37
38
 
38
39
  const PENDING_PROOF = "pending-proof";
39
40
 
41
+ /**
42
+ * The token-estimate done gate (CodySwannGT/lisa#4956): when
43
+ * `workItem.estimate.required` holds, the item needs a usage-ledger entry and
44
+ * an up-to-date actual tally beside its estimate before it may reach done.
45
+ * `completionContext` always resolves the settings; a hand-built context that
46
+ * carries none has made no claim about them, so there is nothing to check.
47
+ */
48
+ function validateEstimateTally(body, documents, context) {
49
+ const settings = context.estimate;
50
+ if (!settings) return;
51
+ requireProof(
52
+ !settings.error,
53
+ `workItem.estimate in .lisa.config.json cannot be used: ${settings.error}`
54
+ );
55
+ const result = checkEstimate(body, settings, "done", documents);
56
+ requireProof(
57
+ result.verdict !== "FAIL",
58
+ `The token estimate is not tallied for done. ${result.lines.join(" ")}`,
59
+ PENDING_PROOF
60
+ );
61
+ }
62
+
40
63
  /** Stable user-facing next action, without declaring merely pending delivery failed. */
41
64
  const NEXT =
42
65
  "Run canonical Verify/evidence, publish the accepted completion proof, then retry completion.";
@@ -245,6 +268,11 @@ export function authorizeCompletion(context) {
245
268
  chosen.record.obligations.usage.entry_ids,
246
269
  context
247
270
  );
271
+ validateEstimateTally(
272
+ fresh.body,
273
+ [fresh.body, ...comments.map(row => row.body)],
274
+ context
275
+ );
248
276
  requireProof(
249
277
  context.hasBacklink(fresh, evaluated.primary.html_url),
250
278
  "The primary pull-request backlink changed before the terminal write; restore canonical linkage.",
@@ -2,6 +2,10 @@
2
2
  // Do not edit directly — durable changes belong upstream in Lisa.
3
3
 
4
4
  /** Provider-native proof discovery/publication adapters; credentials stay in CLI. */
5
+ import {
6
+ EstimateConfigError,
7
+ resolveEstimateGate,
8
+ } from "./work-item-estimate-config.mjs";
5
9
  import {
6
10
  CompletionProofError,
7
11
  MAX_NATIVE_JSON_BYTES,
@@ -12,6 +16,22 @@ const READ_ERROR = "read-error";
12
16
  const WRITE_ERROR = "write-error";
13
17
 
14
18
  /** Construct the same strict authorizer context for supported lifecycle writers. */
19
+ /**
20
+ * The project's token-estimate settings for the done gate
21
+ * (CodySwannGT/lisa#4956). An unusable `workItem.estimate` is carried as an
22
+ * error so completion refuses with the reason instead of crashing, unless the
23
+ * project turned the gate off: then the gate never reads those settings, so
24
+ * they cannot refuse completion either.
25
+ */
26
+ function estimateSettings(config) {
27
+ try {
28
+ return resolveEstimateGate(config);
29
+ } catch (error) {
30
+ if (!(error instanceof EstimateConfigError)) throw error;
31
+ return { required: true, error: error.message };
32
+ }
33
+ }
34
+
15
35
  export function completionContext(options) {
16
36
  const { ref, contract, run, declares, hasBacklink } = options;
17
37
  const github = contract.provider === "github";
@@ -164,6 +184,7 @@ export function completionContext(options) {
164
184
  branch,
165
185
  suppliedPrUrl: options.prUrl,
166
186
  policy: options.config.verification?.completion ?? {},
187
+ estimate: estimateSettings(options.config),
167
188
  run,
168
189
  declares,
169
190
  readSubject,
@@ -5,50 +5,20 @@
5
5
  import { parseLisaUsageSection } from "./usage-ledger.mjs";
6
6
  import { isLisaUsageLedgerIntact } from "./usage-ledger-integrity.mjs";
7
7
  import { requireProof } from "./completion-proof-errors.mjs";
8
-
9
- /** Stable presentation matching; this does not parse or authorize usage data. */
10
- const normalizedRow = line =>
11
- line
12
- .trim()
13
- .split("|")
14
- .map(part => part.trim())
15
- .join("|");
16
-
17
- const CANONICAL_ALIGNMENT = "|---|---|---|---:|---:|";
18
- const ALIGNMENT_ROW = /^\|(?::?-+:?\|){5}$/;
19
- const LEADING_STAR_ITALIC = /^(\|?)\*([^*\r\n]+)\*(?=\||$)/;
20
- const ESCAPED_PUNCTUATION = /\\([!-/:-@[-`{-~])/g;
21
-
22
- /**
23
- * Fold Linear's storage normalization back to the canonical writer's form
24
- * (CodySwannGT/lisa#4690): Linear escapes Markdown punctuation one layer deep
25
- * (`\_`, `\.`), re-serializes `_…_` as `*…*`, and rewrites any table
26
- * alignment row as `| -- | … |`. Only the comparison key changes, and known
27
- * rows pass through the same fold, so a line is dropped solely when its key
28
- * equals a known canonical row; any other prose or row still reaches the
29
- * spec digest.
30
- *
31
- * Accepted limitation: any 5-cell alignment row folds to the canonical
32
- * separator, so an extra alignment row inserted into the section is
33
- * digest-invisible. Such a row carries only dashes and colons, so no
34
- * specification words can hide that way.
35
- */
36
- function comparisonKey(line) {
37
- const row = normalizedRow(line.replace(ESCAPED_PUNCTUATION, "$1"));
38
- return ALIGNMENT_ROW.test(row)
39
- ? CANONICAL_ALIGNMENT
40
- : row.replace(LEADING_STAR_ITALIC, "$1_$2_");
41
- }
8
+ import { trackerRowKey as comparisonKey } from "./tracker-row-fold.mjs";
9
+ import { humanLines } from "./work-item-estimate.mjs";
42
10
 
43
11
  /** Match the canonical writer's visible table rows to the already parsed data. */
44
12
  function accountingRows(entries) {
45
- const known = new Set([
46
- "## Lisa Usage",
47
- "_This section is managed by Lisa. Rewrites update matching usage entries in place and preserve older rows._",
48
- "|Flow|Source|Model|Tokens|Cost|",
49
- CANONICAL_ALIGNMENT,
50
- "|_No direct entries recorded_|||||",
51
- ]);
13
+ const known = new Set(
14
+ [
15
+ "## Lisa Usage",
16
+ "_This section is managed by Lisa. Rewrites update matching usage entries in place and preserve older rows._",
17
+ "|Flow|Source|Model|Tokens|Cost|",
18
+ "|---|---|---|---:|---:|",
19
+ "|_No direct entries recorded_|||||",
20
+ ].map(comparisonKey)
21
+ );
52
22
  for (const entry of entries) {
53
23
  const tokens =
54
24
  entry.totalTokens !== null
@@ -127,6 +97,20 @@ export function usageSpecRemainder(document) {
127
97
  .join("");
128
98
  }
129
99
 
100
+ /**
101
+ * A `## Lisa Estimate` section without the lines Lisa wrote
102
+ * (CodySwannGT/lisa#4956). The estimate and its actual tally are rewritten as
103
+ * work is claimed and completed, so they are metadata, like the usage ledger,
104
+ * not requirements: rewriting them must not invalidate an accepted proof. Only
105
+ * the exact lines re-rendering the section's own tokens produces are dropped;
106
+ * every other line, whatever it starts with, is a person's and stays in the
107
+ * spec digest.
108
+ */
109
+ export function estimateSpecRemainder(document) {
110
+ const human = humanLines(document);
111
+ return human.length ? `${human.join("\n")}\n` : "";
112
+ }
113
+
130
114
  /** Only a closed canonical metadata schema can be omitted from the primary spec. */
131
115
  export function canonicalCompletionBlock(name, payload) {
132
116
  let value;
@@ -9,6 +9,7 @@ import {
9
9
  } from "./completion-proof-markdown.mjs";
10
10
  import {
11
11
  canonicalCompletionBlock,
12
+ estimateSpecRemainder,
12
13
  usageSpecRemainder,
13
14
  } from "./completion-proof-projection.mjs";
14
15
  import {
@@ -75,6 +76,27 @@ export const isTime = value =>
75
76
  /(?:Z|\+00:00)$/.test(value) &&
76
77
  Number.isFinite(Date.parse(value));
77
78
 
79
+ /**
80
+ * Drop the machine-written lines of the `## Lisa Estimate` section
81
+ * (CodySwannGT/lisa#4956), keeping any prose a person added there.
82
+ */
83
+ function withoutEstimateMetadata(body) {
84
+ const headings = topLevelLines(body).filter(row => row.heading);
85
+ const estimate = headings.filter(row => row.text === "## Lisa Estimate");
86
+ requireProof(
87
+ estimate.length <= 1,
88
+ "Duplicate token-estimate sections make the primary specification ambiguous."
89
+ );
90
+ if (!estimate.length) return body;
91
+ const start = estimate[0].start;
92
+ const end = headings.find(row => row.start > start)?.start ?? body.length;
93
+ return (
94
+ body.slice(0, start) +
95
+ estimateSpecRemainder(body.slice(start, end)) +
96
+ body.slice(end)
97
+ );
98
+ }
99
+
78
100
  /** Remove only exact canonical machine-owned sections, retaining unknown prose. */
79
101
  export function primarySpecProjection(body) {
80
102
  requireProof(
@@ -96,6 +118,7 @@ export function primarySpecProjection(body) {
96
118
  usageSpecRemainder(body.slice(start, end)) +
97
119
  body.slice(end);
98
120
  }
121
+ result = withoutEstimateMetadata(result);
99
122
  for (const name of ["authorization", "postcondition"]) {
100
123
  const start = `<!-- lisa:completion-${name}:start -->`;
101
124
  const end = `<!-- lisa:completion-${name}:end -->`;
@@ -27,10 +27,16 @@ const COMMON = [
27
27
  "lib/completion-proof-shape.mjs",
28
28
  "lib/completion-proof-source.mjs",
29
29
  "lib/evidence-release-capacity.mjs",
30
+ "lib/tracker-row-fold.mjs",
30
31
  "lib/usage-artifact-ref.mjs",
31
32
  "lib/usage-effectiveness.mjs",
32
33
  "lib/usage-ledger-integrity.mjs",
33
34
  "lib/usage-ledger.mjs",
35
+ "lib/work-item-estimate.mjs",
36
+ "lib/work-item-estimate-actual.mjs",
37
+ "lib/work-item-estimate-check.mjs",
38
+ "lib/work-item-estimate-config.mjs",
39
+ "lib/work-item-estimate-tally.mjs",
34
40
  "lib/process-tree-runner.mjs",
35
41
  "lib/windows-process-job.mjs",
36
42
  "lib/windows-process-job.ps1",
@@ -0,0 +1,48 @@
1
+ // This file is managed by Lisa and IS replaced on each `lisa` run.
2
+ // Do not edit directly — durable changes belong upstream in Lisa.
3
+
4
+ /**
5
+ * The comparison key that matches a line a tracker stored against the line
6
+ * Lisa's writer rendered (CodySwannGT/lisa#4690, #4956).
7
+ *
8
+ * Linear escapes Markdown punctuation one layer deep (`\_`, `\.`),
9
+ * re-serializes `_…_` as `*…*`, and rewrites any table alignment row as
10
+ * `| -- | … |`, dropping its colons. Only the comparison key changes, and the
11
+ * writer's rows pass through the same fold, so a line counts as Lisa's solely
12
+ * when its key equals a known rendered row; any other prose or row still
13
+ * reaches the spec digest.
14
+ *
15
+ * Accepted limitation: every alignment row with the same number of cells
16
+ * folds to one key, so an extra alignment row inserted next to a managed one
17
+ * is indistinguishable from it. Such a row carries only dashes and colons, so
18
+ * no specification words can hide that way.
19
+ * @module scripts/lib/tracker-row-fold
20
+ */
21
+
22
+ const ALIGNMENT_ROW = /^\|(?::?-+:?\|)+$/;
23
+ const LEADING_STAR_ITALIC = /^(\|?)\*([^*\r\n]+)\*(?=\||$)/;
24
+ const ESCAPED_PUNCTUATION = /\\([!-/:-@[-`{-~])/g;
25
+
26
+ /**
27
+ * Trim a line and every table cell in it.
28
+ * @param {string} line - Stored or rendered line.
29
+ * @returns {string} The line with cell padding removed.
30
+ */
31
+ const normalizedRow = line =>
32
+ line
33
+ .trim()
34
+ .split("|")
35
+ .map(part => part.trim())
36
+ .join("|");
37
+
38
+ /**
39
+ * The key two lines share when one is a tracker's rewrite of the other.
40
+ * @param {string} line - Stored or rendered line.
41
+ * @returns {string} The comparison key.
42
+ */
43
+ export function trackerRowKey(line) {
44
+ const row = normalizedRow(line.replace(ESCAPED_PUNCTUATION, "$1"));
45
+ if (ALIGNMENT_ROW.test(row))
46
+ return `|${"---|".repeat(row.split("|").length - 2)}`;
47
+ return row.replace(LEADING_STAR_ITALIC, "$1_$2_");
48
+ }
@@ -0,0 +1,131 @@
1
+ // This file is managed by Lisa and IS replaced on each `lisa` run.
2
+ // Do not edit directly — durable changes belong upstream in Lisa.
3
+
4
+ /**
5
+ * The actual-spend lines of the `## Lisa Estimate` section
6
+ * (CodySwannGT/lisa#4956): the `Actual` row, its note and the
7
+ * `<!-- lisa:estimate-actual ... -->` token, rendered and read back.
8
+ *
9
+ * Reading the token back lets the section tell exactly which of its lines
10
+ * Lisa wrote: re-rendering the recorded actual reproduces them, so anything
11
+ * else is a person's text, kept on rewrite and counted in the specification.
12
+ * @module scripts/lib/work-item-estimate-actual
13
+ */
14
+
15
+ const ACTUAL_PATTERN = /<!-- lisa:estimate-actual ((?:[a-z_]+=\S*\s+)+)-->/;
16
+
17
+ /**
18
+ * @typedef {object} Actual
19
+ * @property {number | null} tokens - Complete token total, or null when unknown.
20
+ * @property {number | null} cost - Total cost, or null when unknown.
21
+ * @property {string | null} currency - Cost currency.
22
+ * @property {string[]} sources - Distinct usage `source` values behind the total.
23
+ * @property {number} entries - Usage entries the total covers.
24
+ */
25
+
26
+ /**
27
+ * Human-readable token count: 2000000 -> "2M", 1500 -> "1.5k".
28
+ * @param {number} tokens - Token count.
29
+ * @returns {string} Short form.
30
+ */
31
+ export function formatTokens(tokens) {
32
+ const short = (value, unit) =>
33
+ `${Number(value.toFixed(2)).toString()}${unit}`;
34
+ if (tokens >= 1_000_000) return short(tokens / 1_000_000, "M");
35
+ if (tokens >= 1_000) return short(tokens / 1_000, "k");
36
+ return String(tokens);
37
+ }
38
+
39
+ /**
40
+ * Render the actual row, note and token.
41
+ * @param {Actual} actual - Actual spend.
42
+ * @param {{tokensLow: number, tokensHigh: number} | null} estimate - Parsed estimate, if any.
43
+ * @returns {{row: string, note: string, token: string}} Rendered parts.
44
+ */
45
+ export function renderActual(actual, estimate) {
46
+ const midpoint = estimate
47
+ ? (estimate.tokensLow + estimate.tokensHigh) / 2
48
+ : null;
49
+ const ratio =
50
+ actual.tokens !== null && midpoint
51
+ ? Number((actual.tokens / midpoint).toFixed(2))
52
+ : null;
53
+ const tokens =
54
+ actual.tokens === null ? "unknown" : formatTokens(actual.tokens);
55
+ const cost =
56
+ actual.cost === null
57
+ ? "unknown"
58
+ : `$${actual.cost.toFixed(2)} ${actual.currency ?? ""}`.trim();
59
+ const fields = [
60
+ `tokens=${actual.tokens ?? "null"}`,
61
+ `cost=${actual.cost ?? "null"}`,
62
+ `currency=${actual.currency === null ? "null" : encodeURIComponent(actual.currency)}`,
63
+ `sources=${encodeURIComponent(actual.sources.join(","))}`,
64
+ `entries=${actual.entries}`,
65
+ `ratio=${ratio ?? "null"}`,
66
+ ];
67
+ const comparison =
68
+ ratio === null ? "" : `; ${ratio}x the estimate's midpoint`;
69
+ return {
70
+ row: `| Actual | ${tokens} | ${cost} | — |`,
71
+ note: `Actual: the Lisa Usage ledger total over ${actual.entries} usage entr${actual.entries === 1 ? "y" : "ies"} (source: ${actual.sources.join(", ") || "child work items only"})${comparison}.`,
72
+ token: `<!-- lisa:estimate-actual ${fields.join(" ")} -->`,
73
+ };
74
+ }
75
+
76
+ /**
77
+ * The raw fields of the actual token recorded in a section.
78
+ * @param {string | null} section - Estimate section text.
79
+ * @returns {Record<string, string> | null} Fields as written, or null when there is no token.
80
+ */
81
+ export function actualTokenFields(section) {
82
+ const match = section ? ACTUAL_PATTERN.exec(section) : null;
83
+ if (!match) return null;
84
+ return Object.fromEntries(
85
+ match[1]
86
+ .trim()
87
+ .split(/\s+/)
88
+ .map(pair => [
89
+ pair.slice(0, pair.indexOf("=")),
90
+ pair.slice(pair.indexOf("=") + 1),
91
+ ])
92
+ );
93
+ }
94
+
95
+ /**
96
+ * The actual recorded in a section, read back from its token.
97
+ * @param {string | null} section - Estimate section text.
98
+ * @returns {Actual | null} The recorded actual, or null when none parses.
99
+ */
100
+ export function parseActualToken(section) {
101
+ const fields = actualTokenFields(section);
102
+ if (!fields) return null;
103
+ const number = value =>
104
+ value === undefined || value === "null" ? null : Number(value);
105
+ const tokens = number(fields.tokens);
106
+ const cost = number(fields.cost);
107
+ const entries = Number(fields.entries);
108
+ if (
109
+ [tokens, cost].some(value => value !== null && !Number.isFinite(value)) ||
110
+ !Number.isSafeInteger(entries)
111
+ )
112
+ return null;
113
+ try {
114
+ return {
115
+ tokens,
116
+ cost,
117
+ currency:
118
+ fields.currency === undefined || fields.currency === "null"
119
+ ? null
120
+ : decodeURIComponent(fields.currency),
121
+ sources: decodeURIComponent(fields.sources ?? "")
122
+ .split(",")
123
+ .filter(Boolean),
124
+ entries,
125
+ };
126
+ } catch (error) {
127
+ // A malformed percent escape makes the token unparseable, not the caller.
128
+ if (error instanceof URIError) return null;
129
+ throw error;
130
+ }
131
+ }
@@ -5,18 +5,20 @@
5
5
  * Calibrate a new token estimate against finished work (CodySwannGT/lisa#4955).
6
6
  *
7
7
  * For each comparable finished item that carries both an estimate and a
8
- * complete actual, the ratio is the actual token total (the item's
9
- * `## Lisa Usage` rollup, the same ledger the completion tally reads) over the
10
- * estimate's midpoint. The median ratio scales the new range. Items whose
8
+ * complete actual, the ratio is the actual token total over the estimate's
9
+ * midpoint. The actual is the item's recorded done tally, which counted every
10
+ * usage ledger it carried, comments included; an item finished before tallies
11
+ * were recorded falls back to its body's `## Lisa Usage` ledger. The median ratio scales the new range. Items whose
11
12
  * actual is unknown or partial (no ledger, or any run with `unavailable`
12
13
  * telemetry or a measured subset) are skipped, never counted as zero or as the
13
14
  * sum of only the known runs. With no usable history the range is
14
15
  * returned unchanged and the basis says so.
15
16
  * @module scripts/lib/work-item-estimate-calibration
16
17
  */
17
- import { parseLisaUsageSection } from "./usage-ledger.mjs";
18
18
  import { EstimateConfigError } from "./work-item-estimate-config.mjs";
19
+ import { parseActualToken } from "./work-item-estimate-actual.mjs";
19
20
  import { parseEstimateSection } from "./work-item-estimate.mjs";
21
+ import { ledgerActual } from "./work-item-estimate-tally.mjs";
20
22
 
21
23
  /**
22
24
  * Whether a parsed token count is a usable positive number (NaN is not).
@@ -25,47 +27,28 @@ import { parseEstimateSection } from "./work-item-estimate.mjs";
25
27
  */
26
28
  const isPositive = value => Number.isFinite(value) && value > 0;
27
29
 
28
- /**
29
- * Whether a usage entry lacks a full token count: `unavailable` telemetry or
30
- * a measured subset of the run.
31
- * @param {{totalTokens: number | null, source: string, measuredSubsetTokens?: number | null}} entry - Parsed usage entry.
32
- * @returns {boolean} True when the run's tokens are unknown or partial.
33
- */
34
- const isPartialRun = entry =>
35
- entry.totalTokens === null ||
36
- entry.source === "measured-subset" ||
37
- (entry.measuredSubsetTokens ?? null) !== null;
38
-
39
30
  /**
40
31
  * The actual-to-estimate ratio one finished item shows, if it shows one.
41
32
  * @param {string} body - Finished item body.
42
33
  * @returns {number | null} Ratio, or null when the item cannot calibrate.
43
34
  */
44
35
  export function itemRatio(body) {
45
- const { estimate } = parseEstimateSection(body);
36
+ const { estimate, section } = parseEstimateSection(body);
46
37
  if (
47
38
  !estimate ||
48
39
  !isPositive(estimate.tokensLow) ||
49
40
  !isPositive(estimate.tokensHigh)
50
41
  )
51
42
  return null;
52
- let ledger;
53
- try {
54
- ledger = parseLisaUsageSection(body);
55
- } catch {
56
- return null;
57
- }
58
- const { entries, rollup } = ledger;
59
- const actual = rollup?.totalTokens;
60
- // The rollup adds up only the runs it knows, so one run without a full
61
- // token count makes its total a partial sum, not the actual.
62
- if (
63
- entries.some(isPartialRun) ||
64
- rollup?.childTokensIncomplete ||
65
- !Number.isFinite(actual) ||
66
- actual <= 0
67
- )
68
- return null;
43
+ // The done tally already counted every ledger the item carried, comments
44
+ // included, which a history fetch of bodies never sees. Trust its recorded
45
+ // actual (an unknown one stays unknown); read the body's ledger only for an
46
+ // item finished before tallies were recorded.
47
+ const recorded = parseActualToken(section);
48
+ const actual = recorded
49
+ ? recorded.tokens
50
+ : (ledgerActual([body])?.tokens ?? null);
51
+ if (actual === null || !isPositive(actual)) return null;
69
52
  return actual / ((estimate.tokensLow + estimate.tokensHigh) / 2);
70
53
  }
71
54
 
@@ -13,13 +13,16 @@
13
13
  * not a sound range of its own, or one that disagrees with the price table it
14
14
  * names. When `workItem.estimate.required`
15
15
  * is false the gate is `N/A` and blocks nothing. At claim time a missing
16
- * estimate is a FAIL: the claiming agent must write one before any work.
16
+ * estimate is a FAIL: the claiming agent must write one before any work. At
17
+ * done time (CodySwannGT/lisa#4956) the item needs a usage-ledger entry and an
18
+ * up-to-date actual tally beside the estimate.
17
19
  * @module scripts/lib/work-item-estimate-check
18
20
  */
19
21
  import { costCents, priceFor } from "./work-item-estimate-config.mjs";
20
22
  import { parseEstimateSection } from "./work-item-estimate.mjs";
23
+ import { doneProblems } from "./work-item-estimate-tally.mjs";
21
24
 
22
- const PHASES = new Set(["ready", "claim"]);
25
+ const PHASES = new Set(["ready", "claim", "done"]);
23
26
 
24
27
  /**
25
28
  * Problems with a parsed estimate's own fields.
@@ -115,13 +118,19 @@ function pricingProblems(estimate, settings) {
115
118
  * Run the estimate gate on an item body.
116
119
  * @param {string} body - Item body as stored.
117
120
  * @param {object} settings - Result of `resolveEstimateConfig`.
118
- * @param {string} [phase] - Lifecycle moment: `ready` (default) or `claim`.
121
+ * @param {string} [phase] - Lifecycle moment: `ready` (default), `claim` or `done`.
122
+ * @param {string[]} [documents] - At done: where the usage ledger may live (body, then comments).
119
123
  * @returns {{verdict: "PASS" | "FAIL" | "N/A", lines: string[]}} Gate result.
120
124
  */
121
- export function checkEstimate(body, settings, phase = "ready") {
125
+ export function checkEstimate(
126
+ body,
127
+ settings,
128
+ phase = "ready",
129
+ documents = [body]
130
+ ) {
122
131
  if (!PHASES.has(phase))
123
132
  throw new RangeError(
124
- `Unknown phase ${JSON.stringify(phase)}; expected ready or claim.`
133
+ `Unknown phase ${JSON.stringify(phase)}; expected ready, claim or done.`
125
134
  );
126
135
  const warnings = settings.warnings ?? [];
127
136
  if (!settings.required)
@@ -129,6 +138,18 @@ export function checkEstimate(body, settings, phase = "ready") {
129
138
  verdict: "N/A",
130
139
  lines: ["workItem.estimate.required is false; no estimate is required."],
131
140
  };
141
+ if (phase === "done") {
142
+ const problems = doneProblems(body, documents);
143
+ return problems.length
144
+ ? { verdict: "FAIL", lines: [...warnings, ...problems] }
145
+ : {
146
+ verdict: "PASS",
147
+ lines: [
148
+ ...warnings,
149
+ "The actual tokens and cost are tallied beside the estimate.",
150
+ ],
151
+ };
152
+ }
132
153
  const { count, estimate } = parseEstimateSection(body);
133
154
  if (count > 1)
134
155
  return {
@@ -160,6 +160,27 @@ export function resolveEstimateConfig(config) {
160
160
  };
161
161
  }
162
162
 
163
+ /**
164
+ * The estimate gate's settings, tolerating settings the gate never reads: a
165
+ * project that turned the gate off (`required: false`) gets the disabled gate
166
+ * even when its `models` or `tokenMix` would not validate, so a disabled gate
167
+ * can never refuse anything. With the gate on, unusable settings still throw.
168
+ * @param {unknown} config - Project config (`.lisa.config.json` content).
169
+ * @returns {{required: boolean, warnings: string[]}} Settings for `checkEstimate`.
170
+ */
171
+ export function resolveEstimateGate(config) {
172
+ try {
173
+ return resolveEstimateConfig(config);
174
+ } catch (error) {
175
+ if (
176
+ error instanceof EstimateConfigError &&
177
+ config?.workItem?.estimate?.required === false
178
+ )
179
+ return { required: false, warnings: [] };
180
+ throw error;
181
+ }
182
+ }
183
+
163
184
  /**
164
185
  * Find a model's rates in one price table. Keys are `<provider>/<model>`, as
165
186
  * in the usage-accounting pricing schema; a bare `<model>` key also matches.