@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
@@ -0,0 +1,272 @@
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 completion tally: actual tokens and dollar cost next to the estimate
6
+ * (CodySwannGT/lisa#4956).
7
+ *
8
+ * The actual is the work item's `## Lisa Usage` ledgers, the existing ledger
9
+ * every agent already records its spend into, on the body and on any comment;
10
+ * there is no second ledger. A total that any run leaves unknown
11
+ * (`unavailable` telemetry, a measured subset) is shown as unknown, never as
12
+ * zero, a partial sum or a guess. The tally is
13
+ * written into the `## Lisa Estimate` section as an `Actual` row plus one
14
+ * `<!-- lisa:estimate-actual ... -->` token, and the done gate checks that the
15
+ * recorded tally still matches the ledger.
16
+ * @module scripts/lib/work-item-estimate-tally
17
+ */
18
+ import { LISA_USAGE_HEADING, parseLisaUsageSection } from "./usage-ledger.mjs";
19
+ import {
20
+ actualTokenFields,
21
+ renderActual,
22
+ } from "./work-item-estimate-actual.mjs";
23
+ import { EstimateConfigError } from "./work-item-estimate-config.mjs";
24
+ import {
25
+ parseEstimateSection,
26
+ renderEstimateSection,
27
+ upsertEstimateSection,
28
+ } from "./work-item-estimate.mjs";
29
+
30
+ const NO_LEDGER =
31
+ "No Lisa Usage entry is recorded on this item. It cannot reach done without one: record each run through lisa-usage-accounting (source unavailable is the honest value when the runtime gives no telemetry), then run lisa-estimate tally.";
32
+ const MIXED_CURRENCY = "mixed";
33
+ /** A usage section that has the heading but cannot be read in full. */
34
+ const UNREADABLE = Object.freeze({ unreadable: true });
35
+ /** The source the actual names for a section it could not read. */
36
+ const UNREADABLE_SOURCE = "unreadable-ledger";
37
+ const LOOSE_ENTRY_TOKEN = /<!-- lisa:usage-entry\s/g;
38
+ const LOOSE_ROLLUP_TOKEN = /<!-- lisa:usage-rollup\s/;
39
+ const COST_SCALE = 12;
40
+
41
+ /**
42
+ * A document's usage ledger, when it has a readable one that records any run:
43
+ * a direct entry, or child work its rollup carries (a parent whose only spend
44
+ * is its children's has no direct entries of its own). A section without a
45
+ * rollup token still has its direct entries counted, so no run vanishes from
46
+ * the actual; it simply has no child aggregate.
47
+ *
48
+ * A section that cannot be read in full is UNREADABLE, never dropped: a token
49
+ * the parser refuses, and also one it would skip (an entry or rollup token too
50
+ * damaged to match at all), since either way some of the item's spend is
51
+ * missing and any total over the rest would be a partial sum.
52
+ * @param {unknown} document - Item body or comment.
53
+ * @returns {{entries: object[], children: object | null} | typeof UNREADABLE | null} Direct entries and the rollup when it carries child work, UNREADABLE, or null when the document has no usage section.
54
+ */
55
+ function readLedger(document) {
56
+ if (typeof document !== "string" || !document.includes(LISA_USAGE_HEADING))
57
+ return null;
58
+ let parsed;
59
+ try {
60
+ parsed = parseLisaUsageSection(document);
61
+ } catch {
62
+ return UNREADABLE;
63
+ }
64
+ const { entries, rollup, range } = parsed;
65
+ if (!range) return null;
66
+ const section = document.slice(range.start, range.end);
67
+ const skipped =
68
+ (section.match(LOOSE_ENTRY_TOKEN) ?? []).length !== entries.length ||
69
+ (LOOSE_ROLLUP_TOKEN.test(section) && !rollup);
70
+ if (skipped) return UNREADABLE;
71
+ const children = rollup?.childEntryIds.length ? rollup : null;
72
+ return entries.length || children ? { entries, children } : null;
73
+ }
74
+
75
+ /**
76
+ * Whether a run's token count is unknown or only part of the run.
77
+ * @param {object} entry - Parsed usage entry.
78
+ * @returns {boolean} True when the run has no full token count.
79
+ */
80
+ const partialTokens = entry =>
81
+ entry.totalTokens === null ||
82
+ entry.source === "measured-subset" ||
83
+ (entry.measuredSubsetTokens ?? null) !== null;
84
+
85
+ /**
86
+ * Add decimal amounts without binary floating-point drift.
87
+ * @param {number[]} amounts - Finite amounts.
88
+ * @returns {number} Their sum.
89
+ */
90
+ function addAmounts(amounts) {
91
+ const scale = 10n ** BigInt(COST_SCALE);
92
+ const total = amounts.reduce(
93
+ (sum, amount) => sum + BigInt(amount.toFixed(COST_SCALE).replace(".", "")),
94
+ 0n
95
+ );
96
+ const negative = total < 0n;
97
+ const magnitude = negative ? -total : total;
98
+ const fraction = String(magnitude % scale).padStart(COST_SCALE, "0");
99
+ return Number(`${negative ? "-" : ""}${magnitude / scale}.${fraction}`);
100
+ }
101
+
102
+ /**
103
+ * Every distinct run the item's ledgers record, by run identity (entry id).
104
+ * The same run written in two places (the body's ledger and an evidence
105
+ * comment that repeats it) is counted once, so a comment that repeats the
106
+ * body's runs and adds its own Verify run is an ordinary, complete layout.
107
+ * Child work arrives only as each ledger's aggregate, which cannot be split:
108
+ * a ledger's child runs are counted once when none was counted before,
109
+ * skipped when every one was, and make the total ambiguous only when some
110
+ * were counted and some were not.
111
+ * @param {{entries: object[], children: object | null}[]} ledgers - Parsed ledgers, body first.
112
+ * @returns {{runs: object[], children: object[], ids: Set<string>, ambiguous: boolean}} Distinct direct runs, child aggregates, every run id, and whether the total is ambiguous.
113
+ */
114
+ function distinctRuns(ledgers) {
115
+ const ids = new Set();
116
+ const runs = [];
117
+ const children = [];
118
+ let ambiguous = false;
119
+ for (const { entries } of ledgers)
120
+ for (const entry of entries)
121
+ if (!ids.has(entry.entryId)) {
122
+ ids.add(entry.entryId);
123
+ runs.push(entry);
124
+ }
125
+ for (const { children: rollup } of ledgers) {
126
+ const own = rollup?.childEntryIds ?? [];
127
+ const repeated = own.filter(id => ids.has(id)).length;
128
+ if (own.length === 0 || repeated === own.length) continue;
129
+ ambiguous ||= repeated > 0;
130
+ for (const id of own) ids.add(id);
131
+ children.push(rollup);
132
+ }
133
+ return { runs, children, ids, ambiguous };
134
+ }
135
+
136
+ /**
137
+ * The actual spend across every usage ledger the item carries: the body's and
138
+ * any comment's. Completion accepts a run recorded in either place, so the
139
+ * actual counts every distinct run once. A total is unknown, never a partial
140
+ * sum, when any run behind it is unknown or the runs cannot be told apart.
141
+ * @param {string[]} documents - Item body, then its comments.
142
+ * A usage section that cannot be read in full makes every total unknown and
143
+ * is named among the sources.
144
+ * @returns {import("./work-item-estimate-actual.mjs").Actual | null} The actual, or null when no document has a usage section with a run.
145
+ */
146
+ export function ledgerActual(documents) {
147
+ const found = documents.map(readLedger).filter(ledger => ledger !== null);
148
+ if (found.length === 0) return null;
149
+ const unreadable = found.includes(UNREADABLE);
150
+ const ledgers = found.filter(ledger => ledger !== UNREADABLE);
151
+ const { runs, children, ids, ambiguous } = distinctRuns(ledgers);
152
+ const unknown = ambiguous || unreadable;
153
+ const tokensKnown =
154
+ !unknown &&
155
+ !runs.some(partialTokens) &&
156
+ children.every(
157
+ child =>
158
+ child.childTokensIncomplete !== true && child.childTokens !== null
159
+ );
160
+ const currencies = new Set([
161
+ ...runs.map(entry => entry.currency).filter(Boolean),
162
+ ...children.map(child => child.childCurrency).filter(Boolean),
163
+ ]);
164
+ const costKnown =
165
+ !unknown &&
166
+ currencies.size <= 1 &&
167
+ !currencies.has(MIXED_CURRENCY) &&
168
+ runs.every(entry => entry.cost !== null) &&
169
+ children.every(child => child.childCost !== null);
170
+ const currency = unreadable
171
+ ? null
172
+ : currencies.size > 1
173
+ ? MIXED_CURRENCY
174
+ : (currencies.values().next().value ?? null);
175
+ return {
176
+ tokens: tokensKnown
177
+ ? [
178
+ ...runs.map(entry => entry.totalTokens),
179
+ ...children.map(child => child.childTokens),
180
+ ].reduce((sum, value) => sum + value, 0)
181
+ : null,
182
+ cost: costKnown
183
+ ? addAmounts([
184
+ ...runs.map(entry => entry.cost),
185
+ ...children.map(child => child.childCost),
186
+ ])
187
+ : null,
188
+ currency,
189
+ sources: [
190
+ ...new Set([
191
+ ...runs.map(entry => entry.source),
192
+ ...(unreadable ? [UNREADABLE_SOURCE] : []),
193
+ ]),
194
+ ].sort(),
195
+ entries: ids.size,
196
+ };
197
+ }
198
+
199
+ /**
200
+ * Rewrite the estimate section with the actual from the usage ledger.
201
+ * @param {string} body - Item body.
202
+ * @param {string[]} [documents] - Where the ledger may live: the body, then comments.
203
+ * @returns {string} Updated body.
204
+ */
205
+ export function tallyEstimate(body, documents = [body]) {
206
+ const actual = ledgerActual(documents);
207
+ if (!actual) throw new EstimateConfigError(NO_LEDGER);
208
+ const { count, estimate } = parseEstimateSection(body);
209
+ if (count > 1)
210
+ throw new EstimateConfigError(
211
+ "The body has more than one Lisa Estimate section; remove the extra copies first."
212
+ );
213
+ return upsertEstimateSection(
214
+ body,
215
+ renderEstimateSection(estimate, renderActual(actual, estimate))
216
+ );
217
+ }
218
+
219
+ /**
220
+ * The actual tally recorded in a section, as written.
221
+ * @param {string | null} section - Estimate section text.
222
+ * @returns {{tokens: string, cost: string, currency: string, sources: string, entries: string} | null} Raw recorded fields.
223
+ */
224
+ function recordedActual(section) {
225
+ const fields = actualTokenFields(section);
226
+ if (!fields) return null;
227
+ try {
228
+ return {
229
+ tokens: fields.tokens,
230
+ cost: fields.cost,
231
+ currency: decodeURIComponent(fields.currency ?? "null"),
232
+ sources: decodeURIComponent(fields.sources ?? ""),
233
+ entries: fields.entries ?? "null",
234
+ };
235
+ } catch (error) {
236
+ if (error instanceof URIError) return null;
237
+ throw error;
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Why an item may not reach done yet, from the estimate's point of view.
243
+ * @param {string} body - Item body.
244
+ * @param {string[]} [documents] - Where the ledger may live: the body, then comments.
245
+ * @returns {string[]} Problems; empty when done may proceed.
246
+ */
247
+ export function doneProblems(body, documents = [body]) {
248
+ const actual = ledgerActual(documents);
249
+ if (!actual) return [NO_LEDGER];
250
+ const { count, section } = parseEstimateSection(body);
251
+ if (count > 1)
252
+ return [`The body has ${count} Lisa Estimate sections; keep exactly one.`];
253
+ const recorded = recordedActual(section);
254
+ if (!recorded)
255
+ return [
256
+ "The estimate does not yet show the actual tokens and cost. Run lisa-estimate tally and write the body back.",
257
+ ];
258
+ const current = {
259
+ tokens: String(actual.tokens ?? "null"),
260
+ cost: String(actual.cost ?? "null"),
261
+ currency: actual.currency ?? "null",
262
+ sources: actual.sources.join(","),
263
+ entries: String(actual.entries),
264
+ };
265
+ // Every recorded field, not only the totals: two unavailable runs and one
266
+ // both total null, so only the entry count tells them apart.
267
+ return Object.keys(current).every(key => recorded[key] === current[key])
268
+ ? []
269
+ : [
270
+ `The actual tally is stale: it records ${recorded.tokens} tokens and ${recorded.cost} ${recorded.currency} over ${recorded.entries} usage entries, but the usage ledger now totals ${current.tokens} tokens and ${current.cost} ${current.currency} over ${current.entries}. Run lisa-estimate tally again.`,
271
+ ];
272
+ }
@@ -12,6 +12,12 @@
12
12
  * shape cannot drift between agents or trackers.
13
13
  * @module scripts/lib/work-item-estimate
14
14
  */
15
+ import {
16
+ formatTokens,
17
+ parseActualToken,
18
+ renderActual,
19
+ } from "./work-item-estimate-actual.mjs";
20
+ import { trackerRowKey } from "./tracker-row-fold.mjs";
15
21
  import {
16
22
  costCents,
17
23
  EstimateConfigError,
@@ -40,19 +46,6 @@ const encode = value => (value === null ? "null" : encodeURIComponent(value));
40
46
  const decode = value => (value === "null" ? null : decodeURIComponent(value));
41
47
  const dollars = cents => (cents / 100).toFixed(2);
42
48
 
43
- /**
44
- * Human-readable token count: 2000000 -> "2M", 1500 -> "1.5k".
45
- * @param {number} tokens - Token count.
46
- * @returns {string} Short form.
47
- */
48
- export function formatTokens(tokens) {
49
- const short = (value, unit) =>
50
- `${Number(value.toFixed(2)).toString()}${unit}`;
51
- if (tokens >= 1_000_000) return short(tokens / 1_000_000, "M");
52
- if (tokens >= 1_000) return short(tokens / 1_000, "k");
53
- return String(tokens);
54
- }
55
-
56
49
  /**
57
50
  * Parse a token count written as `2000000`, `2M`, `2.5m` or `500k`.
58
51
  * @param {string} text - Count as written.
@@ -106,11 +99,18 @@ export function buildEstimate(input, settings) {
106
99
  }
107
100
 
108
101
  /**
109
- * Render the managed section for an estimate.
110
- * @param {Estimate} estimate - Result of {@link buildEstimate}.
111
- * @returns {string} Markdown section, ending in a newline.
102
+ * The estimate row and machine token, or a plain "none recorded" row when the
103
+ * item reached completion without one.
104
+ * @param {Estimate | null} estimate - Estimate, if any.
105
+ * @returns {{row: string, basis: string, token: string | null}} Rendered parts.
112
106
  */
113
- export function renderEstimateSection(estimate) {
107
+ function estimateParts(estimate) {
108
+ if (!estimate)
109
+ return {
110
+ row: "| Estimate | none recorded | — | — |",
111
+ basis: "no estimate was recorded before work began",
112
+ token: null,
113
+ };
114
114
  const cost =
115
115
  estimate.costLow === null
116
116
  ? "unpriced"
@@ -126,6 +126,22 @@ export function renderEstimateSection(estimate) {
126
126
  `model=${encode(estimate.model)}`,
127
127
  `basis=${encode(estimate.basis)}`,
128
128
  ];
129
+ return {
130
+ row: `| Estimate | ${formatTokens(estimate.tokensLow)}–${formatTokens(estimate.tokensHigh)} | ${cost} | ${estimate.model} |`,
131
+ basis: estimate.basis,
132
+ token: `<!-- lisa:estimate ${fields.join(" ")} -->`,
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Render the managed section for an estimate and, once the work is done, its
138
+ * actual (CodySwannGT/lisa#4956).
139
+ * @param {Estimate | null} estimate - Result of {@link buildEstimate}, or null when none was recorded.
140
+ * @param {{row: string, note: string, token: string} | null} [actual] - Rendered actual parts from the tally.
141
+ * @returns {string} Markdown section, ending in a newline.
142
+ */
143
+ export function renderEstimateSection(estimate, actual = null) {
144
+ const parts = estimateParts(estimate);
129
145
  return [
130
146
  ESTIMATE_HEADING,
131
147
  "",
@@ -133,11 +149,14 @@ export function renderEstimateSection(estimate) {
133
149
  "",
134
150
  "| Row | Tokens | Cost | Model |",
135
151
  "|---|---:|---:|---|",
136
- `| Estimate | ${formatTokens(estimate.tokensLow)}–${formatTokens(estimate.tokensHigh)} | ${cost} | ${estimate.model} |`,
152
+ parts.row,
153
+ ...(actual ? [actual.row] : []),
137
154
  "",
138
- `Basis: ${estimate.basis}`,
155
+ `Basis: ${parts.basis}`,
156
+ ...(actual ? ["", actual.note] : []),
139
157
  "",
140
- `<!-- lisa:estimate ${fields.join(" ")} -->`,
158
+ ...(parts.token ? [parts.token] : []),
159
+ ...(actual ? [actual.token] : []),
141
160
  "",
142
161
  ].join("\n");
143
162
  }
@@ -230,27 +249,35 @@ function parseTokenFields(section) {
230
249
  /**
231
250
  * Parse the item's estimate section.
232
251
  * @param {string} body - Item body.
233
- * @returns {{count: number, estimate: Estimate | null}} Section count and its parsed token.
252
+ * @returns {{count: number, estimate: Estimate | null, section: string | null}} Section count, its parsed estimate token, and its text.
234
253
  */
235
254
  export function parseEstimateSection(body) {
236
255
  const spans = estimateSpans(body);
237
- if (spans.length !== 1) return { count: spans.length, estimate: null };
256
+ if (spans.length !== 1)
257
+ return { count: spans.length, estimate: null, section: null };
238
258
  const lines = body.split("\n").slice(spans[0].start, spans[0].end);
239
- return { count: 1, estimate: parseToken(lines.join("\n")) };
259
+ const section = lines.join("\n");
260
+ return { count: 1, estimate: parseToken(section), section };
240
261
  }
241
262
 
242
263
  /**
243
264
  * The lines Lisa itself wrote in a section: exactly what rendering its own
244
- * token produces. Anything else in the section is a person's text. A section
245
- * with no parseable token has no Lisa-written lines but its heading.
265
+ * tokens produces, the estimate and any recorded actual. Anything else in the
266
+ * section is a person's text. A section with neither token parseable has no
267
+ * Lisa-written lines but its heading.
246
268
  * @param {string} section - Section text, heading first.
247
269
  * @returns {string[]} Trimmed, non-empty managed lines (a multiset).
248
270
  */
249
271
  export function managedEstimateLines(section) {
250
272
  const estimate = parseToken(section);
251
- const rendered = estimate
252
- ? renderEstimateSection(estimate)
253
- : ESTIMATE_HEADING;
273
+ const actual = parseActualToken(section);
274
+ const rendered =
275
+ estimate || actual
276
+ ? renderEstimateSection(
277
+ estimate,
278
+ actual ? renderActual(actual, estimate) : null
279
+ )
280
+ : ESTIMATE_HEADING;
254
281
  return rendered
255
282
  .split("\n")
256
283
  .map(line => line.trim())
@@ -258,14 +285,16 @@ export function managedEstimateLines(section) {
258
285
  }
259
286
 
260
287
  /**
261
- * The lines of a section that Lisa did not write, in order.
288
+ * The lines of a section that Lisa did not write, in order. A line a tracker
289
+ * rewrote (an alignment row stored as `| -- | -- |`, escaped punctuation) is
290
+ * still Lisa's: lines compare by the same fold the usage rows use.
262
291
  * @param {string} section - Section text, heading first.
263
292
  * @returns {string[]} A person's lines, blank lines dropped.
264
293
  */
265
294
  export function humanLines(section) {
266
- const managed = managedEstimateLines(section);
295
+ const managed = managedEstimateLines(section).map(trackerRowKey);
267
296
  return section.split("\n").filter(line => {
268
- const at = managed.indexOf(line.trim());
297
+ const at = managed.indexOf(trackerRowKey(line));
269
298
  if (at !== -1) managed.splice(at, 1);
270
299
  return at === -1 && line.trim() !== "";
271
300
  });
@@ -17,12 +17,19 @@
17
17
  * --model claude-opus-5-5 [--basis <text>] [--body-file <path>]
18
18
  * node scripts/lisa-estimate.mjs calibrate --tokens-low 1M --tokens-high 2M
19
19
  * --history-file <comparable-items.json>
20
- * node scripts/lisa-estimate.mjs check [--phase ready|claim] [--body-file <path>]
20
+ * node scripts/lisa-estimate.mjs tally [--body-file <path>] [--usage-file <path>]...
21
+ * node scripts/lisa-estimate.mjs check [--phase ready|claim|done]
22
+ * [--body-file <path>] [--usage-file <path>]...
21
23
  *
22
24
  * `calibrate` scales a first estimate by how comparable finished items
23
25
  * actually ran (their `## Lisa Usage` totals against their estimates) and
24
26
  * prints the calibrated range and a basis line to pass to `render`.
25
27
  *
28
+ * `tally` rewrites the estimate section with the actual tokens and cost from
29
+ * the item's `## Lisa Usage` ledgers and prints the whole body. Pass every
30
+ * comment that holds a ledger with its own `--usage-file`, as many times as
31
+ * needed, to both `tally` and `check --phase done`.
32
+ *
26
33
  * `check` exits 0 on PASS or N/A and 1 on FAIL; any usage or config error
27
34
  * exits 2. Without `--body-file`, the body is read from standard input.
28
35
  * @module lisa-estimate
@@ -35,6 +42,7 @@ import {
35
42
  DEFAULT_ESTIMATE_PRICING,
36
43
  EstimateConfigError,
37
44
  resolveEstimateConfig,
45
+ resolveEstimateGate,
38
46
  } from "./lib/work-item-estimate-config.mjs";
39
47
  import {
40
48
  buildEstimate,
@@ -47,6 +55,7 @@ import {
47
55
  historyBodies,
48
56
  } from "./lib/work-item-estimate-calibration.mjs";
49
57
  import { checkEstimate } from "./lib/work-item-estimate-check.mjs";
58
+ import { tallyEstimate } from "./lib/work-item-estimate-tally.mjs";
50
59
 
51
60
  const VALUE_FLAGS = new Set([
52
61
  "--tokens-low",
@@ -56,13 +65,18 @@ const VALUE_FLAGS = new Set([
56
65
  "--body-file",
57
66
  "--phase",
58
67
  "--history-file",
68
+ "--usage-file",
59
69
  "--cwd",
60
70
  ]);
61
71
 
72
+ // Every comment that holds a usage ledger is passed with its own --usage-file.
73
+ const REPEATABLE_FLAGS = new Set(["usage-file"]);
74
+
62
75
  /**
63
- * Parse `--flag value` pairs.
76
+ * Parse `--flag value` pairs. A repeatable flag's value is the list of every
77
+ * value it was given, in order.
64
78
  * @param {string[]} args - Arguments after the subcommand.
65
- * @returns {Record<string, string>} Flag values keyed without the dashes.
79
+ * @returns {Record<string, string | string[]>} Flag values keyed without the dashes.
66
80
  */
67
81
  function parseFlags(args) {
68
82
  if (
@@ -72,8 +86,26 @@ function parseFlags(args) {
72
86
  throw new EstimateConfigError(
73
87
  `Unrecognised arguments ${JSON.stringify(args)}. Run with --help for the options.`
74
88
  );
89
+ const pairs = args.flatMap((arg, i) =>
90
+ i % 2 === 0 ? [[arg.slice(2), args[i + 1]]] : []
91
+ );
92
+ const repeated = pairs
93
+ .map(([name]) => name)
94
+ .filter(
95
+ (name, i, names) =>
96
+ !REPEATABLE_FLAGS.has(name) && names.indexOf(name) !== i
97
+ );
98
+ if (repeated.length)
99
+ throw new EstimateConfigError(
100
+ `--${repeated[0]} was given more than once; only --usage-file may repeat.`
101
+ );
75
102
  return Object.fromEntries(
76
- args.flatMap((arg, i) => (i % 2 === 0 ? [[arg.slice(2), args[i + 1]]] : []))
103
+ pairs.map(([name, value]) => [
104
+ name,
105
+ REPEATABLE_FLAGS.has(name)
106
+ ? pairs.filter(([other]) => other === name).map(([, each]) => each)
107
+ : value,
108
+ ])
77
109
  );
78
110
  }
79
111
 
@@ -110,6 +142,11 @@ const readBody = flags =>
110
142
  ? readFileSync(0, "utf8")
111
143
  : readFileSync(flags["body-file"], "utf8");
112
144
 
145
+ const ledgerDocuments = (body, flags) => [
146
+ body,
147
+ ...(flags["usage-file"] ?? []).map(file => readFileSync(file, "utf8")),
148
+ ];
149
+
113
150
  const COMMANDS = {
114
151
  config: (_flags, settings) => ({
115
152
  out: `${JSON.stringify({ ...settings, defaultPricing: DEFAULT_ESTIMATE_PRICING }, null, 2)}\n`,
@@ -149,8 +186,18 @@ const COMMANDS = {
149
186
  );
150
187
  return { out: `${JSON.stringify(result, null, 2)}\n`, code: 0 };
151
188
  },
189
+ tally: flags => {
190
+ const body = readBody(flags);
191
+ return { out: tallyEstimate(body, ledgerDocuments(body, flags)), code: 0 };
192
+ },
152
193
  check: (flags, settings) => {
153
- const result = checkEstimate(readBody(flags), settings, flags.phase);
194
+ const body = readBody(flags);
195
+ const result = checkEstimate(
196
+ body,
197
+ settings,
198
+ flags.phase,
199
+ ledgerDocuments(body, flags)
200
+ );
154
201
  const lines = [`S21 token estimate: ${result.verdict}`, ...result.lines];
155
202
  return {
156
203
  out: `${lines.join("\n")}\n`,
@@ -160,7 +207,7 @@ const COMMANDS = {
160
207
  };
161
208
 
162
209
  const USAGE =
163
- "Usage: lisa-estimate.mjs config | render --tokens-low <n> --tokens-high <n> --model <id> [--basis <text>] [--body-file <path>] | calibrate --tokens-low <n> --tokens-high <n> --history-file <path> | check [--phase ready|claim] [--body-file <path>]\n";
210
+ "Usage: lisa-estimate.mjs config | render --tokens-low <n> --tokens-high <n> --model <id> [--basis <text>] [--body-file <path>] | calibrate --tokens-low <n> --tokens-high <n> --history-file <path> | tally [--body-file <path>] [--usage-file <path>]... | check [--phase ready|claim|done] [--body-file <path>] [--usage-file <path>]...\n";
164
211
 
165
212
  /**
166
213
  * Run the CLI.
@@ -180,9 +227,13 @@ export function runCli(argv = process.argv.slice(2), io = process) {
180
227
  }
181
228
  try {
182
229
  const flags = parseFlags(rest);
183
- const settings = resolveEstimateConfig(
184
- readProjectConfig(flags.cwd ?? process.cwd())
185
- );
230
+ const config = readProjectConfig(flags.cwd ?? process.cwd());
231
+ // `check` honours a disabled gate before it reads the rest of the
232
+ // settings, so it reports N/A instead of failing on settings it ignores.
233
+ const settings =
234
+ command === "check"
235
+ ? resolveEstimateGate(config)
236
+ : resolveEstimateConfig(config);
186
237
  const { out, code } = COMMANDS[command](flags, settings);
187
238
  io.stdout.write(out);
188
239
  return code;