instar 1.3.889 → 1.3.891

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 (126) hide show
  1. package/dashboard/glance.js +1 -0
  2. package/dashboard/index.html +93 -0
  3. package/dist/commands/server.d.ts.map +1 -1
  4. package/dist/commands/server.js +99 -1
  5. package/dist/commands/server.js.map +1 -1
  6. package/dist/config/ConfigDefaults.d.ts.map +1 -1
  7. package/dist/config/ConfigDefaults.js +14 -0
  8. package/dist/config/ConfigDefaults.js.map +1 -1
  9. package/dist/core/BackupManager.d.ts.map +1 -1
  10. package/dist/core/BackupManager.js +22 -15
  11. package/dist/core/BackupManager.js.map +1 -1
  12. package/dist/core/InitiativeTracker.d.ts +7 -0
  13. package/dist/core/InitiativeTracker.d.ts.map +1 -1
  14. package/dist/core/InitiativeTracker.js +17 -0
  15. package/dist/core/InitiativeTracker.js.map +1 -1
  16. package/dist/core/PostUpdateMigrator.d.ts.map +1 -1
  17. package/dist/core/PostUpdateMigrator.js +8 -0
  18. package/dist/core/PostUpdateMigrator.js.map +1 -1
  19. package/dist/core/WriteDomainRegistry.d.ts.map +1 -1
  20. package/dist/core/WriteDomainRegistry.js +12 -0
  21. package/dist/core/WriteDomainRegistry.js.map +1 -1
  22. package/dist/core/canonicalPipelineRegistry.d.ts +73 -0
  23. package/dist/core/canonicalPipelineRegistry.d.ts.map +1 -0
  24. package/dist/core/canonicalPipelineRegistry.js +56 -0
  25. package/dist/core/canonicalPipelineRegistry.js.map +1 -0
  26. package/dist/core/canonicalPipelineRuntimeEvidence.d.ts +13 -0
  27. package/dist/core/canonicalPipelineRuntimeEvidence.d.ts.map +1 -0
  28. package/dist/core/canonicalPipelineRuntimeEvidence.js +15 -0
  29. package/dist/core/canonicalPipelineRuntimeEvidence.js.map +1 -0
  30. package/dist/core/componentCategories.d.ts.map +1 -1
  31. package/dist/core/componentCategories.js +1 -0
  32. package/dist/core/componentCategories.js.map +1 -1
  33. package/dist/core/devGatedFeatures.d.ts.map +1 -1
  34. package/dist/core/devGatedFeatures.js +24 -0
  35. package/dist/core/devGatedFeatures.js.map +1 -1
  36. package/dist/core/types.d.ts +24 -1
  37. package/dist/core/types.d.ts.map +1 -1
  38. package/dist/core/types.js.map +1 -1
  39. package/dist/core/version-skew.d.ts +1 -1
  40. package/dist/core/version-skew.d.ts.map +1 -1
  41. package/dist/data/llmBenchCoverage.d.ts.map +1 -1
  42. package/dist/data/llmBenchCoverage.js +6 -0
  43. package/dist/data/llmBenchCoverage.js.map +1 -1
  44. package/dist/data/provenanceCoverage.d.ts +2 -0
  45. package/dist/data/provenanceCoverage.d.ts.map +1 -1
  46. package/dist/data/provenanceCoverage.js +10 -0
  47. package/dist/data/provenanceCoverage.js.map +1 -1
  48. package/dist/feedback-factory/drain/FeedbackConsumerPromotionStore.d.ts +18 -0
  49. package/dist/feedback-factory/drain/FeedbackConsumerPromotionStore.d.ts.map +1 -0
  50. package/dist/feedback-factory/drain/FeedbackConsumerPromotionStore.js +51 -0
  51. package/dist/feedback-factory/drain/FeedbackConsumerPromotionStore.js.map +1 -0
  52. package/dist/feedback-factory/drain/FeedbackDrainBackupCadence.d.ts +20 -0
  53. package/dist/feedback-factory/drain/FeedbackDrainBackupCadence.d.ts.map +1 -0
  54. package/dist/feedback-factory/drain/FeedbackDrainBackupCadence.js +28 -0
  55. package/dist/feedback-factory/drain/FeedbackDrainBackupCadence.js.map +1 -0
  56. package/dist/feedback-factory/drain/FeedbackDrainPosture.d.ts +14 -0
  57. package/dist/feedback-factory/drain/FeedbackDrainPosture.d.ts.map +1 -0
  58. package/dist/feedback-factory/drain/FeedbackDrainPosture.js +15 -0
  59. package/dist/feedback-factory/drain/FeedbackDrainPosture.js.map +1 -0
  60. package/dist/feedback-factory/drain/FeedbackDrainService.d.ts +121 -0
  61. package/dist/feedback-factory/drain/FeedbackDrainService.d.ts.map +1 -0
  62. package/dist/feedback-factory/drain/FeedbackDrainService.js +370 -0
  63. package/dist/feedback-factory/drain/FeedbackDrainService.js.map +1 -0
  64. package/dist/feedback-factory/drain/FeedbackDrainStore.d.ts +369 -0
  65. package/dist/feedback-factory/drain/FeedbackDrainStore.d.ts.map +1 -0
  66. package/dist/feedback-factory/drain/FeedbackDrainStore.js +1125 -0
  67. package/dist/feedback-factory/drain/FeedbackDrainStore.js.map +1 -0
  68. package/dist/feedback-factory/drain/FeedbackDrainTickProxy.d.ts +67 -0
  69. package/dist/feedback-factory/drain/FeedbackDrainTickProxy.d.ts.map +1 -0
  70. package/dist/feedback-factory/drain/FeedbackDrainTickProxy.js +151 -0
  71. package/dist/feedback-factory/drain/FeedbackDrainTickProxy.js.map +1 -0
  72. package/dist/feedback-factory/drain/FeedbackFactoryGeneratedDefaults.d.ts +32 -0
  73. package/dist/feedback-factory/drain/FeedbackFactoryGeneratedDefaults.d.ts.map +1 -0
  74. package/dist/feedback-factory/drain/FeedbackFactoryGeneratedDefaults.js +47 -0
  75. package/dist/feedback-factory/drain/FeedbackFactoryGeneratedDefaults.js.map +1 -0
  76. package/dist/feedback-factory/drain/FeedbackInitiativeConsumer.d.ts +33 -0
  77. package/dist/feedback-factory/drain/FeedbackInitiativeConsumer.d.ts.map +1 -0
  78. package/dist/feedback-factory/drain/FeedbackInitiativeConsumer.js +71 -0
  79. package/dist/feedback-factory/drain/FeedbackInitiativeConsumer.js.map +1 -0
  80. package/dist/feedback-factory/drain/FeedbackReadinessArbiter.d.ts +36 -0
  81. package/dist/feedback-factory/drain/FeedbackReadinessArbiter.d.ts.map +1 -0
  82. package/dist/feedback-factory/drain/FeedbackReadinessArbiter.js +153 -0
  83. package/dist/feedback-factory/drain/FeedbackReadinessArbiter.js.map +1 -0
  84. package/dist/feedback-factory/drain/index.d.ts +2 -0
  85. package/dist/feedback-factory/drain/index.d.ts.map +1 -0
  86. package/dist/feedback-factory/drain/index.js +2 -0
  87. package/dist/feedback-factory/drain/index.js.map +1 -0
  88. package/dist/feedback-factory/processing/FeedbackProcessingService.d.ts +14 -0
  89. package/dist/feedback-factory/processing/FeedbackProcessingService.d.ts.map +1 -1
  90. package/dist/feedback-factory/processing/FeedbackProcessingService.js +25 -4
  91. package/dist/feedback-factory/processing/FeedbackProcessingService.js.map +1 -1
  92. package/dist/feedback-factory/store/FeedbackSourceGenerations.d.ts +39 -0
  93. package/dist/feedback-factory/store/FeedbackSourceGenerations.d.ts.map +1 -0
  94. package/dist/feedback-factory/store/FeedbackSourceGenerations.js +288 -0
  95. package/dist/feedback-factory/store/FeedbackSourceGenerations.js.map +1 -0
  96. package/dist/feedback-factory/store/JsonlFeedbackStore.d.ts +26 -6
  97. package/dist/feedback-factory/store/JsonlFeedbackStore.d.ts.map +1 -1
  98. package/dist/feedback-factory/store/JsonlFeedbackStore.js +139 -25
  99. package/dist/feedback-factory/store/JsonlFeedbackStore.js.map +1 -1
  100. package/dist/monitoring/AutonomousThroughputFloor.d.ts +118 -0
  101. package/dist/monitoring/AutonomousThroughputFloor.d.ts.map +1 -0
  102. package/dist/monitoring/AutonomousThroughputFloor.js +147 -0
  103. package/dist/monitoring/AutonomousThroughputFloor.js.map +1 -0
  104. package/dist/scaffold/templates.d.ts.map +1 -1
  105. package/dist/scaffold/templates.js +4 -0
  106. package/dist/scaffold/templates.js.map +1 -1
  107. package/dist/server/AgentServer.d.ts +4 -0
  108. package/dist/server/AgentServer.d.ts.map +1 -1
  109. package/dist/server/AgentServer.js +193 -1
  110. package/dist/server/AgentServer.js.map +1 -1
  111. package/dist/server/routes.d.ts +33 -0
  112. package/dist/server/routes.d.ts.map +1 -1
  113. package/dist/server/routes.js +288 -0
  114. package/dist/server/routes.js.map +1 -1
  115. package/package.json +5 -2
  116. package/scripts/lint-canonical-pipeline-completeness.mjs +265 -0
  117. package/src/data/builtin-manifest.json +65 -65
  118. package/src/data/llmBenchCoverage.ts +6 -0
  119. package/src/data/provenanceCoverage.ts +12 -0
  120. package/src/data/state-coherence-registry.json +18 -0
  121. package/src/scaffold/templates/jobs/instar/feedback-factory-process.md +13 -12
  122. package/src/scaffold/templates.ts +4 -0
  123. package/upgrades/1.3.890.md +19 -0
  124. package/upgrades/1.3.891.md +30 -0
  125. package/upgrades/side-effects/autonomous-throughput-floor.md +36 -0
  126. package/upgrades/side-effects/feedback-factory-operating-drain.md +110 -0
@@ -0,0 +1,288 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { SafeFsExecutor } from '../../core/SafeFsExecutor.js';
5
+ const sha = (value) => createHash('sha256').update(value).digest('hex');
6
+ const checksumPayload = (payload) => sha(JSON.stringify(payload));
7
+ /**
8
+ * Cross-process append/compaction authority for feedback.jsonl. The tiny lock is
9
+ * deliberately exclusive for BOTH writers and compaction: publishing a new
10
+ * generation while a legacy writer appends would otherwise lose the append at
11
+ * the handoff boundary.
12
+ */
13
+ export class FeedbackSourceGenerations {
14
+ dir;
15
+ manifestPath;
16
+ generationDir;
17
+ lockPath;
18
+ manifestCache = null;
19
+ constructor(dir) {
20
+ this.dir = dir;
21
+ this.manifestPath = path.join(dir, 'feedback-generations.json');
22
+ this.generationDir = path.join(dir, 'feedback-generations');
23
+ this.lockPath = path.join(dir, '.feedback-generation.lock');
24
+ fs.mkdirSync(dir, { recursive: true });
25
+ }
26
+ current() {
27
+ const manifest = this.readManifest();
28
+ if (!manifest)
29
+ return { generationId: 'canonical-feedback-v1', filePath: path.join(this.dir, 'feedback.jsonl') };
30
+ return {
31
+ generationId: manifest.currentGenerationId,
32
+ filePath: path.join(this.dir, manifest.currentFile),
33
+ };
34
+ }
35
+ planFrom(generationId) {
36
+ const manifest = this.readManifest();
37
+ if (!manifest)
38
+ return [this.current()];
39
+ const generations = new Map();
40
+ for (const handoff of manifest.handoffs) {
41
+ generations.set(handoff.fromGenerationId, {
42
+ generationId: handoff.fromGenerationId,
43
+ filePath: path.join(this.dir, handoff.fromFile),
44
+ handoffToNext: handoff,
45
+ });
46
+ }
47
+ generations.set(manifest.currentGenerationId, {
48
+ generationId: manifest.currentGenerationId,
49
+ filePath: path.join(this.dir, manifest.currentFile),
50
+ });
51
+ const start = generationId ?? manifest.handoffs[0]?.fromGenerationId ?? manifest.currentGenerationId;
52
+ const out = [];
53
+ const seen = new Set();
54
+ let cursor = start;
55
+ while (cursor && !seen.has(cursor)) {
56
+ seen.add(cursor);
57
+ const source = generations.get(cursor);
58
+ if (!source)
59
+ throw new Error(`feedback source generation ${cursor} is missing from the validated manifest`);
60
+ out.push(source);
61
+ cursor = source.handoffToNext?.toGenerationId;
62
+ }
63
+ if (out.at(-1)?.generationId !== manifest.currentGenerationId)
64
+ throw new Error('feedback source handoff chain does not reach the current generation');
65
+ return out;
66
+ }
67
+ append(record, crashPoint) {
68
+ for (let attempt = 0; attempt < 100; attempt++) {
69
+ try {
70
+ this.withLock(() => {
71
+ const current = this.current();
72
+ const durable = { ...record };
73
+ if (typeof durable.sourceRecordId !== 'string' || !durable.sourceRecordId)
74
+ durable.sourceRecordId = `feedback-source:${randomUUID()}`;
75
+ if (crashPoint === 'before-append')
76
+ throw new Error('injected crash before source append');
77
+ const fd = fs.openSync(current.filePath, 'a', 0o600);
78
+ try {
79
+ fs.writeFileSync(fd, `${JSON.stringify(durable)}\n`, 'utf8');
80
+ if (crashPoint === 'after-append')
81
+ throw new Error('injected crash after source append');
82
+ fs.fsyncSync(fd);
83
+ if (crashPoint === 'after-append-fsync')
84
+ throw new Error('injected crash after source append fsync');
85
+ }
86
+ finally {
87
+ fs.closeSync(fd);
88
+ }
89
+ });
90
+ return;
91
+ }
92
+ catch (error) {
93
+ if (!(error instanceof Error) || !error.message.includes('busy') || attempt === 99)
94
+ throw error;
95
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
96
+ }
97
+ }
98
+ }
99
+ compact(now = Date.now(), crashPoint) {
100
+ return this.withLock(() => {
101
+ const current = this.current();
102
+ if (!fs.existsSync(current.filePath))
103
+ return null;
104
+ const bytes = fs.readFileSync(current.filePath);
105
+ if (bytes.length === 0)
106
+ return null;
107
+ const complete = bytes.toString('utf8').split('\n').filter(Boolean);
108
+ const latest = new Map();
109
+ for (const raw of complete) {
110
+ const row = JSON.parse(raw);
111
+ const id = String(row.feedbackId ?? row.feedback_id ?? row.id ?? '');
112
+ if (!id)
113
+ throw new Error('cannot compact feedback source row without a stable feedback id');
114
+ latest.set(id, { row, raw });
115
+ }
116
+ const nextBytes = Buffer.from([...latest.values()].map(({ raw }) => raw).join('\n') + (latest.size ? '\n' : ''));
117
+ const nextId = `feedback-${now}-${sha(nextBytes).slice(0, 12)}`;
118
+ fs.mkdirSync(this.generationDir, { recursive: true });
119
+ const relative = path.join('feedback-generations', `${nextId}.jsonl`);
120
+ const target = path.join(this.dir, relative);
121
+ const tmp = `${target}.${process.pid}.tmp`;
122
+ if (!fs.existsSync(target)) {
123
+ if (fs.existsSync(tmp))
124
+ SafeFsExecutor.safeUnlinkSync(tmp, { operation: 'feedback source generation temp recovery' });
125
+ const fd = fs.openSync(tmp, 'wx', 0o600);
126
+ try {
127
+ fs.writeFileSync(fd, nextBytes);
128
+ fs.fsyncSync(fd);
129
+ }
130
+ finally {
131
+ fs.closeSync(fd);
132
+ }
133
+ fs.renameSync(tmp, target);
134
+ }
135
+ else if (!fs.readFileSync(target).equals(nextBytes)) {
136
+ throw new Error('orphan feedback generation conflicts with deterministic compaction output');
137
+ }
138
+ this.fsyncDirectory(this.generationDir);
139
+ if (crashPoint === 'after-generation-fsync')
140
+ throw new Error('injected crash after generation fsync');
141
+ const previousManifest = this.readManifest();
142
+ const handoff = {
143
+ fromGenerationId: current.generationId,
144
+ fromFile: path.relative(this.dir, current.filePath),
145
+ finalOffset: bytes.length,
146
+ finalChecksum: sha(bytes),
147
+ toGenerationId: nextId,
148
+ toFile: relative,
149
+ startOffset: nextBytes.length,
150
+ startChecksum: sha(nextBytes),
151
+ publishedAt: now,
152
+ };
153
+ const payload = {
154
+ schemaVersion: 1,
155
+ currentGenerationId: nextId,
156
+ currentFile: relative,
157
+ handoffs: [...(previousManifest?.handoffs ?? []), handoff],
158
+ };
159
+ const envelope = { ...payload, checksum: checksumPayload(payload) };
160
+ const manifestTmp = `${this.manifestPath}.${process.pid}.tmp`;
161
+ if (fs.existsSync(manifestTmp))
162
+ SafeFsExecutor.safeUnlinkSync(manifestTmp, { operation: 'feedback handoff manifest temp recovery' });
163
+ const manifestFd = fs.openSync(manifestTmp, 'wx', 0o600);
164
+ try {
165
+ fs.writeFileSync(manifestFd, `${JSON.stringify(envelope, null, 2)}\n`);
166
+ fs.fsyncSync(manifestFd);
167
+ }
168
+ finally {
169
+ fs.closeSync(manifestFd);
170
+ }
171
+ if (crashPoint === 'after-manifest-fsync')
172
+ throw new Error('injected crash after handoff manifest fsync');
173
+ fs.renameSync(manifestTmp, this.manifestPath);
174
+ this.fsyncDirectory(this.dir);
175
+ this.manifestCache = null;
176
+ if (crashPoint === 'after-manifest-publish')
177
+ throw new Error('injected crash after handoff manifest publish');
178
+ return handoff;
179
+ });
180
+ }
181
+ readManifest() {
182
+ if (!fs.existsSync(this.manifestPath))
183
+ return null;
184
+ const stat = fs.statSync(this.manifestPath);
185
+ if (this.manifestCache?.size === stat.size && this.manifestCache.mtimeMs === stat.mtimeMs)
186
+ return this.manifestCache.value;
187
+ const parsed = JSON.parse(fs.readFileSync(this.manifestPath, 'utf8'));
188
+ const payload = {
189
+ schemaVersion: parsed.schemaVersion,
190
+ currentGenerationId: parsed.currentGenerationId,
191
+ currentFile: parsed.currentFile,
192
+ handoffs: parsed.handoffs,
193
+ };
194
+ if (parsed.schemaVersion !== 1 || parsed.checksum !== checksumPayload(payload))
195
+ throw new Error('feedback source generation manifest checksum is invalid');
196
+ for (const handoff of parsed.handoffs) {
197
+ const from = path.join(this.dir, handoff.fromFile);
198
+ const to = path.join(this.dir, handoff.toFile);
199
+ if (!fs.existsSync(from) || !fs.existsSync(to))
200
+ throw new Error('feedback source generation referenced by manifest is missing');
201
+ const fromBytes = fs.readFileSync(from);
202
+ const toBytes = fs.readFileSync(to);
203
+ if (fromBytes.length !== handoff.finalOffset || sha(fromBytes) !== handoff.finalChecksum ||
204
+ toBytes.length < handoff.startOffset || sha(toBytes.subarray(0, handoff.startOffset)) !== handoff.startChecksum) {
205
+ throw new Error('feedback source generation handoff boundary is invalid');
206
+ }
207
+ }
208
+ this.manifestCache = { size: stat.size, mtimeMs: stat.mtimeMs, value: parsed };
209
+ return parsed;
210
+ }
211
+ withLock(fn) {
212
+ let fd;
213
+ try {
214
+ fd = this.acquireLock();
215
+ }
216
+ catch (error) {
217
+ if (error.code === 'EEXIST')
218
+ throw new Error('feedback source generation is busy; retry later');
219
+ throw error;
220
+ }
221
+ try {
222
+ fs.writeFileSync(fd, `${process.pid}\n`, 'utf8');
223
+ fs.fsyncSync(fd);
224
+ return fn();
225
+ }
226
+ finally {
227
+ fs.closeSync(fd);
228
+ try {
229
+ SafeFsExecutor.safeUnlinkSync(this.lockPath, { operation: 'feedback source generation lock release' });
230
+ }
231
+ catch { /* stale lock recovery is explicit */ }
232
+ }
233
+ }
234
+ acquireLock() {
235
+ try {
236
+ return fs.openSync(this.lockPath, 'wx', 0o600);
237
+ }
238
+ catch (error) {
239
+ if (error.code !== 'EEXIST')
240
+ throw error;
241
+ let owner = 0;
242
+ try {
243
+ owner = Number(fs.readFileSync(this.lockPath, 'utf8').trim());
244
+ }
245
+ catch { /* invalid lock is stale */ }
246
+ let alive = false;
247
+ if (Number.isSafeInteger(owner) && owner > 0) {
248
+ try {
249
+ process.kill(owner, 0);
250
+ alive = true;
251
+ }
252
+ catch (probe) {
253
+ alive = probe.code === 'EPERM';
254
+ }
255
+ }
256
+ else {
257
+ // The creator writes its PID immediately after O_EXCL creation. Treat an
258
+ // empty/partial fresh file as live so a contender cannot unlink it in
259
+ // that tiny publication window. Truly corrupt locks age out explicitly.
260
+ try {
261
+ alive = Date.now() - fs.statSync(this.lockPath).mtimeMs < 30_000;
262
+ }
263
+ catch {
264
+ alive = true;
265
+ }
266
+ }
267
+ if (alive)
268
+ throw error;
269
+ try {
270
+ SafeFsExecutor.safeUnlinkSync(this.lockPath, { operation: 'feedback source generation stale lock recovery' });
271
+ }
272
+ catch {
273
+ throw error;
274
+ }
275
+ return fs.openSync(this.lockPath, 'wx', 0o600);
276
+ }
277
+ }
278
+ fsyncDirectory(dir) {
279
+ const fd = fs.openSync(dir, 'r');
280
+ try {
281
+ fs.fsyncSync(fd);
282
+ }
283
+ finally {
284
+ fs.closeSync(fd);
285
+ }
286
+ }
287
+ }
288
+ //# sourceMappingURL=FeedbackSourceGenerations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FeedbackSourceGenerations.js","sourceRoot":"","sources":["../../../src/feedback-factory/store/FeedbackSourceGenerations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AA6B9D,MAAM,GAAG,GAAG,CAAC,KAAsB,EAAU,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACjG,MAAM,eAAe,GAAG,CAAC,OAAwB,EAAU,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;AAE3F;;;;;GAKG;AACH,MAAM,OAAO,yBAAyB;IAMP;IALZ,YAAY,CAAS;IACrB,aAAa,CAAS;IACtB,QAAQ,CAAS;IAC1B,aAAa,GAA8D,IAAI,CAAC;IAExF,YAA6B,GAAW;QAAX,QAAG,GAAH,GAAG,CAAQ;QACtC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,2BAA2B,CAAC,CAAC;QAChE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC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AAE,GAAG,CAAC,CAAC;QACjC,IAAI,CAAC;YAAC,EAAE,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;QAAC,CAAC;gBAAS,CAAC;YAAC,EAAE,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;QAAC,CAAC;IACzD,CAAC;CACF"}
@@ -12,10 +12,9 @@
12
12
  *
13
13
  * Mutation model: append-only log with LAST-WRITE-WINS on load. Every mutation
14
14
  * appends the FULL updated row; on construction all lines are folded into a Map by
15
- * id (later lines supersede earlier). A file with one row per entity — exactly what
16
- * the import produces — is therefore a valid, already-compact log. When superseded
17
- * lines pile up past a threshold the file is compacted at construction time via an
18
- * atomic temp+rename rewrite (crash mid-compaction leaves the original intact).
15
+ * id (later lines supersede earlier). Operated files remain append-only: rewriting
16
+ * an active path would invalidate durable tail cursors. Compaction belongs to the
17
+ * checksummed immutable-generation handoff protocol.
19
18
  *
20
19
  * JSONL (not SQLite) for the same reason as PersistedShadowImportTarget: dependency-
21
20
  * free, no native module, trivially inspectable, and append durability is a plain
@@ -26,15 +25,21 @@ import type { FeedbackItem, Cluster } from '../processor/types.js';
26
25
  import type { ReopenDecision } from '../processor/reopen.js';
27
26
  import type { DispatchRecord } from '../dispatch/dispatch.js';
28
27
  import type { FeedbackStore, FeedbackMetrics } from './FeedbackStore.js';
28
+ import { type FeedbackSourceGeneration, type FeedbackSourceHandoff } from './FeedbackSourceGenerations.js';
29
29
  export declare class JsonlFeedbackStore implements FeedbackStore {
30
30
  private readonly dir;
31
- private readonly feedbackPath;
31
+ private feedbackPath;
32
+ private feedbackGenerationId;
33
+ private readonly sourceGenerations;
32
34
  private readonly clustersPath;
33
35
  private readonly dispatchesPath;
34
36
  private feedback;
35
37
  private clusters;
36
38
  private dispatches;
37
39
  private counts;
40
+ private offsets;
41
+ private sourceLagBytes;
42
+ private projectionRecords;
38
43
  constructor(dir: string);
39
44
  /**
40
45
  * Re-fold all three on-disk JSONL files into fresh in-memory state — the SAME
@@ -55,10 +60,20 @@ export declare class JsonlFeedbackStore implements FeedbackStore {
55
60
  */
56
61
  reload(): void;
57
62
  private loadAll;
58
- private loadAndMaybeCompact;
63
+ /**
64
+ * Fold only complete records appended by another process after our durable
65
+ * offsets. A torn trailing line is left behind for the next pass. This is the
66
+ * normal operating path; `reload()` remains an explicit recovery/import tool.
67
+ */
68
+ syncExternalAppends(maxRecords?: number): {
69
+ projected: number;
70
+ lagBytes: number;
71
+ };
72
+ private loadAppendOnly;
59
73
  private appendFeedback;
60
74
  private appendCluster;
61
75
  getUnprocessedFeedback(): FeedbackItem[];
76
+ withProjectedFeedbackScope<T>(records: Array<Record<string, unknown>>, operation: () => T): T;
62
77
  getActiveClusters(): Cluster[];
63
78
  getCluster(clusterId: string): Cluster | undefined;
64
79
  upsertClusterFromItem(clusterId: string, item: FeedbackItem): void;
@@ -80,6 +95,11 @@ export declare class JsonlFeedbackStore implements FeedbackStore {
80
95
  clusters: number;
81
96
  dispatches: number;
82
97
  };
98
+ lagBytes(): number;
99
+ sourceFeedbackPath(): string;
100
+ sourceFeedbackGeneration(): FeedbackSourceGeneration;
101
+ sourceFeedbackGenerationPlan(fromGenerationId?: string | null): FeedbackSourceGeneration[];
102
+ compactFeedbackSource(now?: number): FeedbackSourceHandoff | null;
83
103
  /**
84
104
  * Read-only aggregate snapshot for `GET /feedback-factory/stats`. Pure read —
85
105
  * never mutates. `byStatus` buckets every feedback row by its `status`
@@ -1 +1 @@
1
- {"version":3,"file":"JsonlFeedbackStore.d.ts","sourceRoot":"","sources":["../../../src/feedback-factory/store/JsonlFeedbackStore.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,KAAK,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AIxC,WAAW,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI;IAMrC,cAAc,CAAC,MAAM,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,cAAc,EAAE;IAQ5E,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS;IAI9D,cAAc,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI;IAQ5C,OAAO,IAAI,eAAe;IAI1B,sDAAsD;IACtD,KAAK,IAAI;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE;IAInE,QAAQ,IAAI,MAAM;IAClB,kBAAkB,IAAI,MAAM;IAC5B,wBAAwB,IAAI,wBAAwB;IACpD,4BAA4B,CAAC,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,wBAAwB,EAAE;IAC1F,qBAAqB,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,qBAAqB,GAAG,IAAI;IAEjE;;;;;;;OAOG;IACH,KAAK,IAAI;QACP,KAAK,EAAE,MAAM,CAAC;QACd,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,YAAY,EAAE,MAAM,CAAC;QACrB,aAAa,EAAE,MAAM,CAAC;QACtB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;KAC5B;CA4BF;AAuDD,mEAAmE;AACnE,wBAAgB,gCAAgC,IAAI,IAAI,CAEvD"}
@@ -12,34 +12,39 @@
12
12
  *
13
13
  * Mutation model: append-only log with LAST-WRITE-WINS on load. Every mutation
14
14
  * appends the FULL updated row; on construction all lines are folded into a Map by
15
- * id (later lines supersede earlier). A file with one row per entity — exactly what
16
- * the import produces — is therefore a valid, already-compact log. When superseded
17
- * lines pile up past a threshold the file is compacted at construction time via an
18
- * atomic temp+rename rewrite (crash mid-compaction leaves the original intact).
15
+ * id (later lines supersede earlier). Operated files remain append-only: rewriting
16
+ * an active path would invalidate durable tail cursors. Compaction belongs to the
17
+ * checksummed immutable-generation handoff protocol.
19
18
  *
20
19
  * JSONL (not SQLite) for the same reason as PersistedShadowImportTarget: dependency-
21
20
  * free, no native module, trivially inspectable, and append durability is a plain
22
21
  * appendFileSync. Volume is fleet feedback — low write rate; the import's measured
23
22
  * 148k-row artifact parses in well under a second.
24
23
  */
25
- import { appendFileSync, mkdirSync, readFileSync, existsSync, writeFileSync, renameSync, statSync } from 'node:fs';
24
+ import { appendFileSync, mkdirSync, readFileSync, existsSync, statSync, openSync, readSync, closeSync } from 'node:fs';
26
25
  import { join } from 'node:path';
27
- /** Compact a file at load when more than half its lines are superseded AND it has real volume. */
28
- const COMPACT_MIN_LINES = 1000;
29
- const COMPACT_SUPERSEDED_RATIO = 0.5;
26
+ import { FeedbackSourceGenerations } from './FeedbackSourceGenerations.js';
30
27
  export class JsonlFeedbackStore {
31
28
  dir;
32
29
  feedbackPath;
30
+ feedbackGenerationId;
31
+ sourceGenerations;
33
32
  clustersPath;
34
33
  dispatchesPath;
35
34
  feedback;
36
35
  clusters;
37
36
  dispatches;
38
37
  counts = { captured: 0, created: 0, merged: 0, reopened: 0 };
38
+ offsets = { feedback: 0, clusters: 0, dispatches: 0 };
39
+ sourceLagBytes = 0;
40
+ projectionRecords = null;
39
41
  constructor(dir) {
40
42
  this.dir = dir;
41
43
  mkdirSync(dir, { recursive: true });
42
- this.feedbackPath = join(dir, 'feedback.jsonl');
44
+ this.sourceGenerations = new FeedbackSourceGenerations(dir);
45
+ const current = this.sourceGenerations.current();
46
+ this.feedbackPath = current.filePath;
47
+ this.feedbackGenerationId = current.generationId;
43
48
  this.clustersPath = join(dir, 'clusters.jsonl');
44
49
  this.dispatchesPath = join(dir, 'dispatches.jsonl');
45
50
  this.loadAll();
@@ -65,32 +70,131 @@ export class JsonlFeedbackStore {
65
70
  this.loadAll();
66
71
  }
67
72
  loadAll() {
68
- this.feedback = this.loadAndMaybeCompact(this.feedbackPath, (r) => pickId(r, 'feedbackId', 'feedback_id', 'id'));
69
- this.clusters = this.loadAndMaybeCompact(this.clustersPath, (r) => pickId(r, 'clusterId', 'cluster_id', 'id'));
70
- this.dispatches = this.loadAndMaybeCompact(this.dispatchesPath, (r) => pickId(r, 'dispatchId', 'dispatch_id', 'id'));
73
+ this.feedback = this.loadAppendOnly(this.feedbackPath, (r) => pickId(r, 'feedbackId', 'feedback_id', 'id'));
74
+ this.clusters = this.loadAppendOnly(this.clustersPath, (r) => pickId(r, 'clusterId', 'cluster_id', 'id'));
75
+ this.dispatches = this.loadAppendOnly(this.dispatchesPath, (r) => pickId(r, 'dispatchId', 'dispatch_id', 'id'));
76
+ this.offsets = {
77
+ feedback: existsSync(this.feedbackPath) ? statSync(this.feedbackPath).size : 0,
78
+ clusters: existsSync(this.clustersPath) ? statSync(this.clustersPath).size : 0,
79
+ dispatches: existsSync(this.dispatchesPath) ? statSync(this.dispatchesPath).size : 0,
80
+ };
81
+ this.sourceLagBytes = 0;
71
82
  }
72
- loadAndMaybeCompact(path, idOf) {
73
- const { rows, totalLines } = loadJsonl(path, idOf);
74
- const superseded = totalLines - rows.size;
75
- if (totalLines >= COMPACT_MIN_LINES && superseded / totalLines >= COMPACT_SUPERSEDED_RATIO) {
76
- // Atomic rewrite: full snapshot to a temp file in the same dir, then rename.
77
- const tmp = `${path}.compact.tmp`;
78
- writeFileSync(tmp, [...rows.values()].map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8');
79
- renameSync(tmp, path);
83
+ /**
84
+ * Fold only complete records appended by another process after our durable
85
+ * offsets. A torn trailing line is left behind for the next pass. This is the
86
+ * normal operating path; `reload()` remains an explicit recovery/import tool.
87
+ */
88
+ syncExternalAppends(maxRecords = 500) {
89
+ const current = this.sourceGenerations.current();
90
+ if (current.generationId !== this.feedbackGenerationId) {
91
+ this.feedbackGenerationId = current.generationId;
92
+ this.feedbackPath = current.filePath;
93
+ this.feedback = this.loadAppendOnly(this.feedbackPath, (row) => pickId(row, 'feedbackId', 'feedback_id', 'id'));
94
+ this.offsets.feedback = existsSync(this.feedbackPath) ? statSync(this.feedbackPath).size : 0;
80
95
  }
81
- return rows;
96
+ const bounded = Math.max(0, Math.min(500, Math.trunc(maxRecords)));
97
+ let remaining = bounded;
98
+ let projected = 0;
99
+ const fold = (filePath, key, rows, idOf) => {
100
+ if (remaining === 0 || !existsSync(filePath))
101
+ return;
102
+ const size = statSync(filePath).size;
103
+ const offset = this.offsets[key];
104
+ if (size < offset)
105
+ throw new Error(`feedback source truncated before persisted ${key} cursor`);
106
+ if (size === offset)
107
+ return;
108
+ const bytes = Buffer.allocUnsafe(Math.min(size - offset, 4 * 1024 * 1024));
109
+ const fd = openSync(filePath, 'r');
110
+ let read = 0;
111
+ try {
112
+ read = readSync(fd, bytes, 0, bytes.length, offset);
113
+ }
114
+ finally {
115
+ closeSync(fd);
116
+ }
117
+ const slice = bytes.subarray(0, read);
118
+ let consumed = 0;
119
+ for (let start = 0; start < slice.length && remaining > 0;) {
120
+ const newline = slice.indexOf(0x0a, start);
121
+ if (newline < 0)
122
+ break;
123
+ const raw = slice.subarray(start, newline).toString('utf8').trim();
124
+ consumed = newline + 1;
125
+ start = newline + 1;
126
+ if (!raw)
127
+ continue;
128
+ let parsed;
129
+ try {
130
+ parsed = JSON.parse(raw);
131
+ }
132
+ catch {
133
+ throw new Error(`invalid complete JSONL record after persisted ${key} cursor`);
134
+ }
135
+ const id = idOf(parsed);
136
+ if (!id)
137
+ throw new Error(`source record after persisted ${key} cursor has no stable id`);
138
+ rows.set(id, parsed);
139
+ projected++;
140
+ remaining--;
141
+ }
142
+ this.offsets[key] += consumed;
143
+ };
144
+ fold(this.feedbackPath, 'feedback', this.feedback, (row) => pickId(row, 'feedbackId', 'feedback_id', 'id'));
145
+ fold(this.clustersPath, 'clusters', this.clusters, (row) => pickId(row, 'clusterId', 'cluster_id', 'id'));
146
+ fold(this.dispatchesPath, 'dispatches', this.dispatches, (row) => pickId(row, 'dispatchId', 'dispatch_id', 'id'));
147
+ this.sourceLagBytes = [
148
+ [this.feedbackPath, this.offsets.feedback], [this.clustersPath, this.offsets.clusters], [this.dispatchesPath, this.offsets.dispatches],
149
+ ].reduce((sum, [file, offset]) => sum + (existsSync(file) ? Math.max(0, statSync(file).size - Number(offset)) : 0), 0);
150
+ return { projected, lagBytes: this.sourceLagBytes };
151
+ }
152
+ loadAppendOnly(path, idOf) {
153
+ return loadJsonl(path, idOf).rows;
82
154
  }
83
155
  appendFeedback(row) {
84
- appendFileSync(this.feedbackPath, JSON.stringify(row) + '\n', 'utf8');
156
+ const priorSize = existsSync(this.feedbackPath) ? statSync(this.feedbackPath).size : 0;
157
+ this.sourceGenerations.append(row);
158
+ const current = this.sourceGenerations.current();
159
+ if (current.generationId !== this.feedbackGenerationId) {
160
+ this.feedbackGenerationId = current.generationId;
161
+ this.feedbackPath = current.filePath;
162
+ this.offsets.feedback = 0;
163
+ }
164
+ if (this.offsets.feedback === priorSize)
165
+ this.offsets.feedback = statSync(this.feedbackPath).size;
85
166
  }
86
167
  appendCluster(row) {
168
+ const priorSize = existsSync(this.clustersPath) ? statSync(this.clustersPath).size : 0;
87
169
  appendFileSync(this.clustersPath, JSON.stringify(row) + '\n', 'utf8');
170
+ if (this.offsets.clusters === priorSize)
171
+ this.offsets.clusters = statSync(this.clustersPath).size;
88
172
  }
89
173
  // ── FeedbackStore ──────────────────────────────────────────────────────────
90
174
  getUnprocessedFeedback() {
91
- return [...this.feedback.values()]
175
+ const authoritativeRows = this.projectionRecords ? [...this.projectionRecords.values()] : [...this.feedback.values()];
176
+ return authoritativeRows
92
177
  .filter((f) => (f.status ?? 'unprocessed') === 'unprocessed')
93
- .sort((a, b) => String(a.receivedAt ?? '').localeCompare(String(b.receivedAt ?? '')));
178
+ .sort((a, b) => String(a.receivedAt ?? '').localeCompare(String(b.receivedAt ?? '')))
179
+ .slice(0, 500);
180
+ }
181
+ withProjectedFeedbackScope(records, operation) {
182
+ const exact = new Map();
183
+ for (const record of records) {
184
+ const id = pickId(record, 'feedbackId', 'feedback_id', 'id');
185
+ if (!id)
186
+ throw new Error('projected feedback record has no stable id');
187
+ if (exact.has(id))
188
+ throw new Error(`projected feedback batch duplicated id ${id}`);
189
+ exact.set(id, { ...record, feedbackId: id });
190
+ }
191
+ this.projectionRecords = exact;
192
+ try {
193
+ return operation();
194
+ }
195
+ finally {
196
+ this.projectionRecords = null;
197
+ }
94
198
  }
95
199
  getActiveClusters() {
96
200
  return [...this.clusters.values()].filter((c) => c.status !== 'resolved');
@@ -139,10 +243,12 @@ export class JsonlFeedbackStore {
139
243
  this.counts.reopened++;
140
244
  }
141
245
  markProcessed(feedbackId, clusterId) {
142
- const f = this.feedback.get(feedbackId);
246
+ const projected = this.projectionRecords?.get(feedbackId);
247
+ const f = projected ? { ...projected } : this.feedback.get(feedbackId);
143
248
  if (f) {
144
249
  f.status = 'processing';
145
250
  f.clusterId = clusterId;
251
+ this.feedback.set(feedbackId, f);
146
252
  this.appendFeedback(f);
147
253
  }
148
254
  this.counts.captured++;
@@ -168,7 +274,10 @@ export class JsonlFeedbackStore {
168
274
  createDispatch(record) {
169
275
  const row = { active: true, ...record };
170
276
  this.dispatches.set(record.dispatchId, row);
277
+ const priorSize = existsSync(this.dispatchesPath) ? statSync(this.dispatchesPath).size : 0;
171
278
  appendFileSync(this.dispatchesPath, JSON.stringify(row) + '\n', 'utf8');
279
+ if (this.offsets.dispatches === priorSize)
280
+ this.offsets.dispatches = statSync(this.dispatchesPath).size;
172
281
  }
173
282
  metrics() {
174
283
  return { ...this.counts };
@@ -177,6 +286,11 @@ export class JsonlFeedbackStore {
177
286
  sizes() {
178
287
  return { feedback: this.feedback.size, clusters: this.clusters.size, dispatches: this.dispatches.size };
179
288
  }
289
+ lagBytes() { return this.sourceLagBytes; }
290
+ sourceFeedbackPath() { return this.sourceGenerations.current().filePath; }
291
+ sourceFeedbackGeneration() { return this.sourceGenerations.current(); }
292
+ sourceFeedbackGenerationPlan(fromGenerationId) { return this.sourceGenerations.planFrom(fromGenerationId); }
293
+ compactFeedbackSource(now) { return this.sourceGenerations.compact(now); }
180
294
  /**
181
295
  * Read-only aggregate snapshot for `GET /feedback-factory/stats`. Pure read —
182
296
  * never mutates. `byStatus` buckets every feedback row by its `status`