@digital-lake/lognexus 1.3.6 → 1.4.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 (87) hide show
  1. package/LICENSE +2 -1
  2. package/NOTICE.md +15 -7
  3. package/README.md +67 -42
  4. package/dist/audit/audit.d.ts +37 -2
  5. package/dist/audit/audit.d.ts.map +1 -1
  6. package/dist/audit/audit.js +483 -57
  7. package/dist/audit/audit.js.map +1 -1
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.d.ts.map +1 -1
  10. package/dist/cli.js +292 -32
  11. package/dist/cli.js.map +1 -1
  12. package/dist/commit.d.ts +6 -0
  13. package/dist/commit.d.ts.map +1 -1
  14. package/dist/commit.js +61 -23
  15. package/dist/commit.js.map +1 -1
  16. package/dist/doctor.d.ts +1 -0
  17. package/dist/doctor.d.ts.map +1 -1
  18. package/dist/doctor.js +31 -16
  19. package/dist/doctor.js.map +1 -1
  20. package/dist/index.d.ts +2 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/mcp/prompts.d.ts.map +1 -1
  25. package/dist/mcp/prompts.js +12 -8
  26. package/dist/mcp/prompts.js.map +1 -1
  27. package/dist/notes/attach.d.ts +11 -0
  28. package/dist/notes/attach.d.ts.map +1 -1
  29. package/dist/notes/attach.js +22 -5
  30. package/dist/notes/attach.js.map +1 -1
  31. package/dist/routing/profile.d.ts +44 -0
  32. package/dist/routing/profile.d.ts.map +1 -0
  33. package/dist/routing/profile.js +256 -0
  34. package/dist/routing/profile.js.map +1 -0
  35. package/dist/scaffold.d.ts +2 -2
  36. package/dist/scaffold.d.ts.map +1 -1
  37. package/dist/scaffold.js +22 -17
  38. package/dist/scaffold.js.map +1 -1
  39. package/dist/state/handoff.d.ts +18 -0
  40. package/dist/state/handoff.d.ts.map +1 -1
  41. package/dist/state/handoff.js +60 -10
  42. package/dist/state/handoff.js.map +1 -1
  43. package/dist/state/manager.d.ts.map +1 -1
  44. package/dist/state/manager.js +60 -1
  45. package/dist/state/manager.js.map +1 -1
  46. package/dist/state/schema.d.ts +38 -0
  47. package/dist/state/schema.d.ts.map +1 -1
  48. package/dist/state/schema.js +9 -0
  49. package/dist/state/schema.js.map +1 -1
  50. package/dist/status.d.ts +10 -0
  51. package/dist/status.d.ts.map +1 -1
  52. package/dist/status.js +167 -42
  53. package/dist/status.js.map +1 -1
  54. package/dist/telemetry/benchmark.d.ts +51 -0
  55. package/dist/telemetry/benchmark.d.ts.map +1 -0
  56. package/dist/telemetry/benchmark.js +541 -0
  57. package/dist/telemetry/benchmark.js.map +1 -0
  58. package/dist/telemetry/collector.d.ts +109 -3
  59. package/dist/telemetry/collector.d.ts.map +1 -1
  60. package/dist/telemetry/collector.js +737 -178
  61. package/dist/telemetry/collector.js.map +1 -1
  62. package/dist/telemetry/consent-prompt.d.ts +35 -0
  63. package/dist/telemetry/consent-prompt.d.ts.map +1 -0
  64. package/dist/telemetry/consent-prompt.js +213 -0
  65. package/dist/telemetry/consent-prompt.js.map +1 -0
  66. package/dist/telemetry/detector.d.ts +16 -1
  67. package/dist/telemetry/detector.d.ts.map +1 -1
  68. package/dist/telemetry/detector.js +261 -31
  69. package/dist/telemetry/detector.js.map +1 -1
  70. package/dist/telemetry/index.d.ts +5 -4
  71. package/dist/telemetry/index.d.ts.map +1 -1
  72. package/dist/telemetry/index.js +5 -4
  73. package/dist/telemetry/index.js.map +1 -1
  74. package/dist/telemetry/report.d.ts +3 -2
  75. package/dist/telemetry/report.d.ts.map +1 -1
  76. package/dist/telemetry/report.js +66 -14
  77. package/dist/telemetry/report.js.map +1 -1
  78. package/dist/telemetry/schema.d.ts +305 -2
  79. package/dist/telemetry/schema.d.ts.map +1 -1
  80. package/dist/telemetry/schema.js +142 -4
  81. package/dist/telemetry/schema.js.map +1 -1
  82. package/dist/update/gate.d.ts +1 -1
  83. package/dist/update/gate.d.ts.map +1 -1
  84. package/dist/update/gate.js +2 -0
  85. package/dist/update/gate.js.map +1 -1
  86. package/package.json +4 -4
  87. package/server.json +3 -3
@@ -7,7 +7,155 @@ import { getCliVersion } from "../cli.js";
7
7
  import { validateGitReference } from "../git/safe.js";
8
8
  import { getNote, listNotes } from "../notes/notes.js";
9
9
  import { detectProjectStacks, extractCommitDiffStats, extractModelFamilyCategory, inferTierFromAuthor, } from "./detector.js";
10
- import { TelemetryStoreSchema, } from "./schema.js";
10
+ import { DEFAULT_TELEMETRY_SUMMARY, TELEMETRY_POLICY_VERSION, TelemetryStoreSchema, } from "./schema.js";
11
+ export const TIER_PRICING_PROFILES = {
12
+ "tier-1": {
13
+ baseUsd: 0.05,
14
+ perSourceLocUsd: 0.00015,
15
+ perDocsLocUsd: 0.00004,
16
+ baseInputTokens: 3200,
17
+ inputTokensPerLoc: 14,
18
+ outputTokensPerLoc: 8,
19
+ },
20
+ "tier-2": {
21
+ baseUsd: 0.015,
22
+ perSourceLocUsd: 0.000045,
23
+ perDocsLocUsd: 0.000012,
24
+ baseInputTokens: 2400,
25
+ inputTokensPerLoc: 12,
26
+ outputTokensPerLoc: 7,
27
+ },
28
+ "tier-3": {
29
+ baseUsd: 0.002,
30
+ perSourceLocUsd: 0.000008,
31
+ perDocsLocUsd: 0.000002,
32
+ baseInputTokens: 1600,
33
+ inputTokensPerLoc: 10,
34
+ outputTokensPerLoc: 6,
35
+ },
36
+ };
37
+ function round3(value) {
38
+ return Number(value.toFixed(3));
39
+ }
40
+ /**
41
+ * Resolves any tier string (including legacy or unexpected values) onto a priced profile,
42
+ * defaulting to the cheap execution tier used by inline scoped agents.
43
+ */
44
+ function resolvePricingTier(tier) {
45
+ if (tier === "tier-1" || tier === "tier-2" || tier === "tier-3")
46
+ return tier;
47
+ return "tier-3";
48
+ }
49
+ /**
50
+ * Prices a commit from its diff categories alone.
51
+ *
52
+ * Test lines are billed as source because they carry the same authoring effort, which is
53
+ * what makes a large refactor with a matching test suite visibly more expensive than a
54
+ * prose-only change. Rounding happens on the per-commit total so summing thousands of
55
+ * commits cannot drift.
56
+ */
57
+ export function estimateCommitPricing(authorOrTier, linesByCategory) {
58
+ const tier = resolvePricingTier(authorOrTier);
59
+ const profile = TIER_PRICING_PROFILES[tier];
60
+ const sourceLoc = (linesByCategory.source ?? 0) + (linesByCategory.test ?? 0);
61
+ const docsLoc = (linesByCategory.docs ?? 0) + (linesByCategory.config ?? 0);
62
+ const inputTokens = Math.round(profile.baseInputTokens + (sourceLoc + docsLoc) * profile.inputTokensPerLoc);
63
+ const outputTokens = Math.round((sourceLoc + docsLoc) * profile.outputTokensPerLoc);
64
+ const costUsd = Number((profile.baseUsd +
65
+ sourceLoc * profile.perSourceLocUsd +
66
+ docsLoc * profile.perDocsLocUsd).toFixed(6));
67
+ return { sourceLoc, docsLoc, inputTokens, outputTokens, costUsd };
68
+ }
69
+ /**
70
+ * Seeds a model bucket with every numeric field spelled out.
71
+ *
72
+ * Relying on the schema defaults here is not equivalent: `accumulateModelPricing` reads the
73
+ * bucket before validation ever runs, and `undefined + number` would poison the aggregate
74
+ * with `NaN`, which `JSON.stringify` then persists as `null` and rejects on reload.
75
+ */
76
+ function createModelStat(family, tier) {
77
+ return {
78
+ family,
79
+ tier,
80
+ commits: 0,
81
+ totalDurationSec: 0,
82
+ avgSubtaskDurationSec: 0,
83
+ sourceLinesAdded: 0,
84
+ docsLinesAdded: 0,
85
+ estimatedInputTokens: 0,
86
+ estimatedOutputTokens: 0,
87
+ estimatedCostUsd: 0,
88
+ };
89
+ }
90
+ /**
91
+ * Accumulates a commit's LOC split, estimated tokens and estimated cost onto a model
92
+ * bucket so both the live recorder and the Git-note reconciliation price identically.
93
+ */
94
+ function accumulateModelPricing(model, linesByCategory, tier = model.tier) {
95
+ for (const [category, lines] of Object.entries(linesByCategory)) {
96
+ const added = Number.isFinite(lines) ? (lines ?? 0) : 0;
97
+ if (category === "source" || category === "test") {
98
+ model.sourceLinesAdded += added;
99
+ }
100
+ else {
101
+ model.docsLinesAdded += added;
102
+ }
103
+ }
104
+ const pricing = estimateCommitPricing(tier, linesByCategory);
105
+ model.estimatedInputTokens += pricing.inputTokens;
106
+ model.estimatedOutputTokens += pricing.outputTokens;
107
+ model.estimatedCostUsd = round6(model.estimatedCostUsd + pricing.costUsd);
108
+ }
109
+ function round6(value) {
110
+ return Number(value.toFixed(6));
111
+ }
112
+ /** Folds one diff bucket into the summary's per-category line counters. */
113
+ function accumulateCategoryLines(summary, category, linesAdded, linesDeleted) {
114
+ if (category === "test") {
115
+ summary.testLinesAdded += linesAdded;
116
+ }
117
+ else if (category === "docs") {
118
+ summary.docsLinesAdded += linesAdded;
119
+ }
120
+ else if (category === "config") {
121
+ summary.configLinesAdded += linesAdded;
122
+ }
123
+ else {
124
+ summary.sourceLinesAdded += linesAdded;
125
+ summary.sourceLinesDeleted += linesDeleted;
126
+ }
127
+ }
128
+ /**
129
+ * Folds one diff bucket into the per-extension roll-up.
130
+ *
131
+ * A commit that touches `.ts` files in both `src/` and `tests/` is one `.ts` commit, so the
132
+ * commit counter only moves on the first sighting of the extension, while the line totals
133
+ * always accumulate — otherwise the second bucket's lines would be dropped.
134
+ */
135
+ function accumulateExtensionLines(extensions, item, isNewExtInCommit) {
136
+ const existing = extensions[item.ext] ?? {
137
+ ext: item.ext,
138
+ category: item.category,
139
+ commits: 0,
140
+ linesAdded: 0,
141
+ linesDeleted: 0,
142
+ };
143
+ if (isNewExtInCommit)
144
+ existing.commits += 1;
145
+ if (item.category === "source")
146
+ existing.category = "source";
147
+ existing.linesAdded += item.linesAdded;
148
+ existing.linesDeleted += item.linesDeleted;
149
+ extensions[item.ext] = existing;
150
+ }
151
+ /** Totals a commit's added lines per diff category for the LOC-weighted pricing model. */
152
+ function linesByCategory(items) {
153
+ const totals = {};
154
+ for (const item of items) {
155
+ totals[item.category] = (totals[item.category] ?? 0) + item.linesAdded;
156
+ }
157
+ return totals;
158
+ }
11
159
  export const LOCAL_ONLY_TELEMETRY_ERROR = "Community telemetry dispatch has been retired in favor of strict local-only telemetry. Run 'lognexus telemetry enable' for local performance metrics (zero network calls).";
12
160
  export function isTelemetryGloballyDisabled() {
13
161
  return (process.env.DO_NOT_TRACK === "1" ||
@@ -20,30 +168,20 @@ export function getTelemetryPath(targetDir = process.cwd()) {
20
168
  }
21
169
  export function createDefaultTelemetryStore(targetDir = process.cwd()) {
22
170
  return {
23
- schemaVersion: "1.0.0",
171
+ schemaVersion: "2.0.0",
24
172
  mode: "off",
25
173
  anonymousProjectId: randomUUID(),
26
174
  consent: {
27
175
  accepted: false,
28
- policyVersion: "1.0.0",
176
+ policyVersion: TELEMETRY_POLICY_VERSION,
29
177
  acceptedAt: null,
178
+ declinedAt: null,
30
179
  },
31
180
  detectedStacks: detectProjectStacks(targetDir),
32
181
  taskTimings: {},
33
182
  extensions: {},
34
183
  models: {},
35
- summary: {
36
- totalCommits: 0,
37
- totalLinesAdded: 0,
38
- totalLinesDeleted: 0,
39
- totalSubtasksCompleted: 0,
40
- gitNotesCoveragePct: 100,
41
- reviewGateBlocksPrevented: 0,
42
- estimatedBaselineCostUsd: 0,
43
- estimatedActualCostUsd: 0,
44
- estimatedCostSavingsUsd: 0,
45
- estimatedCostSavingsPct: 0,
46
- },
184
+ summary: { ...DEFAULT_TELEMETRY_SUMMARY },
47
185
  lastUpdated: new Date().toISOString(),
48
186
  };
49
187
  }
@@ -54,6 +192,9 @@ export function loadTelemetry(targetDir = process.cwd()) {
54
192
  return store;
55
193
  }
56
194
  const filePath = getTelemetryPath(targetDir);
195
+ // The identity must outlive a single run: without a persisted store every export would mint a
196
+ // fresh id, and a cohort could never tell two snapshots of one repository apart from two
197
+ // repositories. The id is a random UUID, never derived from the path or the repository name.
57
198
  if (!existsSync(filePath)) {
58
199
  return createDefaultTelemetryStore(targetDir);
59
200
  }
@@ -71,20 +212,49 @@ export function loadTelemetry(targetDir = process.cwd()) {
71
212
  return createDefaultTelemetryStore(targetDir);
72
213
  }
73
214
  export function saveTelemetry(store, targetDir = process.cwd()) {
74
- const dirPath = join(targetDir, ".lognexus");
75
- if (!existsSync(dirPath)) {
76
- mkdirSync(dirPath, { recursive: true });
215
+ try {
216
+ const dirPath = join(targetDir, ".lognexus");
217
+ if (!existsSync(dirPath)) {
218
+ mkdirSync(dirPath, { recursive: true });
219
+ }
220
+ store.schemaVersion = "2.0.0";
221
+ store.lastUpdated = new Date().toISOString();
222
+ store.detectedStacks = detectProjectStacks(targetDir);
223
+ const filePath = getTelemetryPath(targetDir);
224
+ writeFileSync(filePath, JSON.stringify(store, null, 2), "utf8");
77
225
  }
78
- store.lastUpdated = new Date().toISOString();
79
- store.detectedStacks = detectProjectStacks(targetDir);
80
- const filePath = getTelemetryPath(targetDir);
81
- writeFileSync(filePath, JSON.stringify(store, null, 2), "utf8");
226
+ catch {
227
+ /* fail-silent */
228
+ }
229
+ }
230
+ export function getTelemetryConsentState(targetDir = process.cwd()) {
231
+ if (isTelemetryGloballyDisabled() || !existsSync(getTelemetryPath(targetDir))) {
232
+ return "unanswered";
233
+ }
234
+ const store = loadTelemetry(targetDir);
235
+ if (store.consent.accepted && store.consent.policyVersion === TELEMETRY_POLICY_VERSION) {
236
+ return "accepted";
237
+ }
238
+ if (!store.consent.accepted &&
239
+ store.consent.declinedAt !== null &&
240
+ store.consent.policyVersion === TELEMETRY_POLICY_VERSION) {
241
+ return "declined";
242
+ }
243
+ if ((store.consent.accepted || store.consent.declinedAt !== null || store.mode === "local") &&
244
+ store.consent.policyVersion !== TELEMETRY_POLICY_VERSION) {
245
+ return "outdated";
246
+ }
247
+ return "unanswered";
82
248
  }
83
249
  export function isTelemetryActive(targetDir = process.cwd()) {
84
250
  if (isTelemetryGloballyDisabled())
85
251
  return false;
252
+ if (!existsSync(getTelemetryPath(targetDir)))
253
+ return false;
86
254
  const store = loadTelemetry(targetDir);
87
- return store.mode === "local";
255
+ return (store.mode === "local" &&
256
+ store.consent.accepted === true &&
257
+ store.consent.policyVersion === TELEMETRY_POLICY_VERSION);
88
258
  }
89
259
  export function enableTelemetry(options) {
90
260
  const cwd = options.cwd ?? process.cwd();
@@ -93,123 +263,461 @@ export function enableTelemetry(options) {
93
263
  throw new Error(LOCAL_ONLY_TELEMETRY_ERROR);
94
264
  }
95
265
  store.mode = "local";
266
+ if (options.acceptTerms === true) {
267
+ store.consent = {
268
+ accepted: true,
269
+ policyVersion: TELEMETRY_POLICY_VERSION,
270
+ acceptedAt: new Date().toISOString(),
271
+ declinedAt: null,
272
+ };
273
+ }
96
274
  saveTelemetry(store, cwd);
97
275
  return { mode: store.mode, anonymousProjectId: store.anonymousProjectId };
98
276
  }
99
- export function disableTelemetry(targetDir = process.cwd()) {
277
+ export function declineTelemetry(targetDir = process.cwd()) {
100
278
  const store = loadTelemetry(targetDir);
101
279
  store.mode = "off";
280
+ store.consent = {
281
+ accepted: false,
282
+ policyVersion: TELEMETRY_POLICY_VERSION,
283
+ acceptedAt: null,
284
+ declinedAt: new Date().toISOString(),
285
+ };
102
286
  saveTelemetry(store, targetDir);
103
287
  }
288
+ export function disableTelemetry(targetDir = process.cwd()) {
289
+ declineTelemetry(targetDir);
290
+ }
291
+ function readStoredConsent(targetDir) {
292
+ const filePath = getTelemetryPath(targetDir);
293
+ if (!existsSync(filePath))
294
+ return null;
295
+ try {
296
+ const parsed = TelemetryStoreSchema.safeParse(JSON.parse(readFileSync(filePath, "utf8")));
297
+ return parsed.success ? parsed.data.consent : null;
298
+ }
299
+ catch {
300
+ return null;
301
+ }
302
+ }
104
303
  export function clearTelemetry(targetDir = process.cwd()) {
304
+ const previousConsent = readStoredConsent(targetDir);
105
305
  const store = createDefaultTelemetryStore(targetDir);
106
306
  store.mode = "off";
307
+ if (previousConsent !== null &&
308
+ (previousConsent.accepted === true || previousConsent.declinedAt !== null)) {
309
+ store.consent = {
310
+ accepted: false,
311
+ policyVersion: previousConsent.policyVersion,
312
+ acceptedAt: null,
313
+ declinedAt: previousConsent.declinedAt ?? new Date().toISOString(),
314
+ };
315
+ }
107
316
  saveTelemetry(store, targetDir);
108
317
  }
109
318
  export function recordTaskStart(taskId, targetDir = process.cwd()) {
110
- if (!isTelemetryActive(targetDir))
111
- return;
112
- const store = loadTelemetry(targetDir);
113
- store.taskTimings[taskId] = {
114
- taskId,
115
- startedAt: new Date().toISOString(),
116
- completedAt: null,
117
- durationSec: 0,
118
- };
119
- saveTelemetry(store, targetDir);
319
+ try {
320
+ if (!isTelemetryActive(targetDir))
321
+ return;
322
+ const store = loadTelemetry(targetDir);
323
+ store.taskTimings[taskId] = {
324
+ taskId,
325
+ startedAt: new Date().toISOString(),
326
+ completedAt: null,
327
+ durationSec: 0,
328
+ };
329
+ saveTelemetry(store, targetDir);
330
+ }
331
+ catch {
332
+ /* fail-silent */
333
+ }
120
334
  }
121
335
  export function recordTaskFinish(taskId, targetDir = process.cwd()) {
122
- if (!isTelemetryActive(targetDir))
336
+ try {
337
+ if (!isTelemetryActive(targetDir))
338
+ return 0;
339
+ const store = loadTelemetry(targetDir);
340
+ const entry = store.taskTimings[taskId];
341
+ let durationSec = 0;
342
+ if (entry?.startedAt) {
343
+ const started = new Date(entry.startedAt).getTime();
344
+ const now = Date.now();
345
+ durationSec = Math.max(1, Math.round((now - started) / 1000));
346
+ entry.completedAt = new Date(now).toISOString();
347
+ entry.durationSec = durationSec;
348
+ }
349
+ store.summary.totalSubtasksCompleted += 1;
350
+ saveTelemetry(store, targetDir);
351
+ return durationSec;
352
+ }
353
+ catch {
354
+ /* fail-silent */
123
355
  return 0;
124
- const store = loadTelemetry(targetDir);
125
- const entry = store.taskTimings[taskId];
126
- let durationSec = 0;
127
- if (entry?.startedAt) {
128
- const started = new Date(entry.startedAt).getTime();
129
- const now = Date.now();
130
- durationSec = Math.max(1, Math.round((now - started) / 1000));
131
- entry.completedAt = new Date(now).toISOString();
132
- entry.durationSec = durationSec;
133
- }
134
- store.summary.totalSubtasksCompleted += 1;
135
- saveTelemetry(store, targetDir);
136
- return durationSec;
356
+ }
137
357
  }
138
358
  export function recordReviewGateBlock(targetDir = process.cwd()) {
139
- if (!isTelemetryActive(targetDir))
140
- return;
141
- const store = loadTelemetry(targetDir);
142
- store.summary.reviewGateBlocksPrevented += 1;
143
- saveTelemetry(store, targetDir);
359
+ try {
360
+ if (!isTelemetryActive(targetDir))
361
+ return;
362
+ const store = loadTelemetry(targetDir);
363
+ store.summary.reviewGateBlocksPrevented += 1;
364
+ saveTelemetry(store, targetDir);
365
+ }
366
+ catch {
367
+ /* fail-silent */
368
+ }
144
369
  }
370
+ /**
371
+ * Recomputes the cost/token roll-up from the per-model buckets.
372
+ *
373
+ * The baseline prices every commit as if a frontier orchestrator had authored it alone,
374
+ * from LOC-weighted profiles rather than a flat per-commit rate, so a heavy refactor is
375
+ * never under-priced. Totals are re-derived from `store.models`, which keeps the call
376
+ * idempotent and lets a partially-backfilled store converge after one pass.
377
+ */
145
378
  export function updateCostSavingsEstimate(store) {
146
- // Economic model:
147
- // Monolithic Tier-1 (Frontier) Baseline: Assumes 100% of tasks done by frontier model without file scoping
148
- // Heuristic average cost: $0.05 per commit / diff unit
149
- // LogNexus Multi-Tier actual cost:
150
- // tier-1 (Arch/Review): $0.04
151
- // tier-2 (Orchestration): $0.015
152
- // tier-3 (Execution with Flash / DeepSeek V3 / Haiku / Kimi): $0.002
153
- const totalCommits = store.summary.totalCommits;
379
+ const sum = store.summary;
380
+ const models = Object.values(store.models);
381
+ let totalSourceLoc = 0;
382
+ let totalDocsLoc = 0;
383
+ let totalCommits = 0;
384
+ let actualCostRaw = 0;
385
+ let actualInputTokens = 0;
386
+ let actualOutputTokens = 0;
387
+ for (const model of models) {
388
+ totalSourceLoc += model.sourceLinesAdded;
389
+ totalDocsLoc += model.docsLinesAdded;
390
+ totalCommits += model.commits;
391
+ actualCostRaw += model.estimatedCostUsd;
392
+ actualInputTokens += model.estimatedInputTokens;
393
+ actualOutputTokens += model.estimatedOutputTokens;
394
+ }
395
+ // `tierCommits` is accumulated per commit by the callers, so a mixed-tier history keeps its
396
+ // real split. It is only re-derived from the model buckets when the totals disagree — as a
397
+ // legacy store would, or one assembled by hand without going through a commit recorder.
398
+ const declaredTierCommits = sum.tierCommits;
399
+ const declaredTierTotal = (declaredTierCommits?.["tier-1"] ?? 0) +
400
+ (declaredTierCommits?.["tier-2"] ?? 0) +
401
+ (declaredTierCommits?.["tier-3"] ?? 0);
402
+ if (declaredTierCommits === undefined || declaredTierTotal !== totalCommits) {
403
+ sum.tierCommits = { "tier-1": 0, "tier-2": 0, "tier-3": 0 };
404
+ for (const model of models) {
405
+ const tier = resolvePricingTier(model.tier);
406
+ sum.tierCommits[tier] += model.commits;
407
+ }
408
+ }
154
409
  if (totalCommits === 0) {
155
- store.summary.estimatedBaselineCostUsd = 0;
156
- store.summary.estimatedActualCostUsd = 0;
157
- store.summary.estimatedCostSavingsUsd = 0;
158
- store.summary.estimatedCostSavingsPct = 0;
410
+ sum.estimatedBaselineCostUsd = 0;
411
+ sum.estimatedActualCostUsd = 0;
412
+ sum.estimatedCostSavingsUsd = 0;
413
+ sum.estimatedCostSavingsPct = 0;
414
+ sum.estimatedBaselineTokens = 0;
415
+ sum.estimatedActualTokens = 0;
416
+ sum.estimatedTokensSaved = 0;
159
417
  return;
160
418
  }
161
- const baselineCost = totalCommits * 0.05;
162
- let actualCost = 0;
163
- for (const model of Object.values(store.models)) {
164
- const unitCost = model.tier === "tier-1" ? 0.04 : model.tier === "tier-2" ? 0.015 : 0.002;
165
- actualCost += model.commits * unitCost;
419
+ const baselineProfile = TIER_PRICING_PROFILES["tier-1"];
420
+ const totalLoc = totalSourceLoc + totalDocsLoc;
421
+ const baselineCostRaw = totalCommits * baselineProfile.baseUsd +
422
+ totalSourceLoc * baselineProfile.perSourceLocUsd +
423
+ totalDocsLoc * baselineProfile.perDocsLocUsd;
424
+ const baselineTokens = Math.round(totalCommits * baselineProfile.baseInputTokens +
425
+ totalLoc * baselineProfile.inputTokensPerLoc +
426
+ totalLoc * baselineProfile.outputTokensPerLoc);
427
+ const actualTokens = actualInputTokens + actualOutputTokens;
428
+ const roundedBaseline = round3(baselineCostRaw);
429
+ const roundedActual = round3(actualCostRaw);
430
+ const savingsUsd = Math.max(0, round3(roundedBaseline - roundedActual));
431
+ sum.estimatedBaselineCostUsd = roundedBaseline;
432
+ sum.estimatedActualCostUsd = roundedActual;
433
+ sum.estimatedCostSavingsUsd = savingsUsd;
434
+ sum.estimatedCostSavingsPct =
435
+ roundedBaseline > 0 ? Number(((savingsUsd / roundedBaseline) * 100).toFixed(1)) : 0;
436
+ sum.estimatedBaselineTokens = baselineTokens;
437
+ sum.estimatedActualTokens = actualTokens;
438
+ sum.estimatedTokensSaved = Math.max(0, baselineTokens - actualTokens);
439
+ }
440
+ const GIT_LOG_FORMAT = "--format=%H%x1f%s%x1f%an%x1f%aI%x1f%B%x1e";
441
+ const EPHEMERAL_PATH_PREFIX = ".lognexus/";
442
+ const REWORK_SUBJECT_PATTERN = /^(?:fix|revert)(?:\(|:)/i;
443
+ const ESCALATION_SUBJECT_PATTERN = /\[escalated\]/i;
444
+ function percentage(part, whole, whenEmpty) {
445
+ if (whole === 0)
446
+ return whenEmpty;
447
+ return Number(((part / whole) * 100).toFixed(1));
448
+ }
449
+ function isSwarmAuthor(author) {
450
+ const lowered = author.toLowerCase();
451
+ return (lowered.includes("gemini-flash-worker-agy") ||
452
+ lowered.includes("orchestrator (carbon)") ||
453
+ lowered.includes("orchestrator (argon)") ||
454
+ lowered.includes("orchestrator (neon)") ||
455
+ lowered.includes("gemini-pro-orchestrator"));
456
+ }
457
+ function readCommitSubject(safeSha, targetDir) {
458
+ try {
459
+ return execFileSync("git", ["show", "-s", "--format=%s", safeSha], {
460
+ cwd: targetDir,
461
+ encoding: "utf8",
462
+ stdio: ["pipe", "pipe", "pipe"],
463
+ shell: false,
464
+ }).trim();
465
+ }
466
+ catch {
467
+ return "";
166
468
  }
167
- const savingsUsd = Math.max(0, baselineCost - actualCost);
168
- const savingsPct = baselineCost > 0 ? (savingsUsd / baselineCost) * 100 : 0;
169
- store.summary.estimatedBaselineCostUsd = Number(baselineCost.toFixed(3));
170
- store.summary.estimatedActualCostUsd = Number(actualCost.toFixed(3));
171
- store.summary.estimatedCostSavingsUsd = Number(savingsUsd.toFixed(3));
172
- store.summary.estimatedCostSavingsPct = Number(savingsPct.toFixed(1));
469
+ }
470
+ function listChangedFiles(sha, targetDir) {
471
+ try {
472
+ const raw = execFileSync("git", ["diff-tree", "--root", "--no-commit-id", "--name-only", "-r", validateGitReference(sha)], {
473
+ cwd: targetDir,
474
+ encoding: "utf8",
475
+ stdio: ["pipe", "pipe", "pipe"],
476
+ shell: false,
477
+ });
478
+ return raw
479
+ .split("\n")
480
+ .map((line) => line.trim().replace(/\\/g, "/"))
481
+ .filter((line) => line !== "" && !line.startsWith(EPHEMERAL_PATH_PREFIX));
482
+ }
483
+ catch {
484
+ return [];
485
+ }
486
+ }
487
+ /**
488
+ * Checks whether every non-ephemeral file of a commit fell inside the active subtask
489
+ * contract, which is what makes the contract a real execution boundary and not a comment.
490
+ */
491
+ function isCommitContracted(sha, allowedFiles, targetDir) {
492
+ const allowed = new Set(allowedFiles.map((file) => file.trim().replace(/\\/g, "/")));
493
+ const changed = listChangedFiles(sha, targetDir);
494
+ if (changed.length === 0)
495
+ return true;
496
+ return changed.every((file) => allowed.has(file));
173
497
  }
174
498
  export function recordCommitTelemetry(options) {
175
- const cwd = options.targetDir ?? process.cwd();
176
- if (!isTelemetryActive(cwd))
177
- return;
178
- const store = loadTelemetry(cwd);
179
- const diffItems = extractCommitDiffStats(options.sha, cwd);
180
- let commitAdded = 0;
181
- let commitDeleted = 0;
182
- for (const item of diffItems) {
183
- commitAdded += item.linesAdded;
184
- commitDeleted += item.linesDeleted;
185
- const existing = store.extensions[item.ext] ?? {
186
- ext: item.ext,
187
- commits: 0,
188
- linesAdded: 0,
189
- linesDeleted: 0,
190
- };
191
- existing.commits += 1;
192
- existing.linesAdded += item.linesAdded;
193
- existing.linesDeleted += item.linesDeleted;
194
- store.extensions[item.ext] = existing;
195
- }
196
- store.summary.totalCommits += 1;
197
- store.summary.totalLinesAdded += commitAdded;
198
- store.summary.totalLinesDeleted += commitDeleted;
199
- const modelKey = extractModelFamilyCategory(options.author);
200
- const tier = options.tier ?? "tier-3";
201
- const existingModel = store.models[modelKey] ?? {
202
- family: modelKey,
203
- tier,
204
- commits: 0,
205
- totalDurationSec: 0,
206
- avgSubtaskDurationSec: 0,
499
+ try {
500
+ const cwd = options.targetDir ?? process.cwd();
501
+ if (!isTelemetryActive(cwd))
502
+ return;
503
+ const store = loadTelemetry(cwd);
504
+ const diffItems = extractCommitDiffStats(options.sha, cwd);
505
+ let commitAdded = 0;
506
+ let commitDeleted = 0;
507
+ const seenExts = new Set();
508
+ for (const item of diffItems) {
509
+ commitAdded += item.linesAdded;
510
+ commitDeleted += item.linesDeleted;
511
+ accumulateCategoryLines(store.summary, item.category, item.linesAdded, item.linesDeleted);
512
+ // One commit touching `.ts` in `src/` and `tests/` counts as a single `.ts` commit.
513
+ const isNewExtInCommit = !seenExts.has(item.ext);
514
+ if (isNewExtInCommit)
515
+ seenExts.add(item.ext);
516
+ accumulateExtensionLines(store.extensions, item, isNewExtInCommit);
517
+ }
518
+ store.summary.totalCommits += 1;
519
+ store.summary.totalLinesAdded += commitAdded;
520
+ store.summary.totalLinesDeleted += commitDeleted;
521
+ const modelKey = extractModelFamilyCategory(options.author);
522
+ const tier = options.tier ?? inferTierFromAuthor(options.author) ?? "tier-3";
523
+ const existingModel = store.models[modelKey] ?? createModelStat(modelKey, tier);
524
+ existingModel.tier = tier;
525
+ existingModel.commits += 1;
526
+ accumulateModelPricing(existingModel, linesByCategory(diffItems), tier);
527
+ store.models[modelKey] = existingModel;
528
+ const pricingTier = resolvePricingTier(tier);
529
+ if (store.summary.tierCommits === undefined) {
530
+ store.summary.tierCommits = { "tier-1": 0, "tier-2": 0, "tier-3": 0 };
531
+ }
532
+ store.summary.tierCommits[pricingTier] += 1;
533
+ let safeSha = null;
534
+ try {
535
+ safeSha = validateGitReference(options.sha);
536
+ }
537
+ catch {
538
+ safeSha = null;
539
+ }
540
+ const parsedNote = readParsedNote(safeSha ?? options.sha, cwd);
541
+ const subject = safeSha !== null ? readCommitSubject(safeSha, cwd) : "";
542
+ if (parsedNote?.escalated === true || ESCALATION_SUBJECT_PATTERN.test(subject)) {
543
+ store.summary.escalatedCommits = (store.summary.escalatedCommits ?? 0) + 1;
544
+ }
545
+ if (REWORK_SUBJECT_PATTERN.test(subject)) {
546
+ store.summary.reworkCommits = (store.summary.reworkCommits ?? 0) + 1;
547
+ }
548
+ store.summary.reworkRatioPct = percentage(store.summary.reworkCommits ?? 0, store.summary.totalCommits, 0);
549
+ const allowedFiles = parsedNote?.subtask?.contract?.allowedFiles;
550
+ if (Array.isArray(allowedFiles) && safeSha !== null) {
551
+ const declared = allowedFiles.filter((file) => typeof file === "string");
552
+ if (declared.length > 0) {
553
+ const prevContracted = store.summary.contractedCommits ?? 0;
554
+ const prevCompliant = prevContracted === 0
555
+ ? 0
556
+ : Math.round(((store.summary.contractCompliancePct ?? 100) / 100) * prevContracted);
557
+ const compliant = isCommitContracted(safeSha, declared, cwd) ? 1 : 0;
558
+ const nextContracted = prevContracted + 1;
559
+ store.summary.contractedCommits = nextContracted;
560
+ store.summary.contractCompliancePct = percentage(prevCompliant + compliant, nextContracted, 100);
561
+ }
562
+ }
563
+ const swarmMetrics = extractNoteSwarmMetrics(parsedNote);
564
+ if (swarmMetrics.isSwarm || isSwarmAuthor(options.author ?? "")) {
565
+ store.summary.swarmCommits = (store.summary.swarmCommits ?? 0) + 1;
566
+ store.summary.totalSwarmPosts = (store.summary.totalSwarmPosts ?? 0) + swarmMetrics.posts;
567
+ store.summary.maxSwarmWorkers = Math.max(store.summary.maxSwarmWorkers ?? 0, swarmMetrics.workers);
568
+ }
569
+ updateCostSavingsEstimate(store);
570
+ saveTelemetry(store, cwd);
571
+ }
572
+ catch {
573
+ /* fail-silent */
574
+ }
575
+ }
576
+ /**
577
+ * Normalizes an issue filter into a bare identifier: `58`, `"58"`, `"#58"` and `"#058"`
578
+ * all collapse to `"58"`, while alphanumeric tickets such as `"SLM-201"` are upper-cased.
579
+ */
580
+ export function normalizeIssueFilter(issue) {
581
+ const raw = String(issue).trim().replace(/^#+/, "");
582
+ const numeric = Number.parseInt(raw, 10);
583
+ if (raw !== "" && String(numeric) === raw)
584
+ return String(numeric);
585
+ return raw.toUpperCase();
586
+ }
587
+ function readScopedCommits(targetDir, filter) {
588
+ // Merge commits carry no authored diff of their own, so counting them would inflate the
589
+ // commit totals and dilute the rework and coverage ratios.
590
+ const args = ["log", "--no-merges", GIT_LOG_FORMAT, "--no-color"];
591
+ if (filter?.since !== undefined && filter.since !== "") {
592
+ // Rejecting a leading dash keeps the value from ever being parsed as a Git flag.
593
+ if (filter.since.startsWith("-")) {
594
+ throw new Error(`Governance violation: Invalid telemetry scope value: "${filter.since}" (leading dash).`);
595
+ }
596
+ args.push(`--since=${filter.since}`);
597
+ }
598
+ if (filter?.branch !== undefined && filter.branch !== "") {
599
+ args.push(validateGitReference(filter.branch));
600
+ }
601
+ let raw = "";
602
+ try {
603
+ raw = execFileSync("git", args, {
604
+ cwd: targetDir,
605
+ encoding: "utf8",
606
+ stdio: ["pipe", "pipe", "pipe"],
607
+ shell: false,
608
+ });
609
+ }
610
+ catch {
611
+ return [];
612
+ }
613
+ const commits = [];
614
+ for (const record of raw.split("\u001e")) {
615
+ const trimmed = record.replace(/^\n+/, "");
616
+ if (trimmed === "")
617
+ continue;
618
+ const fields = trimmed.split("\u001f");
619
+ if (fields.length < 5)
620
+ continue;
621
+ const [sha = "", subject = "", author = "", committedAt = "", ...bodyParts] = fields;
622
+ const committedAtMs = Date.parse(committedAt);
623
+ if (Number.isNaN(committedAtMs))
624
+ continue;
625
+ commits.push({
626
+ sha: sha.trim(),
627
+ subject: subject.trim(),
628
+ author,
629
+ body: bodyParts.join("\u001f"),
630
+ committedAtMs,
631
+ });
632
+ }
633
+ return commits;
634
+ }
635
+ function median(values) {
636
+ if (values.length === 0)
637
+ return 0;
638
+ const sorted = [...values].sort((a, b) => a - b);
639
+ const middle = Math.floor(sorted.length / 2);
640
+ return sorted.length % 2 === 0
641
+ ? Math.round((sorted[middle - 1] + sorted[middle]) / 2)
642
+ : sorted[middle];
643
+ }
644
+ function parseNonNegativeInt(value) {
645
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
646
+ return null;
647
+ }
648
+ return value;
649
+ }
650
+ function readParsedNote(sha, targetDir) {
651
+ const rawNote = getNote(sha, { cwd: targetDir });
652
+ if (rawNote === null || rawNote === "")
653
+ return null;
654
+ try {
655
+ return JSON.parse(rawNote);
656
+ }
657
+ catch {
658
+ return null;
659
+ }
660
+ }
661
+ export function extractNoteSwarmMetrics(parsedNote) {
662
+ const workers = parseNonNegativeInt(parsedNote?.swarm?.workers) ??
663
+ parseNonNegativeInt(parsedNote?.subtask?.contract?.swarmWorkers);
664
+ const posts = parseNonNegativeInt(parsedNote?.swarm?.posts) ??
665
+ parseNonNegativeInt(parsedNote?.subtask?.contract?.swarmPosts);
666
+ const isSwarm = parsedNote?.subtask?.contract?.isolation === "swarm" ||
667
+ workers !== null ||
668
+ posts !== null ||
669
+ (parsedNote?.swarm !== null && typeof parsedNote?.swarm === "object");
670
+ return {
671
+ isSwarm,
672
+ workers: workers ?? 0,
673
+ posts: posts ?? 0,
207
674
  };
208
- existingModel.tier = tier;
209
- existingModel.commits += 1;
210
- store.models[modelKey] = existingModel;
211
- updateCostSavingsEstimate(store);
212
- saveTelemetry(store, cwd);
675
+ }
676
+ /**
677
+ * Resolves the routing tier of a noted commit.
678
+ *
679
+ * Modern notes (carrying `$schema`) honour explicit `--tier` overrides: `inferredTier`
680
+ * overrides `noteTier` only when `noteTier` merely inherited `issue.tier`, while legacy
681
+ * notes without `$schema` still upgrade the historical `tier-3` default when an author
682
+ * identity resolves.
683
+ */
684
+ export function resolveCommitTier(parsedNote, inferredTier) {
685
+ const noteTier = typeof parsedNote?.tier === "string" ? parsedNote.tier : null;
686
+ const isModernNote = typeof parsedNote?.$schema === "string";
687
+ if (noteTier === null)
688
+ return resolvePricingTier(inferredTier);
689
+ if (isModernNote) {
690
+ const issueTier = typeof parsedNote?.issue?.tier === "string" ? parsedNote.issue.tier : null;
691
+ if (inferredTier !== null && issueTier !== null && noteTier === issueTier) {
692
+ return resolvePricingTier(inferredTier);
693
+ }
694
+ return resolvePricingTier(noteTier);
695
+ }
696
+ if (noteTier !== "tier-3")
697
+ return resolvePricingTier(noteTier);
698
+ return resolvePricingTier(inferredTier ?? noteTier);
699
+ }
700
+ function hasScope(filter) {
701
+ if (filter === undefined)
702
+ return false;
703
+ return filter.issue !== undefined || filter.since !== undefined || filter.branch !== undefined;
704
+ }
705
+ function matchesIssueFilter(issueFilter, commit, noteId) {
706
+ if (typeof noteId === "number" || typeof noteId === "string") {
707
+ if (normalizeIssueFilter(noteId) === issueFilter)
708
+ return true;
709
+ }
710
+ // The subject convention carries the issue id before the subtask tag, as in
711
+ // `feat(#61/T2): ...` or `fix(SLM-201/T1): ...`, so both prefixes are matched.
712
+ const loweredIssue = issueFilter.toLowerCase();
713
+ const normalizedSubject = commit.subject.toLowerCase();
714
+ const candidates = [
715
+ `(#${loweredIssue}/`,
716
+ `(#${loweredIssue})`,
717
+ `(${loweredIssue}/`,
718
+ `(${loweredIssue})`,
719
+ ];
720
+ return candidates.some((candidate) => normalizedSubject.includes(candidate));
213
721
  }
214
722
  /**
215
723
  * Rebuilds the commit aggregates from `refs/notes/lognexus`.
@@ -218,114 +726,155 @@ export function recordCommitTelemetry(options) {
218
726
  * run where the store was rewritten — still leaves a Git note behind. The notes are the
219
727
  * authoritative record: this reads them and recomputes the aggregates from scratch,
220
728
  * which makes the reconciliation idempotent and keeps it entirely offline.
729
+ *
730
+ * A scoped call (`filter` set) is a read-only projection: it is returned in memory and
731
+ * never persisted, so an ad-hoc `issue`/`since`/`branch` report can never shrink the
732
+ * aggregates a user accumulated over months.
221
733
  */
222
- export function syncTelemetryFromGitNotes(targetDir = process.cwd()) {
734
+ export function syncTelemetryFromGitNotes(targetDir = process.cwd(), filter) {
223
735
  const store = loadTelemetry(targetDir);
224
736
  if (isTelemetryGloballyDisabled())
225
737
  return store;
226
- const notes = listNotes({ cwd: targetDir });
227
- if (notes.length === 0 || notes.length <= store.summary.totalCommits)
738
+ const scoped = hasScope(filter);
739
+ const allNotes = listNotes({ cwd: targetDir });
740
+ const notedShas = new Set(allNotes.map((note) => note.commitSha));
741
+ const commits = readScopedCommits(targetDir, filter);
742
+ // An unscoped reconciliation is a no-op only when the repository carries nothing to
743
+ // rebuild from; otherwise it always runs, so a legacy 1.x store is upgraded in place.
744
+ if (!scoped && allNotes.length === 0 && commits.length === 0)
228
745
  return store;
746
+ const issueFilter = filter?.issue !== undefined && filter.issue !== null
747
+ ? normalizeIssueFilter(filter.issue)
748
+ : null;
229
749
  const extensions = {};
230
750
  const models = {};
231
751
  const notedSubtasks = new Set();
752
+ const summary = store.summary;
753
+ // Every aggregate is re-derived from the scanned commits, including the per-category line
754
+ // counters; carrying a previous partial recording over would double count the same commit.
755
+ summary.sourceLinesAdded = 0;
756
+ summary.sourceLinesDeleted = 0;
757
+ summary.testLinesAdded = 0;
758
+ summary.docsLinesAdded = 0;
759
+ summary.configLinesAdded = 0;
760
+ summary.tierCommits = { "tier-1": 0, "tier-2": 0, "tier-3": 0 };
761
+ summary.swarmCommits = 0;
762
+ summary.totalSwarmPosts = 0;
763
+ summary.maxSwarmWorkers = 0;
232
764
  let totalLinesAdded = 0;
233
765
  let totalLinesDeleted = 0;
234
- for (const { commitSha } of notes) {
766
+ let commitsInScope = 0;
767
+ let coveredCommits = 0;
768
+ let contractedCommits = 0;
769
+ let compliantCommits = 0;
770
+ let escalatedCommits = 0;
771
+ let reworkCommits = 0;
772
+ let swarmCommits = 0;
773
+ let totalSwarmPosts = 0;
774
+ let maxSwarmWorkers = 0;
775
+ const timestamps = [];
776
+ for (const commit of commits) {
235
777
  let safeSha;
236
778
  try {
237
- safeSha = validateGitReference(commitSha);
779
+ safeSha = validateGitReference(commit.sha);
238
780
  }
239
781
  catch {
240
782
  continue;
241
783
  }
242
- let subject = "";
243
- let gitAuthor = "";
244
- let body = "";
245
- try {
246
- const raw = execFileSync("git", ["log", "-1", "--format=%s%x1f%an%x1f%B", safeSha], {
247
- cwd: targetDir,
248
- encoding: "utf8",
249
- stdio: ["pipe", "pipe", "pipe"],
250
- shell: false,
251
- });
252
- const [rawSubject = "", rawAuthor = "", rawBody = ""] = raw.split("\u001f");
253
- subject = rawSubject.trim();
254
- gitAuthor = rawAuthor;
255
- body = rawBody;
256
- }
257
- catch {
784
+ const parsedNote = readParsedNote(safeSha, targetDir);
785
+ if (issueFilter !== null && !matchesIssueFilter(issueFilter, commit, parsedNote?.issue?.id)) {
258
786
  continue;
259
787
  }
260
- let parsedNote = null;
261
- const rawNote = getNote(safeSha, { cwd: targetDir });
262
- if (rawNote !== null && rawNote !== "") {
263
- try {
264
- parsedNote = JSON.parse(rawNote);
265
- }
266
- catch {
267
- parsedNote = null;
268
- }
269
- }
270
- const author = extractTrailers(body).author ?? gitAuthor.trim();
271
- const noteTier = typeof parsedNote?.tier === "string" ? parsedNote.tier : null;
272
- const inferredTier = inferTierFromAuthor(author);
273
- const tier = noteTier !== null && noteTier !== "tier-3"
274
- ? noteTier
275
- : (inferredTier ?? noteTier ?? "tier-3");
788
+ const isNoted = notedShas.has(safeSha);
789
+ const author = extractTrailers(commit.body).author ?? commit.author.trim();
790
+ const tier = resolveCommitTier(parsedNote, inferTierFromAuthor(author));
276
791
  const noteSubtaskId = typeof parsedNote?.subtask?.id === "string" ? parsedNote.subtask.id : null;
277
792
  if (noteSubtaskId !== null) {
278
- const issueId = typeof parsedNote?.issue?.id === "number" ? String(parsedNote.issue.id) : "0";
793
+ const issueId = typeof parsedNote?.issue?.id === "number"
794
+ ? String(parsedNote.issue.id)
795
+ : (issueFilter ?? "0");
279
796
  notedSubtasks.add(`${issueId}/${noteSubtaskId}`);
280
797
  }
281
798
  else {
282
- const subjectSubtasks = subject.match(new RegExp(SUBJECT_TASK_PATTERN, "gi"));
799
+ const subjectSubtasks = commit.subject.match(new RegExp(SUBJECT_TASK_PATTERN, "gi"));
283
800
  for (const match of subjectSubtasks ?? []) {
284
801
  notedSubtasks.add(match);
285
802
  }
286
803
  }
804
+ commitsInScope += 1;
805
+ timestamps.push(commit.committedAtMs);
806
+ if (isNoted)
807
+ coveredCommits += 1;
808
+ if (parsedNote?.escalated === true || ESCALATION_SUBJECT_PATTERN.test(commit.subject)) {
809
+ escalatedCommits += 1;
810
+ }
811
+ if (REWORK_SUBJECT_PATTERN.test(commit.subject))
812
+ reworkCommits += 1;
813
+ const allowedFiles = parsedNote?.subtask?.contract?.allowedFiles;
814
+ if (Array.isArray(allowedFiles)) {
815
+ const declared = allowedFiles.filter((file) => typeof file === "string");
816
+ if (declared.length > 0) {
817
+ contractedCommits += 1;
818
+ if (isCommitContracted(safeSha, declared, targetDir))
819
+ compliantCommits += 1;
820
+ }
821
+ }
287
822
  const diffItems = extractCommitDiffStats(safeSha, targetDir);
823
+ const seenExts = new Set();
288
824
  for (const item of diffItems) {
289
825
  totalLinesAdded += item.linesAdded;
290
826
  totalLinesDeleted += item.linesDeleted;
291
- const existing = extensions[item.ext] ?? {
292
- ext: item.ext,
293
- commits: 0,
294
- linesAdded: 0,
295
- linesDeleted: 0,
296
- };
297
- existing.commits += 1;
298
- existing.linesAdded += item.linesAdded;
299
- existing.linesDeleted += item.linesDeleted;
300
- extensions[item.ext] = existing;
827
+ accumulateCategoryLines(store.summary, item.category, item.linesAdded, item.linesDeleted);
828
+ const isNewExtInCommit = !seenExts.has(item.ext);
829
+ if (isNewExtInCommit)
830
+ seenExts.add(item.ext);
831
+ accumulateExtensionLines(extensions, item, isNewExtInCommit);
301
832
  }
302
833
  const modelKey = extractModelFamilyCategory(author);
303
- const existingModel = models[modelKey] ?? {
304
- family: modelKey,
305
- tier,
306
- commits: 0,
307
- totalDurationSec: 0,
308
- avgSubtaskDurationSec: 0,
309
- };
310
- existingModel.tier = tier;
834
+ const existingModel = models[modelKey] ?? createModelStat(modelKey, tier);
311
835
  existingModel.commits += 1;
836
+ accumulateModelPricing(existingModel, linesByCategory(diffItems), tier);
312
837
  models[modelKey] = existingModel;
838
+ summary.tierCommits[resolvePricingTier(tier)] += 1;
839
+ const swarmMetrics = extractNoteSwarmMetrics(parsedNote);
840
+ if (swarmMetrics.isSwarm || isSwarmAuthor(author)) {
841
+ swarmCommits += 1;
842
+ totalSwarmPosts += swarmMetrics.posts;
843
+ maxSwarmWorkers = Math.max(maxSwarmWorkers, swarmMetrics.workers);
844
+ }
313
845
  }
314
846
  store.extensions = extensions;
315
847
  store.models = models;
316
- store.summary.totalCommits = notes.length;
317
- store.summary.totalLinesAdded = totalLinesAdded;
318
- store.summary.totalLinesDeleted = totalLinesDeleted;
319
- store.summary.totalSubtasksCompleted = Math.max(store.summary.totalSubtasksCompleted, notedSubtasks.size);
848
+ summary.totalCommits = commitsInScope;
849
+ summary.totalLinesAdded = totalLinesAdded;
850
+ summary.totalLinesDeleted = totalLinesDeleted;
851
+ summary.totalSubtasksCompleted = Math.max(summary.totalSubtasksCompleted, notedSubtasks.size);
852
+ summary.gitNotesCoveragePct = percentage(coveredCommits, commitsInScope, 100);
853
+ summary.contractedCommits = contractedCommits;
854
+ summary.contractCompliancePct = percentage(compliantCommits, contractedCommits, 100);
855
+ summary.escalatedCommits = escalatedCommits;
856
+ summary.reworkCommits = reworkCommits;
857
+ summary.reworkRatioPct = percentage(reworkCommits, commitsInScope, 0);
858
+ summary.swarmCommits = swarmCommits;
859
+ summary.totalSwarmPosts = totalSwarmPosts;
860
+ summary.maxSwarmWorkers = maxSwarmWorkers;
861
+ const ordered = [...timestamps].sort((a, b) => a - b);
862
+ summary.activeDevelopmentSpanSec =
863
+ ordered.length >= 2 ? Math.round((ordered[ordered.length - 1] - ordered[0]) / 1000) : 0;
864
+ summary.medianCommitCadenceSec = median(ordered.slice(1).map((value, index) => Math.round((value - ordered[index]) / 1000)));
320
865
  updateCostSavingsEstimate(store);
866
+ // Scoped projections stay in memory: persisting them would overwrite the full history.
867
+ if (scoped)
868
+ return store;
321
869
  if (isTelemetryActive(targetDir)) {
322
870
  saveTelemetry(store, targetDir);
323
871
  }
324
872
  return store;
325
873
  }
326
- export function buildAnonymousCommunityPayload(store) {
327
- return {
328
- schemaVersion: "1.0.0",
874
+ export function buildAnonymousDiagnosticPayload(store, filter) {
875
+ const timestamp = new Date().toISOString();
876
+ const payload = {
877
+ schemaVersion: "2.0.0",
329
878
  anonymousProjectId: store.anonymousProjectId,
330
879
  consent: store.consent,
331
880
  environment: {
@@ -337,7 +886,17 @@ export function buildAnonymousCommunityPayload(store) {
337
886
  summary: store.summary,
338
887
  languageBreakdown: Object.values(store.extensions),
339
888
  modelBreakdown: Object.values(store.models),
340
- dispatchedAt: new Date().toISOString(),
889
+ generatedAt: timestamp,
890
+ dispatchedAt: timestamp,
341
891
  };
892
+ if (filter !== undefined) {
893
+ payload.scope = {
894
+ issue: filter.issue ?? null,
895
+ since: filter.since ?? null,
896
+ branch: filter.branch ?? null,
897
+ };
898
+ }
899
+ return payload;
342
900
  }
901
+ export const buildAnonymousCommunityPayload = buildAnonymousDiagnosticPayload;
343
902
  //# sourceMappingURL=collector.js.map