@unson/brainbase-mcp 0.50.13 → 0.50.16

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,30 +135,157 @@ 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
 
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;
179
+ const groups = new Map();
180
+ for (const site of sites ?? []) {
181
+ const label = typeof site.purpose_label === 'string' && site.purpose_label.trim() ? site.purpose_label.trim() : null;
182
+ const key = label ?? '';
183
+ if (!groups.has(key)) groups.set(key, { key, label, sites: [] });
184
+ groups.get(key).sites.push(site);
185
+ }
186
+ const blocks = [...groups.values()].map((group) => ({ ...group, sites: group.sites.sort(byCreation) }));
187
+ blocks.sort((a, b) => {
188
+ if ((a.label === null) !== (b.label === null)) return a.label === null ? 1 : -1;
189
+ const first = byCreation(a.sites[0], b.sites[0]);
190
+ return first !== 0 ? first : a.key.localeCompare(b.key);
191
+ });
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);
208
+ const lots = {};
209
+ const streets = [];
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 };
256
+ }
257
+
258
+ /**
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.
261
+ */
262
+ export function districtRingPlan(layout) {
263
+ return {
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) },
269
+ };
270
+ }
271
+ function round2(value) {
272
+ return Math.round(value * 100) / 100;
273
+ }
274
+
275
+ /*
276
+ * The straight-street layout of 0.50.13 and earlier, kept only so that a hosting page which still holds
277
+ * an older world module can import these names from this file during a deploy. Nothing in this package
278
+ * calls them; remove them once every host checks exports per screen rather than per file.
279
+ */
280
+ const LEGACY_STREETS = Object.freeze({ frontLot: 4, backLot: 10, row: 3.4, cross: 2.6 });
281
+ const LEGACY_LOT_COLUMNS = Object.freeze([
282
+ { x: -LEGACY_STREETS.frontLot, facing: 1 },
283
+ { x: LEGACY_STREETS.frontLot, facing: -1 },
284
+ { x: -LEGACY_STREETS.backLot, facing: 1 },
285
+ { x: LEGACY_STREETS.backLot, facing: -1 },
286
+ ]);
287
+
288
+ /** @deprecated since 0.50.14; districts are laid out by `districtRingLots`. */
162
289
  export function districtStreetLots(sites, { minRows = 4 } = {}) {
163
290
  const groups = new Map();
164
291
  for (const site of sites ?? []) {
@@ -173,32 +300,27 @@ export function districtStreetLots(sites, { minRows = 4 } = {}) {
173
300
  const first = byCreation(a.sites[0], b.sites[0]);
174
301
  return first !== 0 ? first : a.key.localeCompare(b.key);
175
302
  });
176
- const rowsOf = (block) => Math.max(1, Math.ceil(block.sites.length / LOT_COLUMNS.length));
303
+ const rowsOf = (block) => Math.max(1, Math.ceil(block.sites.length / LEGACY_LOT_COLUMNS.length));
177
304
  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
- const round = (value) => Math.round(value * 100) / 100;
305
+ const used = rows * LEGACY_STREETS.row + Math.max(0, blocks.length - 1) * LEGACY_STREETS.cross;
306
+ const length = Math.max(used, minRows * LEGACY_STREETS.row);
181
307
  const lots = {};
182
308
  const streets = [];
183
309
  let cursor = -used / 2;
184
310
  for (const block of blocks) {
185
311
  const blockRows = rowsOf(block);
186
312
  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 };
313
+ const row = Math.floor(index / LEGACY_LOT_COLUMNS.length);
314
+ const column = LEGACY_LOT_COLUMNS[index % LEGACY_LOT_COLUMNS.length];
315
+ lots[site.task_id] = { x: column.x, z: round2(cursor + (row + 0.5) * LEGACY_STREETS.row), facing: column.facing, street: block.key };
190
316
  });
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;
317
+ streets.push({ key: block.key, label: block.label, count: block.sites.length, z_from: round2(cursor), z_to: round2(cursor + blockRows * LEGACY_STREETS.row) });
318
+ cursor += blockRows * LEGACY_STREETS.row + LEGACY_STREETS.cross;
193
319
  }
194
320
  return { lots, streets, rows, length };
195
321
  }
196
322
 
197
- /**
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.
201
- */
323
+ /** @deprecated since 0.50.14; districts are laid out by `districtRingPlan`. */
202
324
  export function districtGroundPlan(length) {
203
325
  const plazaRadius = 3.85;
204
326
  const plazaZ = -length / 2 - 1.5 - plazaRadius;
@@ -326,3 +448,159 @@ export function districtTaskActors(site, now = Date.now()) {
326
448
  return { ...actor, moving: site.work.status === 'in_progress' && actor.activity?.moving === true && actor.activity?.state === 'running' && Number.isFinite(age) && age >= 0 && age <= 300000 };
327
449
  });
328
450
  }
451
+
452
+ /*
453
+ * The pulse of the work (story-world-three-scales-v1): what each scale of the world says about how the
454
+ * work is going. The world says which businesses have work in progress; a district says how far each
455
+ * gathering of work (a street) has come and who is on it; a street says which agent is on which work and
456
+ * how. All of it is counted from the same records the lots are drawn from. "動いている" is said of an
457
+ * agent only on the evidence `districtTaskActors` asks for (an in-progress Task and a runtime heartbeat
458
+ * confirmed within five minutes); a count of in-progress Tasks stays "進行中", the record's own word.
459
+ */
460
+
461
+ /** Soft colours an agent keeps wherever it appears (its figure in the street and its mark in the panel). */
462
+ export const ACTOR_TONES = Object.freeze(['#e8927c', '#6fa8dc', '#8fbf7f', '#b39ddb', '#e6b655', '#5fb8b0']);
463
+
464
+ export function actorTone(id) {
465
+ let h = 2166136261;
466
+ for (const char of String(id ?? '')) {
467
+ h ^= char.codePointAt(0);
468
+ h = Math.imul(h, 16777619);
469
+ }
470
+ return ACTOR_TONES[(h >>> 0) % ACTOR_TONES.length];
471
+ }
472
+
473
+ export const ACTOR_PRESENCE = Object.freeze({
474
+ running: Object.freeze({ key: 'running', label: '動いている', rank: 0 }),
475
+ quiet: Object.freeze({ key: 'quiet', label: '知らせが途絶えている', rank: 1 }),
476
+ waiting: Object.freeze({ key: 'waiting', label: '待っている', rank: 2 }),
477
+ unconfirmed: Object.freeze({ key: 'unconfirmed', label: '稼働は未確認', rank: 3 }),
478
+ queued: Object.freeze({ key: 'queued', label: 'これから', rank: 4 }),
479
+ done: Object.freeze({ key: 'done', label: '終えた', rank: 5 }),
480
+ });
481
+
482
+ const STALE_HEARTBEAT_MS = 300000;
483
+
484
+ /** What the street a work stands on is called: its purpose, or '' for the unlabelled lots by the gate. */
485
+ export function streetKeyOf(site) {
486
+ return typeof site?.purpose_label === 'string' && site.purpose_label.trim() ? site.purpose_label.trim() : '';
487
+ }
488
+
489
+ /**
490
+ * The agents on a work, each with how it is there now. Only actors the host confirmed for this Task in
491
+ * its recorded state are returned (see `districtTaskActors`).
492
+ */
493
+ export function siteActors(site, now = Date.now()) {
494
+ return districtTaskActors(site, now).map((actor) => {
495
+ const status = site.work?.status ?? null;
496
+ const at = Date.parse(actor.activity?.heartbeat_at ?? '');
497
+ const age = Number.isFinite(at) ? now - at : Number.NaN;
498
+ let presence = ACTOR_PRESENCE.unconfirmed;
499
+ if (status === 'completed') presence = ACTOR_PRESENCE.done;
500
+ else if (status === 'waiting') presence = ACTOR_PRESENCE.waiting;
501
+ else if (status === 'pending') presence = ACTOR_PRESENCE.queued;
502
+ else if (status === 'in_progress') presence = actor.moving ? ACTOR_PRESENCE.running : Number.isFinite(age) && age > STALE_HEARTBEAT_MS ? ACTOR_PRESENCE.quiet : ACTOR_PRESENCE.unconfirmed;
503
+ return {
504
+ id: actor.id,
505
+ name: actor.name,
506
+ kind: actor.kind ?? null,
507
+ tone: actorTone(actor.id),
508
+ task_id: site.task_id,
509
+ presence: presence.key,
510
+ label: presence.label,
511
+ heartbeat_at: Number.isFinite(at) ? actor.activity.heartbeat_at : null,
512
+ /** Whole minutes since the last confirmed heartbeat; null when there is none to count from. */
513
+ minutes: Number.isFinite(age) && age >= 0 ? Math.floor(age / 60000) : null,
514
+ waiting_on: status === 'waiting' ? site.work?.waiting_on ?? null : null,
515
+ };
516
+ });
517
+ }
518
+
519
+ const emptyCounts = () => ({ total: 0, done: 0, in_progress: 0, waiting: 0, pending: 0 });
520
+ function countSite(counts, site) {
521
+ counts.total += 1;
522
+ const status = site.work?.status;
523
+ if (status === 'completed') counts.done += 1;
524
+ else if (status === 'in_progress') counts.in_progress += 1;
525
+ else if (status === 'waiting') counts.waiting += 1;
526
+ else counts.pending += 1;
527
+ }
528
+
529
+ function gatherActors(entries) {
530
+ const byId = new Map();
531
+ for (const { site, actor } of entries) {
532
+ 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: [] });
533
+ const entry = byId.get(actor.id);
534
+ 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 });
535
+ if (ACTOR_PRESENCE[actor.presence].rank < ACTOR_PRESENCE[entry.presence].rank) {
536
+ entry.presence = actor.presence;
537
+ entry.label = actor.label;
538
+ }
539
+ }
540
+ const actors = [...byId.values()];
541
+ 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'));
542
+ return actors.sort((a, b) => ACTOR_PRESENCE[a.presence].rank - ACTOR_PRESENCE[b.presence].rank || a.name.localeCompare(b.name, 'ja'));
543
+ }
544
+
545
+ /**
546
+ * How a district's work is going: its counts by recorded state, its agents with where each is, and the
547
+ * same for each street in the order the streets stand (`districtRingLots`). Cancelled work is left
548
+ * out, as it is from the streets. `actors_unconfirmed` counts work whose agents the host could not
549
+ * confirm: for those, no agent is not "nobody".
550
+ */
551
+ export function districtPulse(sites, now = Date.now()) {
552
+ const live = (Array.isArray(sites) ? sites : []).filter((site) => site?.work?.status !== 'cancelled');
553
+ const counts = emptyCounts();
554
+ const entries = [];
555
+ const streets = new Map();
556
+ const order = districtRingLots(live.map((site) => ({ task_id: site.task_id, created_at: site.work?.created_at, purpose_label: site.purpose_label }))).streets;
557
+ for (const street of order) streets.set(street.key, { key: street.key, label: street.label, counts: emptyCounts(), task_ids: [], entries: [], actors_unconfirmed: 0 });
558
+ let unconfirmed = 0;
559
+ for (const site of live) {
560
+ countSite(counts, site);
561
+ const street = streets.get(streetKeyOf(site));
562
+ countSite(street.counts, site);
563
+ street.task_ids.push(site.task_id);
564
+ if (site.actors_state === 'unconfirmed') {
565
+ unconfirmed += 1;
566
+ street.actors_unconfirmed += 1;
567
+ }
568
+ for (const actor of siteActors(site, now)) {
569
+ entries.push({ site, actor });
570
+ street.entries.push({ site, actor });
571
+ }
572
+ }
573
+ const running = (list) => list.filter((actor) => actor.presence === 'running').length;
574
+ const actors = gatherActors(entries);
575
+ return {
576
+ counts,
577
+ actors,
578
+ running: running(actors),
579
+ actors_unconfirmed: unconfirmed,
580
+ streets: [...streets.values()].map(({ entries: own, ...street }) => {
581
+ const streetActors = gatherActors(own);
582
+ return { ...street, actors: streetActors, running: running(streetActors) };
583
+ }),
584
+ };
585
+ }
586
+
587
+ /**
588
+ * How a business's work stands as the world's summary records it (`by_status`), or null when the summary
589
+ * was not read: unread work is never shown as none.
590
+ */
591
+ export function cityPulse(summary) {
592
+ if (!summary || (summary.state !== 'complete' && summary.state !== 'partial') || !summary.by_status || typeof summary.by_status !== 'object') return null;
593
+ const count = (key) => (Number.isInteger(summary.by_status[key]) && summary.by_status[key] > 0 ? summary.by_status[key] : 0);
594
+ return { in_progress: count('in_progress'), waiting: count('waiting'), pending: count('pending'), done: count('completed'), partial: summary.state === 'partial' };
595
+ }
596
+
597
+ /**
598
+ * The businesses of the world with their pulse, the ones with the most work in progress first (then the
599
+ * most waiting, then by name). The order is a way to find where things move; it is not a score.
600
+ */
601
+ export function worldPulse(businesses, summaries) {
602
+ const rows = (Array.isArray(businesses) ? businesses : []).map((business) => ({ code: business.code, name: business.name, pulse: cityPulse(summaries?.[business.code]) }));
603
+ 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'));
604
+ const read = rows.filter((row) => row.pulse);
605
+ return { rows, read: read.length, active: read.filter((row) => row.pulse.in_progress > 0).length };
606
+ }