@bongos/core 1.19.296 → 1.19.297

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.
@@ -0,0 +1,399 @@
1
+ // tests/idea_develop_spark.mjs
2
+ //
3
+ // task 1002922 (BV1.R146, goal 1000062) — develop a Spark into a Full Idea,
4
+ // preserving attribution.
5
+ //
6
+ // The done-when, as assertions: the row keeps its ID and its ORIGINAL AUTHOR; a
7
+ // DISTINCT DEVELOPER is recorded; references to the idea never break (nothing
8
+ // writes idea_inbox); and a spark can be developed ONLY ONCE — enforced in the
9
+ // UPDATE predicate, not by a read-then-write that loses the race.
10
+ //
11
+ // It also pins the scope boundary that matters for money: this path must NOT pay
12
+ // the stream-2 "Full Idea passed" credit. awardIdeaFullPassCredit is idempotent
13
+ // per (builder, idea), so paying the DEVELOPER here would not block a later
14
+ // payment to the AUTHOR — one idea would pay twice. R147 owns the split.
15
+ //
16
+ // DB-free the idea_full_capture.mjs way: pool.query patched on the doorway before
17
+ // the modules load, so the REAL SQL is captured and the REAL handler runs.
18
+ //
19
+ // Run: node tests/idea_develop_spark.mjs
20
+
21
+ import { strict as assert } from 'node:assert';
22
+ import { createRequire } from 'node:module';
23
+
24
+ const require = createRequire(import.meta.url);
25
+ const api = require('../src/module-api.js');
26
+
27
+ let queries = [];
28
+ let idea = null;
29
+ let developRows = []; // what the guarded UPDATE returns ([] = guard fired)
30
+
31
+ api.pool.query = async (sql, params = []) => {
32
+ queries.push({ sql, params });
33
+ if (/UPDATE ideas_grades/i.test(sql)) return { rows: developRows };
34
+ if (/FROM idea_inbox/i.test(sql)) return { rows: idea ? [idea] : [] };
35
+ return { rows: [] };
36
+ };
37
+
38
+ // Which ports the handler asked the kernel for — the credit boundary is asserted
39
+ // by the ABSENCE of 'reward' here, which is stronger than checking for no INSERT.
40
+ let portsResolved = [];
41
+ const realResolveOptional = api.resolveOptional;
42
+ api.resolveOptional = (name) => { portsResolved.push(name); return undefined; };
43
+
44
+ const { BASE_TEMPLATE } = require('../modules/ideas/templates.js');
45
+ const routesFactory = require('../modules/ideas/routes/inbox.js');
46
+ const router = routesFactory({});
47
+
48
+ function handlerFor(pathStr, method) {
49
+ const layer = router.stack.find((l) => l.route && l.route.path === pathStr && l.route.methods[method]);
50
+ assert.ok(layer, `route ${method.toUpperCase()} ${pathStr} is not mounted`);
51
+ const stack = layer.route.stack.map((s) => s.handle);
52
+ return stack[stack.length - 1];
53
+ }
54
+ const postDevelop = handlerFor('/inbox/:id/develop', 'post');
55
+
56
+ const FULL = Object.fromEntries(
57
+ BASE_TEMPLATE.fields.map((f) => [f.key, `A substantive answer for ${f.key}, long enough to clear the floor.`]),
58
+ );
59
+
60
+ function call({ body = { field_values: FULL }, builderId = '42' } = {}) {
61
+ return new Promise((resolve, reject) => {
62
+ const req = { params: { id: '77' }, body, query: {}, builder: { id: builderId, rank: 'xenos' } };
63
+ const res = {
64
+ statusCode: 200,
65
+ status(c) { this.statusCode = c; return this; },
66
+ json(payload) { resolve({ status: this.statusCode, payload }); },
67
+ // Production nests res.fail's third argument under error.details (ADR 0116).
68
+ // Kept BOTH here: `details` verbatim (so an ARRAY of field errors survives —
69
+ // spreading one yields {0:…} and silently loses the shape), plus the object
70
+ // spread the sibling idea tests read.
71
+ fail(code, status, extra) {
72
+ const s = typeof status === 'number' ? status : (status && status.status) || 500;
73
+ const spread = extra && !Array.isArray(extra) ? extra : {};
74
+ resolve({ status: s, payload: { error: code, details: extra, ...spread } });
75
+ },
76
+ };
77
+ Promise.resolve(postDevelop(req, res, (err) => reject(err || new Error('next() called')))).catch(reject);
78
+ });
79
+ }
80
+
81
+ const updateQ = () => queries.find((q) => /UPDATE ideas_grades/i.test(q.sql));
82
+ const writes = () => queries.filter((q) => /^\s*(UPDATE|INSERT|DELETE)/i.test(q.sql));
83
+
84
+ let passed = 0;
85
+ let failed = 0;
86
+ const basePoolQuery = async (sql, params = []) => {
87
+ queries.push({ sql, params });
88
+ if (/UPDATE ideas_grades/i.test(sql)) return { rows: developRows };
89
+ if (/FROM idea_inbox/i.test(sql)) return { rows: idea ? [idea] : [] };
90
+ return { rows: [] };
91
+ };
92
+
93
+ async function test(name, fn) {
94
+ queries = [];
95
+ portsResolved = [];
96
+ // Restored every test: one case below swaps in a two-phase stub to simulate a
97
+ // triager closing the idea mid-request, and it must not leak into the next.
98
+ api.pool.query = basePoolQuery;
99
+ // The author is builder 9; the developer in call() defaults to 42.
100
+ idea = {
101
+ id: '77', title: 'a spark', body_md: 'the thought', status: 'open',
102
+ captured_by: '9', captured_at: '2026-08-01T00:00:00Z',
103
+ grade: 'spark', template_key: null, field_values: null,
104
+ completeness_score: null, developed_by: null, developed_at: null,
105
+ };
106
+ developRows = [{
107
+ idea_id: '77', grade: 'full', template_key: 'base-v1', field_values: FULL,
108
+ completeness_score: 100, developed_by: '42', developed_at: '2026-08-22T12:00:00Z',
109
+ }];
110
+ try { await fn(); passed++; console.log(` ok ${name}`); }
111
+ catch (err) { failed++; console.error(` FAIL ${name}\n ${err.message}`); }
112
+ }
113
+
114
+ // --- the happy path, and what it preserves ------------------------------
115
+
116
+ await test('ANY builder can develop a spark — cross-builder pickup is the point', async () => {
117
+ const r = await call();
118
+ assert.equal(r.status, 200);
119
+ assert.equal(r.payload.developed, true);
120
+ assert.equal(r.payload.idea.grade, 'full');
121
+ assert.equal(r.payload.idea.completeness_score, 100);
122
+ });
123
+
124
+ await test('the row keeps its ID and its ORIGINAL author; only the grade moves', async () => {
125
+ const r = await call();
126
+ assert.equal(r.payload.idea.id, '77', 'same id — references never break');
127
+ assert.equal(r.payload.idea.captured_by, '9', 'the author is NOT overwritten');
128
+ assert.equal(r.payload.idea.captured_at, '2026-08-01T00:00:00Z', 'nor the capture time');
129
+ // The strongest form of "references never break": idea_inbox is never WRITTEN.
130
+ // Matched on the write verb + table, not the bare table name — the status guard
131
+ // legitimately READS idea_inbox in an EXISTS subquery inside the grade UPDATE.
132
+ assert.ok(
133
+ !queries.some((q) => /(UPDATE\s+idea_inbox|INSERT\s+INTO\s+idea_inbox|DELETE\s+FROM\s+idea_inbox)/i.test(q.sql)),
134
+ 'development touches ideas_grades only — no new row, no idea_inbox mutation',
135
+ );
136
+ // And the write really is to the grade table.
137
+ assert.match(updateQ().sql, /^\s*UPDATE ideas_grades/i);
138
+ });
139
+
140
+ await test('a DISTINCT developer is recorded, and both parties are named in the response', async () => {
141
+ const r = await call({ builderId: '42' });
142
+ assert.equal(r.payload.idea.developed_by, '42');
143
+ assert.equal(r.payload.developer_id, '42');
144
+ assert.equal(r.payload.author_id, '9');
145
+ assert.equal(r.payload.self_developed, false);
146
+ assert.equal(updateQ().params.at(-1), '42', 'the developer is the AUTHENTICATED builder, not a body field');
147
+ });
148
+
149
+ await test('self-development is legal and reported as such', async () => {
150
+ developRows[0].developed_by = '9';
151
+ const r = await call({ builderId: '9' });
152
+ assert.equal(r.status, 200, 'an author may develop their own spark');
153
+ assert.equal(r.payload.self_developed, true);
154
+ });
155
+
156
+ await test('the developer cannot be spoofed: the body allowlist REFUSES the field', async () => {
157
+ // The write takes req.builder.id (asserted above), and the validator is a
158
+ // strict allowlist on top of that — so an attempt to name a developer, or to
159
+ // rewrite the author, is refused by NAME before the handler reads anything.
160
+ for (const spoof of ['developed_by', 'developer_id', 'captured_by']) {
161
+ queries = [];
162
+ const r = await call({ body: { field_values: FULL, [spoof]: '1' } });
163
+ assert.equal(r.status, 400, `${spoof} is not an accepted body field`);
164
+ assert.equal(r.payload.error, 'validation_failed');
165
+ assert.deepEqual(r.payload.details, [{ field: spoof, reason: 'unknown_field' }], 'the refused field is named');
166
+ assert.equal(writes().length, 0);
167
+ }
168
+ });
169
+
170
+ // --- developed only once, and where that is actually enforced -----------
171
+
172
+ await test('"only once" lives in the UPDATE predicate, not in a read-then-write', async () => {
173
+ await call();
174
+ const sql = updateQ().sql;
175
+ assert.match(sql, /WHERE idea_id = \$1/);
176
+ assert.match(sql, /AND grade = 'spark'/, 'the guard is in the write, so a race cannot double-develop');
177
+ });
178
+
179
+ await test('a lost race is a 409, and the winner\'s work is not overwritten', async () => {
180
+ developRows = []; // the guard matched zero rows: someone developed it first
181
+ const r = await call();
182
+ assert.equal(r.status, 409);
183
+ assert.equal(r.payload.error, 'spark_already_developed');
184
+ assert.match(r.payload.reason, /their version stands/);
185
+ });
186
+
187
+ await test('an ALREADY-DEVELOPED idea is refused before any write', async () => {
188
+ idea.grade = 'full';
189
+ idea.developed_by = '7';
190
+ const r = await call();
191
+ assert.equal(r.status, 409);
192
+ assert.equal(r.payload.error, 'not_a_spark');
193
+ assert.equal(r.payload.developed_by, '7', 'it says who got there first');
194
+ assert.equal(writes().length, 0);
195
+ });
196
+
197
+ await test('a QUICK idea cannot be developed — there is no consent to develop it', async () => {
198
+ idea.grade = 'quick';
199
+ const r = await call();
200
+ assert.equal(r.status, 409);
201
+ assert.equal(r.payload.error, 'not_a_spark');
202
+ assert.match(r.payload.reason, /author has to mark it first/);
203
+ assert.equal(writes().length, 0);
204
+ });
205
+
206
+ // --- a spark is not necessarily still DEVELOPABLE (grader finding, R146) -
207
+
208
+ // Triage writes idea_inbox.status and NEVER touches ideas_grades, so a discarded
209
+ // or promoted spark keeps grade='spark' forever. Grade alone therefore does not
210
+ // mean "still developable" — and developing a dead idea would open a fresh board
211
+ // ratification window for content triage already killed.
212
+ for (const dead of ['discarded', 'promoted', 'merged']) {
213
+ await test(`a ${dead} spark cannot be developed, even though its grade is still 'spark'`, async () => {
214
+ idea.status = dead;
215
+ const r = await call();
216
+ assert.equal(r.status, 409);
217
+ assert.equal(r.payload.error, 'idea_not_open');
218
+ assert.equal(r.payload.status, dead);
219
+ assert.equal(writes().length, 0, 'refused before any write');
220
+ assert.ok(!portsResolved.includes('government'), 'and no board window is opened for a dead idea');
221
+ });
222
+ }
223
+
224
+ await test('the status guard is in the WRITE PREDICATE too, not just the pre-check', async () => {
225
+ await call();
226
+ const sql = updateQ().sql;
227
+ // A pre-check cannot stop a triager who discards the idea mid-request; the fix
228
+ // for a race is never a check that ran earlier.
229
+ assert.match(sql, /EXISTS/i);
230
+ assert.match(sql, /idea_inbox i WHERE i\.id = \$1 AND i\.status = 'open'/);
231
+ });
232
+
233
+ await test('losing to a TRIAGER mid-request is reported as such, not as a lost race', async () => {
234
+ developRows = []; // the guard fired
235
+ idea.status = 'discarded'; // ...because triage closed it
236
+ // The pre-check catches this one first, which is the desired outcome; the
237
+ // post-write branch below covers the genuinely concurrent case.
238
+ const r = await call();
239
+ assert.equal(r.payload.error, 'idea_not_open');
240
+ });
241
+
242
+ await test('a spark closed BETWEEN the read and the write reports the triager, not a rival', async () => {
243
+ developRows = [];
244
+ // Open on the pre-read, closed by the time the re-read happens.
245
+ let reads = 0;
246
+ api.pool.query = async (sql, params = []) => {
247
+ queries.push({ sql, params });
248
+ if (/UPDATE ideas_grades/i.test(sql)) return { rows: [] };
249
+ if (/FROM idea_inbox/i.test(sql)) {
250
+ reads += 1;
251
+ return { rows: [{ ...idea, status: reads === 1 ? 'open' : 'discarded' }] };
252
+ }
253
+ return { rows: [] };
254
+ };
255
+ const r = await call();
256
+ assert.equal(r.status, 409);
257
+ assert.equal(r.payload.error, 'idea_not_open');
258
+ assert.equal(r.payload.status, 'discarded');
259
+ assert.match(r.payload.reason, /triager closed this idea while you were developing it/);
260
+ });
261
+
262
+ // --- the same standard as any other Full Idea --------------------------
263
+
264
+ await test('an invalid field set is a 400 NAMING the field, and nothing is written', async () => {
265
+ const r = await call({ body: { field_values: { ...FULL, rogue: 'x' } } });
266
+ assert.equal(r.status, 400);
267
+ assert.equal(r.payload.error, 'invalid_field_values');
268
+ assert.deepEqual(r.payload.errors, [{ field: 'rogue', reason: 'unknown_field' }]);
269
+ assert.equal(writes().length, 0, 'a spark is not consumed by a failed attempt');
270
+ });
271
+
272
+ await test('a missing required field is refused the same way', async () => {
273
+ const { fit, ...four } = FULL;
274
+ const r = await call({ body: { field_values: four } });
275
+ assert.equal(r.status, 400);
276
+ assert.ok(r.payload.errors.some((e) => e.field === 'fit' && e.reason === 'missing_required'));
277
+ assert.equal(writes().length, 0);
278
+ });
279
+
280
+ await test('field_values is required — an empty develop is not a developed idea', async () => {
281
+ const r = await call({ body: {} });
282
+ assert.equal(r.status, 400);
283
+ assert.equal(writes().length, 0);
284
+ });
285
+
286
+ await test('a missing idea is a 404, not a 500', async () => {
287
+ idea = null;
288
+ const r = await call();
289
+ assert.equal(r.status, 404);
290
+ assert.equal(r.payload.error, 'idea_not_found');
291
+ assert.equal(writes().length, 0);
292
+ });
293
+
294
+ // --- the money boundary: R147 owns the split ---------------------------
295
+
296
+ await test('the stream-2 pass credit is NOT paid here — R147 owns the split', async () => {
297
+ const r = await call();
298
+ assert.equal(r.status, 200);
299
+ // Stronger than "no INSERT INTO credit_log": the handler never even asks for
300
+ // the reward port. awardIdeaFullPassCredit is idempotent per (builder, idea),
301
+ // so paying the DEVELOPER here would NOT block a later payment to the AUTHOR —
302
+ // the same idea would pay twice.
303
+ assert.ok(!portsResolved.includes('reward'), 'the reward port is never resolved on the develop path');
304
+ assert.ok(!queries.some((q) => /credit_log/i.test(q.sql)), 'no credit is booked');
305
+ assert.equal(r.payload.ideator_credit, undefined);
306
+ });
307
+
308
+ await test('but the board window IS opened — otherwise the handoff dead-ends', async () => {
309
+ await call();
310
+ // Recipient-agnostic (an idea and a score, no builder), and without it a
311
+ // developed Full Idea could never reach ratification.
312
+ assert.ok(portsResolved.includes('government'), 'the government port is consulted');
313
+ });
314
+
315
+ await test('a board-window failure does not roll back the development (fail-open)', async () => {
316
+ api.resolveOptional = (name) => {
317
+ portsResolved.push(name);
318
+ if (name === 'government') return { openBoardWindowForIdea: async () => { throw new Error('synthetic board outage'); } };
319
+ return undefined;
320
+ };
321
+ const r = await call();
322
+ assert.equal(r.status, 200, 'the development landed');
323
+ assert.equal(r.payload.developed, true);
324
+ assert.equal(r.payload.board_window, undefined);
325
+ api.resolveOptional = (name) => { portsResolved.push(name); return undefined; };
326
+ });
327
+
328
+ api.resolveOptional = realResolveOptional;
329
+
330
+ // --- what the developer actually reads -----------------------------------
331
+
332
+ const cli = require('../scripts/gds/spark.js');
333
+
334
+ await test('the CLI names both parties, and never prints "undefined"', () => {
335
+ const out = cli.renderDeveloped({
336
+ idea: { id: '77', completeness_score: 88 },
337
+ author_id: '9', developer_id: '42', self_developed: false,
338
+ board_window: { item_id: '3', closes_at: '2026-08-29T00:00:00Z' },
339
+ });
340
+ assert.match(out, /completeness 88\/100/);
341
+ assert.match(out, /\/builders\/#\/idea\/77/, 'the hall link, never a bare ref');
342
+ assert.match(out, /credited to builder 9/, 'the author keeps the thought');
343
+ assert.match(out, /developer \(42\)/);
344
+ assert.match(out, /ratification window is open/);
345
+ assert.doesNotMatch(out, /undefined|null/);
346
+ });
347
+
348
+ await test('self-development reads as one person, not a handoff to yourself', () => {
349
+ const out = cli.renderDeveloped({ idea: { id: '1', completeness_score: 70 }, author_id: '9', developer_id: '9', self_developed: true });
350
+ assert.match(out, /You had the thought and you developed it/);
351
+ assert.doesNotMatch(out, /credited to builder/);
352
+ });
353
+
354
+ await test('a sub-bar result says WHICH section is thinnest', () => {
355
+ const out = cli.renderDeveloped({
356
+ idea: { id: '1', completeness_score: 40, rejection: { section_key: 'why_matters', reason_md: 'barely there' } },
357
+ author_id: '9', developer_id: '42', self_developed: false,
358
+ });
359
+ assert.match(out, /thinnest section: why_matters/);
360
+ assert.match(out, /barely there/);
361
+ assert.doesNotMatch(out, /ratification window/, 'no window was opened');
362
+ });
363
+
364
+ await test('an unscored idea says so rather than printing nothing', () => {
365
+ const out = cli.renderDeveloped({ idea: { id: '1', completeness_score: null }, author_id: '9', developer_id: '42' });
366
+ assert.match(out, /completeness unscored\/100/);
367
+ });
368
+
369
+ await test('--template is read from the R141 declaration, not restated', () => {
370
+ const out = cli.templateSkeleton();
371
+ for (const f of BASE_TEMPLATE.fields) {
372
+ assert.ok(out.includes(f.key), `names ${f.key}`);
373
+ assert.ok(out.includes(f.label), `names the label for ${f.key}`);
374
+ }
375
+ assert.match(out, /padding scores nothing/, 'it warns about the substance floor');
376
+ // The skeleton must be valid JSON for the five keys, or --fields-file advice lies.
377
+ const json = out.slice(out.indexOf('{'), out.lastIndexOf('}') + 1);
378
+ assert.deepEqual(Object.keys(JSON.parse(json)).sort(), BASE_TEMPLATE.fields.map((f) => f.key).sort());
379
+ });
380
+
381
+ await test('the CLI explains each server refusal in the developer\'s own terms', () => {
382
+ const { envelope } = require('../src/bongos/api-errors.js');
383
+ const already = cli.explain(409, envelope('not_a_spark', undefined, { grade: 'full', developed_by: '7' }));
384
+ assert.match(already, /already been developed/);
385
+ assert.match(already, /builder 7/);
386
+ assert.doesNotMatch(already, /undefined/);
387
+
388
+ const notMarked = cli.explain(409, envelope('not_a_spark', undefined, { grade: 'quick' }));
389
+ assert.match(notMarked, /author has to mark it first/);
390
+
391
+ const race = cli.explain(409, envelope('spark_already_developed', undefined, {}));
392
+ assert.match(race, /Their version stands/);
393
+
394
+ const bad = cli.explain(400, envelope('invalid_field_values', undefined, { errors: [{ field: 'fit', reason: 'missing_required' }] }));
395
+ assert.match(bad, /fit: missing required/);
396
+ });
397
+
398
+ console.log(`\nidea_develop_spark: ${passed} passed, ${failed} failed`);
399
+ if (failed > 0) process.exit(1);
@@ -101,13 +101,21 @@ await test('the queue asks for grade=spark AND status=open — nothing else', as
101
101
  assert.match(sql, /i\.status = 'open'/, 'only open ideas');
102
102
  });
103
103
 
104
- await test('a DEVELOPED spark leaves the queue by GRADE, with no `developed` flag', async () => {
104
+ await test('a DEVELOPED spark leaves the queue by GRADE, not by a `developed` filter', async () => {
105
105
  await call();
106
106
  const sql = listSql().sql;
107
107
  // R146 develops in place and flips the grade spark→full, so grade='spark' IS
108
108
  // "not yet developed". A second source of truth could disagree with the grade.
109
- assert.doesNotMatch(sql, /developed/i, 'no separate developed column/flag');
110
- assert.doesNotMatch(sql, /promoted_to_task_id\s*IS\s*NULL/i, 'exit is the grade flip, not a promote link');
109
+ //
110
+ // The invariant is about the PREDICATE, so only the predicate is asserted.
111
+ // R146 later added developed_by/developed_at to the SELECT list (attribution
112
+ // rides along on every idea read) — that is not a filter and must not trip this.
113
+ const predicate = sql.slice(sql.search(/\bWHERE\b/i));
114
+ assert.doesNotMatch(predicate, /developed/i, 'nothing in the WHERE keys off a developed flag');
115
+ assert.doesNotMatch(predicate, /promoted_to_task_id\s*IS\s*NULL/i, 'exit is the grade flip, not a promote link');
116
+ // And the positive half, so the two tasks' expectations are explicit rather
117
+ // than merely non-conflicting: the attribution IS returned.
118
+ assert.match(sql, /g\.developed_by/, 'who developed it rides along on the read (R146)');
111
119
  });
112
120
 
113
121
  await test('newest first, with a stable tiebreak', async () => {