@codyswann/lisa 8.0.1 → 8.1.1

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 (116) 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-bun.mjs +8 -3
  6. package/all/copy-overwrite/scripts/lib/npm-update-cache-seed.mjs +145 -0
  7. package/all/copy-overwrite/scripts/lib/npm-update-helper-inventory.mjs +7 -0
  8. package/all/copy-overwrite/scripts/lib/npm-update-prepare.mjs +34 -6
  9. package/all/copy-overwrite/scripts/lib/tracker-row-fold.mjs +48 -0
  10. package/all/copy-overwrite/scripts/lib/work-item-estimate-actual.mjs +131 -0
  11. package/all/copy-overwrite/scripts/lib/work-item-estimate-calibration.mjs +16 -33
  12. package/all/copy-overwrite/scripts/lib/work-item-estimate-check.mjs +26 -5
  13. package/all/copy-overwrite/scripts/lib/work-item-estimate-config.mjs +21 -0
  14. package/all/copy-overwrite/scripts/lib/work-item-estimate-tally.mjs +272 -0
  15. package/all/copy-overwrite/scripts/lib/work-item-estimate.mjs +60 -31
  16. package/all/copy-overwrite/scripts/lisa-estimate.mjs +60 -9
  17. package/all/copy-overwrite/scripts/npm-updater-helper-graph.json +74 -10
  18. package/dist/core/lisa-owned-hash-ledger.json +112 -6
  19. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  20. package/dist/core/upstream-evidence-manifest.json +48 -19
  21. package/dist/utils/usage-accounting-totals.d.ts.map +1 -1
  22. package/dist/utils/usage-accounting-totals.js +6 -1
  23. package/dist/utils/usage-accounting-totals.js.map +1 -1
  24. package/package.json +4 -4
  25. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  26. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  27. package/plugins/lisa/.codex-plugin/skills/lisa-tracker-evidence/SKILL.md +1 -0
  28. package/plugins/lisa/.codex-plugin/skills/lisa-usage-accounting/SKILL.md +2 -1
  29. package/plugins/lisa/.codex-plugin/skills/lisa-usage-accounting/references/estimate.md +49 -0
  30. package/plugins/lisa/rules/reference/work-item-definition-of-ready.md +5 -2
  31. package/plugins/lisa/skills/lisa-tracker-evidence/SKILL.md +1 -0
  32. package/plugins/lisa/skills/lisa-usage-accounting/SKILL.md +2 -1
  33. package/plugins/lisa/skills/lisa-usage-accounting/references/estimate.md +49 -0
  34. package/plugins/lisa-agy/plugin.json +1 -1
  35. package/plugins/lisa-agy/skills/lisa-tracker-evidence/SKILL.md +1 -0
  36. package/plugins/lisa-agy/skills/lisa-usage-accounting/SKILL.md +2 -1
  37. package/plugins/lisa-agy/skills/lisa-usage-accounting/references/estimate.md +49 -0
  38. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  39. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  40. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  41. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  42. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  43. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  44. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  45. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  46. package/plugins/lisa-copilot/rules/reference/work-item-definition-of-ready.md +5 -2
  47. package/plugins/lisa-copilot/skills/lisa-tracker-evidence/SKILL.md +1 -0
  48. package/plugins/lisa-copilot/skills/lisa-usage-accounting/SKILL.md +2 -1
  49. package/plugins/lisa-copilot/skills/lisa-usage-accounting/references/estimate.md +49 -0
  50. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  51. package/plugins/lisa-cursor/rules/work-item-definition-of-ready-reference.mdc +5 -2
  52. package/plugins/lisa-cursor/skills/lisa-tracker-evidence/SKILL.md +1 -0
  53. package/plugins/lisa-cursor/skills/lisa-usage-accounting/SKILL.md +2 -1
  54. package/plugins/lisa-cursor/skills/lisa-usage-accounting/references/estimate.md +49 -0
  55. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  56. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  57. package/plugins/lisa-devin/rules/reference/work-item-definition-of-ready.md +5 -2
  58. package/plugins/lisa-devin/skills/lisa-tracker-evidence/SKILL.md +1 -0
  59. package/plugins/lisa-devin/skills/lisa-usage-accounting/SKILL.md +2 -1
  60. package/plugins/lisa-devin/skills/lisa-usage-accounting/references/estimate.md +49 -0
  61. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  62. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  63. package/plugins/lisa-expo-agy/plugin.json +1 -1
  64. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  65. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  67. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  68. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  69. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  70. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  71. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  72. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  73. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  74. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  75. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  77. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  78. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  79. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  80. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  81. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  82. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  83. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  84. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  85. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  86. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  87. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  88. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  89. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  90. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  91. package/plugins/lisa-rails-agy/plugin.json +1 -1
  92. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  93. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  94. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  95. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  96. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  97. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  98. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  99. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  100. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  101. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  102. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  103. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  104. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  105. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  106. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  107. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  108. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  109. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  110. package/plugins/src/base/rules/reference/work-item-definition-of-ready.md +5 -2
  111. package/plugins/src/base/skills/lisa-tracker-evidence/SKILL.md +1 -0
  112. package/plugins/src/base/skills/lisa-usage-accounting/SKILL.md +2 -1
  113. package/plugins/src/base/skills/lisa-usage-accounting/references/estimate.md +49 -0
  114. package/scripts/record-npm-update-dual-lock-seed.mjs +203 -0
  115. package/scripts/two-channel-couplings.json +1 -1
  116. package/typescript/copy-overwrite/.prettierignore +4 -0
@@ -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.
@@ -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
  });