@unson/brainbase-mcp 0.50.13 → 0.50.14

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.
@@ -135,31 +135,47 @@ export function changesSince(lastVisit, businesses, judgmentsByBusiness, rows) {
135
135
  }
136
136
 
137
137
  /**
138
- * The lots inside a district (story-world-work-sites-and-gaps-v1, AC-12, AC-16, AC-17): a main street along
139
- * z, a back street on each side, and lots facing them in four columns. Work with the same `purpose_label`
140
- * stands in one block (a street of its own); blocks run from the hall toward the gate in the order of their
141
- * oldest task, and work with no label stands last, by the gate. Inside a block the lots fill in order of
142
- * creation (`created_at`, then id), row by row: left front, right front, left back, right back. So a new
143
- * task never moves an older one and a change of state never moves any; only when a block's rows are full do
144
- * the blocks after it shift one row toward the gate. A cross street separates the blocks.
145
- * Returns `{ lots: { [taskId]: { x, z, facing, street } }, streets: [{ key, label, count, z_from, z_to }],
146
- * rows, length }`, `facing` being +1 when the lot's front looks toward +x, `label` null for the unlabelled.
138
+ * Which lot a task's site stands on, in a district that grows in rings round its hall
139
+ * (story-world-district-rings-v1). The hall and its plaza are the centre. Work stated to be for the same
140
+ * thing (`purpose_label`, from the Task record) is one gathering and takes one sector of the circle; the
141
+ * sectors run clockwise from the gate's avenue in the order of their oldest task, and work with no label
142
+ * takes the last one, by the gate. Inside a sector the lots fill ring by ring, from the plaza outward, in
143
+ * order of creation (`created_at`, then id): more work makes the town one ring wider, never one street
144
+ * longer.
145
+ *
146
+ * A sector's width follows a coarse step of its count (`districtStreetWeight`), so the town stays round
147
+ * when one gathering is much larger than the others. A new task in a gathering, or a change of state,
148
+ * therefore never moves an older site; the sectors are re-divided only when a gathering begins or ends, or
149
+ * crosses a step.
150
+ *
151
+ * Returns `{ lots: { [taskId]: { x, z, yaw, street, ring } }, streets: [{ key, label, count, from, to,
152
+ * sign: { x, z }, name: { x, z }, box: { minX, maxX, minZ, maxZ } }], roads: [radius…], plaza, radius,
153
+ * open: [{ x, z, ring }] }`. `open` are the places left on the rings the town already reaches. Angles are
154
+ * measured clockwise from the gate's avenue (+z); `yaw` turns a lot's front to its ring road; `label` is
155
+ * null for the unlabelled; `radius` is how far the built town reaches.
147
156
  */
148
- export const DISTRICT_STREETS = Object.freeze({ main: 2, frontLot: 4, backStreet: 7, backLot: 10, lot: 2.8, row: 3.4, cross: 2.6 });
149
-
150
- const LOT_COLUMNS = Object.freeze([
151
- { x: -DISTRICT_STREETS.frontLot, facing: 1 },
152
- { x: DISTRICT_STREETS.frontLot, facing: -1 },
153
- { x: -DISTRICT_STREETS.backLot, facing: 1 },
154
- { x: DISTRICT_STREETS.backLot, facing: -1 },
155
- ]);
157
+ export const DISTRICT_STREETS = Object.freeze({ main: 2, lot: 2.8, pitch: 3.3, road: 1.6, spoke: 1.4, plaza: 7.5, setback: 2.5, band: 8.2 });
156
158
 
157
159
  function byCreation(a, b) {
158
160
  const at = String(a.created_at ?? '').localeCompare(String(b.created_at ?? ''));
159
161
  return at !== 0 ? at : String(a.task_id).localeCompare(String(b.task_id));
160
162
  }
161
163
 
162
- export function districtStreetLots(sites, { minRows = 4 } = {}) {
164
+ /** How many shares of the circle a gathering of `count` tasks takes: 1 up to 4, 2 up to 16, 3 up to 36… */
165
+ export function districtStreetWeight(count) {
166
+ return Math.max(1, Math.ceil(Math.sqrt(Math.max(count, 0) / 4)));
167
+ }
168
+
169
+ /** The radius of the `ring`th ring of lots (0 is the one facing the plaza's road), given the first road. */
170
+ function lotRing(ring, firstRoad) {
171
+ if (ring === 0) return { radius: firstRoad + DISTRICT_STREETS.setback, road: 0, inward: true };
172
+ const road = Math.ceil(ring / 2);
173
+ const inward = ring % 2 === 0;
174
+ return { radius: firstRoad + road * DISTRICT_STREETS.band + (inward ? 1 : -1) * DISTRICT_STREETS.setback, road, inward };
175
+ }
176
+
177
+ export function districtRingLots(sites) {
178
+ const S = DISTRICT_STREETS;
163
179
  const groups = new Map();
164
180
  for (const site of sites ?? []) {
165
181
  const label = typeof site.purpose_label === 'string' && site.purpose_label.trim() ? site.purpose_label.trim() : null;
@@ -173,43 +189,88 @@ export function districtStreetLots(sites, { minRows = 4 } = {}) {
173
189
  const first = byCreation(a.sites[0], b.sites[0]);
174
190
  return first !== 0 ? first : a.key.localeCompare(b.key);
175
191
  });
176
- const rowsOf = (block) => Math.max(1, Math.ceil(block.sites.length / LOT_COLUMNS.length));
177
- const rows = blocks.reduce((sum, block) => sum + rowsOf(block), 0);
178
- const used = rows * DISTRICT_STREETS.row + Math.max(0, blocks.length - 1) * DISTRICT_STREETS.cross;
179
- const length = Math.max(used, minRows * DISTRICT_STREETS.row);
180
192
  const round = (value) => Math.round(value * 100) / 100;
193
+ // Shares are counted against the smallest gathering, so a town of equally large ones has no wider plaza.
194
+ const steps = blocks.map((block) => districtStreetWeight(block.sites.length));
195
+ const smallest = Math.min(...steps, Infinity);
196
+ const weights = steps.map((step) => step / smallest);
197
+ const units = weights.reduce((sum, weight) => sum + weight, 0);
198
+ // Kept clear on each side of a sector: half a lane between sectors. The gate's avenue takes its own
199
+ // slice of the circle first, and the sectors share the rest.
200
+ const lane = S.spoke / 2 + 0.2;
201
+ const avenue = S.main + 0.8;
202
+ // The first ring holds at least one lot for each share, so a town of many gatherings has a wider plaza.
203
+ const around = units * (S.pitch + lane * 2) + avenue * 2;
204
+ const plaza = round(Math.max(S.plaza, around / (Math.PI * 2) - S.road / 2 - 0.1 - S.setback));
205
+ const firstRoad = plaza + S.road / 2 + 0.1;
206
+ const gap = avenue / (firstRoad + S.setback);
207
+ const share = (Math.PI * 2 - gap * 2) / Math.max(units, 1);
181
208
  const lots = {};
182
209
  const streets = [];
183
- let cursor = -used / 2;
184
- for (const block of blocks) {
185
- const blockRows = rowsOf(block);
186
- block.sites.forEach((site, index) => {
187
- const row = Math.floor(index / LOT_COLUMNS.length);
188
- const column = LOT_COLUMNS[index % LOT_COLUMNS.length];
189
- lots[site.task_id] = { x: column.x, z: round(cursor + (row + 0.5) * DISTRICT_STREETS.row), facing: column.facing, street: block.key };
190
- });
191
- streets.push({ key: block.key, label: block.label, count: block.sites.length, z_from: round(cursor), z_to: round(cursor + blockRows * DISTRICT_STREETS.row) });
192
- cursor += blockRows * DISTRICT_STREETS.row + DISTRICT_STREETS.cross;
193
- }
194
- return { lots, streets, rows, length };
210
+ const open = [];
211
+ let cursor = gap;
212
+ let lastRing = 0;
213
+ blocks.forEach((block, index) => {
214
+ const from = cursor;
215
+ const to = cursor + share * weights[index];
216
+ cursor = to;
217
+ const box = { minX: Infinity, maxX: -Infinity, minZ: Infinity, maxZ: -Infinity };
218
+ let placed = 0;
219
+ let reach = 0;
220
+ const spare = [];
221
+ for (let ring = 0; placed < block.sites.length && ring < 400; ring += 1) {
222
+ const { radius, inward } = lotRing(ring, firstRoad);
223
+ const usable = (to - from) * radius - lane * 2;
224
+ const slots = Math.floor(usable / S.pitch);
225
+ if (slots < 1) continue;
226
+ // Slots are fixed places on the ring; they fill from the middle of the sector outward.
227
+ const order = Array.from({ length: slots }, (_, slot) => slot).sort((a, b) => Math.abs(a - (slots - 1) / 2) - Math.abs(b - (slots - 1) / 2) || a - b);
228
+ for (const slot of order) {
229
+ const angle = from + (lane + (usable - slots * S.pitch) / 2 + (slot + 0.5) * S.pitch) / radius;
230
+ const x = round(Math.sin(angle) * radius);
231
+ const z = round(Math.cos(angle) * radius);
232
+ if (placed >= block.sites.length) {
233
+ spare.push({ x, z, ring });
234
+ continue;
235
+ }
236
+ lots[block.sites[placed].task_id] = { x, z, yaw: Math.round((inward ? angle + Math.PI : angle) * 10000) / 10000, street: block.key, ring };
237
+ box.minX = Math.min(box.minX, x); box.maxX = Math.max(box.maxX, x); box.minZ = Math.min(box.minZ, z); box.maxZ = Math.max(box.maxZ, z);
238
+ placed += 1;
239
+ reach = radius;
240
+ lastRing = Math.max(lastRing, ring);
241
+ }
242
+ }
243
+ open.push(...spare);
244
+ // The sign stands on the plaza's rim, in front of its sector.
245
+ const middle = (from + to) / 2;
246
+ const sign = { x: round(Math.sin(middle) * (plaza - 0.7)), z: round(Math.cos(middle) * (plaza - 0.7)) };
247
+ // Its name floats over the middle of its lots.
248
+ const heart = (firstRoad + S.setback + reach) / 2;
249
+ const name = { x: round(Math.sin(middle) * heart), z: round(Math.cos(middle) * heart) };
250
+ streets.push({ key: block.key, label: block.label, count: block.sites.length, name, from: Math.round(from * 10000) / 10000, to: Math.round(to * 10000) / 10000, sign, box });
251
+ });
252
+ const outer = lotRing(lastRing, firstRoad);
253
+ const roads = Array.from({ length: outer.road + 1 }, (_, road) => round(firstRoad + road * S.band));
254
+ const radius = round(Math.max(outer.radius + S.lot / 2, roads[roads.length - 1] + S.road / 2) + 0.8);
255
+ return { lots, streets, roads, plaza, radius, open };
195
256
  }
196
257
 
197
258
  /**
198
- * Where the gate, the plaza and the hall stand around the blocks of a district (`length` from
199
- * `districtStreetLots`). The main street runs from beyond the gate to the plaza's edge and never into
200
- * it, and the plaza stays clear of the first row of lots.
259
+ * Where the hall, its forecourt and the gate stand in a district laid out by `districtRingLots`. The hall
260
+ * is the centre of the plaza; the avenue runs from beyond the gate to the plaza's rim and never into it.
201
261
  */
202
- export function districtGroundPlan(length) {
203
- const plazaRadius = 3.85;
204
- const plazaZ = -length / 2 - 1.5 - plazaRadius;
262
+ export function districtRingPlan(layout) {
205
263
  return {
206
- gateZ: length / 2 + 4,
207
- plazaZ,
208
- plazaRadius,
209
- hallZ: plazaZ - 5.4,
210
- street: { from: plazaZ + plazaRadius, to: length / 2 + 12 },
264
+ plazaRadius: layout.plaza,
265
+ hallZ: -1.6,
266
+ courtZ: 3.4,
267
+ gateZ: round2(layout.radius + 3.5),
268
+ street: { from: layout.plaza, to: round2(layout.radius + 11.5) },
211
269
  };
212
270
  }
271
+ function round2(value) {
272
+ return Math.round(value * 100) / 100;
273
+ }
213
274
 
214
275
  /*
215
276
  * The town grows (story-world-work-sites-and-gaps-v1, AC-22〜24). It grows only from evidenced outcomes
@@ -326,3 +387,159 @@ export function districtTaskActors(site, now = Date.now()) {
326
387
  return { ...actor, moving: site.work.status === 'in_progress' && actor.activity?.moving === true && actor.activity?.state === 'running' && Number.isFinite(age) && age >= 0 && age <= 300000 };
327
388
  });
328
389
  }
390
+
391
+ /*
392
+ * The pulse of the work (story-world-three-scales-v1): what each scale of the world says about how the
393
+ * work is going. The world says which businesses have work in progress; a district says how far each
394
+ * gathering of work (a street) has come and who is on it; a street says which agent is on which work and
395
+ * how. All of it is counted from the same records the lots are drawn from. "動いている" is said of an
396
+ * agent only on the evidence `districtTaskActors` asks for (an in-progress Task and a runtime heartbeat
397
+ * confirmed within five minutes); a count of in-progress Tasks stays "進行中", the record's own word.
398
+ */
399
+
400
+ /** Soft colours an agent keeps wherever it appears (its figure in the street and its mark in the panel). */
401
+ export const ACTOR_TONES = Object.freeze(['#e8927c', '#6fa8dc', '#8fbf7f', '#b39ddb', '#e6b655', '#5fb8b0']);
402
+
403
+ export function actorTone(id) {
404
+ let h = 2166136261;
405
+ for (const char of String(id ?? '')) {
406
+ h ^= char.codePointAt(0);
407
+ h = Math.imul(h, 16777619);
408
+ }
409
+ return ACTOR_TONES[(h >>> 0) % ACTOR_TONES.length];
410
+ }
411
+
412
+ export const ACTOR_PRESENCE = Object.freeze({
413
+ running: Object.freeze({ key: 'running', label: '動いている', rank: 0 }),
414
+ quiet: Object.freeze({ key: 'quiet', label: '知らせが途絶えている', rank: 1 }),
415
+ waiting: Object.freeze({ key: 'waiting', label: '待っている', rank: 2 }),
416
+ unconfirmed: Object.freeze({ key: 'unconfirmed', label: '稼働は未確認', rank: 3 }),
417
+ queued: Object.freeze({ key: 'queued', label: 'これから', rank: 4 }),
418
+ done: Object.freeze({ key: 'done', label: '終えた', rank: 5 }),
419
+ });
420
+
421
+ const STALE_HEARTBEAT_MS = 300000;
422
+
423
+ /** What the street a work stands on is called: its purpose, or '' for the unlabelled lots by the gate. */
424
+ export function streetKeyOf(site) {
425
+ return typeof site?.purpose_label === 'string' && site.purpose_label.trim() ? site.purpose_label.trim() : '';
426
+ }
427
+
428
+ /**
429
+ * The agents on a work, each with how it is there now. Only actors the host confirmed for this Task in
430
+ * its recorded state are returned (see `districtTaskActors`).
431
+ */
432
+ export function siteActors(site, now = Date.now()) {
433
+ return districtTaskActors(site, now).map((actor) => {
434
+ const status = site.work?.status ?? null;
435
+ const at = Date.parse(actor.activity?.heartbeat_at ?? '');
436
+ const age = Number.isFinite(at) ? now - at : Number.NaN;
437
+ let presence = ACTOR_PRESENCE.unconfirmed;
438
+ if (status === 'completed') presence = ACTOR_PRESENCE.done;
439
+ else if (status === 'waiting') presence = ACTOR_PRESENCE.waiting;
440
+ else if (status === 'pending') presence = ACTOR_PRESENCE.queued;
441
+ else if (status === 'in_progress') presence = actor.moving ? ACTOR_PRESENCE.running : Number.isFinite(age) && age > STALE_HEARTBEAT_MS ? ACTOR_PRESENCE.quiet : ACTOR_PRESENCE.unconfirmed;
442
+ return {
443
+ id: actor.id,
444
+ name: actor.name,
445
+ kind: actor.kind ?? null,
446
+ tone: actorTone(actor.id),
447
+ task_id: site.task_id,
448
+ presence: presence.key,
449
+ label: presence.label,
450
+ heartbeat_at: Number.isFinite(at) ? actor.activity.heartbeat_at : null,
451
+ /** Whole minutes since the last confirmed heartbeat; null when there is none to count from. */
452
+ minutes: Number.isFinite(age) && age >= 0 ? Math.floor(age / 60000) : null,
453
+ waiting_on: status === 'waiting' ? site.work?.waiting_on ?? null : null,
454
+ };
455
+ });
456
+ }
457
+
458
+ const emptyCounts = () => ({ total: 0, done: 0, in_progress: 0, waiting: 0, pending: 0 });
459
+ function countSite(counts, site) {
460
+ counts.total += 1;
461
+ const status = site.work?.status;
462
+ if (status === 'completed') counts.done += 1;
463
+ else if (status === 'in_progress') counts.in_progress += 1;
464
+ else if (status === 'waiting') counts.waiting += 1;
465
+ else counts.pending += 1;
466
+ }
467
+
468
+ function gatherActors(entries) {
469
+ const byId = new Map();
470
+ for (const { site, actor } of entries) {
471
+ if (!byId.has(actor.id)) byId.set(actor.id, { id: actor.id, name: actor.name, kind: actor.kind, tone: actor.tone, presence: actor.presence, label: actor.label, works: [] });
472
+ const entry = byId.get(actor.id);
473
+ entry.works.push({ task_id: site.task_id, title: site.title, street: streetKeyOf(site), presence: actor.presence, label: actor.label, minutes: actor.minutes, waiting_on: actor.waiting_on });
474
+ if (ACTOR_PRESENCE[actor.presence].rank < ACTOR_PRESENCE[entry.presence].rank) {
475
+ entry.presence = actor.presence;
476
+ entry.label = actor.label;
477
+ }
478
+ }
479
+ const actors = [...byId.values()];
480
+ for (const actor of actors) actor.works.sort((a, b) => ACTOR_PRESENCE[a.presence].rank - ACTOR_PRESENCE[b.presence].rank || a.title.localeCompare(b.title, 'ja'));
481
+ return actors.sort((a, b) => ACTOR_PRESENCE[a.presence].rank - ACTOR_PRESENCE[b.presence].rank || a.name.localeCompare(b.name, 'ja'));
482
+ }
483
+
484
+ /**
485
+ * How a district's work is going: its counts by recorded state, its agents with where each is, and the
486
+ * same for each street in the order the streets stand (`districtRingLots`). Cancelled work is left
487
+ * out, as it is from the streets. `actors_unconfirmed` counts work whose agents the host could not
488
+ * confirm: for those, no agent is not "nobody".
489
+ */
490
+ export function districtPulse(sites, now = Date.now()) {
491
+ const live = (Array.isArray(sites) ? sites : []).filter((site) => site?.work?.status !== 'cancelled');
492
+ const counts = emptyCounts();
493
+ const entries = [];
494
+ const streets = new Map();
495
+ const order = districtRingLots(live.map((site) => ({ task_id: site.task_id, created_at: site.work?.created_at, purpose_label: site.purpose_label }))).streets;
496
+ for (const street of order) streets.set(street.key, { key: street.key, label: street.label, counts: emptyCounts(), task_ids: [], entries: [], actors_unconfirmed: 0 });
497
+ let unconfirmed = 0;
498
+ for (const site of live) {
499
+ countSite(counts, site);
500
+ const street = streets.get(streetKeyOf(site));
501
+ countSite(street.counts, site);
502
+ street.task_ids.push(site.task_id);
503
+ if (site.actors_state === 'unconfirmed') {
504
+ unconfirmed += 1;
505
+ street.actors_unconfirmed += 1;
506
+ }
507
+ for (const actor of siteActors(site, now)) {
508
+ entries.push({ site, actor });
509
+ street.entries.push({ site, actor });
510
+ }
511
+ }
512
+ const running = (list) => list.filter((actor) => actor.presence === 'running').length;
513
+ const actors = gatherActors(entries);
514
+ return {
515
+ counts,
516
+ actors,
517
+ running: running(actors),
518
+ actors_unconfirmed: unconfirmed,
519
+ streets: [...streets.values()].map(({ entries: own, ...street }) => {
520
+ const streetActors = gatherActors(own);
521
+ return { ...street, actors: streetActors, running: running(streetActors) };
522
+ }),
523
+ };
524
+ }
525
+
526
+ /**
527
+ * How a business's work stands as the world's summary records it (`by_status`), or null when the summary
528
+ * was not read: unread work is never shown as none.
529
+ */
530
+ export function cityPulse(summary) {
531
+ if (!summary || (summary.state !== 'complete' && summary.state !== 'partial') || !summary.by_status || typeof summary.by_status !== 'object') return null;
532
+ const count = (key) => (Number.isInteger(summary.by_status[key]) && summary.by_status[key] > 0 ? summary.by_status[key] : 0);
533
+ return { in_progress: count('in_progress'), waiting: count('waiting'), pending: count('pending'), done: count('completed'), partial: summary.state === 'partial' };
534
+ }
535
+
536
+ /**
537
+ * The businesses of the world with their pulse, the ones with the most work in progress first (then the
538
+ * most waiting, then by name). The order is a way to find where things move; it is not a score.
539
+ */
540
+ export function worldPulse(businesses, summaries) {
541
+ const rows = (Array.isArray(businesses) ? businesses : []).map((business) => ({ code: business.code, name: business.name, pulse: cityPulse(summaries?.[business.code]) }));
542
+ rows.sort((a, b) => (b.pulse?.in_progress ?? -1) - (a.pulse?.in_progress ?? -1) || (b.pulse?.waiting ?? -1) - (a.pulse?.waiting ?? -1) || String(a.name).localeCompare(String(b.name), 'ja'));
543
+ const read = rows.filter((row) => row.pulse);
544
+ return { rows, read: read.length, active: read.filter((row) => row.pulse.in_progress > 0).length };
545
+ }