1
0
Fork 0
Commit graph

268 commits

Author SHA1 Message Date
1db89addf5 feat(npc-dialogue): hold the typing with an authored pause, and stop squashing long lines
Two things, both about the pace of a line arriving.

An author can now put a beat anywhere in a line with {1.2s} or {400ms}, clamped
to ten seconds. The marker renders nothing; the renderer records where it sat and
the pacing schedule charges that gap between the units either side. Pauses are
absolute, so matching a line to a voice clip stretches or squeezes the typed part
and leaves the authored beat alone. The editor's line help names the marker.

The speed complaint had a mechanical cause. Lines were capped at three seconds,
so anything past about 120 characters was silently compressed: 240 characters ran
at 13ms per character and 360 at 8, against a base of 30. Long lines deeper in a
conversation read as if the typing had sped up. The cap is now twenty seconds,
which only catches a wall of text, and the base unit went from 24ms to 30ms
(about 33 characters a second) because 24 measured as a blur in the app.

The duration rule moved into pacing.ts as lineDurationMs so it is testable
without a browser. One nearby bug fell out of the marker work: when a brace run
turned out not to be markup, the renderer had already spent budget on the text
inside it and then rendered the run literally, so those characters were counted
twice. It now restores what the failed attempt consumed.

Measured in the running app: a {1.2s} marker held the line 1237ms after the fourth
character and never appeared on screen; a 360 character line took 12.5s instead of
3s; a short line still lands at once. 253 tests across 24 files pass.
2026-12-01 13:00:50 -05:00
bff6a7a908 feat(intelligence): render mission chain of command as an editable org chart
Replace the per-person supervisor list as the primary chain-of-command
surface on the mission page with a layered DAG rendered on React Flow.
Both views share one draft; connections stay editable until the first
evaluation or cancellation locks them.

- getChainViewerState: always returns state (viewer-aware), replacing
  getChainEditorState's null-for-viewers contract so plain viewers see
  the chain read-only
- auto-layout wraps wide layers instead of shrinking past readability
- tactical dossier styling for nodes and canvas chrome
2026-12-01 10:18:26 -05:00
0031fdaec8 test(ribbon): cover line geometry, orientation bands and caps
Eighteen specs for computeLineRects clamping/skip behavior, validation
rules, band layout direction, mirror semantics with horizontal bands,
and draw order of lines between stripes and the fabric overlay.
2026-12-01 09:29:14 -05:00
51ead07da0 fix(ai): drive the structured stream and use the chat endpoint
Dialogue drafting hung on "Drafting..." forever against OpenRouter, with the
provider having received and completed the request. Two independent faults, both
found by running the app's own code against the live endpoint.

The hang: streamObject is lazy. Awaiting result.object alone does not pump the
stream in this SDK version, so the promise waited for a parse that never started
and the call sat until its ten minute ceiling. One identical request, measured
twice: object-only never returned in 60s, draining textStream first returned a
valid draft in 6.9s. generateStructured now drains the stream before reading the
object.

The endpoint: provider(modelId) resolves to OpenAI's Responses API, which only
OpenAI implements. OpenRouter answered 200 and never completed. Every
OpenAI-compatible service the app targets serves /chat/completions, which the
plain path already used, so chatModelFor reaches the model through .chat(). The
instrumented request now goes to /chat/completions and Compose's structured
branch uses the same call.

Defences, since a provider can still answer and then go quiet: an idle watchdog
aborts a body that delivers no bytes for 60s on both paths, transport retries are
off so one stall is one wait, a draft is capped at four minutes, and the dialog
has a UI watchdog plus a catch that shows the failure instead of spinning.

Against the live endpoint the real function now returns a five node draft in
6.2s. 246 tests across 24 files pass, including a regression test that fails if
the stream drain is ever removed.
2026-12-01 01:47:49 -05:00
90037711e2 feat(npc-dialogue): hold a line until the player presses Continue
A conversation always advanced on its own once a line finished, so an author had
no way to let a line sit while the player reads it, or to pace a quiet moment.

Dialogue nodes now carry an optional requireContinue flag, off by default. The
line types and plays its clip as usual, then the footer offers a single Continue
button instead of moving on. Enter and Space resume it too.

waitsForContinue in dialogue.ts is the only place the rule lives: the flag must
be on and the node must have a successor, because a dead end would give the
player a button that does nothing. The runtime and the editor's draft preview
both call it, and the canvas card tags such a node continue.

The cascade parks on a promise rather than returning, so Continue resumes the
same walk and the next line still gets its beat between lines. close() and
begin() release a parked promise, so a conversation closed mid-gate cannot leave
a suspended walk behind; the existing token check makes the stale one return.

Also in this change, from the same request: the draft preview is centred
vertically instead of pinned to the top, and gains a Back button that pops a
trail of the cards walked through. The trail is separate from the visited set so
stepping back does not un-spend a once choice.

Verified with a three-line probe document: the gated first line was still alone
in the log after 3.7s with a Continue button showing, clicking it landed the
ungated second line and parked on the gated third, and Enter from there reached
the end node. In the editor, the panel measured 0px off centre and Back returned
to the previous card. 4 pure tests cover the rule; 212 tests pass across 19 files.
2026-11-30 18:04:02 -05:00
de765fe725 feat(npc-dialogue): play an unsaved draft in the editor
Authoring meant saving, leaving the admin, and finding the contact on the player
site to see whether a branch worked. A Play button in the canvas toolbar now
walks the draft exactly as it stands, without saving it.

The walker is not the runtime component: that resolves text and choices through
server actions keyed on a saved dialogue id, and teaching all four a draft mode
would be a much larger change. preview.ts answers what is local (choice order,
branch targets, effect descriptions) and the server answers the one thing it
cannot, flag values, through a new previewDialogueCondition action gated on
npc-dialogues:update. It calls the same evaluateCondition the player runtime
uses, so a preview cannot disagree with the outcome.

Effects are described, never applied. Choices the author's own flags would hide
are shown as hidden rather than silently dropped.

Verified on a temp document with an event effect and a condition node: the event
step showed 'Would set flag preview_probe_flag to true' with a dry-run note, the
condition answered false for a missing flag, the walk followed the false branch to
its END node, and player_flags gained no row (5 before, 5 after).

Bare admin buttons render with the UA's white background, so each one carries an
explicit background; 9 pure tests cover the walker's reading of the graph.
2026-11-24 20:41:19 -05:00
4dc82c0d5d feat(npc-dialogue): mark contacts whose conversation has unread content
The only unread signal was the NEW badge inside a conversation, so players had
no way to see who had something to say. The directory now carries that signal:
a cyan NEW chip on the card for any contact whose offered conversation has a node
this player has never read.

Unread is derived from the per-node read markers that already existed. Two gates
run first so the chip never lies: the contact must have canMessage true, and the
loader resolves the offered conversation with the same selectDialogueForUser gate
the contact page uses (testing conversations filtered by dialogueVisibleTo).

Cost is two queries for the whole directory rather than one per card. A branch
added after a player finished a conversation brings the chip back, which is the
point; a partially explored conversation stays marked until every branch is read.

Measured on the live directory: three contacts chipped (the two with canMessage
and unread flows, plus a seeded probe on a third), the probe's chip cleared after
all its nodes were read, and a canMessage:false contact never chipped.

Pure derivation covered by 6 tests.
2026-11-24 20:26:47 -05:00
b71e94b23d feat(npc-dialogue): announce lines to screen readers and pick choices by number
The conversation had no live region and no keyboard path, so a screen reader
user opened it and heard nothing while the only way to answer was to Tab through
buttons.

The log is now a polite live region with aria-busy while a line types. A polite
region would otherwise announce every mutation of the truncating text, so the
visible copy is hidden from assistive tech during a reveal and the whole line
sits once in an sr-only sibling that never changes.

Digits 1-9 take a choice, numbered over the selectable list so a locked option
does not consume a digit, with the number shown on the button and exposed as
aria-keyshortcuts. Enter or Space finishes the typing line or starts the next one
during the beat; Escape closes, from Radix.

Measured: sr-only copy present at full length while the visible copy read 'Hol',
removed once settled, aria-busy true then false; pressing 2 took 'Follow the
river'; Enter cut a 2587ms line to 382ms.
2026-11-24 20:17:04 -05:00
464ba2d5d4 feat(npc-dialogue): natural typing rhythm, a beat between lines, a typing sound
The reveal was one linear clock, so every character cost the same and a comma
had nowhere to breathe. It now runs off a schedule: each visible unit costs
BASE_UNIT_MS plus a pause after it, longer at a sentence end and longest at a
line or paragraph break. Pauses never stack (a break after a full stop owns the
pause) and a comma inside a number is not a clause. The schedule is built in
relative units and scaled to the target duration, so a line paced to a recorded
clip keeps the rhythm instead of flattening it.

Between two spoken lines there is now a beat with the speaker's typing dots, and
clicking during it starts the next line at once. The opening line of a cascade
gets no beat.

The typing sound is synthesized (one tick per 55ms at most) from precomputed,
seeded tick times, so a re-render cannot re-roll the rhythm. It stays silent on a
line with a recorded clip, when the header mute is on, and under reduced motion.
It follows a new account preference, users.preferences.dialogue.typewriterSound,
separate from the voice switch, with a migration.

visibleLength is now defined as visibleText(text).length, so the schedule and the
renderer cannot disagree about how long a line is.
2026-11-24 19:20:11 -05:00
1110315214 feat(npc-dialogue): testing-only conversations for superusers
An npc-dialogues document can be marked testing, which keeps it off the player
site while letting the superuser tier walk it live. Enforced in one module,
lib/npc-dialogue/visibility.ts: the offer skips the conversation, its new-message
badge never appears, and every node lookup re-checks visibility.

Those lookups now name their conversation. The client sends dialogue.id and the
server verifies it belongs to the NPC and is visible to the reader, so a player
cannot read a testing conversation's nodes by guessing an id. The old lookup
took limit: 1 on the NPC's conversations with no ordering, which with a testing
conversation present could read the wrong document and silently skip an effect.

Tester tier is system:admin-access, not every author: an officer who can edit
conversations still cannot reach a testing one on the player site. Only an
explicit true hides a conversation, so rows written before the flag stay live.
2026-11-24 18:29:20 -05:00
18ea696d1b feat(npc-dialogue): voice clips on dialogue lines
A line can now carry a recorded voice, played when it lands with the text
paced to the clip so speech and text finish together. Clips live in media and
flowData keeps only a pointer, so a deleted file goes quiet instead of
breaking the line; resolveVoiceClip turns it into a URL per read.

Authors get two sources in the node editor: a direct upload, and an accepted
voiceover take imported from the existing submission flow. Both convert to mono
MP3 through the voiceover transcoder, because browser recordings are WebM and
iOS will not always play them, and a failed transcode stores the original
rather than losing the take.

Players control it twice: users.preferences.dialogue.voice (default on) is the
durable choice, and the speaker button in the conversation header mutes for
that conversation. Autoplay is not guaranteed, so a rejected play() shows a
Play voice button on the line rather than failing silently.
2026-11-24 17:59:36 -05:00
66a4337ba5 feat(npc-dialogue): type conversation lines out, with unit and player control
Conversation lines appeared whole after a length-based pause with bouncing
dots. They now type themselves out, and the player can finish a line by
clicking it.

Control is two-tier: npc-dialogue-settings.presentation.typewriterDefault sets
the unit default, users.preferences.dialogue.typewriter (default/on/off) lets a
player override it either way. prefers-reduced-motion turns the animation off
regardless. Changing the unit setting does not bump the prompt revision, since
it is not prompt text.

The reveal truncates the rendered strings rather than the source, so a
half-typed line can never flash {amber} or an unclosed **. visibleLength()
gives pacing the same count, and the choice footer waits for the reveal to
land so nobody answers a line they have not seen.
2026-11-24 17:50:11 -05:00
04bbc66edc feat(npc-dialogue): add defined checks to flag conditions
is_true/is_false test truthiness, so a flag explicitly set to false reads
the same as a flag that was never recorded. is_defined/is_undefined test
existence instead, which lets a branch fire on "has this happened yet".

A pending-activation flag counts as defined (recorded, not yet in effect)
and an expired personal entry now falls through to the global entry, which
is what readFlag's contract already promised.

NUMERIC_CONDITION_OPS becomes the shared list of ops that take an amount, so
the editor, the entryGate field and conditionSummary agree. Adding to
CONDITION_OPS also alters enum_npc_dialogues_entry_gate_op, so the migration
is an ALTER TYPE ADD VALUE, applied to dev.
2026-11-24 17:34:40 -05:00
b2588f26bc docs(npc-dialogue): sync the contract with the start-node exception
Three one-line corrections after the last review, all in text this range
introduced:

- the AI Drafting tab no longer claims the preview is the literal prompt,
  which the shared footer now qualifies;
- the return table and the area guide record that a choice marked as the
  start gets no return, since nothing may point at the start;
- the fragment note names the start rule for a start choice instead of
  claiming the step had nothing after it. A start dialogue with no
  successor still reports the missing successor, which is the actionable
  reason there.
2026-11-24 15:05:19 -05:00
5ccb25e643 fix(ai): bound the structured path too, and stop the dialog overpromising
The timeout from the previous commit only covered the plain-text fetch, so
the default drafting path was still unbounded: `streamObject` for
json_schema had no abort signal, which is what `generateDialogueDraft` and
the probe's structured half use. A provider that answers the plain probe
and then stalls could still hold the Generate modal and the Test button
open, while the docs claimed every request was bounded. Both
`streamObject` calls (the shared structured path and Compose's fallback)
now carry the same ceiling.

Dialog copy told the author the branch continues into the successor even
after they cleared the return box, which is when it does not. It now says
that step becomes unreachable until wired by hand. When the node cannot
take a return at all the checkbox used to vanish without explanation; the
reason is now stated where the toggle would be.

A choice node marked as the start could receive the return hop, drawing an
edge into the start node that `connectHop` and the drop handler both
refuse. It no longer returns, and its open end stays free like the other
cases.

Also: the two misplaced doc comments now sit above the declarations they
describe, and the whole-conversation caveat moved into the shared preview
component so the global settings tab carries it too.
2026-11-24 15:00:30 -05:00
7adfcde72d fix(npc-dialogue): keep the conversation reachable when a branch attaches
Review findings, all in code this range introduced.

Attaching a branch to a node that already had a next step replaced that
hop, and "come back where it attached" pointed the branch back at the
caller, which loops: the caller then leads into the branch it just
returned from. Everything downstream was orphaned. The branch now
continues into the step that hop used to point at, so attaching inserts
in front of it instead of deleting it. Rejoining a condition is refused
outright, because re-entering re-evaluates the same flags and retakes the
same branch. Return candidates are limited to node types that read
`next`: a choice or condition open end would have received a hop no
walker follows.

The dialog says which of the three applies, and only offers the toggle
when a return exists, so an untouched default is not sent and reported
back as a refusal.

Condition true/false dots were drawn on the input handle: the hit-area
class sets left and right on the handle itself, which over-constrains
React Flow's `right: 0`, so both dots drifted to the card's left edge.
They now take the hit area as a child, like the other handles.

Refusals are honest: `connectHop` reports `changed: false` for a write it
did not make (it used to report true and return a new array), the editor
explains instead of rewriting an identical graph, and a refused
tail-drag keeps the original hop rather than deleting it first.

A passing connection test now really is invalidated when the
configuration changes. That ran in `afterChange`, whose return value is
only the operation's response, so the stored row kept showing a stale
pass while the test asserted the response. It moved to `beforeChange`,
counts only fields actually submitted (so the Test button's own result
write does not invalidate itself), and the test reads the row back.

Also: the fragment prompt no longer teaches `isStart: true` through the
worked example or asks for "the whole conversation" on retry; requests
carry a ten minute ceiling so an unreachable-but-accepting host cannot
hang Generate, Compose or the Test button; the API key description no
longer claims at-rest encryption, which does not exist; the per-dialogue
voice override gets the same dash and length cleaning as the global it
outranks; and the unused `describeAttachmentPoint` is gone, with the
attachment output now included in the hint the model receives.
2026-11-24 14:47:08 -05:00
375d04d644 feat(npc-dialogue): generate a branch instead of replacing the conversation
Generate could only hand back a whole graph, so using it inside a
conversation meant losing what was already there. It now offers three
placements, and the branch one is the default whenever a node is selected.

Select a node, press Generate, and the model writes the next beat as a
branch that is wired in from that node's output: a new choice button, a
condition's free branch, or the node's continuation. A "come back" toggle
points the branch's open end back at where it attached, which is what
turns a generated tangent into a side question that returns to the menu.
Empty canvas keeps the old behaviour: a whole conversation, no selector.

The splice lives in `fragmentInsert.ts`, pure and under test. It remaps
every id (a collision would silently repoint the author's hops), strips
any start flag, requires an open end so the branch can be continued, and
places the branch beside its attachment while nudging clear of individual
cards. Attaching under a choice node derives the new button's text from
the branch's first line, since a blank button fails validation; attaching
under an end node inserts the branch unwired and says why rather than
discarding it.

The prompt splits its structure contract by scope (full demands one start
node, fragment demands none and one open end) while FIELDS, STATE and
OUTPUT stay shared, so the schema contract cannot fork. PROMPT_VERSION is
bumped to npc-gen-v2.
2026-11-24 14:18:56 -05:00
ad63217e44 fix(npc-dialogue): make canvas wiring actually work
Three defects in the flow editor, all of which made it look like drag
and drop was simply broken:

- Reconnection was a silent no-op. React Flow enables it by default, so
  the drag drew a line and then threw the drop away with no handler: the
  edge snapped back. Reconnects now write the hop, and a drop over a node
  card (which arrives with no resolved connection) retargets, carrying
  the existing choice text, tooltip, once flag and gate instead of
  blanking the button.
- A refused drop said nothing. Dropping on the start node looked like the
  canvas had frozen; it now explains why nothing can point there.
- Handle dots were unmissable at 100% zoom and unusable zoomed out. A
  child element widens the press target, generously horizontally where
  the only neighbour is empty canvas and barely vertically because choice
  rows stack a few pixels apart when zoomed out.

Dropping a condition branch on the card filled true and false with the
same node, which made the condition pointless; it now takes the first
free branch.

Connection writing moved into `connectHop` in the lib so the rules are
unit-tested rather than exercised only by hand.
2026-11-24 13:58:32 -05:00
31e6cd6509 fix(ai): make the connection key enterable and the probe legible
Three defects found by driving the real admin panel, none of which a
typecheck or a unit test would have caught:

- The API key could not be entered at all. Field-level read access denies
  the value, and Payload does not render a field you cannot read, so the
  input was absent while the collection said it existed. The input is now
  a `ui` component that writes the hidden value through useField, which
  keeps the key server-only and gives it a working control.
- The probe panel and key input used frontend/ zinc styling, which reads
  as an accidental dark block on the admin panel's light theme. They now
  use the admin bundle's own --theme-elevation variables.
- An unreachable host reported "fetch failed" with no cause. Node hides
  the connect error inside `cause`, and that string ("connect
  ECONNREFUSED 10.0.0.5:8888") is the only part an admin can act on, so
  it is now included.

Also labels the acronym fields ("Base URL", "Model ID", "Has API key")
and covers the unreachable-host path in the generate-modes spec.
2026-11-24 13:28:58 -05:00
7abca7185c feat(ai): add admin-configurable model connections
Every AI surface talked to the Unsloth box through env vars, so swapping
provider or model meant editing .env and restarting. A connection is now
a stored record: base URL, model id, key, structured-output mode, and a
reasoning toggle.

Three surfaces with their own selector (Compose, dialogue draft, line
rewrite), because they want different things from a model: a draft needs
strict schema adherence while a line rewrite only needs prose. Blank
means the env defaults, so an empty global behaves exactly as before.

The API key is write-only: field read access denies everyone, so it never
reaches the admin form, REST, GraphQL, or a populated relationship. Blank
submission means "unchanged" and `clearApiKey` is the only delete, which
avoids the masked-field-round-trips-empty bug. Backups still contain it;
a blank connection key falls back to UNSLOTH_API_KEY for that reason.

Structured output is no longer assumed to be json_schema. Some
OpenAI-compatible providers reject it, so a connection selects
json_schema, json_object or prompt, and the weaker modes serialise the
schema into the prompt and parse the reply. The Test button runs a plain
probe and a structured probe, because a provider that refuses json_schema
passes the first and fails every draft.

Compose keeps a single fixed dropdown entry: plugin config is built at
boot and cannot list database rows, so the handler resolves the selected
connection per request instead.

Draft provenance records the connection label, so a stored conversation
still names the provider that produced it.
2026-11-24 13:04:39 -05:00
de27a53044 feat(npc-dialogue): make the AI prompt voice configurable
The system prompt was a single constant, so tuning how drafted dialogue
sounds meant editing code and redeploying. Split it into the half that is
copy and the half that is a contract.

VOICE and optional HOUSE RULES are now editable from a new
`npc-dialogue-settings` global, and per conversation through an
`voiceOverride` field on `npc-dialogues`. Precedence is dialogue, then
global, then the built-in default, resolved by the pure `resolveVoice`.
STRUCTURE, FIELDS, STATE, OUTPUT and the worked example stay in
`LOCKED_RULES`: the draft validator enforces the same rules, so an edit
there would make every draft fail for reasons an author cannot trace.

Both surfaces render the assembled prompt through the same pure
composer the server calls, so the preview cannot drift from what the
model receives. The global normalises dashes on save, bumps `revision`
only on a real text change, and keeps 20 versions for rollback.

Provenance gains `promptSource` and `promptRevision` so a stored draft
still names the voice that shaped it. A draft that fails twice while a
custom voice is active now says so, instead of looking like a model bug.

`composeDialogueSystemPrompt()` with no arguments reproduces the old
prompt byte for byte, pinned by a golden fixture.
2026-11-24 12:53:33 -05:00
74b116b9cf fix(awards): save awards without an advancement tier
The beforeChange hook compared advancement values against undefined, but the admin form always submits the group, so an award outside a lineup arrived as { seriesKey: null, tier: null }. Null counted as set, which tripped the duplicate tier check for standalone ribbons and the ribbons-only guard for medals and commendations.

Normalize null, empty, and non-finite values to "not set" before validating. Non-ribbon awards clear leftover lineup values on a type change instead of throwing on a hidden field, and partial API updates that omit advancement keep the stored lineup.
2026-11-24 08:03:30 -05:00
48556c3688 feat(tech-tree): add note nodes with optional frontend visibility
Planners can now drop annotation cards on the Tech Tree canvas without inventing fake technologies. Notes live in their own tech-tree-notes collection (title, body, treePosition) and carry no prerequisites, costs, approval workflow or research state, so the layout engine, edge builder and research rules never see them.

showOnFrontend defaults to false, making notes a backend authoring aid; ticking it publishes the amber card read-only to the member tech tree, which queries showOnFrontend = true.

Canvas work: amber NoteNode card with no connection handles, NoteDialog for create/edit/delete, a New Note toolbar button (technologies:create gated), viewport-centre placement, and namespaced note-<id> React Flow ids so note and technology ids can never collide. Note drags, Save positions and Auto-arrange reuse the single-statement bulk /api/tech-tree/positions write by sending collection: "tech-tree-notes"; no PATCH-per-note path was added.

Also fixes the note card body being clipped by the inherited line-height: the classification strip and footer now have fixed heights with leading-none, and the body takes the remaining flex space instead of line-clamp.

Tests: tech-tree-notes.int.spec.ts (defaults, required title, publication filter, in-place edits, note layout and id namespacing) plus note coverage in tech-tree-positions.int.spec.ts. Migration 20261123_073019_add_tech_tree_notes must be run on prod after deploy.
2026-11-23 03:11:36 -05:00
4022e5b5f1 feat(intelligence): add attendance-gated feature unlocks to mission pages
Missions gain an attendanceUnlocks tier list (admin tab plus side-op dialog),
rendered as a timeline under the attendance card: reached tiers light up in
their accent, unreached tiers stay muted with an X TO GO tag.

- shared derivation, validation and side-op parser in lib/intelligence
- thresholds sorted on save, duplicates rejected, above-max allowed
- one compact field in the Discord roll-call; attendance hash now includes
  tiers, embed schema version 4
- int tests and an e2e render check at two attendance levels
2026-11-21 02:30:48 -05:00
b90247a288 fix(bot): rewrite the Friday notice in the claimed state
The claim path appended a credit line to the invitation, so a claimed notice
still said the slot was open, that nobody had picked it up, and that Jason
would host if nobody did.

- renderClaimedNotice(): the whole body for the claimed state, role ping
  dropped since there is nothing left to ask for
- compare the live message against the rendered body each poll, so a message
  left contradictory by an older build heals on the next tick
- a cancelled claim still restores the full invitation, ping included
- cover both bodies and the claim parser in the notice integration test
2026-11-20 20:11:53 -05:00
5418d6563e feat(lockers): seed and unlimited-stock sync for limited arsenal 2026-11-20 19:52:15 -05:00
4fba0b03c7 fix(bot): show the Friday op slot date in Eastern time
Discord renders <t:epoch:D> in each viewer's timezone, so the slot's Friday
00:00 Eastern epoch read as Thursday for members west of Eastern. Render the
date as a pinned Eastern label instead.

- add fridayDateLabel(): the upcoming Friday in America/New_York
- noticeToken() now returns that label, keeping dedup stable per Friday
- legacyNoticeToken() still matches older <t:epoch:D> notices and the service
  rewrites them in place, so a deploy does not duplicate or leave one behind
- only match the bot's own messages, since a plain-date token could otherwise
  hit a member's message (which the bot cannot edit)
- document the timezone rule in the bot AGENTS.md
2026-11-20 17:25:04 -05:00
392717bedc feat(intelligence): add a radial graph view to the faction relations page
The matrix answers "what is this faction's score", not "who is tied to whom".
Add a graph view behind a Matrix/Graph switch on the same page.

The player faction sits at the center and every other faction is placed on a
ring by classification (majors innermost, then minors, corporations, specials),
so its relations read as spokes and the rest as chords. Positions are
deterministic: rings ordered by type, members by name, starting at twelve
o'clock, with faint guide rings so the structure is legible without hovering.

Relations are straight lines. A relationship runs both ways, so where both
sides have an opinion the two directions are drawn side by side on either side
of the axis, each spanning the full distance between the factions, colored and
weighted by its own score, with an arrowhead at the faction being regarded. The
two directions differ independently: a faction can be resented by one that it
regards neutrally. A pair with only one opinion keeps a single centered line.

A line that would cut through an unrelated faction steps aside just far enough
to clear it, and only for factions actually alongside the line rather than
beyond either end. Straight stays straight.

Hovering a faction isolates its web and opens a panel listing what it regards
and who regards it; clicking opens the dossier. Pan, wheel zoom and reset are
local, and the whole view is hand-drawn SVG, so no graph library was added.

The layout is pure and unit-tested: input order cannot move a node, the two
directions of a pair run parallel rather than overlapping, single-direction
pairs span the whole pair, and a blocked line dodges instead of crossing a node.
2026-11-18 16:34:50 -05:00
5e1f200261 feat(wiki): replace textarea overlay with a CodeMirror markdown editor
The body editor painted highlighted markdown in a div behind a transparent-text
textarea, so the painted text and the caret were two different layout engines.
Any wrap-point difference (borders, scrollbar gutters, engine rounding, trailing
newlines) shifted the overlay by whole lines once content soft-wrapped, making
clicks land on the wrong glyph and the document end feel unreachable. The CSS
patch that preceded this reduced the drift but could not remove the class of bug.

CodeMirror 6 owns text and caret together, so the failure mode is gone by
construction rather than by maintenance. The body remains a markdown string, so
prepareMarkdown, ::: directives, wikilinks, templates, revisions and the preview
pipeline are untouched, with no data migration.

- WikiMarkdownEditor: EditorView lifecycle, theme and markdown HighlightStyle
  bound to the app's CSS tokens, history, line wrapping, IME-safe keymap.
- markdownCommands: one pure command table shared by toolbar buttons and keys.
- editorChange: toolbar updates dispatch only the differing span, keeping undo
  granular and selections outside the edit intact.
- Removes WikiEditorHighlightLayer, editorMetrics, lib/wiki/editorHighlight,
  useEditorHistory and the now-dead textarea selection reader.
- Adds e2e proof: glyph-precise clicks across wrapped paragraphs, list items,
  image markdown and scrolled documents land at the exact clicked offset.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-11-18 15:12:22 -05:00
9e6cd55fe6 refactor(intelligence): drop the factions.relationships array in favour of the ledger
Nothing stores a pairwise score on a faction any more, so remove the array
field, its admin UI and the masking line that blanked it for undiscovered
factions. The disposal-mask doc comment now points at the ledger, which
applies the same rule by filtering entries that name an undiscovered faction.

The second migration converts every non-zero legacy value into an
opening-balance entry (custom delta, dated at the owning faction's last update
so it does not read as a fresh event, legacy note preserved) and then drops
the table. Zero rows are skipped because a stored 0 and no entries mean the
same thing.

Two integration specs that created or asserted `relationships` now use the
ledger instead.
2026-11-18 14:13:29 -05:00
2384c7f5a4 feat(intelligence): add the faction relation ledger collection and score math
Pairwise faction attitudes were hand-typed into a per-faction array, so the
two directions of one relationship lived in different documents and could
disagree with each other.

Add `faction-relation-entries`: one row per event that moved one faction's
attitude toward another, with the score computed on read instead of stored.
Entries are directed by default with a mutual flag for shared events; severity
tiers set the delta with a custom override; decaying entries halve per
half-life (new GameRules knob, 30 days default) while lasting shifts never
fade; voiding retires an entry with a stamped reason instead of deleting it;
hidden entries still move the score but never explain it to players.

`factionRelations.ts` holds the pure math (severity presets, decay, directed
and mutual scores, bands), and `factionRelationLedger.ts` is the single read
path so the voided, hidden and undiscovered-faction rules exist in one place.
Reads run as the caller, never with `overrideAccess`; GM notes are gated by
field read access, and hidden rows are censored by an `afterRead` hook.

Includes the permission group, the `admin:faction-relation-entries:manage`
page gate, the integration spec, and the migration that creates the table and
its enums.
2026-11-18 14:13:20 -05:00
e15b0923ad fix(wiki): align highlight overlay and textarea wrapping so caret/click match painted text
The markdown overlay shared the wrapper's inset-0 box with the transparent-text
textarea, but its inner div added a 1px transparent border while the textarea is
border-0, shrinking its text width by ~2px; Firefox/Safari classic scrollbars
reserve another ~15px inside the scrolled textarea that the overflow-hidden
overlay never sees. Either gutter makes long unbreakable tokens (e.g. image
markdown URLs) wrap differently between the two layers, so the overlay text
drifts vertically under the caret/click math and editing feels like it's one or
more lines off right after inserting an image.

Compose both layers' classes from a shared WIKI_EDITOR_METRICS constant, drop
the overlay border, hide the textarea scrollbar so its content width matches the
overlay in every browser, and lock class parity with a jsdom RTL spec.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-11-18 13:56:10 -05:00
34c0d5681f fix(rich-text): render full lexical formatting incl. colours across all fields
RichText authored in the admin panel was rendered as plain text on the
public site: headings/lists/quotes were flattened by Tailwind preflight
(no @tailwindcss/typography installed), and Payload's default JSX
converter ignored text colours.

- src/lib/lexical: shared editor factory (ptfLexicalEditor) + shared
  colour palette (textState) + colour converter (richTextConverters)
- RichTextView: canonical .lexical-content renderer (colour-aware),
  swapped into every frontend render site
- All rich-text editors route through the factory, so every field
  inherits the coloured editor (incl. the previously-unedited ones)
- .lexical-content CSS extended with checklist/table/heading rules,
  wrapped in @layer components so per-page utilities still override;
  dropped the now-dead per-page prose hacks
- Remove the now-dead briefingConverters in favour of the shared
  converter; add tests/int/rich-text-view.int.spec.ts
2026-11-18 13:10:26 -05:00
b5f48de0b9 feat(wiki): add private drafts with a one-way publish
Wiki pages gain a Draft flag pinned to their original creator. A draft is
visible only to its creator, wiki moderators and admins: the collection's
read access returns a where clause so the REST/local API filters drafts,
and every frontend query ANDs the same clause (they run with overrideAccess).

Publishing is one-way. A page whose stored draft is false is rejected (403)
when sent draft: true, both in the service and in access.update.

UI: amber DraftBanner on the detail page, a Draft chip in WikiRow, and a
Draft switch in the editor that disables once the page is published.
2026-11-18 11:06:37 -05:00
1d45c3fee1 feat(intelligence): add undiscovered faction state with read masking
Factions gain a discovered checkbox plus a read-time mask so players see
the entry (UNDISCOVERED card, classified detail stub) without its name,
description, standing, relationships, campaigns or cover image.

The mask runs in the Factions afterRead hook, so every reader path is
covered: pages, REST, and populated relationships. Readers holding the new
factions:view-undiscovered permission or system:admin-access see the real
record; admin panel reads are exempt so a masked edit form can never write
the placeholder name back over a record.
2026-11-18 09:19:57 -05:00
4264431e4d feat(npc-dialogue): AI-assisted conversation drafting behind the review gate
Add a Generate button to the flow editor that drafts a whole conversation
from a form brief, and per-line Rewrite/Shorten/Sharpen controls in the node
dialog. Both land in unsaved field state, so a draft only reaches players when
an author saves the document: neither server action writes to npc-dialogues.

- src/lib/ai/generate.ts: extract the Unsloth client out of payload.config so
  Compose and dialogue drafting share one path; add generateStructured and
  resolveModel, with an optional UNSLOTH_MODEL_STRUCTURED override
- generationSchema.ts (pure): strict-safe JSON schema, normalizer with
  breadth layout, validator that rejects unknown flag keys, unauthorised
  effects, dangling hops and missing keys
- generation.ts: context loading, one validate-and-retry, then give up rather
  than hand back a broken graph; dash normalization keeps shipped copy clean
- effect vocabulary limited to notify and flag; emit, reward and discord stay
  author-only
- provenance group on npc-dialogues (migration 20261112_171955) records model,
  prompt version, attempts and the brief the draft was accepted from
- tests: 21 cases covering the normalizer, validator, retry paths and the
  rewrite parser, with the model call injected
- docs/npc-dialogue-ai.md and src/lib/npc-dialogue/AGENTS.md
2026-11-12 12:26:35 -05:00
c4cbe43c4f fix(bot): survive a stale Discord interaction instead of crashing
A manual /rollcall took the bot down: the command fetched the guild member
and ran the staff check before acknowledging, missed Discord's 3 second ack
window, then died on "Unknown interaction" when it tried to defer (and again
when the error path tried to reply). discord.js re-emits a rejected event
listener on the client as an 'error' event, and with no handler attached Node
threw and exited the process.

Ack first, protect the error paths:
- /rollcall, /remind-evaluations and /debug defer immediately and report
  permission denials through editReply.
- safeEphemeralReply (bot/lib/interactions.ts) never rethrows, and the RSVP
  and transfer handlers use the same guarded behaviour.
- client.on(Events.Error) logs instead of exiting. The entrypoint restarts a
  dead bot after 5 seconds, so the previous symptom was a silent gap.
2026-11-03 12:50:29 -05:00
ef3f26d4f9 feat(missions): add command chain editor and MissionCommandLinks collection
Introduce a per-mission command chain: a new MissionCommandLinks collection, a
lib/command-chain resolver, and an admin/mission-page editor for supervisor ->
subordinate links. Evaluations and mission reminders later consume this chain to
resolve equal-rank command relationships.
2026-11-02 09:59:55 -05:00
e64c477250 fix(evaluations): require attendance from both players and route direct-supervisor reviews
- peer eligibility now requires a yes-RSVP from both rater and ratee, so
  absent players can neither rate nor be rated for that op
- a rating from the ratee's direct supervisor (rater leads an assignment the
  ratee is a member of and ranks above them) is the command review; every
  other rating feeds the anonymous leadership spectrum
- dialog copy and collection docs updated to match; tests cover both rules
2026-11-01 15:51:45 -05:00
99ef9ec73c fix(mission-ratings): block mission authors from rating their own mission
Authors can no longer rate a mission they ran or planned. The rating action, the availability check and the server submit all enforce it, and the UI explains why. The mission-ratings fixtures now use a dedicated author so the rater accounts stay non-authors.
2026-11-01 15:21:53 -05:00
e9bc929213 feat(bot): post modlist reminder 8 hours before scheduled operations
Adds reconcileModlistBuffer, which resends the modlist-updated message once per Scheduled mission with a modlist attached, when its start is within DISCORD_MODLIST_BUFFER_HOURS (default 8). Tracked by the new discordModlistBufferSentAt marker, so it is independent of the roll-call modlist sync. Also fixes type errors in modlist-file-access.int.spec.ts.
2026-11-01 15:20:02 -05:00
a6709e4cf3 fix(modlists): allow anonymous link download of preset files
The file-serving route (/api/mod-lists/file/<name>) runs the collection
read access with isReadingStaticFile: true, but mod-lists required the
mod-lists:read permission, so anyone clicking a shared download link got
403 until they signed in. Gate the read access on isReadingStaticFile: the
file-serving path serves the preset to anyone with the link, while REST and
admin-panel reads keep the mod-lists:read gate. Documented in
src/collections/AGENTS.md and covered by an integration test.
2026-10-31 15:01:29 -04:00
8faa45a954 test(mission-ratings): eligibility, aggregate math, threshold, XP
Covers window classification, yes-RSVP/prior-rating gating, idempotent write,
factor validation, per-factor/distribution/overall-average aggregation,
anonymity threshold, custom-factor aggregation, numeric myValues, XP grant +
per-user idempotency, and permission gating (deny without / allow with read).
2026-10-31 10:25:37 -04:00
66666547ad refactor(evaluations): drop stored kind, derive rating direction from ranks 2026-10-31 03:26:51 -04:00
80f71dc917 fix(map-objectives): read Playwright request failure via errorText 2026-10-27 02:13:44 -04:00
3bef63af33 feat(map-objectives): superuser-authored strategic objectives on mission maps
Add a superuser-authored objective layer (defend, assault, secure, etc.)
shown as labelled map markers on both the world map and mission planning
map, with per-layer toggles on the planning map.

- collection: MapObjectives (map_objectives table, enums, FKs)
- lib: objectives service + objectiveTypes + permissions + event emit
- actions/api: create/update/delete objectives server actions
- UI: feature-layer toggles, objective picker dialog, world/plan markers,
  SQF export, dossier dialog integration
- generated: regenerate payload schema + types for map_objectives
- tests: 10 integration specs + e2e spec
- docs: CHANGELOG, map-system, AGENTS guides
2026-10-27 02:12:31 -04:00
7430251adf feat(awards): render ribbon devices as vectors with tier-driven auto-layout
Introduce RibbonArt, a single shared SVG renderer used by both the production viewer and admin/studio preview so they can no longer diverge. Devices are now vector glyphs (star/oak leaf/campaign clasp/arrow up) instead of Unicode text, laid out as one centered cluster that shrinks to fit. Device count derives from advancement tier using the service-star convention (tier N shows N-1, cap 6; bare ribbon at tier 1 or for non-tiered awards). Legacy per-device x/y positions are stored but ignored, so no schema change. Designers add/remove/reorder device types and preview tiers.
2026-10-26 22:21:10 -04:00
acf47a75ea feat(operations): gate logistics extractions behind an officer review screen
Logistics operation-extraction effects now park as pending_action instead of auto-settling. Officers visit Operations > Extractions to keep, scrap, or expel each line; only kept lines deposit into HQ. A capacity failure leaves the effect retryable (pending_action) so a full HQ can free space and re-resolve. Adds resolveLogisticsExtraction/listPendingExtractions actions + ExtractionReview UI + tests.
2026-10-26 22:20:14 -04:00
40b074a693 feat(vehicles): add per-vehicle disallowed-cargo blacklist enforced at shipment
Vehicles gain a virtual-block disallowedCargo array (asset/vehicle/resource item + optional amount cap, 0 forbids outright). createShipment consults findDisallowedCargo() before deducting any origin stock and rejects matching cargo lines cleanly. Includes Payload migration + 7 integration tests.
2026-10-26 22:17:21 -04:00
977f841056 feat(evaluations): gate leadership ratings by rank instead of squad assignments
Eligibility now requires a strict rank gap plus a yes-RSVP from at least
one side of the pair on an evaluable mission. Junior rates senior writes
leader-direct (feeds the anonymous aggregate); senior rates junior writes
subordinate; leader-indirect stays readable for legacy rows only.

- New src/lib/evaluations/ranks.ts ladder helpers shared by all call sites
- Profile page: eligible missions union viewer+subject attendance, dialog
  hidden without a rank gap, subordinate line visible to higher ranks
- Bot and in-app reminder planners pair co-attendees by rank, not squads
- isDirectLeaderOf/isAnyLeader removed; no schema change or migration
2026-10-25 02:53:49 -04:00