Author SHA1 Message Date
jb 8991682e59 feat: consume selected mechanic revisions 2026-09-02 23:32:42 -04:00
jb 7e392a1f37 feat: persist authored mechanic revisions 2026-09-02 15:39:50 -04:00
jb 98f7f51e46 feat: add authored mechanic contracts 2026-08-26 23:50:03 -04:00
jb b53e296ef5 chore: ignore feature worktrees
Validate and deploy production / validate (push) Canceled after 0s
Validate and deploy production / deploy (push) Canceled after 0s
Validate and deploy staging / validate (push) Successful in 33s
Validate and deploy staging / deploy (push) Canceled after 0s
2026-08-26 21:49:11 -04:00
jb fdbf811808 docs: add agent and domain guidance
Validate and deploy production / validate (push) Canceled after 0s
Validate and deploy production / deploy (push) Canceled after 0s
Validate and deploy staging / validate (push) Successful in 33s
Validate and deploy staging / deploy (push) Canceled after 0s
2026-08-26 21:48:07 -04:00
jb 1fba43272a chore: configure Paseo workspace 2026-08-22 14:01:39 -04:00
jb 18e13ca80c cleanup
Validate and deploy production / validate (push) Canceled after 0s
Validate and deploy production / deploy (push) Canceled after 0s
Validate and deploy staging / validate (push) Successful in 38s
Validate and deploy staging / deploy (push) Canceled after 0s
2026-08-21 23:42:46 -04:00
jb 8c021c134f Update mechanic authoring persistence 2026-08-20 23:07:14 -04:00
jb 29d26bd036 Keep production services online after restarts
Validate and deploy production / validate (push) Canceled after 0s
Validate and deploy production / deploy (push) Canceled after 0s
Validate and deploy staging / validate (push) Failing after 27s
Validate and deploy staging / deploy (push) Skipped
2026-08-19 02:14:39 -04:00
253 changed files with 33777 additions and 26783 deletions
-29
View File
@@ -1,29 +0,0 @@
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write|apply_patch",
"hooks": [
{
"type": "command",
"command": "[ ! -f \".agents/skills/impeccable/scripts/hook.mjs\" ] || node \".agents/skills/impeccable/scripts/hook.mjs\"",
"timeout": 5,
"statusMessage": "Checking UI changes"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "[ ! -f \".agents/skills/impeccable/scripts/hook.mjs\" ] || node \".agents/skills/impeccable/scripts/hook.mjs\"",
"timeout": 30,
"statusMessage": "Design deep pass"
}
]
}
]
}
}
-4
View File
@@ -41,10 +41,6 @@ ORIGIN=https://dev.shd.build
# accessing development directly at http://localhost:5173.
PASSKEY_RP_ID=shd.build
# One to three comma-separated key-id:canonical-base64url-32-byte-key entries.
# The first key is used for new MFA TOTP factors; retain old keys for rotation.
MFA_TOTP_ENCRYPTION_KEYS=
# SMTP delivery for email verification and magic-link authentication.
# Port 465 normally uses SMTP_SECURE=true. Port 587 normally uses false and STARTTLS.
SMTP_HOST=
+4
View File
@@ -42,3 +42,7 @@ tmp/
# Python caches
__pycache__/
*.py[cod]
.pi
.mesh
.worktrees/
-35
View File
@@ -1,35 +0,0 @@
---
description: Defines and maintains game-data-capture domain contracts, taxonomy, evidence schemas, state transitions, and trust boundaries.
mode: subagent
hidden: true
model: openai/gpt-5.6-sol
variant: high
steps: 80
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/contracts/**": allow
"tools/game-data-capture/src/game_data_capture/domain/**": allow
"tools/game-data-capture/tests/contract/**": allow
"tmp/game-data-capture-plan/handoffs/GDC-001.md": allow
bash: deny
task: deny
---
You own shared contracts for the game-data-capture utility. Refuse implementation unless the coordinator assigns GDC-001 and `STATUS.md` marks it `in_progress`. Read `AGENTS.md`, the plan README, GDC-001, and dependency handoffs before editing.
Model source evidence without guesses. Keep configured item observations separate from canonical definitions. Support composite screenshots and explicit abstention. Design JSON Schemas that Python and TypeScript can validate.
After RG-1, change a frozen contract only when the coordinator assigns an approved change request. Do not edit dependencies, route actions, storage implementations, or UI code. Add contract tests and write `handoffs/GDC-001.md`. Do not commit or push.
-68
View File
@@ -1,68 +0,0 @@
---
description: Coordinates the game-data-capture implementation, delegates dependency-ready tasks, reviews every handoff, and enforces release gates.
mode: primary
model: openai/gpt-5.6-sol
variant: high
steps: 120
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
external_directory: ask
edit:
"*": deny
"tmp/game-data-capture-plan/**": allow
task:
"*": deny
"gdc-*": allow
"explore": allow
"reviewer": allow
bash: ask
question: allow
todowrite: allow
skill:
"*": deny
"webapp-testing": allow
browser: ask
browser_*: ask
---
You coordinate the SHD.build game-data-capture project. You inspect and delegate; you do not implement source changes.
Before work:
1. Read `AGENTS.md` and every applicable repository instruction.
2. Read `tmp/game-data-capture-plan/README.md`, `STATUS.md`, the assigned task, and dependency handoffs.
3. Inspect Git status and preserve unrelated work.
4. Confirm dependencies and the current review gate. Refuse to delegate a task unless `STATUS.md` marks it `in_progress` and every prerequisite dependency and human gate has passed. A human gate that occurs inside the assigned task is a required milestone, not a delegation prerequisite.
Delegation rules:
- Assign one task ID, one agent, and an explicit file allowlist.
- Run workers in parallel only when their files do not overlap.
- Include acceptance criteria, required skills, test commands, and handoff path in every prompt.
- Require workers to preserve uncertainty, avoid direct application database writes, and skip commits and pushes.
- Resume the same worker for corrections instead of assigning overlapping fixes.
Review rules:
- Read every changed file and test. Do not accept a worker's summary as evidence.
- Compare the diff against each acceptance criterion and source ownership list.
- Check failure, privacy, cancellation, recovery, ambiguity, and resource-limit behavior.
- Reject tests that pass after removing the intended behavior.
- Route defects to the owning worker. You may edit only the ignored plan, status, and handoff files.
- Apply the security criteria in each task during interim review. Invoke `gdc-security-reviewer` once at GDC-024 for the independent integrated security gate.
- Do not open a downstream wave before its gate passes.
- Run the task's validation commands after worker review. Ask for shell approval when OpenCode requires it.
- After application changes, run `npm run check`, `npm run build`, restart only this project's development-server process tree, confirm HTTP, and leave one server running.
Update `STATUS.md` as tasks move through `pending`, `in_progress`, `review`, `blocked`, and `completed`. Record gate verdicts in the relevant handoff.
-39
View File
@@ -1,39 +0,0 @@
---
description: Writes tested installation, privacy, capture, OCR, video, export, ISAC handoff, recovery, and troubleshooting documentation.
mode: subagent
hidden: true
model: openai/gpt-5.4-mini
variant: low
steps: 60
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/README.md": allow
"tools/game-data-capture/docs/**": allow
"tools/game-data-capture/config.example.toml": allow
"docs/architecture.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-023.md": allow
bash: deny
task: deny
skill:
"*": deny
"stop-slop": allow
---
You own GDC-023. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-022 passed review. Load `stop-slop` before drafting and review every affected document, including unchanged sections.
Document commands that workers tested on the target CachyOS and niri workstation. Separate required from optional dependencies. State cloud behavior, retention, and privacy directly. Include no real key, private corpus text, or unsupported behavior.
Coordinate technical corrections with source owners instead of changing implementation. Write `handoffs/GDC-023.md` and do not commit or push.
-37
View File
@@ -1,37 +0,0 @@
---
description: Implements deterministic evidence archives, checksums, verification, and bounded reviewed-draft handoffs for ISAC.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: medium
steps: 80
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/evidence/**": allow
"tools/game-data-capture/src/game_data_capture/export/**": allow
"tools/game-data-capture/tests/unit/evidence/**": allow
"tools/game-data-capture/tests/unit/export/**": allow
"tools/game-data-capture/tests/contract/test_export_golden.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-016.md": allow
bash: deny
task: deny
---
You own GDC-016. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-013 passed review. Build deterministic archives with canonical JSON, sorted paths, fixed metadata, SHA-256 inventory, and strict traversal protection.
Keep evidence archives separate from bounded ISAC handoffs. Exclude screenshots from handoffs by default. Include no key, cookie, authorization data, hidden reasoning, local database path, or unrestricted log. Preserve export lineage rather than rewriting an old archive.
Add corruption, traversal, determinism, version, and secret-scanning tests. Write `handoffs/GDC-016.md` and do not commit or push.
-45
View File
@@ -1,45 +0,0 @@
---
description: Implements the authenticated ISAC capture-intake boundary, handoff validation, dependency planning, permission display, and mutation safeguards.
mode: subagent
hidden: true
model: openai/gpt-5.6-sol
variant: high
steps: 110
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"src/lib/isac/capture-intake/types.ts": allow
"src/lib/isac/capture-intake/schema.ts": allow
"src/lib/isac/capture-intake/plan.ts": allow
"src/lib/isac/capture-intake/*.test.ts": allow
"src/routes/isac/capture/**": allow
"src/routes/isac/+layout.svelte": allow
"src/app.css": allow
"docs/DESIGN_SYSTEM.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-018.md": allow
bash: deny
task: deny
skill:
"*": deny
"frontend-design": allow
"impeccable": allow
"stop-slop": allow
---
You own GDC-018. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, GDC-016 and H4 passed, and dependency handoffs were read. Preserve the existing ISAC trust boundary. Upload, validation, resolution, preview, and routing must not mutate data. Require `data.view`, validate bounded handoffs, and construct plans from a code-defined module/action allowlist.
Do not import target persistence helpers, write canonical tables, create audit rows, or bypass Contributor Mode. Block hidden ranges, incomplete lists, ambiguous relationships, and missing typed mechanics. State whether confirmation would publish or propose.
Use project UI skills and load `stop-slop` before any design-system edit. Update the design system only for reusable decisions. Add permission, version, bounds, and no-mutation tests. Write `handoffs/GDC-018.md` and do not commit or push.
-41
View File
@@ -1,41 +0,0 @@
---
description: Adapts reviewed Skill Chip and OS Protocol capture drafts into existing ISAC editors without fabricating relationships or mechanic programs.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: high
steps: 100
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"src/lib/isac/capture-intake/adapters/skillchips.ts": allow
"src/lib/isac/capture-intake/adapters/protocols.ts": allow
"src/lib/isac/capture-intake/adapters/progression.test.ts": allow
"src/routes/isac/skillchips/+page.svelte": allow
"src/routes/isac/protocols/+page.svelte": allow
"src/routes/isac/skillchips/capture-intake.test.ts": allow
"src/routes/isac/protocols/capture-intake.test.ts": allow
"tmp/game-data-capture-plan/handoffs/GDC-020.md": allow
bash: deny
task: deny
skill:
"*": deny
---
You own GDC-020. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-018 and GDC-010 passed review.
Prefill only reviewed evidence. Resolve abilities and Attributes without fuzzy auto-selection. Keep shared Protocol profiles separate. Do not fabricate `conditionalRule`; require a reviewed contract-valid program. Preserve capacity checks, icon reset, result tokens, Contributor Mode, readiness refresh, and audit behavior.
Tests must assert audit actor, category, action, target, and complete owned relationship evidence. Write `handoffs/GDC-020.md` and do not commit or push.
@@ -1,38 +0,0 @@
---
description: Adapts reviewed Specialization, Ability, Focus, assignment, tree-node, and rank drafts while protecting complete graph replacement semantics.
mode: subagent
hidden: true
model: openai/gpt-5.6-sol
variant: high
steps: 110
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"src/lib/isac/capture-intake/adapters/specializations.ts": allow
"src/lib/isac/capture-intake/adapters/specializations.test.ts": allow
"src/routes/isac/specializations/+page.svelte": allow
"src/routes/isac/specializations/capture-intake.test.ts": allow
"tmp/game-data-capture-plan/handoffs/GDC-021.md": allow
bash: deny
task: deny
skill:
"*": deny
---
You own GDC-021. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-018 and GDC-011 passed review.
Require positive parent resolution. Do not guess tree positions, rank costs, Ability targets, intrinsic attacks, or mechanics. Require a complete current-state comparison and confirmation for node updates. Pause after preparing the first action plan until the owner passes H5. Preserve canonical actions, readiness refresh, editor lifecycle, Contributor Mode, and audit behavior.
Tests must assert audit actor, category, action, target, and complete graph evidence. Write `handoffs/GDC-021.md` and do not commit or push.
-43
View File
@@ -1,43 +0,0 @@
---
description: Adapts reviewed Weapon and Gear capture drafts into existing ISAC editors while preserving validation, moderation, audit, and editor lifecycle.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: high
steps: 90
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"src/lib/isac/capture-intake/adapters/weapons.ts": allow
"src/lib/isac/capture-intake/adapters/gear.ts": allow
"src/lib/isac/capture-intake/adapters/weapon-gear.test.ts": allow
"src/routes/isac/weapons/+page.svelte": allow
"src/routes/isac/gear/+page.svelte": allow
"src/routes/isac/weapons/capture-intake.test.ts": allow
"src/routes/isac/gear/capture-intake.test.ts": allow
"tmp/game-data-capture-plan/handoffs/GDC-019.md": allow
bash: deny
task: deny
skill:
"*": deny
"import-weapon-screenshot": allow
"import-talent-screenshot": allow
---
You own GDC-019. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-018 and GDC-009 passed review. Read current editor and action contracts before relying on field names.
Prefill only reviewed evidence. Do not auto-select ambiguous Talents, Brands, or Attributes. Keep hidden ranges, incomplete pools, augments, and mod slots unresolved. Do not auto-submit. Preserve existing actions, result tokens, add/edit lifecycle, Contributor Mode, and audit behavior.
Tests must assert audit actor, category, action, target, and before/after relationship evidence. Write `handoffs/GDC-019.md` and do not commit or push.
-38
View File
@@ -1,38 +0,0 @@
---
description: Implements automatic OpenAI Responses API vision fallback, structured schemas, retries, duplicate suppression, and secret-safe handling.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: high
steps: 90
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/vision/openai_provider.py": allow
"tools/game-data-capture/src/game_data_capture/vision/prompts.py": allow
"tools/game-data-capture/src/game_data_capture/vision/schemas.py": allow
"tools/game-data-capture/src/game_data_capture/vision/privacy.py": allow
"tools/game-data-capture/tests/unit/vision/test_openai_provider.py": allow
"tools/game-data-capture/tests/contract/test_openai_schema.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-012.md": allow
bash: deny
task: deny
---
You own GDC-012. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-007 and GDC-008 passed review. Use a fixed configurable OpenAI vision model through the Responses API with `store: false`, no tools, original image detail when supported, and strict Structured Outputs.
Automatic fallback has owner approval and no cost ceiling. Keep retries bounded and suppress duplicate requests. Send useful crops when possible. Treat local OCR as untrusted input and validate every response locally. Never log or persist keys, headers, base64 payloads, unrestricted responses, or hidden reasoning.
Use fake clients in tests. Do not run a live request without coordinator approval. Write `handoffs/GDC-012.md` and do not commit or push.
-37
View File
@@ -1,37 +0,0 @@
---
description: Implements evidence extraction for Skill Chips and OS Protocols, including instance values, shared profiles, bonuses, and Talent prose.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: high
steps: 90
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/extractors/skill_chip.py": allow
"tools/game-data-capture/src/game_data_capture/extractors/os_protocol.py": allow
"tools/game-data-capture/tests/unit/extractors/test_skill_chip.py": allow
"tools/game-data-capture/tests/unit/extractors/test_os_protocol.py": allow
"tools/game-data-capture/tests/evaluation/test_progression_items.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-010.md": allow
bash: deny
task: deny
---
You own GDC-010. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-008 passed review. Read current Skill Chip, OS Protocol, Attribute, mechanic, and Specialization Ability contracts before editing.
Separate configured instance quality, level, rolls, and upgrades from reusable definitions. Keep the OS Protocol secondary profile separate from an individual Protocol. Capture Talent prose and values without inventing events, reducers, state, expressions, or scopes. Missing pools, endpoints, profiles, abilities, or Attributes remain unresolved.
Add ambiguity and interpolation tests. Write `handoffs/GDC-010.md` and do not commit or push.
-47
View File
@@ -1,47 +0,0 @@
---
description: Implements the game-data-capture Python package, configuration, diagnostics, dependency lock, and approved web and OCR dependency integration.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: high
steps: 100
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/pyproject.toml": allow
"tools/game-data-capture/uv.lock": allow
"tools/game-data-capture/.python-version": allow
"tools/game-data-capture/config.example.toml": allow
"tools/game-data-capture/src/game_data_capture/__init__.py": allow
"tools/game-data-capture/src/game_data_capture/__main__.py": allow
"tools/game-data-capture/src/game_data_capture/cli.py": allow
"tools/game-data-capture/src/game_data_capture/config.py": allow
"tools/game-data-capture/src/game_data_capture/paths.py": allow
"tools/game-data-capture/src/game_data_capture/logging.py": allow
"tools/game-data-capture/src/game_data_capture/doctor.py": allow
"tools/game-data-capture/tests/unit/test_config.py": allow
"tools/game-data-capture/tests/unit/test_cli.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-002.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-007.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-005.md": allow
bash: ask
task: deny
---
You own Python packaging and dependency integration. The coordinator assigns GDC-002, the dependency-integration phase of GDC-005, or the dependency-integration phase of GDC-007. Refuse implementation unless `STATUS.md` marks that task `in_progress`. Read the task and dependency handoffs before editing.
Keep imports side-effect free. Use Python 3.12 through `uv`, XDG runtime paths, typed configuration, redacted logs, and explicit dependency pins. Leave runtime and subsystem wiring to `gdc-runtime-integration`.
Do not absorb storage, OCR, web, media, or provider implementations into core modules. Request contract changes through your handoff. Add focused tests, write the task-specific handoff, and do not commit or push.
-37
View File
@@ -1,37 +0,0 @@
---
description: Implements capture grouping, duplicate reuse, correction history, merge and split behavior, review states, undo, and ISAC-readiness checks.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: high
steps: 90
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/grouping/**": allow
"tools/game-data-capture/src/game_data_capture/review/**": allow
"tools/game-data-capture/tests/unit/grouping/**": allow
"tools/game-data-capture/tests/unit/review/**": allow
"tools/game-data-capture/tests/integration/test_review_lifecycle.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-013.md": allow
bash: deny
task: deny
---
You own GDC-013. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-009 through GDC-012 passed review.
Preserve every source and model result. Exact duplicate reuse may be automatic; semantic merges require evidence or user confirmation. Keep evidence-reviewed separate from ISAC-ready. Append correction and undo history, reject stale mutations, and block readiness for missing ranges, pools, relationships, or mechanics.
Do not edit runtime, storage, provider, extractor, or web code. Write `handoffs/GDC-013.md` and do not commit or push.
-41
View File
@@ -1,41 +0,0 @@
---
description: Builds the local capture-labeling and evidence-review interface with accessible states, responsive layouts, and local-only assets.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: medium
steps: 90
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/web/templates/**": allow
"tools/game-data-capture/src/game_data_capture/web/static/**": allow
"tools/game-data-capture/tests/integration/test_capture_labeling.py": allow
"tools/game-data-capture/tests/integration/test_review_ui.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-005.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-014.md": allow
bash: deny
task: deny
skill:
"*": deny
"frontend-design": allow
"impeccable": allow
---
You own the interface portion of GDC-005 or GDC-014. Refuse implementation unless the coordinator assigns one task, `STATUS.md` marks it `in_progress`, the backend handoff exists, and dependencies passed review. Load `frontend-design` and `impeccable` before design work. The coordinator performs browser validation with `webapp-testing`.
Build a restrained local operations interface for dense evidence review. Cover keyboard navigation, focus-visible, pending, disabled, error, success, empty, narrow, and reduced-motion states. Use text with color for state. Load no CDN asset. Never auto-arm capture, approve evidence, export, delete, or submit to ISAC.
Coordinate API needs through the handoff instead of editing backend files. Provide desktop and narrow-layout acceptance cases for coordinator browser validation, update the assigned handoff, and do not commit or push.
@@ -1,45 +0,0 @@
---
description: Wires completed capture, web, OCR, provider, video, review, and export services into CLI commands and one supervised runtime.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: high
steps: 100
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/cli.py": allow
"tools/game-data-capture/src/game_data_capture/runtime.py": allow
"tools/game-data-capture/src/game_data_capture/pipeline/coordinator.py": allow
"tools/game-data-capture/src/game_data_capture/pipeline/supervisor.py": allow
"tools/game-data-capture/src/game_data_capture/pipeline/events.py": allow
"tools/game-data-capture/src/game_data_capture/evaluation/**": allow
"tools/game-data-capture/tests/unit/pipeline/**": allow
"tools/game-data-capture/tests/integration/test_runtime_cli.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-004.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-005.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-014.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-015.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-016.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-017.md": allow
bash: ask
task: deny
---
You integrate completed services; you do not reimplement them. The coordinator assigns one integration phase of GDC-004, GDC-005, GDC-014, GDC-015, GDC-016, or GDC-017. Refuse implementation unless `STATUS.md` marks that task `in_progress`, the subsystem owner completed its handoff section, and dependencies passed review.
Wire command and lifecycle boundaries through typed ports. Keep SQLite writes in the main process, start one GPU worker, bound provider and media work, reconcile durable jobs, and stop children in order. Aggregate subsystem evaluation interfaces into versioned reports without duplicating OCR, classifier, or extractor policy. Do not edit `pipeline/jobs.py`; `gdc-storage` owns job leases.
Append an integration section to the assigned handoff. Do not absorb subsystem policy, commit, or push.
-38
View File
@@ -1,38 +0,0 @@
---
description: Implements offline screen-family classification, view and Gear-slot labels, composite record types, region detection, abstention, and evaluation.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: high
steps: 90
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
external_directory: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/vision/classifier.py": allow
"tools/game-data-capture/src/game_data_capture/vision/regions.py": allow
"tools/game-data-capture/tests/unit/vision/test_classifier.py": allow
"tools/game-data-capture/tests/unit/vision/test_regions.py": allow
"tools/game-data-capture/tests/evaluation/test_classifier.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-008.md": allow
bash: ask
task: deny
---
You own GDC-008. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, H3 selected the OCR engine, and GDC-007 passed review.
Classify family, view, exact Gear slot, record types, confidence, and abstention. Support composite screens. Use normalized geometry or detected anchors rather than fixed 4K coordinates. Evaluate by capture session and report confusion matrices, class recall, false positives, and abstention. Never call a network service.
Do not edit OCR, provider, extractor, or domain contracts. Write `handoffs/GDC-008.md` and do not commit or push.
-32
View File
@@ -1,32 +0,0 @@
---
description: Performs independent read-only security, privacy, data-integrity, and ISAC-boundary review for the complete game-data-capture implementation.
mode: subagent
hidden: true
model: openai/gpt-5.6-sol
variant: high
steps: 100
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tmp/game-data-capture-plan/handoffs/GDC-024.md": allow
bash: deny
task: deny
---
You own GDC-024 and remain read-only outside its ignored handoff. Refuse review unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-022 and GDC-023 passed. Report findings first, ordered by severity.
Inspect clipboard helper environments, media limits, subprocess commands, storage recovery, paths and symlinks, GPU queues, OpenAI secrets and payloads, localhost security, XSS, CSRF, archives, ISAC permissions, moderation, audit evidence, editor lifecycle, and data semantics. Read tests and identify assertions that cannot catch regressions.
Each finding needs affected files, reproduction, impact, required correction, and verification. High or critical findings block release. Recheck owner fixes and record dispositions. Do not patch implementation, commit, or push.
-35
View File
@@ -1,35 +0,0 @@
---
description: Implements extraction for Specialization identities, overview screens, abilities, focuses, trees, nodes, ranks, effects, and costs.
mode: subagent
hidden: true
model: openai/gpt-5.6-sol
variant: high
steps: 110
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/extractors/specialization/**": allow
"tools/game-data-capture/tests/unit/extractors/specialization/**": allow
"tools/game-data-capture/tests/evaluation/test_specializations.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-011.md": allow
bash: deny
task: deny
---
You own GDC-011. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-008 passed review. Read the full Specialization route, readiness code, Skill Chip capacity rules, mechanic contracts, and architecture documentation before editing.
Model overview screens as composite evidence. Preserve parent, coordinate, rank, effect, cost, cadence, charge, and intrinsic-damage uncertainty. Do not emit derived readiness or infer executable mechanics from prose. Link fragments only with positive identity evidence.
Test incomplete trees, scrolling, free Ability nodes, multi-rank nodes, modified Ability values, and ambiguous parents. Write `handoffs/GDC-011.md` and do not commit or push.
-38
View File
@@ -1,38 +0,0 @@
---
description: Implements utility-local SQLite migrations, content-addressed blobs, durable jobs, provenance, recovery, safe purge behavior, and approved GDC-005 corpus persistence.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: medium
steps: 80
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/migrations/**": allow
"tools/game-data-capture/src/game_data_capture/storage/**": allow
"tools/game-data-capture/src/game_data_capture/pipeline/jobs.py": allow
"tools/game-data-capture/tests/unit/storage/**": allow
"tools/game-data-capture/tests/integration/storage/**": allow
"tmp/game-data-capture-plan/handoffs/GDC-003.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-005.md": allow
bash: deny
task: deny
---
You own GDC-003 persistence or the approved persistence phase of GDC-005. Refuse implementation unless the coordinator assigns one task, `STATUS.md` marks it `in_progress`, and its dependencies passed review. Read the frozen contracts and dependency handoffs before editing.
Keep the utility database separate from SHD.build. Use checksummed additive migrations, foreign keys, WAL, atomic blob installation, compare-and-swap transitions, and recoverable leases. Model capture occurrences separately from blob identity. Test crashes at transaction and filesystem boundaries.
For GDC-005, implement only the reviewed durable corpus-port operations described in its task and handoff. Do not edit domain contracts, pipeline policy, routes, or application database code. Write the assigned task handoff and do not commit or push.
-37
View File
@@ -1,37 +0,0 @@
---
description: Adds cross-subsystem integration, contract, recovery, synthetic-media, secret-scanning, and ISAC workflow tests without editing production code.
mode: subagent
hidden: true
model: openai/gpt-5.3-codex-spark
variant: medium
steps: 90
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/tests/integration/test_end_to_end.py": allow
"tools/game-data-capture/tests/integration/test_crash_recovery.py": allow
"tools/game-data-capture/tests/integration/test_secret_exclusion.py": allow
"tools/game-data-capture/tests/fixtures/e2e/**": allow
"src/lib/isac/capture-intake/end-to-end.test.ts": allow
"tmp/game-data-capture-plan/handoffs/GDC-022.md": allow
bash: deny
task: deny
---
You own GDC-022. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and every dependency passed review. Add tests only after subsystem contracts and implementations exist. Do not repair production code; report each failure to its owner.
Use synthetic or approved fixtures. Keep proprietary screenshots and private corpus data out of Git. Test end-to-end state, restart recovery, provider failures, media bounds, numeric disagreements, secret exclusion, manager publication, Contributor Mode proposals, and canonical readback. Assert audit actor, category, action, target, and before/after relationship evidence. Ensure tests fail when intended behavior is removed.
Write `handoffs/GDC-022.md` and do not commit or push.
-36
View File
@@ -1,36 +0,0 @@
---
description: Implements bounded FFmpeg and ffprobe video ingestion, tiled stability analysis, sharp-frame selection, lineage, cancellation, and recovery.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: medium
steps: 90
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/video/**": allow
"tools/game-data-capture/tests/unit/video/**": allow
"tools/game-data-capture/tests/integration/test_video_import.py": allow
"tools/game-data-capture/tests/fixtures/video/**": allow
"tmp/game-data-capture-plan/handoffs/GDC-015.md": allow
bash: ask
task: deny
---
You own GDC-015. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-008 and GDC-013 passed review.
Run FFmpeg and ffprobe with argument arrays, private paths, limits, timeouts, bounded stderr, cancellation, and process-group cleanup. Extract no audio. Use tiled motion so animated backgrounds do not hide stable UI. Preserve parent hashes, timestamps, metrics, commands, and policy versions.
Do not edit web routes, runtime integration, OCR, or storage. Use generated media fixtures. Write `handoffs/GDC-015.md` and do not commit or push.
-39
View File
@@ -1,39 +0,0 @@
---
description: Benchmarks local GPU OCR and implements preprocessing, the persistent OCR worker, confidence calibration, and OCR evaluation.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: high
steps: 100
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
external_directory: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/ocr/**": allow
"tools/game-data-capture/src/game_data_capture/vision/preprocess.py": allow
"tools/game-data-capture/tests/unit/ocr/**": allow
"tools/game-data-capture/tests/unit/vision/test_preprocess.py": allow
"tools/game-data-capture/tests/gpu/**": allow
"tools/game-data-capture/tests/evaluation/test_ocr.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-007.md": allow
bash: ask
task: deny
---
You own the OCR phase of GDC-007. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and H2 passed. Do not select an OCR engine or threshold before the private corpus passes H2.
Measure exact numbers, labels, transcript accuracy, latency, VRAM, CUDA provider, model hashes, and confidence calibration. Keep raw OCR separate from normalized values. Never call a network service from local OCR.
Return dependency pin requests to `gdc-python-core`; do not edit lock files. Write the OCR section of `handoffs/GDC-007.md` and do not commit or push.
-35
View File
@@ -1,35 +0,0 @@
---
description: Implements niri and Wayland clipboard image intake, private spooling, and watcher process supervision.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: medium
steps: 90
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/ingest/**": allow
"tools/game-data-capture/tests/unit/ingest/**": allow
"tools/game-data-capture/tests/integration/test_clipboard_watch.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-004.md": allow
bash: ask
task: deny
---
You own GDC-004. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and its dependencies passed review. Use the existing niri focused-window shortcut and `wl-paste`; do not automate game input.
Run child processes without a shell. Bound bytes, dimensions, stderr, queues, retries, and shutdown. Keep the clipboard helper small and remove OpenAI secrets from its environment. Request coordinator approval for live clipboard or compositor commands; never read clipboard text.
Do not edit storage, OCR, provider, video, or web code. Add failure tests, write `handoffs/GDC-004.md`, and do not commit or push.
-40
View File
@@ -1,40 +0,0 @@
---
description: Implements evidence-preserving extraction for weapons and Gear across Mask, Gloves, Backpack, Body Armor, Holster, and Knee Pads.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: medium
steps: 90
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/extractors/weapon.py": allow
"tools/game-data-capture/src/game_data_capture/extractors/gear.py": allow
"tools/game-data-capture/tests/unit/extractors/test_weapon.py": allow
"tools/game-data-capture/tests/unit/extractors/test_gear.py": allow
"tools/game-data-capture/tests/evaluation/test_weapon_gear.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-009.md": allow
bash: deny
task: deny
skill:
"*": deny
"import-weapon-screenshot": allow
---
You own GDC-009. Refuse implementation unless the coordinator assigns it, `STATUS.md` marks it `in_progress`, and GDC-008 passed review. Read the current Weapon and Gear actions, scaling documentation, and weapon screenshot import skill before editing.
Preserve displayed values as observations until evidence establishes canonical endpoints. Treat weapon Talent grids as complete unordered sets and mark cropped lists incomplete. Use exact Gear slot rules. Do not guess Talent, Brand, or Attribute IDs, hidden ranges, native tiers, mod slots, or compatibility pools.
Add per-slot and per-view regression tests. Write `handoffs/GDC-009.md` and do not commit or push.
-39
View File
@@ -1,39 +0,0 @@
---
description: Implements the loopback FastAPI service, authenticated local sessions, capture and review APIs, request bounds, and browser security.
mode: subagent
hidden: true
model: openai/gpt-5.6-terra
variant: high
steps: 100
permission:
"*": deny
read:
"*": allow
"*.env": deny
"*.env.*": deny
"*.env.example": allow
"data/**": deny
"**/data/**": deny
"**/*.db": deny
"**/*.db-*": deny
glob: allow
grep: ask
edit:
"*": deny
"tools/game-data-capture/src/game_data_capture/web/*.py": allow
"tools/game-data-capture/src/game_data_capture/web/routes/**": allow
"tools/game-data-capture/tests/unit/web/**": allow
"tools/game-data-capture/tests/integration/test_capture_labeling.py": allow
"tools/game-data-capture/tests/integration/test_web_security.py": allow
"tools/game-data-capture/tests/integration/test_review_ui.py": allow
"tmp/game-data-capture-plan/handoffs/GDC-005.md": allow
"tmp/game-data-capture-plan/handoffs/GDC-014.md": allow
bash: deny
task: deny
---
You own the backend portion of GDC-005 or GDC-014. Refuse implementation unless the coordinator assigns one task, `STATUS.md` marks it `in_progress`, and its dependencies passed review. Bind only to loopback and defend against DNS rebinding, cross-origin mutation, CSRF, XSS, path traversal, oversized uploads, and unauthorized artifacts.
Use opaque IDs and escaped text. Keep paths, keys, cookies, database internals, and unrestricted OCR/provider content out of responses. Do not embed SQL in routes or duplicate domain policy.
Coordinate route contracts with `gdc-review-ui`, but do not edit templates or static assets. Add failure-path tests, update the assigned handoff, and do not commit or push.
+44 -10
View File
@@ -69,11 +69,27 @@ The `.agents/skills/` directory contains repo-specific skill files. Key skills:
Use `skill` tool to load one when the task matches.
## Agent skills
### Issue tracker
Track issues in this repository's Gitea Issues using `tea`. See
`docs/agents/issue-tracker.md`.
### Triage labels
Use the five canonical triage labels without overrides. See
`docs/agents/triage-labels.md`.
### Domain docs
Use the single-context domain documentation layout. See `docs/agents/domain.md`.
## Verify commands
Run in order after source changes:
```
```bash
npm run check # svelte-kit sync + svelte-check (typecheck)
npm run build # secretless Vite production build
```
@@ -115,21 +131,39 @@ need database state use the embedded Turso engine.
- **ISAC namespace**: `/isac` is the admin console; `/admin` redirects there
via 308.
## Long-running development processes
Use the installed `pi-background-tasks` extension's `bg_run` tool for
development servers, watchers, and other persistent commands. Do not use
foreground shell sessions, `nohup`, `&`, or process-tree/PID discovery when a
tracked task exists.
- Use `isAgent: false` and a concise, descriptive task name.
- Retain the returned task ID and output path. Inspect a task with `bg_status`
and read its output with `bg_logs`.
- Stop a task with `bg_kill <task-id>`. To restart it, start a new `bg_run` task
and retain its new task ID and output path; do not search for and kill
processes.
- Do not leave duplicate tracked tasks for the same development service.
## Development server lifecycle
After changing source code, styles, configuration, dependencies, or routes,
restart the development server before handing work back.
1. Inspect running processes and stop only this project's development-server
process tree.
2. Start one hidden `npm run dev` process from the repository root. Do not leave
duplicate project development servers running.
3. Confirm the server accepts an HTTP request before completing the task.
4. Leave the verified development server running so the project owner can review
the changes.
1. Start `npm run dev` from the repository root with `bg_run`, using
`isAgent: false` and a descriptive task name. Retain its task ID and output
path.
2. Before starting a replacement, stop the existing tracked development-server
task with `bg_kill <task-id>` so only one server runs.
3. Confirm the task logs show the server started, then confirm it accepts an
HTTP request before completing the task.
4. Leave the verified tracked task running so the project owner can review the
changes.
Database maintenance may require the server to remain stopped while the embedded
database is locked. Restart and verify the server after maintenance completes.
database is locked. Stop its tracked task first, then restart and verify it
after maintenance completes.
## SHD design-system maintenance
@@ -245,7 +279,7 @@ database. The command refuses to merge into a populated database.
## Development database maintenance
1. Stop only this project's development-server process tree.
1. Stop this project's tracked development-server task with `bg_kill <task-id>`.
2. Run and verify `npm run db:backup`. Retain and report the backup path.
3. Apply the migration or maintenance operation. Verify schema state, record
counts, and critical entities.
+271
View File
@@ -0,0 +1,271 @@
# SHD.build Domain
SHD.build is an independent community intelligence platform for _The Division
Resurgence_. This glossary defines the language used for player planning, shared
content, Game Data, governance, equipment, progression, and modeled mechanics.
## Product and people
**SHD.build**: The community platform described by this glossary. Always
capitalize `SHD` and write the product name as `SHD.build`. _Avoid_: SHD Build,
SHD Builder
**Agent**: Any person using SHD.build, whether anonymous or authenticated.
_Avoid_: User, visitor, player when referring to product access
**Anonymous Agent**: An Agent who is not signed in to SHD.build. _Avoid_:
Visitor, guest
**Registered Agent**: An Agent with an SHD.build account. _Avoid_: Registered
user, member
**Modeling Session**: An interactive agentic work session that prepares one
Mechanic Program at a time for a Registered Agent to confirm in chat before the
session submits it through an existing ISAC action. _Avoid_: Agent, Modeling
Client, bulk job
**Contributor**: A Registered Agent who has accepted the contributor guidelines
and may submit proposed Game Data changes for review. _Avoid_: Editor when the
Agent cannot change Canonical Game Data directly
**Operator**: A Registered Agent performing an authorized task in ISAC.
Contributor, reviewer, moderator, and administrator authority remain distinct
from this situational term. _Avoid_: Admin as a generic name for anyone using
ISAC
**Oversight**: The human review function for proposed Game Data, moderated
Community Content, and identity assets. Use the qualified names Data Oversight,
Community Oversight, Guide Oversight, and Avatar Oversight when the review area
matters. _Avoid_: Moderation as a name for every review function
## Planning and shared content
**Builder**: The planning tool an Agent uses to configure a Loadout and inspect
supported calculations. _Avoid_: Build when referring to the tool
**Loadout**: A complete planned character configuration, including selected
Equipment, progression choices, and combat assumptions. A Loadout may exist
without becoming a saved Build. _Avoid_: Build when persistence, ownership, or
sharing matters
**Loadout Draft**: An editable Loadout that has not become a saved Build.
Anonymous and Registered Agents may both work with drafts. _Avoid_: Build draft
**Build**: A saved, owned, and shareable planning artifact whose central content
is a Loadout. A Build may be Private, Unlisted, or Public and may derive from
another Build. _Avoid_: Loadout when persistence, ownership, or sharing matters
**Guide**: A revisioned long-form community article that may include snapshots
of one or more Builds. A Guide is prose-led content rather than a Loadout
container. _Avoid_: Build guide when referring to every Guide
**News Article**: A revisioned editorial or syndicated article published through
the News channel. _Avoid_: Guide, post
**Article Revision**: An immutable edition of a Guide or News Article. Editors
select one revision for publication while later revisions may await review.
_Avoid_: Version when referring to published article history
**Community Content**: Agent-authored comments, profile biographies, custom
avatars, and Guides governed by the shared moderation lifecycle. _Avoid_:
User-generated content, UGC
**Community Note**: A visible comment that Community Oversight pins to a Public
Database discussion. It remains Community Content and follows the same removal
rules as other comments. _Avoid_: Official correction, staff note
**Content Report**: An Agent's request for Oversight to review visible Community
Content, with no immediate change to the content's visibility. _Avoid_: Takedown
request
**Public Database**: The Agent-facing reference view of Canonical Game Data.
_Avoid_: Database when the term could mean application storage
## Game Data and governance
**Game Data**: Community-maintained structured facts about _The Division
Resurgence_ used by the Public Database, Builder, Builds, and contribution
workflow. _Avoid_: Source data, builder data, reference data
**Canonical Game Data**: The authoritative, approved body of Game Data. _Avoid_:
Live data, production data
**Canonical Record**: One authoritative record within Canonical Game Data.
_Avoid_: Approved proposal
**Contribution Proposal**: A pending request from a Contributor to create or
change Canonical Game Data. Approval still requires the proposed change to
satisfy the canonical rules for its record family. _Avoid_: Draft record,
pending record
**ISAC**: The operational console for Game Data, contribution review, community
governance, identity and access management, audit history, and system
operations. _Avoid_: Admin panel, calculation engine
**Registry**: An ISAC workspace containing one family of related records and its
management controls. _Avoid_: Table, list page
**Audit Event**: An immutable account of a consequential operation or review
decision, including the actor, target, and change evidence. _Avoid_: Audit-log
row, activity log
**Compensating Reversion**: A new operation that restores an earlier state while
preserving the original Audit Event and recording the reversal. _Avoid_:
Rollback, undo when either implies rewriting history
## Equipment and progression
**Equipment**: The items and enhancements selected for a Loadout, including
Weapons, Gear, Weapon Mods, Gear Mods, Skill Chips, and an OS Protocol. _Avoid_:
Item when the equipment relationship matters
**Gear**: Equippable protective equipment assigned to a character slot. Gear may
provide core values, Attributes, a Brand Set, a Talent, and augmentation
capacity. _Avoid_: Armor as a collective name for all Gear
**Body Armor**: The canonical name for the equippable torso Gear slot. _Avoid_:
Vest
**Weapon**: An equippable firearm with a Weapon Category, damage and handling
properties, progression values, and applicable Talents and Mods. _Avoid_: Gun
when referring to the modeled record
**Weapon Category**: The classification that groups Weapons as Shotgun, Rifle,
MMR, AR, LMG, or SMG. _Avoid_: Weapon type, weapon family
**Weapon Mod**: An enhancement fitted to a compatible Weapon slot. Regular and
Exotic Weapon Mods follow different selection rules. _Avoid_: Attachment
**Gear Mod**: An enhancement fitted to Gear according to the Gear's available
mod capacity. _Avoid_: Tactical Augment
**Tactical Augment**: A numbered augmentation position recorded on selected Gear
in a Loadout. _Avoid_: Gear Mod
**Attribute**: A named measurable game property with defined units and
calculation meaning. _Avoid_: Stat when referring to the canonical Attribute
catalog
**Core Attribute**: One of the three primary character alignments: Firepower,
Toughness, or Engineering. _Avoid_: Main stat, primary stat
**Brand Set**: A Gear identity whose bonuses depend on how many pieces from that
set the Loadout equips. _Avoid_: Gear set
**Quality**: The item classification Standard, Specialized, Superior, or
High-end. Quality governs available or scaled properties for applicable
Equipment. _Avoid_: Rarity
**Exotic**: A special scope used by certain Weapons, Talents, and Weapon Mods.
Exotic is not a fifth Quality. _Avoid_: Exotic quality
**Item Level**: An Equipment progression coordinate used to resolve
level-dependent values. _Avoid_: Tier, Quality
**Equipment Tier**: The T0, T1, or T2 progression band that controls Equipment
capabilities and values. _Avoid_: Talent Tier, Item Level
**Talent Tier**: The Tier I or Tier II value variant of a Talent. _Avoid_:
Equipment Tier, T1, T2 when the distinction could be unclear
**Reference Level**: The Item Level at which an observed value or range applies.
_Avoid_: Base level
**Hidden Base**: A level-independent value inferred from observed Equipment
values and the game's progression rules. _Avoid_: Displayed Value, Raw Value
**Raw Value**: A calculated value before the presentation rules that reproduce
the game's displayed number. _Avoid_: Hidden Base, Displayed Value
**Displayed Value**: The player-visible number produced after applying the
game's presentation rules to a Raw Value. _Avoid_: Raw Value
**OS Protocol**: A single equipped progression item with a Quality, Core
Attribute alignment, primary effect, inherited secondary profile, and
upgradeable Talent. _Avoid_: Protocol when the operating-system meaning could be
inferred
**Skill**: A selectable combat capability associated with a Specialization.
Skills may own Skill Chip Sets and may have explicit compatibility relationships
with another Skill. _Avoid_: Ability or Specialization Ability for the
selectable game concept
**Signature Skill**: A Specialization's defining Skill, distinguished from its
other selectable Skills. _Avoid_: Signature ability
**Skill Chip**: An Equipment selection that modifies the Skill occupying its
Loadout position. Skill Chips belong to a Skill Chip Set and may provide
primary, secondary, and set effects. _Avoid_: Chip when the equipment family is
unclear
**Skill Chip Set**: A reusable Skill Chip definition associated with a Skill,
including its set bonus and optional Talent. An explicit compatibility
relationship may let another Skill equip the set. _Avoid_: Skill set
**Specialization**: A character progression identity containing Focuses, Skills,
and progression choices. _Avoid_: Class
**Focus**: A path within a Specialization aligned to one Core Attribute and
defining a selection of Skills and progression choices. _Avoid_: Subclass,
specialization path
**Talent**: A named conditional behavior owned by its source, such as a Weapon,
Gear item, OS Protocol, or Skill Chip Set. Different Talent sources may use
different progression variants. _Avoid_: Perk, passive
## Modeled mechanics
**Mechanic Program**: The structured, source-owned description of a Talent or
other conditional behavior. It captures the conditions, state changes, and
outcomes needed to evaluate that behavior. _Avoid_: Script, Trigger record
**Event**: An observed occurrence on a combat timeline that a Mechanic Program
may inspect. _Avoid_: Trigger when referring to the occurrence itself
**Trigger Condition**: The criteria that an Event must satisfy before a mechanic
can proceed toward Activation. A Trigger Condition is part of a Mechanic
Program, not a standalone Game Data record. _Avoid_: Trigger as an entity
**Activation**: A successful mechanic occurrence after its Event, conditions,
chance, and Cooldown requirements resolve. _Avoid_: Proc when precision matters
**Cooldown**: The period after a successful Activation during which the same
mechanic cannot activate again. A failed chance does not begin the Cooldown.
_Avoid_: Delay
**Mechanic State**: A value retained across Events for one mechanic, such as a
flag, count, stack, duration, mark, or resource. _Avoid_: Runtime state when
discussing game behavior
**Outcome**: The effect emitted by an activated mechanic, such as an Attribute
change, damage, restoration, resource change, or marker. _Avoid_: Effect when
the source Talent and emitted result could be confused
**Combat Profile**: The encounter assumptions and observed rates used to project
a Loadout's combat performance. _Avoid_: Simulation when no event simulation
occurs
**Scenario Input**: An explicit encounter assumption required to evaluate a
mechanic whose result cannot be determined from the Loadout alone. _Avoid_:
Guess, default assumption
**Ready**: The mechanic readiness state indicating that typed Game Data can
evaluate the mechanic without additional Scenario Inputs. _Avoid_: Complete
**Requires Assumptions**: The mechanic readiness state indicating that
evaluation needs one or more explicit Scenario Inputs. _Avoid_: Ready,
unsupported
**Captured Only**: The mechanic readiness state indicating that SHD.build
preserves the authored behavior but cannot calculate it. _Avoid_: Unsupported
when the behavior has still been recorded
**Extra Health**: Temporary Health granted in addition to an Agent's normal
Health. Each grant remains distinct from later changes to the current Extra
Health total. _Avoid_: Health, healing, bonus armor
**Hit Taken**: A hit received by an Agent, including one absorbed by Extra
Health. A Hit Taken does not require normal Health loss. _Avoid_: Taking Damage
**Taking Damage**: A loss of an Agent's normal Health. A hit absorbed by Extra
Health does not count as Taking Damage. _Avoid_: Hit Taken
+2 -17
View File
@@ -32,23 +32,8 @@ npm run db:seed-users
The seed creates `Aewyn` and `Quartermaster` with the standard user role. It
generates and displays strong temporary passwords once, then stores only salted
Argon2id hashes. `DEFAULT_ADMIN_PASSWORD` is the password variable name for
`Aewyn`; it does not grant administrator authority.
Sign-in never grants administrator authority automatically. For local
development, give the target account a verified email, enroll TOTP at
`/account/security`, and save its one-time recovery codes. Stop the development
server, then run:
```sh
npm run admin:bootstrap -- <verified-email>
```
The offline command requires an active TOTP factor and an unused recovery code,
revokes the target account's sessions, and refuses to run when an active full
administrator already exists. Restart the development server after it succeeds.
See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) for staging and production
operation.
Argon2id hashes. The separate bootstrap policy promotes the first authenticated
account when no administrator exists.
## Develop
+261 -57
View File
@@ -555,7 +555,7 @@ CREATE TABLE IF NOT EXISTS equipment_types (id TEXT PRIMARY KEY, name TEXT NOT N
CREATE TABLE IF NOT EXISTS stat_definitions (id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE, value_kind TEXT NOT NULL, min_value REAL, max_value REAL, unit TEXT, active INTEGER NOT NULL DEFAULT 1);
CREATE TABLE IF NOT EXISTS stat_equipment_types (stat_id TEXT NOT NULL REFERENCES stat_definitions(id), equipment_type_id TEXT NOT NULL REFERENCES equipment_types(id), PRIMARY KEY(stat_id, equipment_type_id));
CREATE TABLE IF NOT EXISTS audit_log (id TEXT PRIMARY KEY, actor_id TEXT NOT NULL REFERENCES users(id), entity_type TEXT NOT NULL, entity_id TEXT NOT NULL, action TEXT NOT NULL, before_json TEXT, after_json TEXT, created_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, token_hash TEXT NOT NULL UNIQUE, expires_at TEXT NOT NULL, created_at TEXT NOT NULL, aal INTEGER NOT NULL DEFAULT 1 CHECK(aal IN (1,2)), aal_verified_at TEXT NOT NULL, aal2_verified_at TEXT);
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, token_hash TEXT NOT NULL UNIQUE, expires_at TEXT NOT NULL, created_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS roles (id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE, description TEXT);
CREATE TABLE IF NOT EXISTS deleted_roles (role_id TEXT PRIMARY KEY, deleted_at TEXT NOT NULL, deleted_by TEXT NOT NULL REFERENCES users(id));
CREATE TABLE IF NOT EXISTS permissions (id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE, description TEXT);
@@ -591,8 +591,6 @@ CREATE TABLE IF NOT EXISTS login_events (
session_ended_at TEXT,
session_end_reason TEXT,
sensitive_purged_at TEXT,
aal INTEGER CHECK(aal IS NULL OR aal IN (1,2)),
aal2_verified_at TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS user_emails (
@@ -645,60 +643,6 @@ CREATE TABLE IF NOT EXISTS deleted_accounts (
reason TEXT
);
CREATE INDEX IF NOT EXISTS login_events_user_created_idx ON login_events(user_id, created_at DESC);
CREATE TABLE IF NOT EXISTS mfa_totp_factors (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
state TEXT NOT NULL CHECK(state IN ('pending','active','revoked')),
encrypted_secret TEXT NOT NULL,
encryption_key_id TEXT NOT NULL,
issuer TEXT NOT NULL DEFAULT 'SHD.build',
account_label TEXT NOT NULL,
algorithm TEXT NOT NULL DEFAULT 'SHA1' CHECK(algorithm='SHA1'),
digits INTEGER NOT NULL DEFAULT 6 CHECK(digits=6),
period_seconds INTEGER NOT NULL DEFAULT 30 CHECK(period_seconds=30),
last_counter INTEGER,
failed_attempts INTEGER NOT NULL DEFAULT 0 CHECK(failed_attempts BETWEEN 0 AND 5),
locked_until TEXT,
expires_at TEXT,
created_at TEXT NOT NULL,
activated_at TEXT,
revoked_at TEXT,
CHECK((state='pending' AND expires_at IS NOT NULL AND activated_at IS NULL AND revoked_at IS NULL)
OR (state='active' AND activated_at IS NOT NULL AND expires_at IS NULL AND revoked_at IS NULL)
OR (state='revoked' AND revoked_at IS NOT NULL))
);
CREATE UNIQUE INDEX IF NOT EXISTS mfa_totp_factors_one_active_idx
ON mfa_totp_factors(user_id) WHERE state='active';
CREATE UNIQUE INDEX IF NOT EXISTS mfa_totp_factors_one_pending_idx
ON mfa_totp_factors(user_id) WHERE state='pending';
CREATE INDEX IF NOT EXISTS mfa_totp_factors_expiry_idx
ON mfa_totp_factors(state,expires_at) WHERE state='pending';
CREATE TABLE IF NOT EXISTS mfa_recovery_codes (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
code_hash TEXT NOT NULL,
created_at TEXT NOT NULL,
consumed_at TEXT,
revoked_at TEXT,
UNIQUE(user_id,code_hash)
);
CREATE INDEX IF NOT EXISTS mfa_recovery_codes_available_idx
ON mfa_recovery_codes(user_id,consumed_at,revoked_at);
CREATE TABLE IF NOT EXISTS authentication_transactions (
id TEXT PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
provider TEXT CHECK(provider IS NULL OR provider IN ('password','discord','magic_link','passkey')),
kind TEXT NOT NULL CHECK(kind IN ('login','step_up')),
return_path TEXT NOT NULL CHECK(length(return_path) BETWEEN 1 AND 2048 AND substr(return_path,1,1)='/'),
required_aal INTEGER NOT NULL DEFAULT 2 CHECK(required_aal=2),
attempt_count INTEGER NOT NULL DEFAULT 0 CHECK(attempt_count BETWEEN 0 AND 5),
expires_at TEXT NOT NULL,
consumed_at TEXT,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS authentication_transactions_expiry_idx
ON authentication_transactions(expires_at);
INSERT OR IGNORE INTO roles(id,name,description) VALUES('role-data-editor','Data Editor','Access to ISAC game-data management');
INSERT OR IGNORE INTO roles(id,name,description) VALUES('role-user-operator','User Operator','View and moderate SHD.build users');
INSERT OR IGNORE INTO roles(id,name,description) VALUES('role-access-manager','Access Manager','Manage user roles and direct permissions');
@@ -982,6 +926,266 @@ CREATE TABLE IF NOT EXISTS conditional_effect_outcomes (
);
CREATE INDEX IF NOT EXISTS conditional_effect_outcomes_rule_idx
ON conditional_effect_outcomes(rule_id,variant_key,outcome_key,sort_order);
-- Phase 2 mechanic persistence. Revision rows are append-only by application
-- convention. No database triggers enforce immutability.
CREATE TABLE IF NOT EXISTS mechanic_authored_sources (
id TEXT PRIMARY KEY,
owner_type TEXT NOT NULL CHECK(owner_type IN (
'talent','os_protocol_talent','skill_chip_talent','specialization_tree_rank'
)),
owner_id TEXT NOT NULL CHECK(length(trim(owner_id))>0),
template TEXT NOT NULL CHECK(length(trim(template))>0),
authored_contract_version INTEGER NOT NULL CHECK(authored_contract_version>0),
source_fingerprint TEXT NOT NULL CHECK(
length(source_fingerprint)=64
AND lower(source_fingerprint)=source_fingerprint
AND source_fingerprint NOT GLOB '*[^0-9a-f]*'
),
talent_scope TEXT CHECK(talent_scope IS NULL OR talent_scope IN ('standard','exotic')),
talent_has_tier_ii INTEGER CHECK(talent_has_tier_ii IS NULL OR talent_has_tier_ii IN (0,1)),
specialization_rank_description TEXT,
specialization_effect_id TEXT,
specialization_effect_template TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(owner_type,owner_id),
CHECK(
(owner_type='talent'
AND talent_scope IS NOT NULL
AND specialization_rank_description IS NULL
AND specialization_effect_id IS NULL
AND specialization_effect_template IS NULL)
OR
(owner_type='specialization_tree_rank'
AND talent_scope IS NULL
AND talent_has_tier_ii IS NULL
AND specialization_rank_description IS NOT NULL
AND length(trim(specialization_rank_description))>0
AND specialization_effect_id IS NOT NULL
AND length(trim(specialization_effect_id))>0
AND specialization_effect_template IS NOT NULL
AND length(trim(specialization_effect_template))>0)
OR
(owner_type IN ('os_protocol_talent','skill_chip_talent')
AND talent_scope IS NULL
AND talent_has_tier_ii IS NULL
AND specialization_rank_description IS NULL
AND specialization_effect_id IS NULL
AND specialization_effect_template IS NULL)
)
);
CREATE INDEX IF NOT EXISTS mechanic_authored_sources_owner_idx
ON mechanic_authored_sources(owner_type,owner_id);
CREATE TABLE IF NOT EXISTS mechanic_authored_variants (
source_id TEXT NOT NULL REFERENCES mechanic_authored_sources(id) ON DELETE CASCADE,
variant_key TEXT NOT NULL CHECK(length(trim(variant_key))>0),
materialized TEXT NOT NULL CHECK(length(materialized)>0),
sort_order INTEGER NOT NULL CHECK(sort_order>=0),
PRIMARY KEY(source_id,variant_key),
UNIQUE(source_id,sort_order)
);
CREATE INDEX IF NOT EXISTS mechanic_authored_variants_source_order_idx
ON mechanic_authored_variants(source_id,sort_order);
CREATE TABLE IF NOT EXISTS mechanic_authored_slots (
source_id TEXT NOT NULL,
variant_key TEXT NOT NULL,
slot_key TEXT NOT NULL CHECK(length(trim(slot_key))>0),
display_value TEXT NOT NULL CHECK(
display_value=trim(display_value)
AND display_value GLOB '*[0-9]*'
AND display_value NOT GLOB '*[^0-9.+-]*'
AND substr(display_value,2) NOT GLOB '*[+-]*'
AND length(display_value)-length(replace(display_value,'.',''))<=1
AND substr(display_value,-1)<>'.'
AND display_value NOT IN ('+','-','.','+.','-.')
),
sort_order INTEGER NOT NULL CHECK(sort_order>=0),
unit TEXT,
stat_attribute_id TEXT REFERENCES stat_attributes(id),
PRIMARY KEY(source_id,variant_key,slot_key),
UNIQUE(source_id,variant_key,sort_order),
FOREIGN KEY(source_id,variant_key)
REFERENCES mechanic_authored_variants(source_id,variant_key) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS mechanic_authored_slots_variant_order_idx
ON mechanic_authored_slots(source_id,variant_key,sort_order);
CREATE INDEX IF NOT EXISTS mechanic_authored_slots_attribute_idx
ON mechanic_authored_slots(stat_attribute_id)
WHERE stat_attribute_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS mechanic_model_revisions (
id TEXT PRIMARY KEY,
source_id TEXT NOT NULL REFERENCES mechanic_authored_sources(id) ON DELETE CASCADE,
revision_number INTEGER NOT NULL CHECK(revision_number>0),
source_fingerprint TEXT NOT NULL CHECK(
length(source_fingerprint)=64
AND lower(source_fingerprint)=source_fingerprint
AND source_fingerprint NOT GLOB '*[^0-9a-f]*'
),
mechanic_contract_version INTEGER NOT NULL CHECK(mechanic_contract_version>0),
program_hash TEXT NOT NULL CHECK(
length(program_hash)=64
AND lower(program_hash)=program_hash
AND program_hash NOT GLOB '*[^0-9a-f]*'
),
simulation_readiness TEXT NOT NULL CHECK(simulation_readiness IN ('ready','requires_assumptions','captured_only')),
scenario_inputs_json TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(scenario_inputs_json)),
source_variants_json TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(source_variants_json)),
program_name TEXT NOT NULL CHECK(length(trim(program_name))>0),
origin TEXT NOT NULL CHECK(length(trim(origin))>0),
actor_id TEXT REFERENCES users(id) ON DELETE SET NULL,
created_at TEXT NOT NULL,
UNIQUE(source_id,revision_number),
UNIQUE(source_id,id)
);
CREATE INDEX IF NOT EXISTS mechanic_model_revisions_source_created_idx
ON mechanic_model_revisions(source_id,revision_number DESC,created_at DESC);
CREATE INDEX IF NOT EXISTS mechanic_model_revisions_fingerprint_idx
ON mechanic_model_revisions(source_id,source_fingerprint);
CREATE TABLE IF NOT EXISTS mechanic_model_revision_pools (
id TEXT PRIMARY KEY,
revision_id TEXT NOT NULL REFERENCES mechanic_model_revisions(id) ON DELETE CASCADE,
pool_key TEXT NOT NULL CHECK(length(trim(pool_key))>0),
label TEXT NOT NULL CHECK(length(trim(label))>0),
state_kind TEXT NOT NULL CHECK(state_kind IN ('flag','count','stack','duration','scalar','target_mark','resource')),
state_scope TEXT NOT NULL CHECK(state_scope IN ('agent','target')),
initial_value REAL NOT NULL,
minimum_value REAL,
maximum_value REAL,
best_case_value REAL,
duration_seconds REAL CHECK(duration_seconds IS NULL OR duration_seconds>0),
duration_variants_json TEXT CHECK(duration_variants_json IS NULL OR json_valid(duration_variants_json)),
sort_order INTEGER NOT NULL CHECK(sort_order>=0),
UNIQUE(revision_id,id),
UNIQUE(revision_id,pool_key),
UNIQUE(revision_id,sort_order),
CHECK(minimum_value IS NULL OR maximum_value IS NULL OR maximum_value>=minimum_value),
CHECK(best_case_value IS NULL OR minimum_value IS NULL OR best_case_value>=minimum_value),
CHECK(best_case_value IS NULL OR maximum_value IS NULL OR best_case_value<=maximum_value),
CHECK(NOT (duration_seconds IS NOT NULL AND duration_variants_json IS NOT NULL))
);
CREATE INDEX IF NOT EXISTS mechanic_model_revision_pools_revision_order_idx
ON mechanic_model_revision_pools(revision_id,sort_order);
CREATE TABLE IF NOT EXISTS mechanic_model_revision_clauses (
id TEXT PRIMARY KEY,
revision_id TEXT NOT NULL REFERENCES mechanic_model_revisions(id) ON DELETE CASCADE,
clause_key TEXT NOT NULL CHECK(length(trim(clause_key))>0),
label TEXT,
event_kind TEXT NOT NULL CHECK(event_kind IN (
'shot_fired','weapon_hit','skill_deployed','signature_ability_deployed',
'skill_hit','skill_multishot_triggered','agent_hit','health_damage_taken',
'damage_dealt','enemy_killed','assist','ally_downed','agent_downed',
'ally_rescued','grenade_thrown','medical_kit_used','healing_applied',
'extra_health_granted','extra_health_changed','movement_snapshot',
'proximity_snapshot','firing_started','firing_stopped','reload_started',
'reload_completed','weapon_swapped','tick'
)),
recipe_key TEXT,
conditions_json TEXT CHECK(conditions_json IS NULL OR json_valid(conditions_json)),
reducer_json TEXT NOT NULL DEFAULT '{"kind":"none"}' CHECK(json_valid(reducer_json)),
weight_expression_json TEXT CHECK(weight_expression_json IS NULL OR json_valid(weight_expression_json)),
mutations_json TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(mutations_json)),
cooldown_seconds REAL CHECK(cooldown_seconds IS NULL OR cooldown_seconds>0),
proc_chance_percent REAL CHECK(proc_chance_percent IS NULL OR (proc_chance_percent>=0 AND proc_chance_percent<=100)),
requires_assigned_ability_active INTEGER CHECK(requires_assigned_ability_active IS NULL OR requires_assigned_ability_active IN (0,1)),
sort_order INTEGER NOT NULL CHECK(sort_order>=0),
UNIQUE(revision_id,id),
UNIQUE(revision_id,clause_key),
UNIQUE(revision_id,sort_order)
);
CREATE INDEX IF NOT EXISTS mechanic_model_revision_clauses_revision_order_idx
ON mechanic_model_revision_clauses(revision_id,sort_order);
CREATE INDEX IF NOT EXISTS mechanic_model_revision_clauses_event_idx
ON mechanic_model_revision_clauses(event_kind,revision_id,sort_order);
CREATE TABLE IF NOT EXISTS mechanic_model_revision_outcomes (
id TEXT PRIMARY KEY,
revision_id TEXT NOT NULL REFERENCES mechanic_model_revisions(id) ON DELETE CASCADE,
clause_id TEXT NOT NULL,
state_pool_id TEXT,
effect_key TEXT NOT NULL CHECK(length(trim(effect_key))>0),
variant_key TEXT NOT NULL CHECK(length(trim(variant_key))>0),
label TEXT NOT NULL CHECK(length(trim(label))>0),
outcome_kind TEXT NOT NULL CHECK(outcome_kind IN ('attribute_modifier','direct_damage','restoration','resource_cost','weapon_reload','marker')),
effect_scope TEXT NOT NULL CHECK(effect_scope IN ('self','equipped_weapon','inactive_weapon','target','allies','self_and_allies','assigned_ability','all_skills')),
value REAL NOT NULL,
value_expression_json TEXT CHECK(value_expression_json IS NULL OR json_valid(value_expression_json)),
value_basis TEXT NOT NULL CHECK(value_basis IN ('flat','max_health_percent','current_health_percent','weapon_base_percent')),
resource_kind TEXT CHECK(resource_kind IS NULL OR resource_kind IN ('health','armor','ammo','signature_ability_charge')),
delivery_mode TEXT NOT NULL DEFAULT 'instant' CHECK(delivery_mode IN ('instant','continuous')),
delivery_duration_seconds REAL CHECK(delivery_duration_seconds IS NULL OR delivery_duration_seconds>0),
application_phase TEXT NOT NULL CHECK(application_phase IN ('on_event','after_event','on_enter','on_exit','while_active')),
combat_timing TEXT CHECK(combat_timing IS NULL OR combat_timing IN ('pre_event','current')),
stat_attribute_id TEXT REFERENCES stat_attributes(id),
per_stack INTEGER CHECK(per_stack IS NULL OR per_stack IN (0,1)),
min_state_value REAL CHECK(min_state_value IS NULL OR min_state_value>=0),
max_state_value REAL CHECK(max_state_value IS NULL OR max_state_value>=0),
targeting_json TEXT CHECK(targeting_json IS NULL OR json_valid(targeting_json)),
probability_percent REAL CHECK(probability_percent IS NULL OR (probability_percent>=0 AND probability_percent<=100)),
sort_order INTEGER NOT NULL CHECK(sort_order>=0),
UNIQUE(revision_id,id),
UNIQUE(revision_id,clause_id,variant_key,effect_key),
UNIQUE(revision_id,clause_id,variant_key,sort_order),
CHECK(max_state_value IS NULL OR min_state_value IS NULL OR max_state_value>=min_state_value),
CHECK(
(delivery_mode='instant' AND delivery_duration_seconds IS NULL)
OR (delivery_mode='continuous' AND outcome_kind='restoration' AND delivery_duration_seconds IS NOT NULL)
),
CHECK(
(outcome_kind='attribute_modifier' AND stat_attribute_id IS NOT NULL AND resource_kind IS NULL)
OR (outcome_kind IN ('restoration','resource_cost') AND stat_attribute_id IS NULL AND resource_kind IS NOT NULL)
OR (outcome_kind IN ('direct_damage','weapon_reload','marker') AND stat_attribute_id IS NULL AND resource_kind IS NULL)
),
FOREIGN KEY(revision_id,clause_id)
REFERENCES mechanic_model_revision_clauses(revision_id,id) ON DELETE CASCADE,
FOREIGN KEY(revision_id,state_pool_id)
REFERENCES mechanic_model_revision_pools(revision_id,id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS mechanic_model_revision_outcomes_clause_order_idx
ON mechanic_model_revision_outcomes(revision_id,clause_id,variant_key,sort_order);
CREATE INDEX IF NOT EXISTS mechanic_model_revision_outcomes_pool_idx
ON mechanic_model_revision_outcomes(revision_id,state_pool_id)
WHERE state_pool_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS mechanic_model_revision_outcomes_attribute_idx
ON mechanic_model_revision_outcomes(stat_attribute_id)
WHERE stat_attribute_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS mechanic_model_selections (
source_id TEXT PRIMARY KEY REFERENCES mechanic_authored_sources(id) ON DELETE CASCADE,
revision_id TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY(source_id,revision_id)
REFERENCES mechanic_model_revisions(source_id,id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS mechanic_model_selections_revision_idx
ON mechanic_model_selections(revision_id,source_id);
CREATE TABLE IF NOT EXISTS mechanic_public_variants (
source_id TEXT NOT NULL,
variant_key TEXT NOT NULL,
selected_revision_id TEXT,
current_source_fingerprint TEXT NOT NULL CHECK(
length(current_source_fingerprint)=64
AND lower(current_source_fingerprint)=current_source_fingerprint
AND current_source_fingerprint NOT GLOB '*[^0-9a-f]*'
),
authored_contract_version INTEGER NOT NULL CHECK(authored_contract_version>0),
mechanic_contract_version INTEGER CHECK(mechanic_contract_version IS NULL OR mechanic_contract_version>0),
status TEXT NOT NULL CHECK(status IN ('modeled','not_modeled')),
behavior_text TEXT NOT NULL CHECK(length(behavior_text)>0),
display_source TEXT NOT NULL CHECK(display_source IN ('model','authored')),
updated_at TEXT NOT NULL,
PRIMARY KEY(source_id,variant_key),
CHECK(
(display_source='model' AND status='modeled' AND selected_revision_id IS NOT NULL)
OR (display_source='authored' AND status='not_modeled')
),
FOREIGN KEY(source_id,variant_key)
REFERENCES mechanic_authored_variants(source_id,variant_key) ON DELETE CASCADE,
FOREIGN KEY(source_id,selected_revision_id)
REFERENCES mechanic_model_revisions(source_id,id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS mechanic_public_variants_status_idx
ON mechanic_public_variants(status,source_id,variant_key);
CREATE INDEX IF NOT EXISTS mechanic_public_variants_revision_idx
ON mechanic_public_variants(selected_revision_id)
WHERE selected_revision_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS talent_tier_effects (
id TEXT PRIMARY KEY,
talent_tier_id TEXT NOT NULL REFERENCES talent_tiers(id) ON DELETE CASCADE,
+265
View File
@@ -0,0 +1,265 @@
import { connect, type Database } from '@tursodatabase/database';
import { readFile } from 'node:fs/promises';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
let database: Database;
const applySchema = async (target: Database) => {
const schema = await readFile(new URL('./schema.sql', import.meta.url), 'utf8');
for (const statement of schema
.split(';')
.map((value) => value.trim())
.filter(Boolean)) {
await target.exec(statement);
}
};
const insertSource = async (
target: Database,
id: string,
ownerId: string,
fingerprint: string,
) => {
await (
await target.prepare(
`INSERT INTO mechanic_authored_sources(
id,owner_type,owner_id,template,authored_contract_version,source_fingerprint,
talent_scope,talent_has_tier_ii,created_at,updated_at
) VALUES(?,?,?,?,?,?,?,?,?,?)`,
)
).run(
id,
'talent',
ownerId,
'Gain {1}',
1,
fingerprint,
'standard',
1,
'2026-08-27T00:00:00.000Z',
'2026-08-27T00:00:00.000Z',
);
};
describe('mechanic persistence schema', () => {
beforeEach(async () => {
database = await connect(':memory:');
await database.exec('PRAGMA foreign_keys=ON');
await applySchema(database);
});
afterEach(async () => {
await database.close();
});
it('installs the complete schema with clean foreign keys', async () => {
const rows = await (
await database.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'mechanic_%' ORDER BY name",
)
).all();
expect(rows.map((row) => row.name)).toEqual([
'mechanic_authored_slots',
'mechanic_authored_sources',
'mechanic_authored_variants',
'mechanic_model_revision_clauses',
'mechanic_model_revision_outcomes',
'mechanic_model_revision_pools',
'mechanic_model_revisions',
'mechanic_model_selections',
'mechanic_public_variants',
]);
expect(await (await database.prepare('PRAGMA foreign_key_check')).all()).toEqual([]);
});
it('enforces owner metadata, ordered authored children, and source cascades', async () => {
const fingerprint = 'a'.repeat(64);
await insertSource(database, 'source-1', 'talent-1', fingerprint);
await expect(
insertSource(database, 'source-2', 'talent-1', fingerprint),
).rejects.toThrow();
await expect(
database.exec(
`INSERT INTO mechanic_authored_sources(
id,owner_type,owner_id,template,authored_contract_version,source_fingerprint,
specialization_rank_description,specialization_effect_id,specialization_effect_template,
created_at,updated_at
) VALUES('source-3','talent','talent-3','Gain',1,'${fingerprint}',
'rank','effect','template','now','now')`,
),
).rejects.toThrow();
await (
await database.prepare(
`INSERT INTO mechanic_authored_variants(source_id,variant_key,materialized,sort_order)
VALUES('source-1','I','Gain 1',0),('source-1','II','Gain 2',1)`,
)
).run();
await (
await database.prepare(
`INSERT INTO mechanic_authored_slots(
source_id,variant_key,slot_key,display_value,sort_order
) VALUES('source-1','I','1','1',0)`,
)
).run();
await expect(
database.exec(
`INSERT INTO mechanic_authored_slots(
source_id,variant_key,slot_key,display_value,sort_order
) VALUES('source-1','missing','1','1',0)`,
),
).rejects.toThrow();
await expect(
database.exec(
`INSERT INTO mechanic_authored_slots(
source_id,variant_key,slot_key,display_value,sort_order
) VALUES('source-1','II','1','10% Weapon Damage',0)`,
),
).rejects.toThrow();
await database.exec("DELETE FROM mechanic_authored_sources WHERE id='source-1'");
for (const table of [
'mechanic_authored_variants',
'mechanic_authored_slots',
]) {
expect(
await (
await database.prepare(`SELECT COUNT(*) AS count FROM ${table}`)
).get(),
).toMatchObject({ count: 0 });
}
});
it('allows deliberate duplicate graphs while proving selection ownership', async () => {
const sourceFingerprint = 'a'.repeat(64);
const programHash = 'b'.repeat(64);
await insertSource(database, 'source-1', 'talent-1', sourceFingerprint);
await (
await database.prepare(
`INSERT INTO mechanic_authored_variants(source_id,variant_key,materialized,sort_order)
VALUES('source-1','I','Gain 1',0)`,
)
).run();
await (
await database.prepare(
`INSERT INTO mechanic_model_revisions(
id,source_id,revision_number,source_fingerprint,mechanic_contract_version,
program_hash,simulation_readiness,scenario_inputs_json,source_variants_json,
program_name,origin,created_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`,
)
).run(
'revision-1',
'source-1',
1,
sourceFingerprint,
1,
programHash,
'ready',
'[]',
'["I"]',
'Model',
'manual',
'now',
);
await (
await database.prepare(
`INSERT INTO mechanic_model_revisions(
id,source_id,revision_number,source_fingerprint,mechanic_contract_version,
program_hash,simulation_readiness,scenario_inputs_json,source_variants_json,
program_name,origin,created_at
) SELECT 'revision-2',source_id,2,source_fingerprint,mechanic_contract_version,
program_hash,simulation_readiness,scenario_inputs_json,source_variants_json,
program_name,origin,created_at FROM mechanic_model_revisions WHERE id='revision-1'`,
)
).run();
await expect(
database.exec(
`INSERT INTO mechanic_model_revisions(
id,source_id,revision_number,source_fingerprint,mechanic_contract_version,
program_hash,simulation_readiness,scenario_inputs_json,source_variants_json,
program_name,origin,created_at
) SELECT 'revision-3',source_id,1,source_fingerprint,mechanic_contract_version,
program_hash,simulation_readiness,scenario_inputs_json,source_variants_json,
program_name,origin,created_at FROM mechanic_model_revisions WHERE id='revision-1'`,
),
).rejects.toThrow();
await (
await database.prepare(
`INSERT INTO mechanic_model_selections(source_id,revision_id,updated_at)
VALUES('source-1','revision-2','now')`,
)
).run();
await expect(
database.exec(
`INSERT INTO mechanic_model_selections(source_id,revision_id,updated_at)
VALUES('source-1','not-this-source','now')`,
),
).rejects.toThrow();
await (
await database.prepare(
`INSERT INTO mechanic_model_revision_pools(
id,revision_id,pool_key,label,state_kind,state_scope,initial_value,
minimum_value,maximum_value,best_case_value,duration_seconds,
duration_variants_json,sort_order
) VALUES('pool-1','revision-1','stacks','Stacks','stack','agent',0,0,5,5,NULL,NULL,0)`,
)
).run();
await (
await database.prepare(
`INSERT INTO mechanic_model_revision_clauses(
id,revision_id,clause_key,label,event_kind,recipe_key,conditions_json,
reducer_json,weight_expression_json,mutations_json,cooldown_seconds,
proc_chance_percent,requires_assigned_ability_active,sort_order
) VALUES('clause-1','revision-1','on-hit','On hit','weapon_hit',NULL,NULL,
'{"kind":"none"}',NULL,'[]',NULL,25,NULL,0)`,
)
).run();
await (
await database.prepare(
`INSERT INTO mechanic_model_revision_outcomes(
id,revision_id,clause_id,state_pool_id,effect_key,variant_key,label,
outcome_kind,effect_scope,value,value_expression_json,value_basis,
resource_kind,delivery_mode,delivery_duration_seconds,application_phase,
combat_timing,stat_attribute_id,per_stack,min_state_value,max_state_value,
targeting_json,probability_percent,sort_order
) VALUES('outcome-1','revision-1','clause-1','pool-1','mark','I','Mark',
'marker','self',1,NULL,'flat',NULL,'instant',NULL,'while_active','current',
NULL,0,NULL,NULL,NULL,NULL,0)`,
)
).run();
await (
await database.prepare(
`INSERT INTO mechanic_public_variants(
source_id,variant_key,selected_revision_id,current_source_fingerprint,
authored_contract_version,mechanic_contract_version,status,behavior_text,
display_source,updated_at
) VALUES('source-1','I','revision-1',?,1,1,'modeled','Modeled behavior','model','now')`,
)
).run(sourceFingerprint);
await database.exec("DELETE FROM mechanic_authored_sources WHERE id='source-1'");
for (const table of [
'mechanic_authored_variants',
'mechanic_authored_slots',
'mechanic_model_revisions',
'mechanic_model_revision_pools',
'mechanic_model_revision_clauses',
'mechanic_model_revision_outcomes',
'mechanic_model_selections',
'mechanic_public_variants',
]) {
expect(
await (
await database.prepare(`SELECT COUNT(*) AS count FROM ${table}`)
).get(),
).toMatchObject({ count: 0 });
}
});
});
+2 -2
View File
@@ -3,7 +3,7 @@ name: shd-build-production
services:
app:
image: ${SHD_IMAGE:-shd-build-production:local}
restart: unless-stopped
restart: always
init: true
environment:
INFISICAL_PROJECT_ID: 2ee94b27-e599-4194-9797-3372d42e53f6
@@ -42,7 +42,7 @@ services:
scheduler:
image: ${SHD_IMAGE:-shd-build-production:local}
restart: unless-stopped
restart: always
init: true
command:
- scheduler
+5 -6
View File
@@ -140,12 +140,12 @@ describe('container runtime startup', () => {
writeFile(join(temporaryRoot, 'chown'), ownershipStub, { mode: 0o755 }),
writeExport(appExport, [
{ key: 'APP_ORIGIN', value: 'https://exported.invalid' },
{
key: 'MFA_TOTP_ENCRYPTION_KEYS',
value: 'primary:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
},
{ key: 'DISCORD_CLIENT_ID', value: 'exported-discord-client' },
{ key: 'DISCORD_CLIENT_SECRET', value: 'exported-discord-secret' },
{
key: 'MFA_TOTP_ENCRYPTION_KEYS',
value: 'totp-encryption-keyring',
},
]),
writeExport(sharedExport, [
{ key: 'SCHEDULER_TOKEN', value: schedulerToken },
@@ -222,10 +222,9 @@ describe('container runtime startup', () => {
);
expect(childEnvironment).toMatchObject({
APP_ORIGIN: 'https://stage.shd.build',
MFA_TOTP_ENCRYPTION_KEYS:
'primary:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
DISCORD_CLIENT_ID: 'exported-discord-client',
DISCORD_CLIENT_SECRET: 'exported-discord-secret',
MFA_TOTP_ENCRYPTION_KEYS: 'totp-encryption-keyring',
ORIGIN: 'https://stage.shd.build',
PASSKEY_RP_ID: 'shd.build',
SCHEDULER_TOKEN: schedulerToken,
+3 -81
View File
@@ -98,81 +98,9 @@ remove the old dotenv private keys and `SCHEDULER_TOKEN_PRODUCTION` from Gitea,
and delete local and hosted dotenv key material. Removing encrypted files from
the current Git tree does not revoke values stored in Git history.
## Authentication bootstrap and MFA secrets
Set the required app-only `MFA_TOTP_ENCRYPTION_KEYS` secret under `/app` in the
`dev`, `staging`, and `prod` Infisical environments before starting each app.
The value contains one to three comma-separated, unique
`key-id:canonical-base64url-32-byte-key` entries. Each key is a random 32-byte
value encoded as canonical Base64URL. The first entry is the active write key;
following entries are retained decryption keys for older TOTP factors. Do not
put this secret under `/shared/scheduler`, in a Gitea variable, in the image, or
in a deployment log. A missing, malformed, duplicate, or overlong keyring fails
app runtime validation.
Rotate the keyring without losing access to existing factors:
1. Generate a new random 32-byte key in the approved secret-management process
and assign it a new key ID. Do not copy the value into a document or shell
history.
2. Prepend the new `key-id` entry and retain the old entries in Infisical.
3. Deploy or restart the app, then verify an existing TOTP sign-in and a new
enrollment. A successful verification rewraps that factor under the first
key.
4. Retain each old key until every factor encrypted with it has been rewrapped
and verified. Never remove old entries merely because new enrollments use the
new key; losing a required old key prevents decryption of those factors.
TOTP enrollment issues ten recovery codes and displays them once. The database
stores only their domain-separated hashes. The account owner must save the codes
in an offline password manager or another protected offline record; do not put
their values in Infisical, logs, tickets, backups, audit snapshots, or this
documentation. Each code works once. Regenerating codes immediately revokes all
unused previous codes and displays a replacement set once. Disabling TOTP also
revokes its recovery codes.
Sign-in never grants administrator authority automatically. Before offline
elevation, the target administrator must have a verified email, an active TOTP
factor, and at least one unused recovery code. The target enrolls TOTP at
`/account/security` while the app is running. Then stop every app and scheduler
service that can access the database and run the environment-specific command.
The command requires that no active full administrator already exists, assigns
the canonical administrator role, revokes the target's sessions, and records
`role_management / administrator.bootstrapped`.
For local development:
```sh
npm run admin:bootstrap -- <verified-email>
```
For staging, from `/opt/shd-build-stage`:
```sh
docker compose --env-file .env.deploy -f compose.staging.yml stop scheduler app
docker compose --env-file .env.deploy -f compose.staging.yml run --rm --no-deps \
app node scripts/admin-bootstrap.mjs <verified-email>
docker compose --env-file .env.deploy -f compose.staging.yml up -d app scheduler
```
For production, from `/opt/shd-build-production`:
```sh
docker compose --env-file .env.deploy -f compose.production.yml stop scheduler app
docker compose --env-file .env.deploy -f compose.production.yml run --rm --no-deps \
app node scripts/admin-bootstrap.mjs <verified-email>
docker compose --env-file .env.deploy -f compose.production.yml up -d app scheduler
```
The script requires exactly one active, unblocked account with a verified email,
an active TOTP factor, and an unused recovery code. It exits without changing
roles when an active full administrator already exists. The Compose commands
restart their services; restart the local development server after its command.
The target must sign in again because its old sessions were revoked.
The staging container disables default-user seeding. A first sign-in never
receives Admin; use the offline flow above after a new database or an initial
data bootstrap.
The staging container disables default-user seeding. On a brand-new staging
database, the existing bootstrap policy grants Admin to the first real account
that signs in instead of writing generated credentials into deployment logs.
## Gitea Actions runner
@@ -460,12 +388,6 @@ import. The importer verifies the bundle target, creates a production safety
backup, and refuses to replace a production database containing users, builds,
audit events, or proposals. Remove the remote host copy after verification.
If the imported database has no active full administrator, complete the offline
administrator flow with the production Compose command in
[Authentication bootstrap and MFA secrets](#authentication-bootstrap-and-mfa-secrets)
before reopening the site. Do not rely on the first production sign-in for
elevation.
### Promote one News article
Export a locally authored News article by ID or slug while the development
+76 -11
View File
@@ -896,6 +896,20 @@ error, or danger indicators.
- Tiered records with shared structure use one shared selector and side-by-side
value columns rather than duplicating the entire editor. Template-driven copy
must show live previews for every tier and document its placeholder syntax.
- Talent, OS Protocol Talent, Skill Chip Talent, and Specialization rank-effect
forms use the shared authored-description editor. Place the exact source text
first because it remains authoritative when no model revision is selected.
Put model controls in a separate bordered section with explicit Preserve,
Save, and Clear choices. Keep fixed units and Attribute wording in the
authored template; every token value is numeric and contains only the number
that changes between variants, while the combat model owns Attribute
semantics. The token matrix
keeps one row per varying authored value and one column per variant so
operators can compare substitutions without duplicating the program editor.
On narrow screens, keep the matrix
horizontally scrollable instead of collapsing labels into ambiguous cards.
Show modeled previews, readiness, assumptions, and validation as text; color
may reinforce these states but must not replace their labels.
### Forms
@@ -1843,6 +1857,34 @@ responsive card grid. Record cards use the same hierarchy:
- bordered fact cells for primary values;
- relationship lines and tier descriptions only when applicable.
#### Public mechanic behavior status
Mechanic owners use the shared integrated card hierarchy. The public DTO carries a
stable group ID, owner type, label and optional context, plus explicitly labeled
variants. Each variant provides public behavior text, `modeled` or `not_modeled`
status, and `model` or `authored` display source. Public cards never receive
lifecycle, readiness, revision, fingerprint, or program data.
Every owner group displays one textual `MODELED` or `NOT MODELED` badge beside
its identity. `MODELED` uses the model surface, model border, and blue
informational text. `NOT MODELED` uses neutral borders and muted text. Orange
remains reserved for navigation, focus, and actions. Each behavior block labels
its displayed basis as `MODELED BEHAVIOR` or `AUTHORED DESCRIPTION`.
Talent groups retain Tier I and Tier II variants. Exotic Talents omit Tier II
when the authored source omits it. OS Protocol Talents use a Base variant beside
their existing level and upgrade controls. Skill Chip Talents use Minimum and
Maximum variants in the three-piece section. Specialization tree-rank effects
remain independent groups under their Focus, node, and rank context.
Compact cards visually clamp long behavior text without removing it from the
accessible name or linked detail. Quick views render the same shared card at a
wider reading measure, retain the binary badge, and add `DISPLAY SOURCE` with
`MODELED BEHAVIOR` or `AUTHORED DESCRIPTION`. Global Database results show the
owner category, record name, current public behavior, binary status, and an
explicit registry navigation label. Status is textual at every breakpoint;
mobile places it after identity and before behavior.
When a record represents an ordered progression rather than independent facts,
use the stacked fact treatment. Brand Set bonuses are shown vertically in two-,
three-, then four-piece order; do not add a redundant “3/3 bonuses” badge when
@@ -2390,9 +2432,11 @@ display `ADVANCED`, and stay visible in the generated script. State rows expose
label, agent or target scope, initial value, bounds, best-case value, and
optional expiry. A state change that writes a target pool uses a `STATE OWNER`
segmented control with `EVENT TARGET` and `EVENT ACTOR`; the selected owner
remains visible in the generated script. Outcome rows expose kind, target scope,
Attribute or resource when applicable, value basis, state scaling, phase, and
every source-specific value column. The Value Model control supports static
remains visible in the generated script. The `DERIVED VALUE` operation writes
the branch reducer's numeric result into the selected pool and displays that
link as a text readout instead of a numeric input. Outcome rows expose kind,
target scope, Attribute or resource when applicable, value basis, state scaling,
phase, and every source-specific value column. The Value Model control supports
values, live Attribute totals, percentage-normalized Attribute values, event
fields, reducer output, source-defined scenario controls, and OS Protocol
upgrade scaling where the source permits it. Selecting either Attribute model
@@ -2404,6 +2448,15 @@ applied to the stored value. Restoration outcomes also expose an `INSTANT` or
field and describes the configured value as the total delivered across that
duration; switching back to instant clears the duration.
Selecting `DERIVE A SCALAR VALUE` exposes a `DERIVED VALUE SOURCE`
`SegmentedChoice`. `STATIC` shows the numeric value input. `EVENT FIELD` shows
the numeric fields registered for the branch event, including the proximity
snapshot's allied-Agent count; it never asks the author to type a field path.
Keep an existing expression that falls outside these manual patterns visible as
disabled `ADVANCED` data. The source and field controls retain `SegmentedChoice`
radio semantics, visible legends, arrow-key operation, focus-visible treatment,
and text labels.
Target-scoped direct-damage outcomes offer `HIT-TARGET EXPLOSION` in the Area
Targeting control. Selecting it creates an event-target-centered enemy area with
a five-meter starting radius, reveals the required radius field, and shows a
@@ -2421,13 +2474,15 @@ source program, where authors may edit its exposed branch, state, and outcome
controls. The recipe label records provenance only. `REPLACE PROGRAM` requires
an inline confirmation that states all existing branches will be discarded.
Builder Controls define source-specific scenario assumptions for the planned
player simulation. ISAC authors choose toggle, slider, or numeric input and
provide a label, Agent guidance, default value, best-case value, and numeric
bounds when applicable. The current player UI does not render these controls or
read their saved values. It uses an explicit `COMING SOON` panel for the future
advanced scenario surface. The authored contract still requires the runtime to
report `REQUIRES ASSUMPTIONS` when a required cadence or environmental value is
Builder Controls define source-specific scenario assumptions for player
simulation. ISAC authors choose toggle, slider, or numeric input and provide a
label, Agent guidance, default value, best-case value, and numeric bounds when
applicable. The calculation timeline builder can consume values supplied for
these controls, including `allies-within-30m-with-agent-granted-buff`. Current
Builder and shared Build pages do not render the controls or let players change
those values. They use an explicit `COMING SOON` panel for the future advanced
scenario surface. The authored contract still requires the runtime to report
`REQUIRES ASSUMPTIONS` when a required cadence or environmental value is
missing; the editor and runtime never invent a cadence.
Use `--shd-model-surface` and `--shd-model-border` for mechanic programs,
@@ -2478,7 +2533,10 @@ The panel presents five explicit states:
polite live region, and disables repeat actions.
- `CLARIFICATION REQUIRED` lists each focused question with its reason and
bounded answer control. The author may answer, revise the source text, or
return to manual authoring.
return to manual authoring. For an unresolved numbered numeric placeholder,
show a required clarification for every source value column whose number is
missing. Do not prefill, infer, or suggest a percentage. Keep
`APPLY TO EDITOR` unavailable until the author answers each required variant.
- `CAPABILITY GAP` names the unsupported behavior and displays the developer
handoff, supported approximation, and optional workaround in separate labeled
blocks. Do not present a capability gap as validation failure.
@@ -2502,6 +2560,13 @@ applying the draft would replace configured branches, pools, controls, or
outcomes. The standard ISAC save lifecycle begins only after the author reviews
and saves the resulting form.
An applied AI draft stores each clarified number in the corresponding
human-facing outcome-variant value. A scaling expression may retain the
draft-only `variant_value` reference so later saves preserve the link to that
displayed value. The runtime adapter resolves the reference separately for each
variant. Show the value and generated formula in the ordinary review controls;
do not require an author to inspect or edit raw JSON.
Use text labels with status colors. Orange marks Generate, Answer, and Apply
actions. Blue identifies modeled information, yellow marks assumptions or
unsupported coverage, and red marks request or validation failures. Never use
+18
View File
@@ -79,6 +79,24 @@ meters:
duration.
- The wearer does not count as an ally.
## Close and Personal
Close and Personal uses a proximity-snapshot qualifying set:
- Include each distinct allied Agent whose distance from the source Agent is
less than or equal to 30 meters and who has at least one buff granted by that
source Agent.
- Count an ally once when several of the source Agent's buffs qualify.
- Do not include an ally whose qualifying buffs come only from other sources.
Record the resolved non-negative integer count in
`proximity_snapshot.values.alliesWithin30MetersWithAgentGrantedBuff`. The
calculation builder supplies it from the
`allies-within-30m-with-agent-granted-buff` scenario input. The confirmed rule
defines this qualifying set but does not provide Close and Personal's base
percentage. Keep that percentage unresolved until source evidence or an author's
clarification supplies it.
## Emergency Retreat
Emergency Retreat activates whenever at least one enemy is within 20 meters and
+60
View File
@@ -0,0 +1,60 @@
# Domain docs
Engineering skills must consult this repository's domain documentation before
exploring code.
## Read before exploring
- Read `CONTEXT.md` at the repository root.
- If `CONTEXT-MAP.md` exists, use it to find the `CONTEXT.md` files relevant to
the task.
- Read ADRs under `docs/adr/` that affect the area you will change. In a
multi-context repository, also check `src/<context>/docs/adr/`.
If these files do not exist, proceed without comment. Do not suggest creating
them before the project resolves domain terms or architectural decisions. The
`/domain-modeling` skill, reached through `/grill-with-docs` and
`/improve-codebase-architecture`, creates them when needed.
## File structure
This repository uses the single-context layout:
```text
/
├── CONTEXT.md
├── docs/adr/
│ ├── 0001-event-sourced-orders.md
│ └── 0002-postgres-for-write-model.md
└── src/
```
A repository with multiple bounded contexts can use this layout:
```text
/
├── CONTEXT-MAP.md
├── docs/adr/
└── src/
├── ordering/
│ ├── CONTEXT.md
│ └── docs/adr/
└── billing/
├── CONTEXT.md
└── docs/adr/
```
## Use glossary terms
Use the terms defined in `CONTEXT.md` in issue titles, refactor proposals,
hypotheses, and test names. Do not substitute synonyms that the glossary
rejects.
If a needed concept is absent, reconsider whether the project uses that concept.
If it represents a real gap, record it for `/domain-modeling`.
## Flag ADR conflicts
Call out any proposal that conflicts with an ADR:
> _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_
+106
View File
@@ -0,0 +1,106 @@
# Issue tracker: Gitea
Issues and specs for this repo live as Gitea issues. Use the
[`tea`](https://gitea.com/gitea/tea) CLI for all operations.
## Repository context
Run commands inside the clone so `tea` can infer the repository and login from
its Git remote. If the clone has multiple Gitea remotes or logins, pass
`--remote <name>` or `--login <name>`. Use `--repo <owner>/<repo>` only outside
the clone.
Before the first operation, verify the instance with
`tea logins list --output json`. If it is missing, ask the user to run
`tea login add`; never ask for or handle their access token.
## Conventions
- **Create an issue**: `tea issues create --title "..." --description "..."`.
For a multi-line body, use shell command substitution around a quoted heredoc:
```bash
tea issues create --title "..." --description "$(cat <<'EOF'
Multi-line issue body.
EOF
)"
```
- **Read an issue with comments**:
`tea issues <number> --comments --fields index,state,author,url,title,body,assignees,labels,comments --output json`.
- **List issues**:
`tea issues list --state open --fields index,state,author,url,title,body,assignees,labels,comments --output json`,
adding `--labels "label-one,label-two"`, `--assignee <user>`, or another
supported filter as needed. Paginate with `--page` and `--limit`; do not
assume the default first 30 results are complete.
- **Comment on an issue**: `tea comments add <number> --description "..."`.
- **Apply or remove labels**: `tea issues edit <number> --add-labels "..."` or
`--remove-labels "..."`. Separate multiple labels with commas.
- **Assign or unassign**: `tea issues edit <number> --add-assignees "..."` or
`--remove-assignees "..."`.
- **Close**: post the closing explanation with
`tea comments add <number> --description "..."`, then run
`tea issues close <number>`.
- **Reopen**: `tea issues reopen <number>`.
- **Raw API fallback**: use `tea api '<endpoint>'` only for a Gitea feature
without a first-class `tea` command. Prefer `{owner}` and `{repo}`
placeholders so repository context remains explicit.
Use `--output json` for machine-readable reads. Do not scrape table output.
## Pull requests as a triage surface
**PRs as a request surface: no.** _(Set this to `yes` if this repo treats
external pull requests as feature requests; `/triage` reads this flag.)_
When set to `yes`, PRs use the same labels and states as issues:
- **Read a PR with comments and diff**:
`tea pulls <number> --comments --fields index,state,author,url,title,body,diff,assignees,labels,comments --output json`.
- **List open PRs**:
`tea pulls list --state open --fields index,state,author,author-id,url,title,body,assignees,labels,comments --output json`.
Determine whether an author is external from the repository's Gitea membership
data; the PR listing does not classify author membership.
- **Comment**: `tea comments add <number> --description "..."`.
- **Apply or remove labels**: `tea pulls edit <number> --add-labels "..."` or
`--remove-labels "..."`.
- **Close**: `tea pulls close <number>`.
Gitea pull requests use the repository's issue index space, so `#42` may refer
to either surface. If the context is unclear, inspect it with
`tea pulls 42 --output json`; if that command reports no PR, read it with
`tea issues 42 --output json`.
## When a skill says "publish to the issue tracker"
Create a Gitea issue with `tea issues create`.
## When a skill says "fetch the relevant ticket"
Run
`tea issues <number> --comments --fields index,state,author,url,title,body,assignees,labels,comments --output json`.
## Wayfinding operations
`/wayfinder` uses one **map** issue with linked **child** issues. These
conventions store relationships in issue bodies, so they work across Gitea
versions.
- **Map**: create one issue labelled `wayfinder:map` containing the Notes,
Decisions-so-far, and Fog sections. Use
`tea issues create --labels "wayfinder:map"` with its title and description.
- **Child ticket**: start the body with `Part of #<map>` and apply a
`wayfinder:<type>` label: `research`, `prototype`, `grilling`, or `task`. Add
each child as a task-list item in the map body to preserve frontier order.
- **Blocking**: put `Blocked by: #<n>, #<n>` near the top of the child body. A
ticket becomes unblocked after every referenced blocker closes.
- **Frontier query**: list all open children, order them by the map's task list,
and discard tickets with an open blocker or an assignee. Select the first
remaining ticket. Fetch each referenced blocker; do not infer its state from
map text.
- **Claim**: resolve the active username with `tea whoami`, then run
`tea issues edit <n> --add-assignees "<username>"` as the session's first
write. Do not assume `@me` works.
- **Resolve**: run `tea comments add <n> --description "<answer>"`, close the
child with `tea issues close <n>`, then append a context pointer and link to
the map's Decisions-so-far section.
+14
View File
@@ -0,0 +1,14 @@
# Triage labels
Engineering skills use five canonical triage roles. This table maps each role to
the label string in this repository's issue tracker.
| Canonical role | Tracker label | Meaning |
| ----------------- | ----------------- | -------------------------------------- |
| `needs-triage` | `needs-triage` | A maintainer must evaluate the issue |
| `needs-info` | `needs-info` | Waiting for more information |
| `ready-for-agent` | `ready-for-agent` | Fully specified and ready for an agent |
| `ready-for-human` | `ready-for-human` | Requires human implementation |
| `wontfix` | `wontfix` | Maintainers will not act on the issue |
When a skill names a canonical role, use the corresponding tracker label.
+49 -55
View File
@@ -9,8 +9,8 @@ The team builds the project in vertical slices.
data
- Auth.js-compatible server authentication with Discord OAuth and credentials
providers
- Argon2id password hashing, TOTP MFA with encrypted secrets, server-side
sessions, CSRF protection, and role checks
- Argon2id password hashing, server-side sessions, CSRF protection, and role
checks
- Browser `localStorage` only for anonymous build drafts
## Product boundaries
@@ -41,43 +41,6 @@ Local credentials use Argon2id PHC strings with a unique random salt per
password. Current work factors meet OWASP's 19 MiB / 2 iteration / single-lane
minimum profile. Successful login rehashes credentials with outdated parameters.
## Authentication and MFA
Sign-in never grants administrator authority. The first full administrator is
created through an offline database operation after the target account has
enrolled TOTP. The local command is:
```sh
npm run admin:bootstrap -- <verified-email>
```
Staging and production use the stopped-container Compose workflow documented in
[`DEPLOYMENT.md`](DEPLOYMENT.md), not a host-side npm command. The bootstrap
operation accepts exactly one active, unblocked account with a verified email,
requires an active TOTP factor and an unused recovery code, requires that no
active full administrator exists, assigns the canonical `role-admin`
relationship, revokes the target's sessions, and records
`role_management / administrator.bootstrapped`. Administrators must enroll TOTP
before offline elevation.
`MFA_TOTP_ENCRYPTION_KEYS` is a required app-only secret. Its value contains one
to three comma-separated, unique `key-id:canonical-base64url-32-byte-key`
entries. The first entry is the active encryption key for new factors; later
entries retain decryption access to older factors during rotation. There is no
generated-key fallback. Rotate by prepending a newly generated 32-byte key with
a new ID, deploying it with the old entries retained, and verifying existing
TOTP authentication. A successful verification rewraps that factor under the
first key. Do not remove an old entry until every factor encrypted with it has
been rewrapped and verified. Keep key material in the secret manager and never
place it in source, logs, audit snapshots, or documentation.
TOTP enrollment issues ten one-time recovery codes. The interface displays them
only once; the database stores only domain-separated hashes. Save the codes in
an offline password manager or another protected offline record. Each code is
consumed once. Regenerating codes immediately revokes all unused previous codes
and displays a new set once. Disabling TOTP revokes its recovery codes, and a
full administrator cannot disable TOTP.
## Database runtime
The application uses Turso Database in-process through its native Node package.
@@ -281,9 +244,10 @@ does not become part of the canonical action replay.
# Administrator bootstrap
The first full administrator is created only through the offline flow documented
in [Authentication and MFA](#authentication-and-mfa). Sign-in never grants
administrator authority or changes an account's roles.
The authentication service promotes the first authenticated user to `admin` if
the database does not contain an administrator. Promotion uses one conditional
database update so concurrent first sign-ins cannot both become administrators.
Once an administrator exists, later sign-ins never alter roles.
# Database backup and restore
@@ -674,12 +638,24 @@ normalized events are `shot_fired`, `weapon_hit`, `skill_deployed`,
`weapon_swapped`, and `tick`. Event details such as target, distance, critical
state, source, movement, and nearby counts travel as typed event values. The
event registry publishes authoritative field metadata where branches need a
bounded contract. For those events, the mechanic editor derives its event-field
controls from that metadata. For example, `weapon_hit.values.headshot` is a
boolean that distinguishes headshots from body shots. `enemy_killed` and
`assist` may carry `values.assignedAbilityActive`; a Skill Chip Talent uses that
boolean to restrict a kill or assist trigger to its assigned ability's active
period. `skill_deployed` and `signature_ability_deployed` may carry
bounded contract. For those events, the mechanic editor derives event-field
conditions and manual derived-scalar controls from that metadata.
`proximity_snapshot.values.alliesWithin30MetersWithAgentGrantedBuff` is an
optional non-negative integer. It contains the resolved count of distinct allied
Agents at a distance less than or equal to 30 meters who have at least one buff
granted by the source Agent. Several qualifying buffs on one ally count once.
`proximity_snapshot` remains non-strict, so saved mechanic data and producers
that omit the field remain compatible.
`src/lib/builder/loadout-combat.ts` bridges the calculation scenario input
`allies-within-30m-with-agent-granted-buff` into that field on each generated
`proximity_snapshot`. For example, a derived-scalar reducer can select the
registered numeric field without requiring a hand-entered path. Other registered
metadata includes `weapon_hit.values.headshot`, a boolean that distinguishes
headshots from body shots. `enemy_killed` and `assist` may carry
`values.assignedAbilityActive`; a Skill Chip Talent uses that boolean to
restrict a kill or assist trigger to its assigned ability's active period.
`skill_deployed` and `signature_ability_deployed` may carry
`values.assignedAbilityDurationSeconds` to start assigned-ability state. The
runtime expires that state before it evaluates another event at the same
timestamp.
@@ -743,11 +719,20 @@ The program graph uses three child tables:
rolls separately. Restoration outcomes may deliver their total immediately or
continuously over an explicit duration.
Target-scoped direct damage may use `event_target_area` targeting for an
explosion around its event target. This targeting selects valid enemies and
stores a positive radius in meters. It is valid only for `on_event` or
`after_event` outcomes. The legacy `within_radius` shape remains descriptive
targeting metadata and does not select runtime entities.
Draft outcome expressions may use `{"ref":{"source":"variant_value"}}`. This
reference belongs to the conditional draft grammar and does not enter the
runtime expression grammar. Each persisted outcome-variant row keeps its
human-facing numeric `value`, while `value_expression_json` preserves the
reference and its semantic link. The adapters in
`src/lib/calculations/mechanic-editor.ts` and
`src/lib/calculations/mechanic-persistence.ts` resolve the reference from the
current row's `value` when they construct a runtime program.
Target-scoped direct damage may use `event_target_area` targeting for an
explosion around its event target. This targeting selects valid enemies and
stores a positive radius in meters. It is valid only for `on_event` or
`after_event` outcomes. The legacy `within_radius` shape remains descriptive
targeting metadata and does not select runtime entities.
The generic runtime in `src/lib/calculations/mechanic.ts` processes combat
events in timestamp order. Predicates decide whether an event enters a clause.
@@ -836,6 +821,13 @@ descriptions, and calculation metadata. The client cannot replace the system
instructions, choose arbitrary models, attach files, add tools, or add external
URLs.
When source wording contains an unresolved numbered numeric placeholder, the
assistant must return `clarification_required` and ask for the value of every
required source variant. It must not infer a percentage or other numeric value.
After clarification, the draft places each answer in the corresponding
outcome-variant `value`; any scaling expression uses the draft-only
`variant_value` reference instead of repeating that number.
The deterministic draft parser owns the canonical outcome-capability manifest.
The AI context serializes that manifest instead of maintaining a second outcome
grammar. The parser rejects outcome fields absent from the manifest. Contract
@@ -932,8 +924,10 @@ events remain the evidence for revision saves and activation.
Source authors define planned player scenario controls as typed toggle, slider,
or numeric inputs. Each input records its label, guidance, bounds when
applicable, default value, and best-case value. ISAC retains these definitions
for continued mechanic authoring. Current Builder and shared Build pages do not
render or evaluate them. Their calculation panels display `COMING SOON` instead.
for continued mechanic authoring, and the calculation timeline builder can
consume scenario values supplied by calculation orchestration. Current Builder
and shared Build pages do not expose those controls or invoke the simulation.
Their calculation panels display `COMING SOON` instead.
Loadout schema version 6 stores one focus, selected tree ranks, nine Skill
Chips, independent T1/T2 choices for each equipped gear and weapon Talent, a
-25
View File
@@ -21,7 +21,6 @@
"argon2": "^0.45.1",
"nodemailer": "^9.0.3",
"openai": "^6.49.0",
"otpauth": "9.5.1",
"sharp": "^0.35.3"
},
"devDependencies": {
@@ -707,18 +706,6 @@
"@emnapi/runtime": "^1.7.1"
}
},
"node_modules/@noble/hashes": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.2.0.tgz",
"integrity": "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==",
"license": "MIT",
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@oxc-project/types": {
"version": "0.139.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.139.0.tgz",
@@ -3499,18 +3486,6 @@
"integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==",
"license": "MIT"
},
"node_modules/otpauth": {
"version": "9.5.1",
"resolved": "https://registry.npmjs.org/otpauth/-/otpauth-9.5.1.tgz",
"integrity": "sha512-fJmDAHc8wImfqqqOXIlBvT1dEKrZK0Cmb2VEgScpNTolCz0PHh6ExUZGv4sLtOsWNaHCQlD+rRqaPgnoxFoZjQ==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "2.2.0"
},
"funding": {
"url": "https://github.com/hectorm/otpauth?sponsor=1"
}
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
-2
View File
@@ -16,7 +16,6 @@
"db:migrate:production": "infisical run --env=prod --path=/app --path=/shared/scheduler -- node scripts/db-migrate.mjs",
"db:seed-users": "infisical run --env=dev --path=/app -- node scripts/seed-initial-users.mjs",
"db:seed-users:reset": "infisical run --env=dev --path=/app -- node scripts/seed-initial-users.mjs --reset-passwords",
"admin:bootstrap": "infisical run --env=dev --path=/app -- node scripts/admin-bootstrap.mjs",
"db:backup": "infisical run --env=dev --path=/app -- node scripts/db-backup.mjs",
"db:backup:staging": "infisical run --env=staging --path=/app -- node scripts/db-backup.mjs",
"db:backup:production": "infisical run --env=prod --path=/app -- node scripts/db-backup.mjs",
@@ -80,7 +79,6 @@
"argon2": "^0.45.1",
"nodemailer": "^9.0.3",
"openai": "^6.49.0",
"otpauth": "9.5.1",
"sharp": "^0.35.3"
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"worktree": {
"setup": "npm install"
}
}
-204
View File
@@ -1,204 +0,0 @@
import { connect } from '@tursodatabase/database';
import { randomUUID } from 'node:crypto';
import { resolve } from 'node:path';
import process from 'node:process';
const usage = 'Usage: npm run admin:bootstrap -- <verified-email>';
const suppliedEmails = process.argv.slice(2);
if (suppliedEmails.length !== 1) throw new Error(usage);
const email = suppliedEmails[0]
.normalize('NFKC')
.trim()
.toLocaleLowerCase('en-US');
if (
email.length < 3 ||
email.length > 320 ||
!/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(email) ||
/[\r\n]/u.test(email)
) {
throw new Error('Provide one valid verified email address.');
}
const databasePath = resolve(
process.env.TDR_DATABASE_PATH || './data/shd-build-development.db',
);
const database = await connect(databasePath);
let transactionStarted = false;
try {
const now = new Date().toISOString();
await database.exec('BEGIN IMMEDIATE');
transactionStarted = true;
const matchingAccounts = await (
await database.prepare(`
SELECT users.id
FROM users
JOIN user_emails ON user_emails.user_id=users.id
LEFT JOIN user_status ON user_status.user_id=users.id
LEFT JOIN deleted_accounts ON deleted_accounts.user_id=users.id
WHERE user_emails.email=? COLLATE NOCASE
AND user_emails.verified_at IS NOT NULL
AND deleted_accounts.user_id IS NULL
AND user_status.blocked_at IS NULL
AND (user_status.banned_until IS NULL OR user_status.banned_until<=?)
`)
).all(email, now);
if (matchingAccounts.length !== 1)
throw new Error(
'The email must identify exactly one active verified account.',
);
const targetId = String(matchingAccounts[0].id);
const activeAdministrators = await (
await database.prepare(`
SELECT users.id
FROM users
LEFT JOIN user_status ON user_status.user_id=users.id
LEFT JOIN deleted_accounts ON deleted_accounts.user_id=users.id
WHERE deleted_accounts.user_id IS NULL
AND user_status.blocked_at IS NULL
AND (user_status.banned_until IS NULL OR user_status.banned_until<=?)
AND EXISTS (
SELECT 1 FROM user_roles
WHERE user_roles.user_id=users.id AND user_roles.role_id='role-admin'
)
`)
).all(now);
const targetAlreadyAdministrator = activeAdministrators.some(
(administrator) => String(administrator.id) === targetId,
);
if (activeAdministrators.length > 0 && !targetAlreadyAdministrator)
throw new Error('An active full administrator already exists.');
if (!targetAlreadyAdministrator) {
const administratorRole = await (
await database.prepare(`
SELECT roles.id
FROM roles
JOIN role_permissions ON role_permissions.role_id=roles.id
JOIN permissions ON permissions.id=role_permissions.permission_id
WHERE roles.id='role-admin' AND permissions.name='system.admin'
LIMIT 1
`)
).get();
if (!administratorRole)
throw new Error('The canonical administrator role is unavailable.');
const activeFactor = await (
await database.prepare(
"SELECT id FROM mfa_totp_factors WHERE user_id=? AND state='active' LIMIT 1",
)
).get(targetId);
if (!activeFactor)
throw new Error('The target account must have an active TOTP factor.');
const unusedRecoveryCode = await (
await database.prepare(
'SELECT id FROM mfa_recovery_codes WHERE user_id=? AND consumed_at IS NULL AND revoked_at IS NULL LIMIT 1',
)
).get(targetId);
if (!unusedRecoveryCode)
throw new Error('The target account must have an unused recovery code.');
const before = {
roleIds: (
await (
await database.prepare(
'SELECT role_id FROM user_roles WHERE user_id=? ORDER BY role_id',
)
).all(targetId)
).map((row) => String(row.role_id)),
};
await (
await database.prepare(
"INSERT OR IGNORE INTO user_roles(user_id,role_id) VALUES(?,'role-admin')",
)
).run(targetId);
await (
await database.prepare(
"UPDATE users SET role='user' WHERE id=? AND role='admin'",
)
).run(targetId);
const targetSessions = await (
await database.prepare('SELECT id FROM sessions WHERE user_id=?')
).all(targetId);
const sessionIds = targetSessions.map((row) => String(row.id));
if (sessionIds.length) {
const placeholders = sessionIds.map(() => '?').join(',');
await (
await database.prepare(
`UPDATE login_events SET session_ended_at=?,session_end_reason=? WHERE session_id IN (${placeholders})`,
)
).run(now, 'administrator_bootstrap', ...sessionIds);
await (
await database.prepare(
`DELETE FROM sessions WHERE id IN (${placeholders})`,
)
).run(...sessionIds);
}
await (
await database.prepare(`
INSERT INTO audit_log(
id,actor_id,entity_type,entity_id,action,before_json,after_json,created_at
) VALUES(?,?,?,?,?,?,?,?)
`)
).run(
randomUUID(),
targetId,
'role_management',
targetId,
'administrator.bootstrapped',
JSON.stringify(before),
JSON.stringify({
roleId: 'role-admin',
sessionsRevoked: sessionIds.length,
mfaRequired: true,
}),
now,
);
}
const resultingAdministrators = await (
await database.prepare(`
SELECT COUNT(DISTINCT users.id) AS count
FROM users
LEFT JOIN user_status ON user_status.user_id=users.id
LEFT JOIN deleted_accounts ON deleted_accounts.user_id=users.id
WHERE deleted_accounts.user_id IS NULL
AND user_status.blocked_at IS NULL
AND (user_status.banned_until IS NULL OR user_status.banned_until<=?)
AND EXISTS (
SELECT 1 FROM user_roles
WHERE user_roles.user_id=users.id AND user_roles.role_id='role-admin'
)
`)
).get(now);
if (Number(resultingAdministrators?.count) < 1)
throw new Error('The database must retain an active full administrator.');
await database.exec('COMMIT');
transactionStarted = false;
console.log(
targetAlreadyAdministrator
? 'The target account already has unrestricted administration.'
: 'Initial unrestricted administration granted.',
);
} catch (error) {
if (transactionStarted) {
try {
await database.exec('ROLLBACK');
} catch {
// Preserve the original failure without exposing database details.
}
}
console.error(
error instanceof Error ? error.message : 'Administrator bootstrap failed.',
);
process.exitCode = 1;
} finally {
await database.close();
}
-151
View File
@@ -1,151 +0,0 @@
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { connect, type Database } from '@tursodatabase/database';
const run = promisify(execFile);
let directory: string;
let database: Database;
let databasePath: string;
async function invoke() {
try {
const result = await run(
process.execPath,
['scripts/admin-bootstrap.mjs', 'admin@example.com'],
{
cwd: process.cwd(),
env: {
...process.env,
TDR_DATABASE_PATH: databasePath,
NODE_ENV: 'test',
},
},
);
return { status: 0, stdout: result.stdout, stderr: result.stderr };
} catch (error) {
const failure = error as {
code?: number;
stdout?: string;
stderr?: string;
};
return {
status: Number(failure.code ?? 1),
stdout: failure.stdout ?? '',
stderr: failure.stderr ?? '',
};
}
}
describe('administrator bootstrap preconditions', () => {
beforeEach(async () => {
directory = await mkdtemp(join(tmpdir(), 'shd-admin-bootstrap-'));
databasePath = join(directory, 'database.db');
database = await connect(databasePath);
await database.exec(`
CREATE TABLE users (id TEXT PRIMARY KEY, username TEXT, role TEXT, created_at TEXT);
CREATE TABLE user_emails (user_id TEXT, email TEXT, verified_at TEXT);
CREATE TABLE user_status (user_id TEXT PRIMARY KEY, blocked_at TEXT, banned_until TEXT);
CREATE TABLE deleted_accounts (user_id TEXT PRIMARY KEY);
CREATE TABLE roles (id TEXT PRIMARY KEY, name TEXT);
CREATE TABLE permissions (id TEXT PRIMARY KEY, name TEXT);
CREATE TABLE role_permissions (role_id TEXT, permission_id TEXT);
CREATE TABLE user_roles (user_id TEXT, role_id TEXT, PRIMARY KEY(user_id,role_id));
CREATE TABLE mfa_totp_factors (id TEXT PRIMARY KEY, user_id TEXT, state TEXT);
CREATE TABLE mfa_recovery_codes (id TEXT PRIMARY KEY, user_id TEXT, consumed_at TEXT, revoked_at TEXT);
CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT);
CREATE TABLE login_events (id TEXT PRIMARY KEY, session_id TEXT, session_ended_at TEXT, session_end_reason TEXT);
CREATE TABLE audit_log (id TEXT PRIMARY KEY, actor_id TEXT, entity_type TEXT, entity_id TEXT, action TEXT, before_json TEXT, after_json TEXT, created_at TEXT);
INSERT INTO users VALUES ('user-1','agent','user','2026-08-07T00:00:00.000Z');
INSERT INTO user_emails VALUES ('user-1','admin@example.com','2026-08-07T00:00:00.000Z');
INSERT INTO roles VALUES ('role-admin','Admin');
INSERT INTO permissions VALUES ('permission-system-admin','system.admin');
INSERT INTO role_permissions VALUES ('role-admin','permission-system-admin');
`);
});
afterEach(async () => {
await database.close();
await rm(directory, { recursive: true, force: true });
});
it('rejects accounts without both active TOTP and unused recovery code', async () => {
await database.close();
const result = await invoke();
expect(result.status).toBe(1);
expect(result.stderr).toContain('active TOTP factor');
database = await connect(databasePath);
const user = await (await database.prepare('SELECT role FROM users')).get();
expect(user.role).toBe('user');
});
it('grants only after MFA readiness and records sanitized bootstrap evidence', async () => {
await database.exec(`
INSERT INTO mfa_totp_factors VALUES ('factor-1','user-1','active');
INSERT INTO mfa_recovery_codes VALUES ('code-1','user-1',NULL,NULL);
INSERT INTO sessions VALUES ('session-1','user-1');
`);
await database.close();
const result = await invoke();
expect(result.status).toBe(0);
database = await connect(databasePath);
const user = await (await database.prepare('SELECT role FROM users')).get();
const role = await (
await database.prepare('SELECT role_id FROM user_roles WHERE user_id=?')
).get('user-1');
const sessions = await (
await database.prepare('SELECT COUNT(*) AS count FROM sessions')
).get();
const audit = await (
await database.prepare(
'SELECT entity_type,action,after_json FROM audit_log',
)
).get();
expect(user.role).toBe('user');
expect(role.role_id).toBe('role-admin');
expect(Number(sessions.count)).toBe(0);
expect(audit).toMatchObject({
entity_type: 'role_management',
action: 'administrator.bootstrapped',
});
expect(String(audit.after_json)).not.toContain('factor-1');
expect(String(audit.after_json)).not.toContain('code-1');
});
it('is idempotent for an already canonical administrator', async () => {
await database.exec(`
INSERT INTO mfa_totp_factors VALUES ('factor-1','user-1','active');
INSERT INTO mfa_recovery_codes VALUES ('code-1','user-1',NULL,NULL);
`);
await database.close();
expect((await invoke()).status).toBe(0);
database = await connect(databasePath);
const firstAuditCount = await (
await database.prepare(
"SELECT COUNT(*) AS count FROM audit_log WHERE action='administrator.bootstrapped'",
)
).get();
await database.close();
expect((await invoke()).status).toBe(0);
database = await connect(databasePath);
const secondAuditCount = await (
await database.prepare(
"SELECT COUNT(*) AS count FROM audit_log WHERE action='administrator.bootstrapped'",
)
).get();
expect(Number(firstAuditCount.count)).toBe(1);
expect(Number(secondAuditCount.count)).toBe(1);
});
it('keeps only the local development bootstrap command', async () => {
const packageJson = JSON.parse(await readFile('package.json', 'utf8')) as {
scripts: Record<string, string>;
};
expect(packageJson.scripts['admin:bootstrap']).toBeTruthy();
expect(packageJson.scripts['admin:bootstrap:staging']).toBeUndefined();
expect(packageJson.scripts['admin:bootstrap:production']).toBeUndefined();
});
});
+53 -162
View File
@@ -769,138 +769,6 @@ for (const statement of statements) {
await database.exec(statement);
}
// Authentication transactions created by older releases did not retain the
// primary provider. Keep those rows intact and leave their provider unknown;
// new login transactions write the validated provider at creation time.
const authenticationTransactionColumns = await (
await database.prepare("PRAGMA table_info('authentication_transactions')")
).all();
if (
authenticationTransactionColumns.length &&
!authenticationTransactionColumns.some((column) => column.name === 'provider')
) {
console.log('Adding primary providers to authentication transactions.');
await database.exec(
"ALTER TABLE authentication_transactions ADD COLUMN provider TEXT CHECK(provider IS NULL OR provider IN ('password','discord','magic_link','passkey'))",
);
}
// Move legacy administrator rows onto the canonical relationship before the
// legacy users.role projection is cleared. The operation is repeatable and
// keeps the existing account IDs and authored data unchanged.
const legacyAdministratorRows = await (
await database.prepare("SELECT id FROM users WHERE role='admin' ORDER BY id")
).all();
if (legacyAdministratorRows.length) {
const administratorRole = await (
await database.prepare("SELECT id FROM roles WHERE id='role-admin'")
).get();
if (!administratorRole)
throw new Error('Cannot migrate legacy administrators without role-admin.');
await database.exec('BEGIN IMMEDIATE');
try {
for (const user of legacyAdministratorRows) {
await (
await database.prepare(
"INSERT OR IGNORE INTO user_roles(user_id,role_id) VALUES(?,'role-admin')",
)
).run(String(user.id));
}
await database.exec("UPDATE users SET role='user' WHERE role='admin'");
const remainingLegacyAdministrators = await (
await database.prepare(
"SELECT COUNT(*) AS count FROM users WHERE role='admin'",
)
).get();
if (Number(remainingLegacyAdministrators?.count) !== 0)
throw new Error('Legacy administrator authority could not be cleared.');
await database.exec('COMMIT');
} catch (error) {
await database.exec('ROLLBACK');
throw error;
}
}
// MFA rotations keep the current active factor while a replacement is pending.
// Older databases used one partial index for both states, which prevented that
// safe overlap. Drop it and install the two independent idempotent constraints.
const legacyTotpCurrentIndex = await (
await database.prepare(
"SELECT 1 FROM sqlite_master WHERE type='index' AND name='mfa_totp_factors_one_current_idx'",
)
).get();
if (legacyTotpCurrentIndex) {
await database.exec('DROP INDEX mfa_totp_factors_one_current_idx');
}
await database.exec(
"CREATE UNIQUE INDEX IF NOT EXISTS mfa_totp_factors_one_active_idx ON mfa_totp_factors(user_id) WHERE state='active'",
);
await database.exec(
"CREATE UNIQUE INDEX IF NOT EXISTS mfa_totp_factors_one_pending_idx ON mfa_totp_factors(user_id) WHERE state='pending'",
);
// Existing sessions were issued before authentication assurance levels were
// recorded. They cannot be upgraded safely, so invalidate only those legacy
// rows after adding the nullable migration columns. New sessions are written
// with a non-null AAL evidence timestamp by the auth session service.
const sessionTable = await (
await database.prepare(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='sessions'",
)
).get();
if (sessionTable) {
let sessionColumns = await (
await database.prepare("PRAGMA table_info('sessions')")
).all();
if (!sessionColumns.some((column) => column.name === 'aal')) {
await database.exec(
'ALTER TABLE sessions ADD COLUMN aal INTEGER NOT NULL DEFAULT 1 CHECK(aal IN (1,2))',
);
sessionColumns = [...sessionColumns, { name: 'aal' }];
}
if (!sessionColumns.some((column) => column.name === 'aal_verified_at')) {
await database.exec('ALTER TABLE sessions ADD COLUMN aal_verified_at TEXT');
sessionColumns = [...sessionColumns, { name: 'aal_verified_at' }];
}
if (!sessionColumns.some((column) => column.name === 'aal2_verified_at')) {
await database.exec(
'ALTER TABLE sessions ADD COLUMN aal2_verified_at TEXT',
);
}
const legacySessions = await (
await database.prepare(
'SELECT COUNT(*) AS count FROM sessions WHERE aal_verified_at IS NULL',
)
).get();
if (Number(legacySessions?.count) > 0) {
console.log(
`Invalidating ${Number(legacySessions.count)} legacy session(s) without AAL evidence.`,
);
await database.exec('DELETE FROM sessions WHERE aal_verified_at IS NULL');
}
}
const loginEventsTable = await (
await database.prepare(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='login_events'",
)
).get();
if (loginEventsTable) {
const loginEventColumns = await (
await database.prepare("PRAGMA table_info('login_events')")
).all();
if (!loginEventColumns.some((column) => column.name === 'aal')) {
await database.exec(
'ALTER TABLE login_events ADD COLUMN aal INTEGER CHECK(aal IS NULL OR aal IN (1,2))',
);
}
if (!loginEventColumns.some((column) => column.name === 'aal2_verified_at')) {
await database.exec(
'ALTER TABLE login_events ADD COLUMN aal2_verified_at TEXT',
);
}
}
await database.exec(`CREATE TRIGGER IF NOT EXISTS specialization_ability_skill_chip_links_validate_insert
BEFORE INSERT ON specialization_ability_skill_chip_links
BEGIN
@@ -2274,12 +2142,10 @@ if (
user_id TEXT REFERENCES users(id) ON DELETE SET NULL,
provider TEXT NOT NULL CHECK(provider IN ('password', 'discord', 'magic_link', 'passkey')),
succeeded INTEGER NOT NULL CHECK(succeeded IN (0, 1)),
aal INTEGER CHECK(aal IS NULL OR aal IN (1,2)),
aal2_verified_at TEXT,
created_at TEXT NOT NULL
)`);
await database.exec(`INSERT INTO login_events(id,user_id,provider,succeeded,aal,aal2_verified_at,created_at)
SELECT id,user_id,provider,succeeded,NULL,NULL,created_at FROM login_events_legacy`);
await database.exec(`INSERT INTO login_events(id,user_id,provider,succeeded,created_at)
SELECT id,user_id,provider,succeeded,created_at FROM login_events_legacy`);
await database.exec('DROP TABLE login_events_legacy');
await database.exec(
'CREATE INDEX IF NOT EXISTS login_events_user_created_idx ON login_events(user_id, created_at DESC)',
@@ -2304,8 +2170,6 @@ for (const [name, definition] of [
['session_ended_at', 'TEXT'],
['session_end_reason', 'TEXT'],
['sensitive_purged_at', 'TEXT'],
['aal', 'INTEGER CHECK(aal IS NULL OR aal IN (1,2))'],
['aal2_verified_at', 'TEXT'],
]) {
if (!loginEventColumns.some((column) => column.name === name)) {
await database.exec(
@@ -2314,20 +2178,6 @@ for (const [name, definition] of [
}
}
// Earlier releases logged the primary factor as a successful login even when
// the AAL2 challenge was still pending. Retain those events as failure
// telemetry, but prevent abandoned MFA challenges from remaining successful.
await (
await database.prepare(`
UPDATE login_events
SET succeeded=0,
failure_reason=COALESCE(failure_reason,'mfa_required'),
aal=COALESCE(aal,1)
WHERE succeeded=1
AND instr(',' || COALESCE(risk_flags,'') || ',', ',primary_authenticated_mfa_required,')>0
`)
).run();
const proposalColumns = await (
await database.prepare("PRAGMA table_info('data_change_proposals')")
).all();
@@ -2366,6 +2216,17 @@ if (legacyProtocolEffects) {
await database.exec('DROP TABLE os_protocol_attribute_effects');
}
const assertProposalContributorNoteColumn = async () => {
const columns = await (
await database.prepare("PRAGMA table_info('data_change_proposals')")
).all();
if (!columns.some((column) => column.name === 'contributor_note')) {
throw new Error(
'Schema migration lost the contributor_note column from data_change_proposals.',
);
}
};
const proposalDefinition = await (
await database.prepare(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='data_change_proposals'",
@@ -2385,6 +2246,7 @@ if (
draft_entity_id TEXT,
applied_entity_id TEXT,
summary TEXT NOT NULL,
contributor_note TEXT,
payload_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','approved','rejected','failed')),
proposed_by TEXT NOT NULL REFERENCES users(id),
@@ -2394,14 +2256,20 @@ if (
reviewed_at TEXT,
applied_at TEXT
)`);
await database.exec(`INSERT INTO data_change_proposals_expanded
SELECT id,CASE module WHEN 'stats' THEN 'attributes' ELSE module END,action,entity_id,draft_entity_id,applied_entity_id,summary,payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
await database.exec(`INSERT INTO data_change_proposals_expanded(
id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,contributor_note,
payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
)
SELECT id,CASE module WHEN 'stats' THEN 'attributes' ELSE module END,action,entity_id,
draft_entity_id,applied_entity_id,summary,contributor_note,payload_json,status,
proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
FROM data_change_proposals`);
await database.exec('DROP TABLE data_change_proposals');
await database.exec(
'ALTER TABLE data_change_proposals_expanded RENAME TO data_change_proposals',
);
await database.exec('PRAGMA foreign_keys=ON');
await assertProposalContributorNoteColumn();
}
await database.exec(
'CREATE INDEX IF NOT EXISTS data_change_proposals_status_created_idx ON data_change_proposals(status,created_at DESC)',
@@ -2432,6 +2300,7 @@ if (
draft_entity_id TEXT,
applied_entity_id TEXT,
summary TEXT NOT NULL,
contributor_note TEXT,
payload_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','approved','rejected','failed')),
proposed_by TEXT NOT NULL REFERENCES users(id),
@@ -2441,14 +2310,19 @@ if (
reviewed_at TEXT,
applied_at TEXT
)`);
await database.exec(`INSERT INTO data_change_proposals_weaponmods
SELECT id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
await database.exec(`INSERT INTO data_change_proposals_weaponmods(
id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,contributor_note,
payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
)
SELECT id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,contributor_note,
payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
FROM data_change_proposals`);
await database.exec('DROP TABLE data_change_proposals');
await database.exec(
'ALTER TABLE data_change_proposals_weaponmods RENAME TO data_change_proposals',
);
await database.exec('PRAGMA foreign_keys=ON');
await assertProposalContributorNoteColumn();
await database.exec(
'CREATE INDEX IF NOT EXISTS data_change_proposals_status_created_idx ON data_change_proposals(status,created_at DESC)',
);
@@ -2479,6 +2353,7 @@ if (
draft_entity_id TEXT,
applied_entity_id TEXT,
summary TEXT NOT NULL,
contributor_note TEXT,
payload_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','approved','rejected','failed')),
proposed_by TEXT NOT NULL REFERENCES users(id),
@@ -2488,14 +2363,19 @@ if (
reviewed_at TEXT,
applied_at TEXT
)`);
await database.exec(`INSERT INTO data_change_proposals_specializations
SELECT id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
await database.exec(`INSERT INTO data_change_proposals_specializations(
id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,contributor_note,
payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
)
SELECT id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,contributor_note,
payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
FROM data_change_proposals`);
await database.exec('DROP TABLE data_change_proposals');
await database.exec(
'ALTER TABLE data_change_proposals_specializations RENAME TO data_change_proposals',
);
await database.exec('PRAGMA foreign_keys=ON');
await assertProposalContributorNoteColumn();
await database.exec(
'CREATE INDEX IF NOT EXISTS data_change_proposals_status_created_idx ON data_change_proposals(status,created_at DESC)',
);
@@ -2526,6 +2406,7 @@ if (
draft_entity_id TEXT,
applied_entity_id TEXT,
summary TEXT NOT NULL,
contributor_note TEXT,
payload_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','approved','rejected','failed')),
proposed_by TEXT NOT NULL REFERENCES users(id),
@@ -2535,14 +2416,19 @@ if (
reviewed_at TEXT,
applied_at TEXT
)`);
await database.exec(`INSERT INTO data_change_proposals_calculations
SELECT id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
await database.exec(`INSERT INTO data_change_proposals_calculations(
id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,contributor_note,
payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
)
SELECT id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,contributor_note,
payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
FROM data_change_proposals`);
await database.exec('DROP TABLE data_change_proposals');
await database.exec(
'ALTER TABLE data_change_proposals_calculations RENAME TO data_change_proposals',
);
await database.exec('PRAGMA foreign_keys=ON');
await assertProposalContributorNoteColumn();
await database.exec(
'CREATE INDEX IF NOT EXISTS data_change_proposals_status_created_idx ON data_change_proposals(status,created_at DESC)',
);
@@ -2577,6 +2463,7 @@ if (
draft_entity_id TEXT,
applied_entity_id TEXT,
summary TEXT NOT NULL,
contributor_note TEXT,
payload_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','approved','rejected','failed')),
proposed_by TEXT NOT NULL REFERENCES users(id),
@@ -2586,11 +2473,14 @@ if (
reviewed_at TEXT,
applied_at TEXT
)`);
await database.exec(`INSERT INTO data_change_proposals_source_owned
await database.exec(`INSERT INTO data_change_proposals_source_owned(
id,module,action,entity_id,draft_entity_id,applied_entity_id,summary,contributor_note,
payload_json,status,proposed_by,reviewed_by,review_note,created_at,reviewed_at,applied_at
)
SELECT id,
CASE WHEN module='triggers' THEN 'talents' ELSE module END,
CASE WHEN module='triggers' THEN 'legacyTrigger.'||action ELSE action END,
entity_id,draft_entity_id,applied_entity_id,summary,payload_json,
entity_id,draft_entity_id,applied_entity_id,summary,contributor_note,payload_json,
CASE WHEN module='triggers' AND status='pending' THEN 'failed' ELSE status END,
proposed_by,reviewed_by,
CASE
@@ -2616,6 +2506,7 @@ if (
} finally {
await database.exec('PRAGMA foreign_keys=ON');
}
await assertProposalContributorNoteColumn();
await database.exec(
'CREATE INDEX IF NOT EXISTS data_change_proposals_status_created_idx ON data_change_proposals(status,created_at DESC)',
);
@@ -1,81 +0,0 @@
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { connect, type Database } from '@tursodatabase/database';
import { isFullAdministrator } from '../src/lib/server/auth/bootstrap';
const run = promisify(execFile);
let directory: string | undefined;
let database: Database | undefined;
afterEach(async () => {
await database?.close();
if (directory) await rm(directory, { recursive: true, force: true });
database = undefined;
directory = undefined;
});
describe('legacy administrator migration', () => {
it('moves legacy administrator rows to role-admin and is repeatable', async () => {
directory = await mkdtemp(join(tmpdir(), 'shd-admin-migration-'));
const databasePath = join(directory, 'database.db');
database = await connect(databasePath);
await database.exec(await readFile('database/schema.sql', 'utf8'));
await (
await database.prepare(
"INSERT INTO users(id,username,role,created_at) VALUES('legacy-admin','legacy','admin',?)",
)
).run(new Date().toISOString());
await database.close();
database = undefined;
const environment = {
...process.env,
TDR_DATABASE_PATH: databasePath,
SKIP_DEFAULT_USERS: 'true',
};
await run(process.execPath, ['scripts/db-migrate.mjs'], {
cwd: process.cwd(),
env: environment,
});
database = await connect(databasePath);
let user = await (
await database.prepare('SELECT role FROM users WHERE id=?')
).get('legacy-admin');
let relationship = await (
await database.prepare(
'SELECT role_id FROM user_roles WHERE user_id=? AND role_id=?',
)
).get('legacy-admin', 'role-admin');
expect(user.role).toBe('user');
expect(relationship.role_id).toBe('role-admin');
await database.close();
database = undefined;
await run(process.execPath, ['scripts/db-migrate.mjs'], {
cwd: process.cwd(),
env: environment,
});
database = await connect(databasePath);
user = await (
await database.prepare('SELECT role FROM users WHERE id=?')
).get('legacy-admin');
relationship = await (
await database.prepare(
'SELECT COUNT(*) AS count FROM user_roles WHERE user_id=? AND role_id=?',
)
).get('legacy-admin', 'role-admin');
expect(user.role).toBe('user');
expect(Number(relationship.count)).toBe(1);
expect(await isFullAdministrator(database, 'legacy-admin')).toBe(true);
await (
await database.prepare(
'DELETE FROM user_roles WHERE user_id=? AND role_id=?',
)
).run('legacy-admin', 'role-admin');
expect(await isFullAdministrator(database, 'legacy-admin')).toBe(false);
});
});
-59
View File
@@ -5,7 +5,6 @@ const APP_REQUIRED = [
'APP_ORIGIN',
'ORIGIN',
'PASSKEY_RP_ID',
'MFA_TOTP_ENCRYPTION_KEYS',
'SCHEDULER_TOKEN',
'TDR_DATABASE_PATH',
'TDR_AVATAR_STORAGE_PATH',
@@ -49,7 +48,6 @@ export function validateRuntimeEnvironment(mode, environment) {
requireValues(APP_REQUIRED);
validateSchedulerToken(get('SCHEDULER_TOKEN'), errors);
validateMfaTotpEncryptionKeys(get('MFA_TOTP_ENCRYPTION_KEYS'), errors);
const appOrigin = validateOrigin('APP_ORIGIN', get('APP_ORIGIN'), errors);
const adapterOrigin = validateOrigin('ORIGIN', get('ORIGIN'), errors);
@@ -232,60 +230,3 @@ function validateSchedulerToken(value, errors) {
);
}
}
/**
* Validate the app-only TOTP encryption keyring without including configured
* values in an error. The first entry is the active write key.
*
* @param {string} value
* @param {string[]} errors
*/
function validateMfaTotpEncryptionKeys(value, errors) {
if (!value) return;
const entries = value.split(',').map((entry) => entry.trim());
if (
entries.length < 1 ||
entries.length > 3 ||
entries.some((entry) => !entry)
) {
errors.push(
'MFA_TOTP_ENCRYPTION_KEYS must contain 1 through 3 key entries.',
);
return;
}
const ids = new Set();
const keys = new Set();
for (const entry of entries) {
const separator = entry.indexOf(':');
const keyId = separator > 0 ? entry.slice(0, separator) : '';
const encodedKey = separator > 0 ? entry.slice(separator + 1) : '';
if (
!/^[A-Za-z0-9_-]{1,64}$/.test(keyId) ||
!/^[A-Za-z0-9_-]+$/.test(encodedKey) ||
encodedKey.length !== 43
) {
errors.push(
'MFA_TOTP_ENCRYPTION_KEYS entries must use key-id and canonical 32-byte Base64URL values.',
);
continue;
}
let decoded;
try {
decoded = Buffer.from(encodedKey, 'base64url');
} catch {
decoded = Buffer.alloc(0);
}
if (decoded.length !== 32 || decoded.toString('base64url') !== encodedKey) {
errors.push(
'MFA_TOTP_ENCRYPTION_KEYS entries must use key-id and canonical 32-byte Base64URL values.',
);
continue;
}
if (ids.has(keyId) || keys.has(encodedKey)) {
errors.push('MFA_TOTP_ENCRYPTION_KEYS must not repeat key IDs or keys.');
}
ids.add(keyId);
keys.add(encodedKey);
}
}
-23
View File
@@ -5,8 +5,6 @@ const validAppEnvironment = {
APP_ORIGIN: 'https://stage.shd.build',
ORIGIN: 'https://stage.shd.build',
PASSKEY_RP_ID: 'shd.build',
MFA_TOTP_ENCRYPTION_KEYS:
'primary-2026:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
SCHEDULER_TOKEN: 'scheduler-secret-with-32-characters',
TDR_DATABASE_PATH: '/app/data/shd-build-staging.db',
TDR_AVATAR_STORAGE_PATH: '/app/data/avatars',
@@ -23,7 +21,6 @@ describe('validateRuntimeEnvironment', () => {
'APP_ORIGIN is required.',
'ORIGIN is required.',
'PASSKEY_RP_ID is required.',
'MFA_TOTP_ENCRYPTION_KEYS is required.',
'SCHEDULER_TOKEN is required.',
'TDR_DATABASE_PATH is required.',
'TDR_AVATAR_STORAGE_PATH is required.',
@@ -161,24 +158,4 @@ describe('validateRuntimeEnvironment', () => {
validateRuntimeEnvironment('worker' as 'app', validAppEnvironment),
).toThrow('Unsupported runtime mode: worker');
});
it('validates the MFA encryption keyring without echoing secrets', () => {
expect(
validateRuntimeEnvironment('app', {
...validAppEnvironment,
MFA_TOTP_ENCRYPTION_KEYS:
'one:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,one:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
}),
).toEqual(['MFA_TOTP_ENCRYPTION_KEYS must not repeat key IDs or keys.']);
const errors = validateRuntimeEnvironment('app', {
...validAppEnvironment,
MFA_TOTP_ENCRYPTION_KEYS:
'primary:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
});
expect(errors).toEqual([
'MFA_TOTP_ENCRYPTION_KEYS entries must use key-id and canonical 32-byte Base64URL values.',
]);
expect(errors.join('\n')).not.toContain('primary:');
});
});
+1 -1
View File
@@ -7,7 +7,6 @@ import { validateRuntimeEnvironment } from './runtime-environment.js';
const APP_SECRET_NAMES = new Set([
'APP_ORIGIN',
'MFA_TOTP_ENCRYPTION_KEYS',
'DISCORD_CLIENT_ID',
'DISCORD_CLIENT_SECRET',
'DISCORD_REDIRECT_URI',
@@ -15,6 +14,7 @@ const APP_SECRET_NAMES = new Set([
'OPENAI_MECHANIC_MODEL',
'OPENAI_MECHANIC_REASONING_EFFORT',
'OPENAI_MODERATION_API_KEY',
'MFA_TOTP_ENCRYPTION_KEYS',
'ORIGIN',
'PASSKEY_RP_ID',
'REMOVE_BG_API_KEY',
+250
View File
@@ -2818,6 +2818,24 @@ a.secondary:active {
font-size: var(--shd-type-telemetry);
line-height: 1.35;
}
.talent-icon-identity .game-data-render-upload .image-drop-input {
grid-template-columns: 1fr;
gap: 6px;
text-align: center;
}
.talent-icon-identity .game-data-render-upload .image-upload-preview {
width: 100%;
}
.talent-icon-identity .game-data-render-upload .image-upload-actions {
display: grid;
grid-template-columns: 1fr 1fr;
width: 100%;
}
.talent-icon-identity .game-data-render-upload .image-upload-actions button {
min-width: 0;
padding: 7px 3px;
font-size: var(--shd-type-telemetry);
}
.dashboard-row > .registry-render-identity {
display: flex;
align-items: center;
@@ -19386,3 +19404,235 @@ a.secondary:active {
grid-template-columns: 1fr;
}
}
/* Public mechanic behavior status: Variant A integrated card hierarchy. */
.database-item-name-line {
min-width: 0;
display: flex;
align-items: flex-start;
gap: 8px;
}
.database-item-name-line > h2 {
min-width: 0;
}
.database-mechanic-status {
flex: none;
display: inline-flex;
align-items: center;
min-height: 22px;
padding: 4px 6px;
border: 1px solid var(--shd-model-border);
background: var(--shd-model-surface);
color: var(--shd-info);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.7px;
line-height: 1;
white-space: nowrap;
}
.database-mechanic-status.not-modeled {
border-color: var(--shd-border-strong);
background: var(--shd-surface-active);
color: var(--shd-text-muted);
}
.database-mechanic-groups {
display: grid;
gap: var(--shd-gap-sm);
margin: 10px 12px 0;
}
.database-mechanic-group {
min-width: 0;
display: grid;
gap: 6px;
}
.database-mechanic-group-context {
margin: 0;
color: var(--shd-text-muted);
font-size: var(--shd-type-telemetry);
font-weight: 800;
letter-spacing: 0.5px;
}
.database-mechanic-group-identity {
min-height: 48px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
padding: 9px 10px;
border: 1px solid var(--shd-border);
background: var(--shd-surface-raised);
}
.database-mechanic-group-identity > div {
min-width: 0;
display: grid;
gap: 3px;
}
.database-mechanic-group-identity small,
.database-mechanic-behavior > small,
.database-mechanic-variant-label > span,
.database-mechanic-display-source dt {
color: var(--shd-text-dim);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.8px;
line-height: 1.1;
}
.database-mechanic-group-identity strong {
overflow-wrap: anywhere;
color: var(--shd-text);
font-size: var(--shd-type-supporting);
line-height: 1.25;
}
.database-mechanic-variants {
display: grid;
gap: 6px;
}
.database-mechanic-variant {
min-width: 0;
display: grid;
grid-template-columns: 64px minmax(0, 1fr);
border: 1px solid var(--shd-model-border);
background: var(--shd-model-surface);
}
.database-mechanic-variant[data-status='not_modeled'] {
border-color: var(--shd-border);
background: var(--shd-surface-raised);
}
.database-mechanic-variant-label {
align-self: stretch;
display: grid;
align-content: start;
padding: 10px 8px;
border-right: 1px solid var(--shd-model-border);
}
.database-mechanic-variant[data-status='not_modeled'] .database-mechanic-variant-label {
border-color: var(--shd-border);
}
.database-mechanic-variant-label > span {
color: var(--shd-info);
}
.database-mechanic-variant[data-status='not_modeled'] .database-mechanic-variant-label > span {
color: var(--shd-text-muted);
}
.database-mechanic-behavior {
min-width: 0;
padding: 10px 12px;
border-left: 2px solid var(--shd-info);
}
.database-mechanic-variant[data-status='not_modeled'] .database-mechanic-behavior {
border-left-color: var(--shd-text-dim);
}
.database-mechanic-behavior > small {
display: block;
color: var(--shd-info);
}
.database-mechanic-variant[data-status='not_modeled'] .database-mechanic-behavior > small {
color: var(--shd-text-muted);
}
.database-mechanic-behavior > p {
margin: 6px 0 0;
color: var(--shd-text);
font: var(--shd-type-supporting)/1.5 var(--shd-font-editorial);
}
.database-mechanic-group:not(.detail) .database-mechanic-behavior > p {
display: -webkit-box;
overflow: hidden;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
}
.database-mechanic-display-source {
margin: 0;
border: 1px solid var(--shd-border);
background: var(--shd-surface);
}
.database-mechanic-display-source > div {
display: grid;
gap: 4px;
padding: 9px 10px;
}
.database-mechanic-display-source dd {
margin: 0;
color: var(--shd-text-muted);
font-size: var(--shd-type-telemetry);
font-weight: 800;
letter-spacing: 0.5px;
}
.database-specialization-effect-groups {
padding-top: 9px;
border-top: 1px solid var(--shd-border);
}
.database-preview-dialog:has(.database-mechanic-groups) {
width: min(760px, 100%);
}
.database-global-results > div > a {
grid-template-columns: 110px minmax(0, 0.8fr) minmax(120px, 1.35fr) auto auto;
grid-template-areas: 'category identity behavior status navigation';
}
.database-global-results > div > a > small {
grid-area: category;
}
.database-global-results > div > a > .database-global-result-identity {
grid-area: identity;
}
.database-global-results .database-global-result-behavior {
display: block;
grid-area: behavior;
}
.database-global-results .database-mechanic-status {
grid-area: status;
justify-self: end;
}
.database-global-results .database-global-result-navigation {
grid-area: navigation;
color: var(--shd-orange);
}
@media (max-width: 750px) {
.database-item-name-line {
display: grid;
gap: 7px;
}
.database-item-name-line .database-mechanic-status {
width: max-content;
}
.database-mechanic-variant {
grid-template-columns: 1fr;
}
.database-mechanic-variant-label {
padding: 7px 10px;
border-right: 0;
border-bottom: 1px solid var(--shd-model-border);
}
.database-mechanic-variant[data-status='not_modeled'] .database-mechanic-variant-label {
border-color: var(--shd-border);
}
.database-mechanic-group-identity {
align-items: stretch;
flex-direction: column;
}
.database-mechanic-group-identity .database-mechanic-status {
width: max-content;
}
.database-global-results > div > a {
grid-template-columns: minmax(0, 1fr) auto;
grid-template-areas:
'category category'
'identity navigation'
'status navigation'
'behavior behavior';
}
.database-global-results .database-mechanic-status {
justify-self: start;
}
.database-global-results > div > a:not(:has(.database-mechanic-status)) {
grid-template-areas:
'category category'
'identity navigation'
'behavior behavior';
}
}
@media (prefers-reduced-motion: reduce) {
.database-mechanic-status,
.database-mechanic-variant {
transition: none;
}
}
+25 -71
View File
@@ -2,21 +2,13 @@ import { json, type Handle, type HandleServerError } from '@sveltejs/kit';
import { stringify } from 'devalue';
import { randomUUID } from 'node:crypto';
import { getSessionUser } from '$lib/server/auth/session';
import {
hasActiveTotpFactor,
isFullAdministrator,
} from '$lib/server/auth/bootstrap';
import {
createAuthenticationTransaction,
getAuthenticationTransaction,
} from '$lib/server/auth/authentication-transactions';
import { getDatabase } from '$lib/server/database';
import {
getSiteAccessBlock,
getSiteAccessSettings,
} from '$lib/server/site-access';
import {
DATA_MODULES,
ProposalPayloadValidationError,
proposalActionResult,
queueDataProposal,
shouldModerateDataMutation,
@@ -58,62 +50,6 @@ export const handle: Handle = async ({ event, resolve }) => {
{ status: 404 },
);
}
const isIsacRoute =
event.url.pathname === '/isac' || event.url.pathname.startsWith('/isac/');
if (sessionUser && isIsacRoute) {
const database = await getDatabase();
if (await isFullAdministrator(database, sessionUser.id)) {
const hasFactor = await hasActiveTotpFactor(database, sessionUser.id);
const mutation = !['GET', 'HEAD'].includes(event.request.method);
if (!hasFactor) {
if (mutation)
return json(
{ error: 'Administrator MFA enrollment is required.' },
{ status: 403, headers: { 'cache-control': 'no-store' } },
);
return new Response(null, {
status: 303,
headers: {
location: '/account/security?required=admin',
'cache-control': 'no-store',
'referrer-policy': 'no-referrer',
},
});
}
if (sessionUser.aal !== 2) {
if (mutation)
return json(
{ error: 'AAL2 authentication is required.' },
{ status: 403, headers: { 'cache-control': 'no-store' } },
);
const returnPath = `${event.url.pathname}${event.url.search}`;
const existing = await getAuthenticationTransaction(
event.cookies,
database,
);
if (
!existing ||
existing.userId !== sessionUser.id ||
existing.kind !== 'step_up'
) {
await createAuthenticationTransaction(event.cookies, database, {
userId: sessionUser.id,
kind: 'step_up',
returnPath,
});
}
return new Response(null, {
status: 303,
headers: {
location: '/auth/two-factor',
'cache-control': 'no-store',
'referrer-policy': 'no-referrer',
},
});
}
}
}
if (event.request.method === 'POST') {
const match = event.url.pathname.match(/^\/isac\/([^/]+)$/);
const module = match?.[1] as DataModule | undefined;
@@ -147,12 +83,30 @@ export const handle: Handle = async ({ event, resolve }) => {
);
}
const submittedForm = await event.request.formData();
const proposal = await queueDataProposal(
user,
module,
action,
submittedForm,
);
let proposal: Awaited<ReturnType<typeof queueDataProposal>>;
try {
proposal = await queueDataProposal(
user,
module,
action,
submittedForm,
);
} catch (error) {
if (!(error instanceof ProposalPayloadValidationError)) throw error;
if (
event.request.headers.get('accept')?.includes('application/json')
) {
return json(
{
type: 'failure',
status: 413,
data: { proposalError: error.message },
},
{ status: 413 },
);
}
return new Response(error.message, { status: 413 });
}
if (event.request.headers.get('accept')?.includes('application/json')) {
const result = proposalActionResult(
module,
+613 -71
View File
@@ -10,12 +10,36 @@ import {
equippedConditionalProgram,
mechanicModifiersAt,
skillModifierWindowsForMechanic,
evaluateLoadoutCombat,
weaponCriticalChance,
} from './loadout-combat.js';
import {
calculateSkillDps,
type SkillAbilityInput,
} from '$lib/calculations/skill';
import type { MechanicRuntimeSelection } from '$lib/server/mechanic-runtime-selection';
function selectedRuntime(
variants: Record<string, MechanicProgram>,
options: Partial<
Pick<MechanicRuntimeSelection, 'simulationReadiness' | 'scenarioInputs'>
> = {},
): MechanicRuntimeSelection {
return {
owner: { type: 'talent', id: 'talent', scope: 'standard', hasTierII: true },
sourceId: 'source',
sourceFingerprint: 'a'.repeat(64),
revisionId: 'revision',
revisionNumber: 1,
simulationReadiness: options.simulationReadiness ?? 'ready',
scenarioInputs: options.scenarioInputs ?? [],
variants: Object.entries(variants).map(([key, program]) => ({
key,
label: key,
program,
})),
};
}
describe('loadout mechanic timeline', () => {
function magazineBandsFor(magazine: number, encounterSeconds = magazine - 1) {
@@ -176,6 +200,38 @@ describe('loadout mechanic timeline', () => {
).toBe(true);
});
it('emits the Agent-granted-buff ally count from its exact scenario input and defaults it to zero', () => {
const profile = createDraft().combatProfile;
profile.encounterSeconds = 1;
const configured = buildWeaponMechanicTimeline(
{ rpm: 60, magazine: 100, reload_speed: 0 },
profile,
0,
{
scenarioInputs: {
'allies-within-30m-with-agent-granted-buff': 4,
'allies-within-radius': 2,
},
},
).filter((event) => event.kind === 'proximity_snapshot');
const defaults = buildWeaponMechanicTimeline(
{ rpm: 60, magazine: 100, reload_speed: 0 },
profile,
).filter((event) => event.kind === 'proximity_snapshot');
expect(
configured.map(
(event) => event.values?.alliesWithin30MetersWithAgentGrantedBuff,
),
).toEqual([4, 4]);
expect(configured.map((event) => event.values?.allyCount)).toEqual([2, 2]);
expect(
defaults.map(
(event) => event.values?.alliesWithin30MetersWithAgentGrantedBuff,
),
).toEqual([0, 0]);
});
it('seeds Extra Health state before periodic stack evaluation', () => {
const profile = createDraft().combatProfile;
profile.encounterSeconds = 2;
@@ -259,82 +315,568 @@ describe('loadout mechanic timeline', () => {
).toEqual([1, 2]);
});
it('falls back to a documented Tier I mechanic when exotic Tier II is absent', () => {
const persistedRule = {
rule: {
id: 'tier-i-only',
source_type: 'talent',
source_id: 'exotic-talent',
configured: 1,
script_version: 1,
simulation_readiness: 'ready',
scenario_inputs_json: '[]',
},
statePools: [],
clauses: [
{
id: 'shot-clause',
rule_id: 'tier-i-only',
clause_key: 'shot',
label: 'Shot',
trigger_id: null,
event_kind: 'shot_fired',
parameters_json: '{}',
conditions_json: JSON.stringify({ kind: 'true' }),
reducer_json: JSON.stringify({ kind: 'none' }),
emission_kind: 'each_match',
state_pool_id: null,
mutations_json: '[]',
cooldown_seconds: null,
output_branch: 'active',
sort_order: 1,
active: 1,
},
],
outcomes: [
{
id: 'weapon-damage-i',
rule_id: 'tier-i-only',
clause_id: 'shot-clause',
state_pool_id: null,
effect_key: 'Weapon Damage',
variant_key: 'I',
outcome_key: 'weapon-damage',
application_kind: 'active_modifier',
effect_scope: 'equipped_weapon',
stat_attribute_id: 'weapon-damage',
value: 15,
value_expression_json: null,
value_basis: 'flat',
resource_kind: null,
combat_timing: null,
delivery_mode: 'instant',
delivery_duration_seconds: null,
targeting_json: null,
value_scaling: 'flat',
unit: '%',
damage_basis: null,
application_phase: 'on_event',
min_state_value: null,
max_state_value: null,
description_slot: 1,
sort_order: 1,
},
],
triggers: [],
it('selects a direct validated Phase 2 program without adapting legacy rows', () => {
const tierTwo: MechanicProgram = {
id: 'mechanic-runtime:["source","II"]',
name: 'Selected Tier II',
clauses: [],
};
const adapted = equippedConditionalProgram({
key: 'weapon:0:exotic-talent',
tier: 2,
isExotic: true,
rule: persistedRule,
expect(
equippedConditionalProgram({
key: 'weapon:0:talent',
tier: 2,
isExotic: false,
runtime: selectedRuntime({ I: { ...tierTwo, id: 'tier-I' }, II: tierTwo }),
}),
).toBe(tierTwo);
});
it('interpolates Skill Chip minimum and maximum programs from one selected revision', () => {
const program = (id: string, value: number): MechanicProgram => ({
id,
name: 'Skill Chip',
clauses: [
{
id: 'chip-clause',
when: 'weapon_hit',
reducer: { kind: 'none' },
mutations: [],
outcomes: [
{
id: 'chip-outcome',
label: 'Chip outcome',
phase: 'on_event',
kind: 'attribute_modifier',
scope: 'all_skills',
value,
basis: 'flat',
attributeId: 'skill-damage',
},
],
},
],
});
const runtime = selectedRuntime({
minimum: program('minimum', 10),
maximum: program('maximum', 40),
});
expect(adapted?.clauses[0].outcomes?.[0]).toMatchObject({
id: 'weapon-damage-i',
value: 15,
const interpolated = equippedConditionalProgram({
key: 'chips:chip-set:ability',
tier: 2,
isExotic: false,
runtime,
});
expect(interpolated?.clauses[0].outcomes?.[0]?.value).toBe(30);
expect(interpolated?.id).toBe('minimum');
});
it('interpolates expression-backed outcomes, nested values, and pool durations', () => {
const program = (id: string, value: number): MechanicProgram => ({
id,
name: 'Skill Chip',
scenarioInputs: [
{
key: 'target-count',
label: 'Target count',
kind: 'slider',
readiness: 'ready',
defaultValue: value,
bestCaseValue: value + 3,
min: value - 2,
max: value + 7,
},
],
pools: [
{
key: 'chip-pool',
label: 'Chip pool',
scope: 'agent',
initial: value,
min: value - 2,
max: value * 2,
bestCaseValue: value + 2,
expiresAfterSeconds: value - 1,
},
],
clauses: [
{
id: 'chip-clause',
when: 'weapon_hit',
reducer: {
kind: 'periodic',
immediate: true,
intervalSeconds: {
op: 'clamp',
value: {
op: 'add',
left: value,
right: { op: 'floor', value: value + 1 },
},
min: value - 1,
max: value * 3,
},
},
cooldownSeconds: value,
weight: {
op: 'multiply',
left: value,
right: {
op: 'subtract',
left: { ref: { source: 'scenario', key: 'target-count' } },
right: value - 1,
},
},
mutations: [
{
kind: 'add',
pool: 'chip-pool',
value: {
op: 'multiply',
left: value,
right: { op: 'add', left: value, right: 1 },
},
},
],
outcomes: [
{
id: 'chip-outcome',
label: 'Chip outcome',
phase: 'while_active',
kind: 'attribute_modifier',
scope: 'all_skills',
value: {
op: 'multiply',
left: {
op: 'clamp',
value: {
op: 'add',
left: value,
right: { op: 'floor', value: value + 1 },
},
min: value - 1,
max: value * 3,
},
right: {
ref: { source: 'attribute', attributeId: 'skill-damage' },
},
},
basis: 'flat',
attributeId: 'skill-damage',
statePool: 'chip-pool',
perStack: true,
durationSeconds: value,
minStacks: value - 1,
maxStacks: value * 2,
probabilityPercent: value * 10,
},
],
},
],
});
const runtime = selectedRuntime({
minimum: program('minimum', 3),
maximum: program('maximum', 15),
});
const interpolated = equippedConditionalProgram({
key: 'chips:chip-set:ability',
tier: 1,
isExotic: false,
runtime,
});
expect(interpolated?.scenarioInputs?.[0]).toMatchObject({
defaultValue: 7,
bestCaseValue: 10,
min: 5,
max: 14,
});
expect(interpolated?.pools?.[0]).toMatchObject({
initial: 7,
min: 5,
max: 14,
bestCaseValue: 9,
expiresAfterSeconds: 6,
});
expect(interpolated?.clauses[0]).toMatchObject({
cooldownSeconds: 7,
reducer: {
kind: 'periodic',
immediate: true,
intervalSeconds: {
op: 'clamp',
value: {
op: 'add',
left: 7,
right: { op: 'floor', value: 8 },
},
min: 6,
max: 21,
},
},
mutations: [
{
value: {
op: 'multiply',
left: 7,
right: { op: 'add', left: 7, right: 1 },
},
},
],
});
expect(interpolated?.clauses[0].outcomes?.[0]).toMatchObject({
value: {
op: 'multiply',
left: {
op: 'clamp',
value: {
op: 'add',
left: 7,
right: { op: 'floor', value: 8 },
},
min: 6,
max: 21,
},
right: {
ref: { source: 'attribute', attributeId: 'skill-damage' },
},
},
attributeId: 'skill-damage',
statePool: 'chip-pool',
perStack: true,
durationSeconds: 7,
minStacks: 6,
maxStacks: 14,
probabilityPercent: 70,
});
});
it('returns exact endpoint programs and retains quality-count clamping', () => {
const program = (id: string, value: number): MechanicProgram => ({
id,
name: 'Skill Chip',
clauses: [
{
id: 'chip-clause',
when: 'weapon_hit',
reducer: { kind: 'none' },
mutations: [],
outcomes: [
{
id: 'chip-outcome',
label: 'Chip outcome',
phase: 'on_event',
kind: 'attribute_modifier',
scope: 'all_skills',
value,
basis: 'flat',
attributeId: 'skill-damage',
},
],
},
],
});
const minimum = program('minimum', 10);
const maximum = program('maximum', 40);
const runtime = selectedRuntime({ minimum, maximum });
const selected = (tier: number) =>
equippedConditionalProgram({
key: 'chips:chip-set:ability',
tier,
isExotic: false,
runtime,
});
expect(selected(-1)).toBe(minimum);
expect(selected(0)).toBe(minimum);
expect(selected(3)).toBe(maximum);
expect(selected(4)).toBe(maximum);
});
it('withholds Skill Chip execution when minimum and maximum graphs differ', () => {
const minimum: MechanicProgram = {
id: 'minimum',
name: 'Skill Chip',
clauses: [
{
id: 'chip-clause',
when: 'weapon_hit',
reducer: { kind: 'none' },
mutations: [],
outcomes: [
{
id: 'chip-outcome',
label: 'Chip outcome',
phase: 'on_event',
kind: 'attribute_modifier',
scope: 'all_skills',
value: {
op: 'multiply',
left: 10,
right: {
ref: { source: 'attribute', attributeId: 'skill-damage' },
},
},
basis: 'flat',
attributeId: 'skill-damage',
},
],
},
],
};
const maximum: MechanicProgram = {
...minimum,
id: 'maximum',
clauses: [
{
...minimum.clauses[0],
outcomes: [
{
...minimum.clauses[0].outcomes![0],
value: {
op: 'multiply',
left: 40,
right: {
ref: { source: 'attribute', attributeId: 'skill-duration' },
},
},
},
],
},
],
};
const selected = (
runtime: MechanicRuntimeSelection,
tier = 2,
) =>
equippedConditionalProgram({
key: 'chips:chip-set:ability',
tier,
isExotic: false,
runtime,
});
expect(selected(selectedRuntime({ minimum }))).toBeNull();
expect(selected(selectedRuntime({ maximum }))).toBeNull();
expect(selected(selectedRuntime({ minimum, maximum }), 0)).toBeNull();
expect(selected(selectedRuntime({ minimum, maximum }))).toBeNull();
expect(selected(selectedRuntime({ minimum, maximum }), 3)).toBeNull();
const extraOutcomeMaximum: MechanicProgram = {
...minimum,
id: 'maximum-extra-outcome',
clauses: [
{
...minimum.clauses[0],
outcomes: [
...minimum.clauses[0].outcomes!,
{ ...minimum.clauses[0].outcomes![0], id: 'additional-outcome' },
],
},
],
};
expect(
selected(selectedRuntime({ minimum, maximum: extraOutcomeMaximum })),
).toBeNull();
});
it('falls back to Tier I only for an exotic selected revision that omits Tier II', () => {
const tierOne: MechanicProgram = {
id: 'mechanic-runtime:["exotic-source","I"]',
name: 'Selected Tier I',
clauses: [],
};
const runtime = selectedRuntime({ I: tierOne });
expect(
equippedConditionalProgram({
key: 'weapon:0:exotic-talent',
tier: 2,
isExotic: true,
runtime,
}),
).toBe(tierOne);
expect(
equippedConditionalProgram({
key: 'weapon:0:standard-talent',
tier: 2,
isExotic: false,
runtime,
}),
).toBeNull();
});
it('does not execute an unselected or stale legacy payload', () => {
const staleHistorical = {
key: 'weapon:0:talent',
tier: 1,
isExotic: false,
runtime: null,
rule: { clauses: [{ outcomes: [{ value: 999 }] }] },
};
expect(equippedConditionalProgram(staleHistorical)).toBeNull();
});
});
describe('requires-assumptions mechanic gating', () => {
const program: MechanicProgram = {
id: 'assumed-direct-damage',
name: 'Assumed direct damage',
scenarioInputs: [
{
key: 'assumed-direct-damage',
label: 'Assumed direct damage',
kind: 'number',
readiness: 'requires_assumption',
min: 1,
max: 100,
},
],
clauses: [
{
id: 'damage-on-hit',
when: 'weapon_hit',
reducer: { kind: 'none' },
mutations: [],
outcomes: [
{
id: 'assumed-damage',
label: 'Assumed damage',
phase: 'on_event',
kind: 'direct_damage',
scope: 'equipped_weapon',
basis: 'flat',
value: {
ref: { source: 'scenario', key: 'assumed-direct-damage' },
},
},
],
},
],
};
function fixture(inputs?: Record<string, number | boolean>) {
const draft = createDraft();
for (const weapon of draft.weapons) {
weapon.itemId = 'weapon';
weapon.damage = 100;
}
for (const slot of Object.keys(draft.gear)) draft.gear[slot].itemId = 'gear';
for (const chip of draft.chips) chip.setId = 'chip';
draft.protocol.itemId = 'protocol';
draft.specialization.focusId = 'focus';
draft.conditionalEffects['weapon:0:assumed'] = {
mode: 'encounter',
...(inputs ? { inputs } : {}),
};
const runtime = selectedRuntime(
{ I: program },
{
simulationReadiness: 'requires_assumptions',
scenarioInputs: program.scenarioInputs,
},
);
return {
draft,
catalog: {
attributes: [
{
id: 'weapon-damage',
name: 'Weapon Damage',
calculation_type: 'Additive',
unit: '%',
cap_value: null,
},
],
gear: [],
gearAugments: [],
brands: [],
weapons: [
{
id: 'weapon',
name: 'Weapon',
category: 'Assault Rifle',
rpm: 60,
magazine: 100,
reload_speed: 1,
},
],
talents: [],
chipSets: [],
protocols: [],
specializations: [
{
focuses: [
{
id: 'focus',
abilities: [{ id: 'ability-1' }, { id: 'ability-2' }, { id: 'ability-3' }],
nodes: [],
},
],
},
],
calculation: {
revision: { id: 'revision', version: 1 },
stages: [],
profiles: [
{
weapon_category: '*',
stage_key: 'weapon_damage',
stat_attribute_id: 'weapon-damage',
weight: 1,
},
],
},
},
summary: {
stats: [{ id: 'weapon-damage', value: 0, sourceCount: 0 }],
abilityStats: [],
activeBonuses: [],
equippedTalents: [
{
key: 'weapon:0:assumed',
id: 'assumed',
runtime,
tier: 1,
isExotic: false,
source: 'weapon',
description: '',
custom: { name: 'Assumed direct damage' },
},
],
},
};
}
it('blocks combat output when an active requires-assumptions mechanic has no caller input', () => {
const { draft, catalog, summary } = fixture();
const primary = evaluateLoadoutCombat(draft, catalog, summary)[0];
expect(primary.status).toBe('insufficient');
if (primary.status === 'insufficient') {
expect(primary.missing).toContain(
'Conditional mechanic Assumed direct damage requires explicit valid scenario inputs: Assumed direct damage',
);
}
});
it('executes a requires-assumptions mechanic when the caller supplies a valid input', () => {
const { draft, catalog, summary } = fixture({
'assumed-direct-damage': 50,
});
const primary = evaluateLoadoutCombat(draft, catalog, summary)[0];
expect(primary.status).toBe('complete');
if (primary.status === 'complete') {
expect(primary.effectSummaries?.[0]?.activationCount).toBeGreaterThan(0);
expect(primary.encounterDps).toBeGreaterThan(100);
}
});
});
+255 -88
View File
@@ -7,14 +7,15 @@ import {
} from '$lib/calculations/combat';
import {
evaluateMechanicProgram,
PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_VALUE_KEY,
PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_INPUT,
type MechanicCombatContext,
type MechanicEvaluation,
type MechanicEvent,
type MechanicOutcome,
type MechanicProgram,
type NumericExpression,
} from '$lib/calculations/mechanic';
import { adaptConditionalEffectProgram } from '$lib/calculations/mechanic-persistence';
import type { MechanicRuntimeSelection } from '$lib/server/mechanic-runtime-selection';
import {
calculateSkillDps,
skillActivationTimes,
@@ -190,103 +191,157 @@ export function weaponCriticalChance(
);
}
function conditionalProgram(
rule: any,
function selectedRuntimeProgram(
runtime: MechanicRuntimeSelection | null | undefined,
variantKey: string,
valueScale = 1,
): MechanicProgram | null {
if (!rule?.rule) return null;
const adapted = adaptConditionalEffectProgram(rule, { variantKey });
if (
!adapted.program ||
adapted.status === 'INVALID' ||
adapted.status === 'CAPTURED_ONLY'
)
return null;
if (valueScale === 1) return adapted.program;
const scale = (value: NumericExpression): NumericExpression =>
typeof value === 'number' ? value * valueScale : value;
return {
...adapted.program,
clauses: adapted.program.clauses.map((clause) => ({
...clause,
outcomes: clause.outcomes?.map((outcome) => ({
...outcome,
value: scale(outcome.value),
})),
})),
};
return runtime?.variants.find((variant) => variant.key === variantKey)?.program ?? null;
}
function interpolatedConditionalProgram(
rule: any,
function hasMechanicProgram<T extends { program: MechanicProgram | null }>(
source: T,
): source is T & { program: MechanicProgram } {
return source.program !== null;
}
type InterpolatedMechanicValue = { value: unknown };
function isMechanicDefinitionRecord(
value: unknown,
): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
/**
* Interpolates numeric leaves only when the entire mechanic definition graph
* matches. Non-numeric values carry mechanic identity and semantics, so a
* mismatch withholds the program rather than combining different mechanics.
*/
function interpolateMechanicValue(
minimum: unknown,
maximum: unknown,
ratio: number,
): InterpolatedMechanicValue | null {
if (typeof minimum === 'number' || typeof maximum === 'number') {
if (
typeof minimum !== 'number' ||
typeof maximum !== 'number' ||
!Number.isFinite(minimum) ||
!Number.isFinite(maximum)
)
return null;
return { value: minimum + (maximum - minimum) * ratio };
}
if (Object.is(minimum, maximum)) return { value: minimum };
if (Array.isArray(minimum) || Array.isArray(maximum)) {
if (
!Array.isArray(minimum) ||
!Array.isArray(maximum) ||
minimum.length !== maximum.length
)
return null;
const values: unknown[] = [];
for (let index = 0; index < minimum.length; index += 1) {
const interpolated = interpolateMechanicValue(
minimum[index],
maximum[index],
ratio,
);
if (!interpolated) return null;
values.push(interpolated.value);
}
return { value: values };
}
if (
!isMechanicDefinitionRecord(minimum) ||
!isMechanicDefinitionRecord(maximum)
)
return null;
const minimumKeys = Object.keys(minimum).sort();
const maximumKeys = Object.keys(maximum).sort();
if (
minimumKeys.length !== maximumKeys.length ||
minimumKeys.some((key, index) => key !== maximumKeys[index])
)
return null;
const entries: [string, unknown][] = [];
for (const key of minimumKeys) {
const interpolated = interpolateMechanicValue(
minimum[key],
maximum[key],
ratio,
);
if (!interpolated) return null;
entries.push([key, interpolated.value]);
}
return { value: Object.fromEntries(entries) };
}
function interpolateMechanicProgram(
minimum: MechanicProgram,
maximum: MechanicProgram,
ratio: number,
): MechanicProgram | null {
const { id: minimumId, ...minimumDefinition } = minimum;
const { id: _maximumId, ...maximumDefinition } = maximum;
const interpolated = interpolateMechanicValue(
minimumDefinition,
maximumDefinition,
ratio,
);
if (!interpolated || !isMechanicDefinitionRecord(interpolated.value))
return null;
return { id: minimumId, ...interpolated.value } as MechanicProgram;
}
function interpolatedRuntimeProgram(
runtime: MechanicRuntimeSelection | null | undefined,
minimumVariant: string,
maximumVariant: string,
step: number,
totalSteps: number,
): MechanicProgram | null {
const minimum = conditionalProgram(rule, minimumVariant);
const maximum = conditionalProgram(rule, maximumVariant);
if (!minimum || !maximum) return minimum ?? maximum;
const minimum = selectedRuntimeProgram(runtime, minimumVariant);
const maximum = selectedRuntimeProgram(runtime, maximumVariant);
if (!minimum || !maximum) return null;
const ratio = Math.max(
0,
Math.min(1, Number(step) / Math.max(1, Number(totalSteps))),
);
const maximumByKey = new Map(
maximum.clauses.flatMap((clause) =>
(clause.outcomes ?? []).map(
(outcome) => [`${clause.id}:${outcome.id}`, outcome] as const,
),
),
);
return {
...minimum,
clauses: minimum.clauses.map((clause) => ({
...clause,
outcomes: clause.outcomes?.map((outcome) => {
const upper = maximumByKey.get(`${clause.id}:${outcome.id}`);
return upper &&
typeof outcome.value === 'number' &&
typeof upper.value === 'number'
? {
...outcome,
value: outcome.value + (upper.value - outcome.value) * ratio,
}
: outcome;
}),
})),
};
if (!Number.isFinite(ratio)) return null;
const interpolated = interpolateMechanicProgram(minimum, maximum, ratio);
if (!interpolated) return null;
if (ratio === 0) return minimum;
if (ratio === 1) return maximum;
return interpolated;
}
export function equippedConditionalProgram(
equipped: any,
equipped: Pick<
LoadoutSummary['equippedTalents'][number],
'key' | 'runtime' | 'tier' | 'isExotic'
>,
): MechanicProgram | null {
if (String(equipped.key).startsWith('chips:')) {
return interpolatedConditionalProgram(
equipped.rule,
if (equipped.key.startsWith('chips:')) {
return interpolatedRuntimeProgram(
equipped.runtime,
'minimum',
'maximum',
Number(equipped.tier),
3,
);
}
if (String(equipped.key).startsWith('protocol:')) {
return conditionalProgram(equipped.rule, 'base');
if (equipped.key.startsWith('protocol:')) {
return selectedRuntimeProgram(equipped.runtime, 'base');
}
const equipmentTalent =
String(equipped.key).startsWith('weapon:') ||
String(equipped.key).startsWith('gear:');
const variant = equipmentTalent
? Number(equipped.tier) >= 2
? 'II'
: 'I'
: 'base';
return (
conditionalProgram(equipped.rule, variant) ??
equipped.key.startsWith('weapon:') || equipped.key.startsWith('gear:');
const variant = equipmentTalent && Number(equipped.tier) >= 2 ? 'II' : 'I';
const selected = selectedRuntimeProgram(equipped.runtime, variant);
return selected ??
(equipmentTalent && equipped.isExotic && variant === 'II'
? conditionalProgram(equipped.rule, 'I')
: null)
);
? selectedRuntimeProgram(equipped.runtime, 'I')
: null);
}
export type ActiveMechanicEvaluation = {
@@ -297,15 +352,58 @@ export type ActiveMechanicEvaluation = {
events?: MechanicEvent[];
};
function configuredScenarioInputValues(configured: unknown) {
return configured && typeof configured === 'object' && !Array.isArray(configured)
? (configured as Record<string, unknown>)
: {};
}
function requiredScenarioInputs(program: MechanicProgram) {
const inputs = program.scenarioInputs ?? [];
const assumptionInputs = inputs.filter(
(input) => input.readiness === 'requires_assumption',
);
return assumptionInputs.length ? assumptionInputs : inputs;
}
function isValidScenarioInputValue(
input: NonNullable<MechanicProgram['scenarioInputs']>[number],
value: unknown,
) {
if (input.kind === 'toggle') return typeof value === 'boolean';
if (typeof value !== 'number' || !Number.isFinite(value)) return false;
if (input.min !== undefined && value < input.min) return false;
if (input.max !== undefined && value > input.max) return false;
return true;
}
function unresolvedScenarioInputs(
program: MechanicProgram,
configured: unknown,
simulationReadiness: MechanicRuntimeSelection['simulationReadiness'],
) {
if (simulationReadiness !== 'requires_assumptions') return [];
const inputs = requiredScenarioInputs(program);
if (!inputs.length) return ['no supported required scenario inputs'];
const values = configuredScenarioInputValues(configured);
return inputs.flatMap((input) => {
if (!Object.prototype.hasOwnProperty.call(values, input.key))
return [input.label];
return isValidScenarioInputValue(input, values[input.key])
? []
: [`${input.label} (invalid value)`];
});
}
function mechanicScenarioInputs(
program: MechanicProgram,
configured: unknown,
maximum = false,
) {
const values =
configured && typeof configured === 'object' && !Array.isArray(configured)
? (configured as Record<string, number | boolean>)
: {};
): Record<string, number | boolean> {
const values = configuredScenarioInputValues(configured) as Record<
string,
number | boolean
>;
return Object.fromEntries(
(program.scenarioInputs ?? []).map((input) => [
input.key,
@@ -320,22 +418,59 @@ function mechanicScenarioInputs(
);
}
function mechanicIsEnabled(
state: Pick<LoadoutDraft['conditionalEffects'][string], 'mode'>,
calculationMode: LoadoutDraft['calculationMode'],
) {
return calculationMode === 'maximum' || state.mode !== 'off';
}
function unavailableMechanicEvidence(
sources: ReadonlyArray<{
key: string;
name: string;
program: MechanicProgram;
simulationReadiness: MechanicRuntimeSelection['simulationReadiness'];
}>,
draft: LoadoutDraft,
) {
return sources.flatMap((source) => {
const state = draft.conditionalEffects[source.key] ?? { mode: 'off' };
if (!mechanicIsEnabled(state, draft.calculationMode)) return [];
const inputs = unresolvedScenarioInputs(
source.program,
state.inputs,
source.simulationReadiness,
);
return inputs.length
? [
`Conditional mechanic ${source.name} requires explicit valid scenario inputs: ${inputs.join(', ')}`,
]
: [];
});
}
function evaluateConfiguredMechanic(
program: MechanicProgram,
buildEvents: (
scenarioInputs: Record<string, number | boolean>,
) => MechanicEvent[],
state: any,
state: LoadoutDraft['conditionalEffects'][string],
profile: LoadoutDraft['combatProfile'],
weaponBaseDamage: number,
maxHealth: number,
calculationMode: LoadoutDraft['calculationMode'],
equipmentContext = { protocolTalentUpgrades: 0 },
attributes: Record<string, number> = {},
simulationReadiness: MechanicRuntimeSelection['simulationReadiness'] = 'ready',
): ActiveMechanicEvaluation | null {
if (calculationMode !== 'maximum' && state.mode === 'off') return null;
if (!mechanicIsEnabled(state, calculationMode)) return null;
if (unresolvedScenarioInputs(program, state.inputs, simulationReadiness).length)
return null;
const encounterSeconds = Math.max(1, Number(profile.encounterSeconds));
const maximum = calculationMode === 'maximum' || state.mode === 'peak';
const maximum =
simulationReadiness !== 'requires_assumptions' &&
(calculationMode === 'maximum' || state.mode === 'peak');
const scenarioInputs = mechanicScenarioInputs(program, state.inputs, maximum);
const events = buildEvents(scenarioInputs);
const result = evaluateMechanicProgram(
@@ -803,6 +938,11 @@ export function buildWeaponMechanicTimeline(
allyCount: Number(
options.scenarioInputs?.['allies-within-radius'] ?? 0,
),
[PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_VALUE_KEY]: Number(
options.scenarioInputs?.[
PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_INPUT
] ?? 0,
),
},
});
events.push({
@@ -1038,7 +1178,7 @@ function skillModifierWindows(
catalog: Catalog,
summary: LoadoutSummary,
allowedAttributeIds: Set<string>,
): SkillModifierWindow[] {
): { windows: SkillModifierWindow[]; unavailable: string[] } {
const focus = selectedFocus(draft, catalog);
const combatEffects = selectedNodeRanks(draft, catalog).flatMap(
({ node, rank }: any) =>
@@ -1051,21 +1191,25 @@ function skillModifierWindows(
const sources = [
...summary.equippedTalents.map((equipped: any) => ({
key: String(equipped.key),
name: String(equipped.custom?.name ?? 'Talent'),
abilityId: equipped.abilityId ? String(equipped.abilityId) : null,
equipmentContext: {
protocolTalentUpgrades: String(equipped.key).startsWith('protocol:')
? Number(equipped.tier)
: 0,
},
simulationReadiness: equipped.runtime?.simulationReadiness ?? 'ready',
program: equippedConditionalProgram(equipped),
})),
...combatEffects.map((effect: any) => ({
key: String(effect.id),
name: String(effect.definition?.name ?? effect.nodeName ?? 'Specialization effect'),
abilityId: effect.abilityId,
equipmentContext: { protocolTalentUpgrades: 0 },
program: conditionalProgram(effect.rule, 'base'),
simulationReadiness: effect.runtime?.simulationReadiness ?? 'ready',
program: selectedRuntimeProgram(effect.runtime, 'base'),
})),
].filter((source) => source.program);
].filter(hasMechanicProgram);
const primarySelection = draft.weapons[0];
const primaryWeapon = catalog.weapons.find(
(weapon) => weapon.id === primarySelection.itemId,
@@ -1116,6 +1260,7 @@ function skillModifierWindows(
draft.calculationMode,
source.equipmentContext,
baseAttributes,
source.simulationReadiness,
);
return evaluation ? [{ ...source, evaluation }] : [];
});
@@ -1131,7 +1276,10 @@ function skillModifierWindows(
);
}
return windows;
return {
windows,
unavailable: unavailableMechanicEvidence(sources, draft),
};
}
export function evaluateLoadoutCombat(
@@ -1159,6 +1307,7 @@ export function evaluateLoadoutCombat(
? Number(equipped.tier)
: 0,
},
simulationReadiness: equipped.runtime?.simulationReadiness ?? 'ready',
program: equippedConditionalProgram(equipped),
})),
...combatEffects.map((effect: any) => ({
@@ -1167,9 +1316,10 @@ export function evaluateLoadoutCombat(
effect.definition?.name ?? effect.nodeName ?? 'Specialization effect',
),
equipmentContext: { protocolTalentUpgrades: 0 },
program: conditionalProgram(effect.rule, 'base'),
simulationReadiness: effect.runtime?.simulationReadiness ?? 'ready',
program: selectedRuntimeProgram(effect.runtime, 'base'),
})),
].filter((source) => source.program);
].filter(hasMechanicProgram);
const skillDeploymentEvents = loadoutSkillDeploymentEvents(
draft,
catalog,
@@ -1194,6 +1344,7 @@ export function evaluateLoadoutCombat(
missing.push(
`${missingChips} specialization Skill Chip${missingChips === 1 ? '' : 's'}`,
);
missing.push(...unavailableMechanicEvidence(conditionalSources, draft));
return missing;
};
@@ -1244,6 +1395,7 @@ export function evaluateLoadoutCombat(
draft.calculationMode,
source.equipmentContext,
criticalAttributes,
source.simulationReadiness,
);
return evaluation ? [{ ...source, state, evaluation }] : [];
});
@@ -1411,6 +1563,21 @@ export function evaluateLoadoutSkillCombat(
.map((stat) => [stat.id, stat.value]),
);
const abilities = loadoutSkillAbilities(draft, catalog);
const mechanicWindows = skillModifierWindows(
draft,
catalog,
summary,
boundIds,
);
if (mechanicWindows.unavailable.length) {
return {
status: 'INSUFFICIENT_DATA',
revisionId: revisionId || null,
missing: mechanicWindows.unavailable,
abilities: [],
combined: null,
};
}
return calculateSkillDps({
rules: { revisionId, bindings },
abilities,
@@ -1433,7 +1600,7 @@ export function evaluateLoadoutSkillCombat(
];
}),
),
modifierWindows: skillModifierWindows(draft, catalog, summary, boundIds),
modifierWindows: mechanicWindows.windows,
assumptions: {
encounterSeconds: draft.combatProfile.encounterSeconds,
targetCount: Math.max(
+83 -17
View File
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest';
import type { MechanicRuntimeSelection } from '$lib/server/mechanic-runtime-selection';
import { createDraft } from './loadout.js';
import { summarizeLoadout, type LoadoutCatalog } from './loadout-summary.js';
@@ -35,6 +36,24 @@ const catalog = (overrides: Partial<LoadoutCatalog> = {}): LoadoutCatalog => ({
const stat = (summary: ReturnType<typeof summarizeLoadout>, id: string) =>
summary.stats.find((entry) => entry.id === id);
const selectedRuntime = (
sourceId: string,
variantKeys: string[],
): MechanicRuntimeSelection => ({
owner: { type: 'talent', id: sourceId, scope: 'standard', hasTierII: true },
sourceId,
sourceFingerprint: 'a'.repeat(64),
revisionId: `${sourceId}-revision`,
revisionNumber: 1,
simulationReadiness: 'ready',
scenarioInputs: [],
variants: variantKeys.map((key) => ({
key,
label: key,
program: { id: `${sourceId}:${key}`, name: sourceId, clauses: [] },
})),
});
describe('summarizeLoadout', () => {
it('returns an empty deterministic summary for a partial draft', () => {
expect(summarizeLoadout(createDraft(), catalog())).toEqual({
@@ -193,7 +212,6 @@ describe('summarizeLoadout', () => {
max_value: 45,
},
],
rule: null,
},
},
],
@@ -399,7 +417,6 @@ describe('summarizeLoadout', () => {
name: 'Recovery',
description_template: 'Restore {1}.',
effects: [{ stat_attribute_id: 'healing', base_value: 2.5 }],
rule: null,
},
},
],
@@ -536,19 +553,6 @@ describe('summarizeLoadout', () => {
exoticTalentTier: 1,
});
const rule = {
clauses: [
{
outcomes: [
{
kind: 'attribute_modifier',
attributeId: 'talent-stat',
value: 100,
},
],
},
],
};
const summary = summarizeLoadout(
draft,
catalog({
@@ -585,7 +589,6 @@ describe('summarizeLoadout', () => {
],
},
],
rule,
},
{
id: 'talent-two',
@@ -627,7 +630,7 @@ describe('summarizeLoadout', () => {
tier: 1,
tierLabel: 'TIER I',
description: 'Gain 10% for 2 Shots.',
rule,
runtime: null,
}),
expect.objectContaining({
id: 'talent-two',
@@ -645,6 +648,69 @@ describe('summarizeLoadout', () => {
expect(stat(summary, 'talent-stat')).toBeUndefined();
});
it('carries selected runtime capabilities without retaining legacy rule payloads', () => {
const draft = createDraft();
draft.gear.Holster.itemId = 'gear';
draft.gear.Holster.talentId = 'talent';
for (const chip of draft.chips.slice(0, 3)) chip.setId = 'chip-set';
draft.protocol.itemId = 'protocol';
const talentRuntime = selectedRuntime('talent-source', ['I', 'II']);
const chipRuntime = selectedRuntime('chip-source', ['minimum', 'maximum']);
const protocolRuntime = selectedRuntime('protocol-source', ['base']);
const summary = summarizeLoadout(
draft,
catalog({
gear: [{ id: 'gear', tier: 0, base_armor_min: null }],
talents: [
{
id: 'talent',
name: 'Talent',
runtime: talentRuntime,
template: 'Talent',
tiers: [{ tier: 'I', effects: [] }],
},
],
chipSets: [
{
id: 'chip-set',
name: 'Chip',
specialization_ability_id: 'ability',
talent: {
name: 'Chip Talent',
runtime: chipRuntime,
description_template: 'Chip',
effects: [],
},
},
],
protocols: [
{
id: 'protocol',
name: 'Protocol',
talent: {
name: 'Protocol Talent',
runtime: protocolRuntime,
description_template: 'Protocol',
effects: [],
},
},
],
}),
);
expect(summary.equippedTalents.map((equipped) => equipped.runtime)).toEqual([
talentRuntime,
chipRuntime,
protocolRuntime,
]);
expect(
summary.equippedTalents.every(
(equipped) => !Object.hasOwn(equipped, 'rule'),
),
).toBe(true);
});
it('uses the authored tier description when a Talent has no template row', () => {
const draft = createDraft();
draft.weapons[0].itemId = 'weapon';
+20 -8
View File
@@ -4,6 +4,7 @@ import {
type LoadoutDraft,
type TalentTier,
} from '$lib/builder/loadout';
import type { MechanicRuntimeSelection } from '$lib/server/mechanic-runtime-selection';
export type LoadoutCatalog = {
attributes: any[];
@@ -38,7 +39,18 @@ export type LoadoutSummary = {
}>;
}>;
activeBonuses: any[];
equippedTalents: any[];
equippedTalents: Array<{
key: string;
id: string;
runtime: MechanicRuntimeSelection | null;
tier: number;
tierLabel?: string;
isExotic?: boolean;
abilityId?: string | null;
source: string;
description: string;
custom?: { name?: string };
}>;
};
const coreKeys = ['firepower', 'toughness', 'engineering'] as const;
@@ -164,7 +176,7 @@ export function summarizeLoadout(
)?.id ?? '';
const brandCounts = new Map<string, number>();
const activeBonuses: any[] = [];
const equippedTalents: any[] = [];
const equippedTalents: LoadoutSummary['equippedTalents'] = [];
const abilityValues = new Map<string, Map<string, number>>();
const abilitySources = new Map<
string,
@@ -260,9 +272,9 @@ export function summarizeLoadout(
equippedTalents.push({
key: `gear:${slot}:${selection.talentId}`,
id: selection.talentId,
rule:
runtime:
catalog.talents.find((entry) => entry.id === selection.talentId)
?.rule ?? null,
?.runtime ?? null,
tier: selection.talentTier,
tierLabel: selection.talentTier === 2 ? 'TIER II' : 'TIER I',
isExotic: false,
@@ -336,9 +348,9 @@ export function summarizeLoadout(
equippedTalents.push({
key: `weapon:${index}:${equippedTalent.id}`,
id: equippedTalent.id,
rule:
runtime:
catalog.talents.find((entry) => entry.id === equippedTalent.id)
?.rule ?? null,
?.runtime ?? null,
tier: equippedTalent.tier,
tierLabel: equippedTalent.tier === 2 ? 'TIER II' : 'TIER I',
isExotic: equippedTalent.isExotic,
@@ -434,7 +446,7 @@ export function summarizeLoadout(
key: `chips:${group.item.id}:${group.abilityId}`,
id: '',
custom: group.item.talent,
rule: group.item.talent.rule ?? null,
runtime: group.item.talent.runtime ?? null,
tier: group.highEnd,
abilityId: group.abilityId || null,
source: '3 Skill Chips',
@@ -486,7 +498,7 @@ export function summarizeLoadout(
key: `protocol:${protocol.id}`,
id: '',
custom: protocol.talent,
rule: protocol.talent.rule ?? null,
runtime: protocol.talent.runtime ?? null,
tier: draft.protocol.talentUpgrades,
source: 'OS Protocol',
description: protocol.talent.description_template.replace(
@@ -0,0 +1,294 @@
import { describe, expect, it } from 'vitest';
import {
materializeMechanicAuthoredDescription,
mechanicAuthoredFingerprintPayload,
parseMechanicAuthoredSource,
type MechanicAuthoredSource,
} from './mechanic-authored-description.js';
const talentSource = (): MechanicAuthoredSource => ({
version: 1,
owner: { type: 'talent', id: 'talent-1', scope: 'standard' },
template: 'Gain {1}% for {duration} seconds. Gain {1}% again, up to {max_stacks}.',
variants: ['I', 'II'].map((key, index) => ({
key,
materialized: `Gain ${10 + index}% for 5 seconds. Gain ${10 + index}% again, up to 3.`,
slots: [
{ key: 'max_stacks', value: '3', order: 2 },
{ key: '1', value: `${10 + index}`, order: 0, unit: 'percent' },
{ key: 'duration', value: '5', order: 1, unit: 'seconds' },
],
})),
});
describe('mechanic authored descriptions', () => {
it('materializes repeated strict tokens for ordered Talent variants', () => {
expect(materializeMechanicAuthoredDescription(talentSource())).toEqual({
ok: true,
variants: talentSource().variants.map((variant) => ({
key: variant.key,
text: variant.materialized,
slots: variant.slots,
})),
});
});
it.each([
{
owner: { type: 'talent', id: 'exotic', scope: 'exotic' } as const,
keys: ['I'],
},
{
owner: {
type: 'talent',
id: 'exotic',
scope: 'exotic',
hasTierII: true,
} as const,
keys: ['I', 'II'],
},
{
owner: { type: 'os_protocol_talent', id: 'protocol' } as const,
keys: ['base'],
},
{
owner: { type: 'skill_chip_talent', id: 'chip' } as const,
keys: ['minimum', 'maximum'],
},
])('enforces the $owner.type variant contract', ({ owner, keys }) => {
const source: MechanicAuthoredSource = {
version: 1,
owner,
template: 'Gain {1}%.',
variants: keys.map((key) => ({
key,
materialized: 'Gain 10%.',
slots: [{ key: '1', value: '10', order: 0 }],
})),
};
expect(materializeMechanicAuthoredDescription(source).ok).toBe(true);
});
it('requires Specialization rank source identity', () => {
const result = materializeMechanicAuthoredDescription({
version: 1,
owner: { type: 'specialization_tree_rank', id: 'rank-1' },
template: 'Gain {1}%.',
variants: [
{
key: 'base',
materialized: 'Gain 10%.',
slots: [{ key: '1', value: '10', order: 0 }],
},
],
});
expect(result).toMatchObject({
ok: false,
errors: [{ code: 'invalid_specialization_source' }],
});
});
it('rejects malformed and slot-injected placeholders', () => {
const malformed = talentSource();
malformed.template = 'Gain {1.';
malformed.variants.forEach((variant) => {
variant.materialized = 'Gain {1.';
variant.slots = [];
});
expect(materializeMechanicAuthoredDescription(malformed)).toMatchObject({
ok: false,
errors: expect.arrayContaining([
expect.objectContaining({ code: 'unknown_token' }),
]),
});
const injected = talentSource();
injected.variants[0].slots.find((slot) => slot.key === '1')!.value =
'{raw}';
injected.variants[0].materialized =
'Gain {raw}% for 5 seconds. Gain {raw}% again, up to 3.';
expect(materializeMechanicAuthoredDescription(injected)).toMatchObject({
ok: false,
errors: expect.arrayContaining([
expect.objectContaining({ code: 'invalid_slot' }),
expect.objectContaining({ code: 'unresolved_token' }),
]),
});
});
it('rejects units embedded in authored slot values', () => {
const source = talentSource();
source.variants[0].slots.find((slot) => slot.key === '1')!.value = '10%';
expect(materializeMechanicAuthoredDescription(source)).toMatchObject({
ok: false,
errors: expect.arrayContaining([
expect.objectContaining({ code: 'invalid_slot' }),
]),
});
});
it('rejects unknown, unresolved, unused, and mismatched authored values', () => {
const source = talentSource();
source.template = 'Gain {1}% for {cooldown} seconds.';
source.variants[0].slots.push({ key: '2', value: '4', order: 4 });
const result = materializeMechanicAuthoredDescription(source);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(new Set(result.errors.map((error) => error.code))).toEqual(
new Set([
'unknown_token',
'unresolved_token',
'unused_slot',
'materialization_mismatch',
]),
);
});
it('rejects a missing required slot rather than retaining its placeholder', () => {
const source = talentSource();
source.variants[0].slots = source.variants[0].slots.filter(
(slot) => slot.key !== 'duration',
);
const result = materializeMechanicAuthoredDescription(source);
expect(result).toMatchObject({
ok: false,
errors: expect.arrayContaining([
expect.objectContaining({ code: 'unresolved_token' }),
]),
});
});
it('preserves exact authored whitespace and materialized prose', () => {
const source = talentSource();
source.template = ' Gain {1}%.\nNext line. ';
for (const variant of source.variants) {
const value = variant.slots.find((slot) => slot.key === '1')?.value;
variant.slots = variant.slots.filter((slot) => slot.key === '1');
variant.materialized = ` Gain ${value}%.\nNext line. `;
}
const result = materializeMechanicAuthoredDescription(source);
expect(result.ok && result.variants[0].text).toBe(
' Gain 10%.\nNext line. ',
);
});
it('parses unknown source values without throwing on malformed input', () => {
expect(parseMechanicAuthoredSource(null)).toMatchObject({
ok: false,
errors: [{ code: 'invalid_source' }],
});
expect(
parseMechanicAuthoredSource({
...talentSource(),
owner: {
type: new String('os_protocol_talent'),
id: 'protocol-1',
},
}),
).toMatchObject({ ok: false, errors: [{ code: 'invalid_source' }] });
expect(
parseMechanicAuthoredSource({
...talentSource(),
variants: [{ key: 'I', materialized: 10, slots: [] }],
}),
).toMatchObject({ ok: false, errors: [{ code: 'invalid_source' }] });
expect(parseMechanicAuthoredSource(talentSource())).toMatchObject({
ok: true,
});
});
it('rejects malformed typed values and whitespace-only authored content', () => {
expect(
materializeMechanicAuthoredDescription({
...talentSource(),
owner: {
type: 'talent',
id: 'talent-1',
scope: 'exotic',
hasTierII: 'false',
},
}),
).toMatchObject({ ok: false, errors: [{ code: 'invalid_source' }] });
const whitespace = talentSource();
whitespace.template = ' ';
whitespace.variants.forEach((variant) => {
variant.materialized = ' ';
variant.slots = [];
});
expect(materializeMechanicAuthoredDescription(whitespace)).toMatchObject({
ok: false,
errors: expect.arrayContaining([
expect.objectContaining({ code: 'invalid_template' }),
]),
});
});
it('strictly parses Talent Tier II and unknown source fields', () => {
expect(
parseMechanicAuthoredSource({
...talentSource(),
owner: {
type: 'talent',
id: 'talent-1',
scope: 'exotic',
hasTierII: 'false',
},
}),
).toMatchObject({ ok: false, errors: [{ code: 'invalid_source' }] });
expect(
parseMechanicAuthoredSource({ ...talentSource(), unexpected: true }),
).toMatchObject({ ok: false, errors: [{ code: 'invalid_source' }] });
});
it('normalizes omitted and false optional Talent Tier II flags identically', () => {
const omitted = talentSource();
const explicit = talentSource();
explicit.owner = {
type: 'talent',
id: 'talent-1',
scope: 'standard',
hasTierII: false,
};
expect(mechanicAuthoredFingerprintPayload(omitted)).toEqual(
mechanicAuthoredFingerprintPayload(explicit),
);
});
it('reports unsupported parser contracts specifically', () => {
expect(
parseMechanicAuthoredSource({ ...talentSource(), version: 2 }),
).toMatchObject({
ok: false,
errors: [{ code: 'unsupported_contract', path: 'version' }],
});
});
it('rejects duplicate slot ordering', () => {
const source = talentSource();
source.variants[0].slots[1].order = source.variants[0].slots[0].order;
const result = materializeMechanicAuthoredDescription(source);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.errors).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: 'invalid_slot' }),
]),
);
});
it('creates a versioned canonical fingerprint payload with ordered slots', () => {
expect(mechanicAuthoredFingerprintPayload(talentSource())).toMatchObject({
kind: 'mechanic_authored_source',
version: 1,
owner: { type: 'talent', id: 'talent-1' },
variants: [
{
key: 'I',
slots: [{ key: '1' }, { key: 'duration' }, { key: 'max_stacks' }],
},
{ key: 'II' },
],
});
});
});
@@ -0,0 +1,431 @@
export const MECHANIC_AUTHORED_CONTRACT_VERSION = 1 as const;
export type MechanicAuthoredOwner =
| {
type: 'talent';
id: string;
scope: 'standard' | 'exotic';
hasTierII?: boolean;
}
| { type: 'os_protocol_talent'; id: string }
| { type: 'skill_chip_talent'; id: string }
| { type: 'specialization_tree_rank'; id: string };
export type MechanicAuthoredSlot = {
key: string;
value: string;
order: number;
unit?: string;
attributeId?: string;
};
export type MechanicAuthoredVariant = {
key: string;
materialized: string;
slots: MechanicAuthoredSlot[];
};
export type SpecializationAuthoredInputs = {
rankDescription: string;
effectId: string;
effectTemplate: string;
};
export type MechanicAuthoredSource = {
version: typeof MECHANIC_AUTHORED_CONTRACT_VERSION;
owner: MechanicAuthoredOwner;
template: string;
variants: MechanicAuthoredVariant[];
specialization?: SpecializationAuthoredInputs;
};
export type MaterializedMechanicVariant = {
key: string;
text: string;
slots: MechanicAuthoredSlot[];
};
export type MechanicAuthoredDescriptionError = {
code:
| 'invalid_source'
| 'unsupported_contract'
| 'invalid_owner'
| 'invalid_template'
| 'invalid_variant'
| 'invalid_slot'
| 'unknown_token'
| 'unresolved_token'
| 'unused_slot'
| 'materialization_mismatch'
| 'invalid_specialization_source';
path: string;
message: string;
};
export type MechanicAuthoredDescriptionResult =
| { ok: true; variants: MaterializedMechanicVariant[] }
| { ok: false; errors: MechanicAuthoredDescriptionError[] };
export type ParsedMechanicAuthoredSourceResult =
| { ok: true; value: MechanicAuthoredSource }
| { ok: false; errors: MechanicAuthoredDescriptionError[] };
export type MechanicAuthoredFingerprintPayload = {
kind: 'mechanic_authored_source';
version: typeof MECHANIC_AUTHORED_CONTRACT_VERSION;
owner: MechanicAuthoredOwner;
template: string;
variants: Array<{
key: string;
materialized: string;
slots: MechanicAuthoredSlot[];
}>;
specialization?: SpecializationAuthoredInputs;
};
const TOKEN_PATTERN = /\{([^{}]+)\}/g;
const NUMERIC_SLOT_VALUE_PATTERN = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/;
const ALLOWED_NAMED_TOKENS = new Set(['duration', 'max_stacks']);
const objectValue = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
const hasOnlyKeys = (
value: Record<string, unknown>,
allowed: readonly string[],
) => Object.keys(value).every((key) => allowed.includes(key));
function requiredVariantKeys(owner: MechanicAuthoredOwner): readonly string[] {
switch (owner.type) {
case 'talent':
return owner.scope === 'standard' || owner.hasTierII
? ['I', 'II']
: ['I'];
case 'os_protocol_talent':
case 'specialization_tree_rank':
return ['base'];
case 'skill_chip_talent':
return ['minimum', 'maximum'];
}
}
function tokenKeys(template: string) {
return [...template.matchAll(TOKEN_PATTERN)].map((match) => match[1]);
}
function isAllowedToken(key: string) {
return ALLOWED_NAMED_TOKENS.has(key) || /^[1-9]\d*$/.test(key);
}
function sourceErrors(source: MechanicAuthoredSource) {
const errors: MechanicAuthoredDescriptionError[] = [];
if (source.version !== MECHANIC_AUTHORED_CONTRACT_VERSION) {
errors.push({
code: 'unsupported_contract',
path: 'version',
message: `Authored-description contract version ${String(source.version)} is not supported.`,
});
}
if (!source.owner.id.trim()) {
errors.push({
code: 'invalid_owner',
path: 'owner.id',
message: 'The owner ID is required.',
});
}
if (!source.template.trim()) {
errors.push({
code: 'invalid_template',
path: 'template',
message: 'The authored template is required.',
});
}
const tokens = tokenKeys(source.template);
if (/[{}]/.test(source.template.replace(TOKEN_PATTERN, ''))) {
errors.push({
code: 'unknown_token',
path: 'template',
message: 'The authored template contains malformed placeholder braces.',
});
}
for (const token of tokens) {
if (!isAllowedToken(token)) {
errors.push({
code: 'unknown_token',
path: 'template',
message: `The authored template contains unsupported token {${token}}.`,
});
}
}
if (source.owner.type === 'specialization_tree_rank') {
if (
!source.specialization?.rankDescription.trim() ||
!source.specialization.effectId.trim() ||
!source.specialization.effectTemplate.trim()
) {
errors.push({
code: 'invalid_specialization_source',
path: 'specialization',
message:
'Specialization rank description, effect identity, and effect template are required.',
});
}
} else if (source.specialization !== undefined) {
errors.push({
code: 'invalid_specialization_source',
path: 'specialization',
message:
'Specialization inputs are valid only for a Specialization tree-rank owner.',
});
}
const expected = requiredVariantKeys(source.owner);
const actual = source.variants.map((variant) => variant.key);
if (
actual.length !== expected.length ||
actual.some((key, index) => key !== expected[index])
) {
errors.push({
code: 'invalid_variant',
path: 'variants',
message: `Expected authored variants in this order: ${expected.join(', ')}.`,
});
}
return { errors, tokens };
}
function materializeKnownMechanicAuthoredDescription(
source: MechanicAuthoredSource,
): MechanicAuthoredDescriptionResult {
const { errors, tokens } = sourceErrors(source);
const usedTokens = new Set(tokens.filter(isAllowedToken));
const variants: MaterializedMechanicVariant[] = [];
source.variants.forEach((variant, variantIndex) => {
const path = `variants[${variantIndex}]`;
const slots = new Map<string, MechanicAuthoredSlot>();
const slotOrders = new Set<number>();
for (const [slotIndex, slot] of variant.slots.entries()) {
if (
!isAllowedToken(slot.key) ||
!Number.isInteger(slot.order) ||
slot.order < 0 ||
!NUMERIC_SLOT_VALUE_PATTERN.test(slot.value) ||
slots.has(slot.key) ||
slotOrders.has(slot.order)
) {
errors.push({
code: 'invalid_slot',
path: `${path}.slots[${slotIndex}]`,
message: `Authored slot ${slot.key || '(empty)'} must contain a plain numeric value with a unique key and order.`,
});
continue;
}
slots.set(slot.key, slot);
slotOrders.add(slot.order);
if (!usedTokens.has(slot.key)) {
errors.push({
code: 'unused_slot',
path: `${path}.slots[${slotIndex}]`,
message: `Authored slot ${slot.key} is not referenced by the template.`,
});
}
}
for (const token of usedTokens) {
if (!slots.has(token)) {
errors.push({
code: 'unresolved_token',
path: `${path}.slots`,
message: `Authored token {${token}} has no value for variant ${variant.key}.`,
});
}
}
const text = source.template.replace(TOKEN_PATTERN, (match, key: string) =>
isAllowedToken(key) ? (slots.get(key)?.value ?? match) : match,
);
if (/[{}]/.test(text)) {
errors.push({
code: 'unresolved_token',
path: `${path}.materialized`,
message: `Materialized variant ${variant.key} contains an unresolved placeholder.`,
});
}
if (variant.materialized !== text) {
errors.push({
code: 'materialization_mismatch',
path: `${path}.materialized`,
message: `Stored materialization for variant ${variant.key} does not match the authored source.`,
});
}
variants.push({ key: variant.key, text, slots: variant.slots });
});
return errors.length ? { ok: false, errors } : { ok: true, variants };
}
function parseMechanicAuthoredSourceShape(
value: unknown,
): ParsedMechanicAuthoredSourceResult {
const invalid = (
path: string,
message: string,
): ParsedMechanicAuthoredSourceResult => ({
ok: false,
errors: [{ code: 'invalid_source', path, message }],
});
if (!objectValue(value))
return invalid('', 'The authored source must be an object.');
if (
!hasOnlyKeys(value, [
'version',
'owner',
'template',
'variants',
'specialization',
])
)
return invalid('', 'The authored source contains an unknown field.');
if (value.version !== MECHANIC_AUTHORED_CONTRACT_VERSION)
return {
ok: false,
errors: [
{
code: 'unsupported_contract',
path: 'version',
message: 'The authored source has an unsupported contract version.',
},
],
};
if (!objectValue(value.owner) || typeof value.owner.id !== 'string')
return invalid('owner', 'The authored source owner is invalid.');
const ownerType = value.owner.type;
if (
typeof ownerType !== 'string' ||
![
'talent',
'os_protocol_talent',
'skill_chip_talent',
'specialization_tree_rank',
].includes(ownerType)
)
return invalid('owner.type', 'The authored source owner type is invalid.');
if (ownerType === 'talent') {
if (!hasOnlyKeys(value.owner, ['type', 'id', 'scope', 'hasTierII']))
return invalid('owner', 'The Talent owner contains an unknown field.');
if (value.owner.scope !== 'standard' && value.owner.scope !== 'exotic')
return invalid('owner.scope', 'The Talent scope is invalid.');
if (
value.owner.hasTierII !== undefined &&
typeof value.owner.hasTierII !== 'boolean'
)
return invalid(
'owner.hasTierII',
'Talent Tier II presence must be boolean.',
);
} else if (!hasOnlyKeys(value.owner, ['type', 'id'])) {
return invalid(
'owner',
'The authored source owner contains an unknown field.',
);
}
if (typeof value.template !== 'string' || !Array.isArray(value.variants))
return invalid(
'template',
'The authored template or variants are invalid.',
);
for (const [variantIndex, variant] of value.variants.entries()) {
if (
!objectValue(variant) ||
!hasOnlyKeys(variant, ['key', 'materialized', 'slots']) ||
typeof variant.key !== 'string' ||
typeof variant.materialized !== 'string' ||
!Array.isArray(variant.slots)
)
return invalid(
`variants[${variantIndex}]`,
'The authored variant is invalid.',
);
for (const [slotIndex, slot] of variant.slots.entries()) {
if (
!objectValue(slot) ||
!hasOnlyKeys(slot, ['key', 'value', 'order', 'unit', 'attributeId']) ||
typeof slot.key !== 'string' ||
typeof slot.value !== 'string' ||
typeof slot.order !== 'number' ||
(slot.unit !== undefined && typeof slot.unit !== 'string') ||
(slot.attributeId !== undefined && typeof slot.attributeId !== 'string')
)
return invalid(
`variants[${variantIndex}].slots[${slotIndex}]`,
'The authored slot is invalid.',
);
}
}
if (value.specialization !== undefined) {
if (
!objectValue(value.specialization) ||
!hasOnlyKeys(value.specialization, [
'rankDescription',
'effectId',
'effectTemplate',
]) ||
typeof value.specialization.rankDescription !== 'string' ||
typeof value.specialization.effectId !== 'string' ||
typeof value.specialization.effectTemplate !== 'string'
)
return invalid(
'specialization',
'The Specialization authored inputs are invalid.',
);
}
return { ok: true, value: value as unknown as MechanicAuthoredSource };
}
export function materializeMechanicAuthoredDescription(
value: unknown,
): MechanicAuthoredDescriptionResult {
const parsed = parseMechanicAuthoredSourceShape(value);
return parsed.ok
? materializeKnownMechanicAuthoredDescription(parsed.value)
: parsed;
}
export function parseMechanicAuthoredSource(
value: unknown,
): ParsedMechanicAuthoredSourceResult {
const parsed = parseMechanicAuthoredSourceShape(value);
if (!parsed.ok) return parsed;
const materialized = materializeKnownMechanicAuthoredDescription(
parsed.value,
);
return materialized.ok ? parsed : materialized;
}
export function mechanicAuthoredFingerprintPayload(
source: MechanicAuthoredSource,
): MechanicAuthoredFingerprintPayload | null {
const materialized = materializeMechanicAuthoredDescription(source);
if (!materialized.ok) return null;
return {
kind: 'mechanic_authored_source',
version: MECHANIC_AUTHORED_CONTRACT_VERSION,
owner:
source.owner.type === 'talent'
? {
type: source.owner.type,
id: source.owner.id,
scope: source.owner.scope,
...(source.owner.hasTierII ? { hasTierII: true } : {}),
}
: { type: source.owner.type, id: source.owner.id },
template: source.template,
variants: materialized.variants.map((variant) => ({
key: variant.key,
materialized: variant.text,
slots: [...variant.slots].sort((left, right) => left.order - right.order),
})),
...(source.specialization ? { specialization: source.specialization } : {}),
};
}
@@ -2,11 +2,13 @@ import { describe, expect, it } from 'vitest';
import {
currentHealthPercentBandPredicate,
eventFieldComparisonPredicate,
eventFieldNumericExpression,
mechanicTargetingForMode,
mechanicTargetingMode,
parseConditionalMechanicDraft,
readCurrentHealthPercentBand,
readEventFieldComparison,
readEventFieldNumericExpression,
registeredEventFields,
readStatePoolThreshold,
statePoolThresholdPredicate,
@@ -202,6 +204,108 @@ describe('conditional mechanic authoring payload', () => {
});
});
it('round-trips the registered proximity count as a derived scalar and resolves each variant display value', () => {
const path = 'values.alliesWithin30MetersWithAgentGrantedBuff';
expect(registeredEventFields('proximity_snapshot')).toContainEqual({
path,
label: 'Allies within 30 meters with an Agent-granted buff',
type: 'number',
minimum: 0,
integer: true,
});
const expression = eventFieldNumericExpression(path);
expect(readEventFieldNumericExpression(expression)).toBe(path);
expect(
readEventFieldNumericExpression({
op: 'multiply',
left: expression,
right: 2,
}),
).toBeNull();
const value = draft();
value.clauses[0].event = 'proximity_snapshot';
value.clauses[0].recipeKey = undefined;
value.clauses[0].reducer = {
kind: 'derived_scalar',
value: expression,
};
value.clauses[0].mutations = [
{
kind: 'derive',
pool: 'effect',
value: { ref: { source: 'reducer' } },
},
];
const upgradeScale = {
op: 'add' as const,
left: 1,
right: {
op: 'divide' as const,
left: {
ref: {
source: 'equipment' as const,
path: 'protocolTalentUpgrades',
},
},
right: 5,
},
};
value.clauses[0].outcomes[0].variants = {
I: {
value: 7.25,
expression: {
op: 'multiply',
left: { ref: { source: 'variant_value' } },
right: upgradeScale,
},
},
II: {
value: 9.5,
expression: {
op: 'multiply',
left: { ref: { source: 'variant_value' } },
right: upgradeScale,
},
},
};
const result = parseConditionalMechanicDraft(value, {
variantKeys: ['I', 'II'],
allowedAttributeIds: new Set(['weapon-damage']),
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.draft.clauses[0]).toMatchObject({
event: 'proximity_snapshot',
reducer: { kind: 'derived_scalar', value: expression },
outcomes: [
{
variants: {
I: {
value: 7.25,
expression: {
left: { ref: { source: 'variant_value' } },
},
},
},
},
],
});
expect(result.value.programs.I.clauses[0].outcomes?.[0].value).toEqual({
op: 'multiply',
left: 7.25,
right: upgradeScale,
});
expect(result.value.programs.II.clauses[0].outcomes?.[0].value).toEqual({
op: 'multiply',
left: 9.5,
right: upgradeScale,
});
});
it('exposes assigned-ability activity for kill and assist event conditions', () => {
expect(registeredEventFields('enemy_killed')).toEqual(
expect.arrayContaining([
+105 -3
View File
@@ -39,9 +39,28 @@ export type ConditionalMechanicPoolDraft = PoolDefinition & {
expiresAfterSecondsVariants?: Record<string, number>;
};
export type ConditionalMechanicValueReference =
ValueReference | { source: 'variant_value' };
export type ConditionalNumericExpression =
| number
| { ref: ConditionalMechanicValueReference }
| { op: 'floor'; value: ConditionalNumericExpression }
| {
op: 'add' | 'subtract' | 'multiply' | 'divide' | 'min' | 'max';
left: ConditionalNumericExpression;
right: ConditionalNumericExpression;
}
| {
op: 'clamp';
value: ConditionalNumericExpression;
min: ConditionalNumericExpression;
max: ConditionalNumericExpression;
};
export type ConditionalMechanicVariantValue = {
value: number;
expression?: NumericExpression;
expression?: ConditionalNumericExpression;
};
export type ConditionalMechanicOutcomeDraft = Omit<
@@ -200,6 +219,21 @@ export function registeredEventFields(event: MechanicEventKind) {
return MECHANIC_EVENT_REGISTRY[event].fields ?? [];
}
export function eventFieldNumericExpression(path: string): NumericExpression {
return { ref: { source: 'event', path } };
}
export function readEventFieldNumericExpression(
expression: NumericExpression,
): string | null {
return typeof expression === 'object' &&
'ref' in expression &&
expression.ref.source === 'event' &&
expression.ref.path.trim()
? expression.ref.path
: null;
}
export type MechanicTargetingMode =
| 'none'
| 'allies_within_radius'
@@ -452,6 +486,14 @@ function isReference(value: unknown): value is ValueReference {
}
}
function isConditionalReference(
value: unknown,
): value is ConditionalMechanicValueReference {
return (
(object(value) && value.source === 'variant_value') || isReference(value)
);
}
function validateAttributeReferences(
value: unknown,
allowedAttributeIds: ReadonlySet<string> | undefined,
@@ -511,6 +553,29 @@ function isExpression(value: unknown): value is NumericExpression {
);
}
function isConditionalExpression(
value: unknown,
): value is ConditionalNumericExpression {
if (finite(value)) return true;
if (!object(value)) return false;
if ('ref' in value) return isConditionalReference(value.ref);
if (value.op === 'floor') return isConditionalExpression(value.value);
if (value.op === 'clamp') {
return (
isConditionalExpression(value.value) &&
isConditionalExpression(value.min) &&
isConditionalExpression(value.max)
);
}
return (
['add', 'subtract', 'multiply', 'divide', 'min', 'max'].includes(
String(value.op),
) &&
isConditionalExpression(value.left) &&
isConditionalExpression(value.right)
);
}
function isOperand(value: unknown) {
return scalar(value) || isReference(value);
}
@@ -838,7 +903,7 @@ function parseOutcome(
}
if (
configured.expression !== undefined &&
!isExpression(configured.expression)
!isConditionalExpression(configured.expression)
) {
errors.push(
`${path} variant "${variant}" has an invalid value expression.`,
@@ -954,6 +1019,37 @@ function parseClauses(
return clauses;
}
function resolveVariantExpression(
expression: ConditionalNumericExpression,
variantValue: number,
): NumericExpression {
if (typeof expression === 'number') return expression;
if ('ref' in expression) {
return expression.ref.source === 'variant_value'
? variantValue
: { ref: expression.ref };
}
if (expression.op === 'floor') {
return {
op: 'floor',
value: resolveVariantExpression(expression.value, variantValue),
};
}
if (expression.op === 'clamp') {
return {
op: 'clamp',
value: resolveVariantExpression(expression.value, variantValue),
min: resolveVariantExpression(expression.min, variantValue),
max: resolveVariantExpression(expression.max, variantValue),
};
}
return {
op: expression.op,
left: resolveVariantExpression(expression.left, variantValue),
right: resolveVariantExpression(expression.right, variantValue),
};
}
function programsForDraft(
draft: ConditionalMechanicDraftV1,
options: ParseConditionalMechanicDraftOptions,
@@ -1002,7 +1098,13 @@ function programsForDraft(
}) => ({
...outcome,
id: outcomeKey,
value: variants[variant].expression ?? variants[variant].value,
value:
variants[variant].expression === undefined
? variants[variant].value
: resolveVariantExpression(
variants[variant].expression,
variants[variant].value,
),
}),
),
})),
@@ -0,0 +1,534 @@
import { describe, expect, it } from 'vitest';
import {
canonicalMechanicProgramJson,
classifyMechanicLifecycle,
classifyMechanicVariantLifecycle,
hashMechanicAuthoredSource,
hashMechanicProgram,
hashMechanicProgramVariants,
mechanicProgramSemanticPayload,
type MechanicLifecycleInput,
type MechanicModelRevision,
type MechanicProgramHashSource,
} from './mechanic-lifecycle.js';
import type { MechanicProgram } from './mechanic.js';
const program = (): MechanicProgram => ({
id: 'generated-program-id',
name: 'Sustained fire',
scenarioInputs: [
{
key: 'distance',
label: 'Distance',
kind: 'number',
readiness: 'requires_assumption',
description: 'Distance to target',
defaultValue: 10,
bestCaseValue: 5,
min: 0,
max: 100,
},
{
key: 'headshot',
label: 'Headshots',
kind: 'toggle',
defaultValue: false,
bestCaseValue: true,
},
],
pools: [
{
key: 'stacks',
label: 'Stacks',
scope: 'agent',
initial: 0,
min: 0,
max: 3,
bestCaseValue: 3,
},
{
key: 'cooldown',
label: 'Cooldown',
scope: 'agent',
initial: 0,
min: 0,
expiresAfterSeconds: 10,
},
],
clauses: [
{
id: 'generated-clause-id',
label: 'On weapon hit',
when: 'weapon_hit',
reducer: { kind: 'none' },
mutations: [
{
kind: 'add',
pool: 'stacks',
value: { ref: { source: 'scenario', key: 'headshot' } },
},
],
outcomes: [
{
id: 'generated-outcome-id',
label: 'Weapon damage',
phase: 'on_event',
kind: 'attribute_modifier',
scope: 'equipped_weapon',
value: 5,
basis: 'flat',
attributeId: 'weaponDamage',
perStack: true,
},
],
},
],
});
const hashSource = (): MechanicProgramHashSource => ({
...program(),
simulationReadiness: 'captured_only',
sourceVariants: ['I', 'II'],
});
const revision = (
overrides: Partial<MechanicModelRevision> = {},
): MechanicModelRevision => ({
program: program(),
sourceFingerprint: 'a'.repeat(64),
programHash: '0'.repeat(64),
mechanicContractVersion: 1,
simulationReadiness: 'ready',
...overrides,
});
const lifecycleInput = (
selectedRevision: MechanicModelRevision | null,
publiclyRenderable = true,
) => ({
selectedRevision,
currentSourceFingerprint: 'a'.repeat(64),
...(publiclyRenderable
? { resolveAttributeLabel: (attributeId: string) => attributeId }
: {}),
});
describe('Mechanic Program lifecycle and semantic hashing', () => {
it('builds explicit canonical JSON and excludes generated IDs and provenance', () => {
const source = hashSource() as MechanicProgramHashSource &
Record<string, unknown>;
source.persistenceRowId = 'row-1';
source.updatedAt = '2026-08-27T00:00:00Z';
source.editorState = { activeClause: 'generated-clause-id' };
source.recipeProvenance = 'recipe-a';
const json = canonicalMechanicProgramJson(source);
expect(json).toContain('"kind":"mechanic_program"');
expect(json).toContain('"version":1');
expect(json).not.toContain('generated-program-id');
expect(json).not.toContain('generated-clause-id');
expect(json).not.toContain('generated-outcome-id');
expect(json).not.toContain('persistenceRowId');
expect(json).not.toContain('recipeProvenance');
});
it('does not change when keyed Scenario Inputs or pools are reordered', async () => {
const original = hashSource();
const reordered: MechanicProgramHashSource = {
...original,
scenarioInputs: [...(original.scenarioInputs ?? [])].reverse(),
pools: [...(original.pools ?? [])].reverse(),
};
await expect(hashMechanicProgram(original)).resolves.toBe(
await hashMechanicProgram(reordered),
);
});
it('changes when clause, mutation, or outcome execution/render order changes', async () => {
const original = program();
const reorderedClause: MechanicProgram = {
...original,
clauses: [
...original.clauses,
{
id: 'second-clause',
label: 'Later clause',
when: 'tick',
reducer: { kind: 'none' },
mutations: [],
},
],
};
const reorderedMutation: MechanicProgram = {
...original,
clauses: [
{
...original.clauses[0],
mutations: [{ kind: 'none' }, ...original.clauses[0].mutations],
},
],
};
const reorderedOutcome: MechanicProgram = {
...original,
clauses: [
{
...original.clauses[0],
outcomes: [
...(original.clauses[0].outcomes ?? []),
{
...(original.clauses[0].outcomes?.[0] ?? {
id: 'second-outcome',
label: 'Second',
phase: 'on_event',
kind: 'marker',
scope: 'self',
value: 0,
basis: 'flat',
}),
id: 'second-outcome',
label: 'Second',
},
],
},
],
};
const originalHash = await hashMechanicProgram(original);
await expect(hashMechanicProgram(reorderedClause)).resolves.not.toBe(
originalHash,
);
await expect(hashMechanicProgram(reorderedMutation)).resolves.not.toBe(
originalHash,
);
await expect(hashMechanicProgram(reorderedOutcome)).resolves.not.toBe(
originalHash,
);
});
it('rejects invalid pool scopes and reducer kinds from canonical hashes', async () => {
const invalidScope = program();
(invalidScope.pools![0] as { scope: string }).scope = 'squad';
await expect(hashMechanicProgram(invalidScope)).rejects.toThrow(
'unsupported scope',
);
const invalidReducer = program();
(invalidReducer.clauses[0] as { reducer: { kind: string } }).reducer = {
kind: 'unknown',
};
await expect(hashMechanicProgram(invalidReducer)).rejects.toThrow(
'unsupported kind',
);
});
it('keeps generated identities out of the semantic hash', async () => {
const changedIds: MechanicProgram = {
...program(),
id: 'another-program-id',
clauses: [
{
...program().clauses[0],
id: 'another-clause-id',
outcomes: [
{
...(program().clauses[0].outcomes?.[0] as NonNullable<
MechanicProgram['clauses'][number]['outcomes']
>[number]),
id: 'another-outcome-id',
},
],
},
],
};
await expect(hashMechanicProgram(program())).resolves.toBe(
await hashMechanicProgram(changedIds),
);
});
it('classifies selected models with fail-closed lifecycle boundaries', async () => {
await expect(
classifyMechanicLifecycle(lifecycleInput(null)),
).resolves.toEqual({
status: 'absent',
reason: 'no_selected_revision',
});
await expect(
classifyMechanicLifecycle(
lifecycleInput(
revision({
program: { ...program(), clauses: [] },
simulationReadiness: 'captured_only',
}),
),
),
).resolves.toEqual({ status: 'absent', reason: 'empty_captured_program' });
await expect(
classifyMechanicLifecycle(
lifecycleInput(revision({ program: { ...program(), name: '' } })),
),
).resolves.toMatchObject({ status: 'absent', reason: 'invalid_program' });
await expect(
classifyMechanicLifecycle({
selectedRevision: revision({ sourceFingerprint: 'b'.repeat(64) }),
currentSourceFingerprint: 'c'.repeat(64),
resolveAttributeLabel: (attributeId) => attributeId,
}),
).resolves.toEqual({ status: 'stale', reason: 'fingerprint_mismatch' });
await expect(
classifyMechanicLifecycle(
lifecycleInput(revision({ mechanicContractVersion: 999 })),
),
).resolves.toEqual({ status: 'stale', reason: 'unsupported_contract' });
await expect(
classifyMechanicLifecycle(lifecycleInput(revision(), false)),
).resolves.toMatchObject({
status: 'absent',
reason: 'unrenderable_program',
});
await expect(
classifyMechanicLifecycle({
selectedRevision: revision(),
currentSourceFingerprint: 'a'.repeat(64),
} as MechanicLifecycleInput),
).resolves.toMatchObject({
status: 'absent',
reason: 'unrenderable_program',
});
});
it('rejects non-SHA fingerprints and publicly unrenderable program fields', async () => {
await expect(
classifyMechanicLifecycle({
selectedRevision: revision({ sourceFingerprint: 'same' }),
currentSourceFingerprint: 'same',
resolveAttributeLabel: (attributeId) => attributeId,
}),
).resolves.toMatchObject({ status: 'absent', reason: 'invalid_program' });
const invalidPhase = program();
(invalidPhase.clauses[0].outcomes![0] as { phase: string }).phase =
'sometimes';
const selectedRevision = revision({ program: invalidPhase });
selectedRevision.programHash = await hashMechanicProgram({
...invalidPhase,
simulationReadiness: selectedRevision.simulationReadiness,
});
await expect(
classifyMechanicLifecycle(lifecycleInput(selectedRevision)),
).resolves.toMatchObject({
status: 'absent',
reason: 'unrenderable_program',
});
});
it.each(['ready', 'requires_assumptions', 'captured_only'] as const)(
'classifies a matching non-empty %s model as current',
async (simulationReadiness) => {
const selectedRevision = revision({ simulationReadiness });
selectedRevision.programHash = await hashMechanicProgram({
...selectedRevision.program!,
simulationReadiness,
});
await expect(
classifyMechanicLifecycle(lifecycleInput(selectedRevision)),
).resolves.toEqual({
status: 'current',
fingerprint: 'a'.repeat(64),
programHash: selectedRevision.programHash,
simulationReadiness,
});
},
);
it('fails closed when the selected program hash is missing or does not match', async () => {
await expect(
classifyMechanicLifecycle(
lifecycleInput({
...revision(),
programHash: undefined,
} as unknown as MechanicModelRevision),
),
).resolves.toEqual({ status: 'absent', reason: 'invalid_program_hash' });
await expect(
classifyMechanicLifecycle(
lifecycleInput(revision({ programHash: '0'.repeat(64) })),
),
).resolves.toEqual({ status: 'absent', reason: 'invalid_program_hash' });
});
it('distinguishes an explicit zero weight from an omitted weight', async () => {
const implicit = program();
const zeroWeight: MechanicProgram = {
...implicit,
clauses: [{ ...implicit.clauses[0], weight: 0 }],
};
await expect(hashMechanicProgram(zeroWeight)).resolves.not.toBe(
await hashMechanicProgram(implicit),
);
});
it('normalizes omitted runtime defaults to their explicit equivalents', async () => {
const implicit = program();
const explicit: MechanicProgram = {
...implicit,
scenarioInputs: implicit.scenarioInputs?.map((input) => ({
...input,
readiness: input.readiness ?? 'ready',
})),
clauses: implicit.clauses.map((clause) => ({
...clause,
mutations: clause.mutations.map((mutation) =>
mutation.kind === 'transfer'
? {
...mutation,
value: mutation.value ?? 'all',
clearSource: mutation.clearSource ?? true,
}
: mutation,
),
outcomes: clause.outcomes?.map((outcome) => ({
...outcome,
delivery: outcome.delivery ?? 'instant',
combatTiming: outcome.combatTiming ?? 'current',
perStack: outcome.perStack ?? false,
})),
})),
};
await expect(hashMechanicProgram(implicit)).resolves.toBe(
await hashMechanicProgram(explicit),
);
});
it('hashes ordered program variants as one revision graph', async () => {
const tierOne = program();
const tierTwo = program();
tierTwo.clauses[0].outcomes![0].value = 10;
const forward = await hashMechanicProgramVariants({
simulationReadiness: 'ready',
variants: [
{ key: 'I', label: 'Tier I', program: tierOne },
{ key: 'II', label: 'Tier II', program: tierTwo },
],
});
const sameSemantics = await hashMechanicProgramVariants({
simulationReadiness: 'ready',
variants: [
{ key: 'I', label: 'Renamed display label', program: tierOne },
{ key: 'II', label: 'Tier II', program: tierTwo },
],
});
const reversed = await hashMechanicProgramVariants({
simulationReadiness: 'ready',
variants: [
{ key: 'II', label: 'Tier II', program: tierTwo },
{ key: 'I', label: 'Tier I', program: tierOne },
],
});
expect(forward).toBe(sameSemantics);
expect(reversed).not.toBe(forward);
});
it('classifies the complete selected variant graph and fails closed when one variant is invalid', async () => {
const variants = [
{ key: 'I', label: 'Tier I', program: program() },
{ key: 'II', label: 'Tier II', program: program() },
];
variants[1].program.clauses[0].outcomes![0].value = 10;
const programHash = await hashMechanicProgramVariants({
simulationReadiness: 'ready',
variants,
});
await expect(
classifyMechanicVariantLifecycle({
currentSourceFingerprint: 'a'.repeat(64),
resolveAttributeLabel: (attributeId) => attributeId,
selectedRevision: {
variants,
sourceFingerprint: 'a'.repeat(64),
programHash,
mechanicContractVersion: 1,
simulationReadiness: 'ready',
},
}),
).resolves.toMatchObject({ status: 'current', programHash });
variants[1].program.pools = [
{ key: 'bad', label: 'Bad', scope: 'party' as 'agent', initial: 0 },
];
await expect(
classifyMechanicVariantLifecycle({
currentSourceFingerprint: 'a'.repeat(64),
resolveAttributeLabel: (attributeId) => attributeId,
selectedRevision: {
variants,
sourceFingerprint: 'a'.repeat(64),
programHash,
mechanicContractVersion: 1,
simulationReadiness: 'ready',
},
}),
).resolves.toMatchObject({ status: 'absent', reason: 'invalid_program' });
});
it('hashes a valid authored source and rejects unresolved source values', async () => {
const source = {
version: 1 as const,
owner: { type: 'os_protocol_talent' as const, id: 'protocol-1' },
template: 'Gain {1}%.',
variants: [
{
key: 'base',
materialized: 'Gain 10%.',
slots: [{ key: '1', value: '10', order: 0 }],
},
],
};
await expect(hashMechanicAuthoredSource(source)).resolves.toMatchObject({
ok: true,
fingerprint: expect.stringMatching(/^[0-9a-f]{64}$/),
payload: { kind: 'mechanic_authored_source', version: 1 },
});
source.variants[0].slots = [];
await expect(hashMechanicAuthoredSource(source)).resolves.toMatchObject({
ok: false,
errors: expect.arrayContaining([
expect.objectContaining({ code: 'unresolved_token' }),
]),
});
});
it('returns a stable fixed SHA-256 vector as lowercase hexadecimal', async () => {
const hash = await hashMechanicProgram({
id: 'generated-id',
name: 'x',
clauses: [
{
id: 'generated-clause-id',
when: 'tick',
reducer: { kind: 'none' },
mutations: [],
},
],
});
expect(hash).toBe(
'4ba3a6b9ddc7831375779c865928a715bc3dbd2b8aac77b889fc7fcc672d8339',
);
expect(hash).toMatch(/^[0-9a-f]{64}$/);
});
it('exposes canonical payload fields in stable key order', () => {
const payload = mechanicProgramSemanticPayload(hashSource());
expect(Object.keys(payload)).toEqual([
'kind',
'version',
'name',
'scenarioInputs',
'pools',
'clauses',
'simulationReadiness',
'sourceVariants',
]);
});
});
+845
View File
@@ -0,0 +1,845 @@
import {
mechanicAuthoredFingerprintPayload,
materializeMechanicAuthoredDescription,
type MechanicAuthoredDescriptionError,
type MechanicAuthoredFingerprintPayload,
type MechanicAuthoredSource,
} from './mechanic-authored-description.js';
import {
renderPublicMechanicPrograms,
type MechanicAttributeLabelResolver,
type MechanicPublicProgramVariant,
} from './mechanic-public-renderer.js';
import {
validateMechanicProgram,
type ClauseMutation,
type EntitySelector,
type MechanicClause,
type MechanicOutcome,
type MechanicOutcomeTargeting,
type MechanicProgram,
type NumericExpression,
type PoolDefinition,
type Predicate,
type Reducer,
type ScenarioInputDefinition,
type Scalar,
type ValueReference,
} from './mechanic.js';
/** The version of the canonical Mechanic Program hash contract. */
export const MECHANIC_PROGRAM_HASH_VERSION = 1 as const;
export const MECHANIC_PROGRAM_HASH_KIND = 'mechanic_program' as const;
export const MECHANIC_PROGRAM_VARIANTS_HASH_KIND =
'mechanic_program_variants' as const;
export type MechanicLifecycle = 'absent' | 'stale' | 'current';
export type MechanicAuthoredFingerprintResult =
| {
ok: true;
fingerprint: string;
payload: MechanicAuthoredFingerprintPayload;
}
| { ok: false; errors: MechanicAuthoredDescriptionError[] };
export type MechanicSimulationReadiness =
'ready' | 'requires_assumptions' | 'captured_only';
export type CanonicalJsonValue =
| null
| boolean
| number
| string
| CanonicalJsonValue[]
| { [key: string]: CanonicalJsonValue };
export type CanonicalMechanicProgram = {
kind: typeof MECHANIC_PROGRAM_HASH_KIND;
version: typeof MECHANIC_PROGRAM_HASH_VERSION;
name: string;
simulationReadiness?: MechanicSimulationReadiness;
sourceVariants?: CanonicalJsonValue;
scenarioInputs: Array<{ [key: string]: CanonicalJsonValue }>;
pools: Array<{ [key: string]: CanonicalJsonValue }>;
clauses: Array<{ [key: string]: CanonicalJsonValue }>;
};
/**
* A program plus source metadata which belongs to the model contract rather
* than to the executable graph. Metadata is optional because the current
* runtime MechanicProgram type predates model revisions.
*/
export type MechanicProgramHashSource = MechanicProgram & {
simulationReadiness?: MechanicSimulationReadiness;
sourceVariants?: CanonicalJsonValue;
};
export type MechanicProgramHashInput = MechanicProgramHashSource;
export type MechanicProgramVariantsHashInput = {
simulationReadiness: MechanicSimulationReadiness;
variants: MechanicPublicProgramVariant[];
};
export type MechanicModelRevision = {
program: MechanicProgram | null;
sourceFingerprint: string;
programHash: string;
sourceVariants?: CanonicalJsonValue;
mechanicContractVersion: number;
simulationReadiness: MechanicSimulationReadiness;
};
export type MechanicLifecycleInput = {
selectedRevision: MechanicModelRevision | null;
currentSourceFingerprint: string;
resolveAttributeLabel?: MechanicAttributeLabelResolver;
supportedMechanicContractVersion?: number;
};
export type MechanicModelVariantRevision = Omit<
MechanicModelRevision,
'program' | 'sourceVariants'
> & {
variants: MechanicPublicProgramVariant[];
};
export type MechanicVariantLifecycleInput = Omit<
MechanicLifecycleInput,
'selectedRevision'
> & {
selectedRevision: MechanicModelVariantRevision | null;
};
export type MechanicLifecycleReason =
| 'no_selected_revision'
| 'empty_program'
| 'empty_captured_program'
| 'invalid_program'
| 'unrenderable_program'
| 'fingerprint_mismatch'
| 'unsupported_contract'
| 'invalid_program_hash'
| 'hash_unavailable';
export type MechanicLifecycleResult =
| {
status: 'absent';
reason:
| 'no_selected_revision'
| 'empty_program'
| 'empty_captured_program'
| 'invalid_program'
| 'unrenderable_program'
| 'invalid_program_hash'
| 'hash_unavailable';
errors?: string[];
}
| {
status: 'stale';
reason: 'fingerprint_mismatch' | 'unsupported_contract';
}
| {
status: 'current';
fingerprint: string;
programHash: string;
simulationReadiness: MechanicSimulationReadiness;
};
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function canonicalizeValue(value: unknown): CanonicalJsonValue {
if (value === null) return null;
if (typeof value === 'string' || typeof value === 'boolean') return value;
if (typeof value === 'number') {
if (!Number.isFinite(value)) {
throw new TypeError(
'Mechanic Program hash values must be finite numbers.',
);
}
return value;
}
if (Array.isArray(value)) return value.map(canonicalizeValue);
if (isRecord(value)) {
const result: { [key: string]: CanonicalJsonValue } = {};
for (const key of Object.keys(value).sort()) {
const child = value[key];
if (child !== undefined) result[key] = canonicalizeValue(child);
}
return result;
}
throw new TypeError('Mechanic Program hash values must be JSON values.');
}
function canonicalObject(fields: Record<string, unknown>): {
[key: string]: CanonicalJsonValue;
} {
return canonicalizeValue(fields) as { [key: string]: CanonicalJsonValue };
}
function stableJson(value: CanonicalJsonValue): string {
return JSON.stringify(value);
}
function stableSemanticSort<T extends CanonicalJsonValue>(values: T[]): T[] {
return values
.map((value, index) => ({ value, index, key: stableJson(value) }))
.sort((left, right) => {
if (left.key < right.key) return -1;
if (left.key > right.key) return 1;
return left.index - right.index;
})
.map(({ value }) => value);
}
function canonicalScenarioInput(input: ScenarioInputDefinition): {
[key: string]: CanonicalJsonValue;
} {
return canonicalObject({
key: input.key,
label: input.label,
kind: input.kind,
readiness: input.readiness ?? 'ready',
description: input.description,
defaultValue: input.defaultValue,
bestCaseValue: input.bestCaseValue,
min: input.min,
max: input.max,
});
}
function canonicalPool(pool: PoolDefinition): {
[key: string]: CanonicalJsonValue;
} {
if (pool.scope !== 'agent' && pool.scope !== 'target') {
throw new TypeError('Mechanic pools have an unsupported scope.');
}
return canonicalObject({
key: pool.key,
label: pool.label,
scope: pool.scope,
initial: pool.initial,
min: pool.min,
max: pool.max,
bestCaseValue: pool.bestCaseValue,
expiresAfterSeconds: pool.expiresAfterSeconds,
});
}
function canonicalEntitySelector(selector: EntitySelector): {
[key: string]: CanonicalJsonValue;
} {
return canonicalObject({
kind: selector.kind,
path: 'path' in selector ? selector.path : undefined,
});
}
function canonicalReference(reference: ValueReference): {
[key: string]: CanonicalJsonValue;
} {
return canonicalObject({
source: reference.source,
path: 'path' in reference ? reference.path : undefined,
timing: 'timing' in reference ? reference.timing : undefined,
key: 'key' in reference ? reference.key : undefined,
attributeId: 'attributeId' in reference ? reference.attributeId : undefined,
pool: 'pool' in reference ? reference.pool : undefined,
entity:
'entity' in reference && reference.entity
? canonicalEntitySelector(reference.entity)
: undefined,
});
}
function canonicalExpression(
expression: NumericExpression,
): CanonicalJsonValue {
if (typeof expression === 'number') return canonicalizeValue(expression);
if (!isRecord(expression)) {
throw new TypeError('Numeric expressions must be typed JSON values.');
}
if ('ref' in expression) {
if (!isRecord(expression.ref))
throw new TypeError('Numeric expression references must be objects.');
return canonicalObject({
ref: canonicalReference(expression.ref as ValueReference),
});
}
const op = expression.op;
switch (op) {
case 'floor':
return canonicalObject({
op,
value: canonicalExpression(expression.value as NumericExpression),
});
case 'clamp':
return canonicalObject({
op,
value: canonicalExpression(expression.value as NumericExpression),
min: canonicalExpression(expression.min as NumericExpression),
max: canonicalExpression(expression.max as NumericExpression),
});
case 'add':
case 'subtract':
case 'multiply':
case 'divide':
case 'min':
case 'max':
return canonicalObject({
op,
left: canonicalExpression(expression.left as NumericExpression),
right: canonicalExpression(expression.right as NumericExpression),
});
default:
throw new TypeError('Numeric expressions have an unsupported operator.');
}
}
function canonicalOperand(value: ValueReference | Scalar): CanonicalJsonValue {
return isRecord(value) && 'source' in value
? canonicalReference(value as ValueReference)
: canonicalizeValue(value);
}
function canonicalPredicate(predicate: Predicate): CanonicalJsonValue {
if (!isRecord(predicate)) {
throw new TypeError('Predicates must be typed JSON values.');
}
switch (predicate.kind) {
case 'true':
return { kind: 'true' };
case 'exists':
return canonicalObject({
kind: 'exists',
value: canonicalReference(predicate.value as ValueReference),
});
case 'compare':
return canonicalObject({
kind: 'compare',
left: canonicalOperand(predicate.left as ValueReference | Scalar),
operator: predicate.operator,
right: canonicalOperand(predicate.right as ValueReference | Scalar),
});
case 'all':
case 'any':
return canonicalObject({
kind: predicate.kind,
// Logical member order is retained because deterministic rendering
// presents the members in this order.
predicates: (predicate.predicates as Predicate[]).map(
canonicalPredicate,
),
});
case 'not':
return canonicalObject({
kind: 'not',
predicate: canonicalPredicate(predicate.predicate as Predicate),
});
default:
throw new TypeError('Predicates have an unsupported kind.');
}
}
function canonicalReducer(reducer: Reducer): CanonicalJsonValue {
if (!isRecord(reducer)) {
throw new TypeError('Reducers must be typed JSON values.');
}
const groupBy =
'groupBy' in reducer && reducer.groupBy
? canonicalReference(reducer.groupBy as ValueReference)
: undefined;
switch (reducer.kind) {
case 'none':
return { kind: 'none' };
case 'count':
return canonicalObject({
kind: reducer.kind,
threshold: reducer.threshold,
reset: reducer.reset ?? 'zero',
groupBy,
});
case 'sliding_count':
return canonicalObject({
kind: reducer.kind,
threshold: reducer.threshold,
reset: reducer.reset ?? 'zero',
windowSeconds: reducer.windowSeconds,
groupBy,
});
case 'modulo':
return canonicalObject({ kind: 'modulo', every: reducer.every, groupBy });
case 'consecutive_count':
return canonicalObject({
kind: 'consecutive_count',
threshold: reducer.threshold,
groupBy,
});
case 'distinct_count':
return canonicalObject({
kind: 'distinct_count',
threshold: reducer.threshold,
windowSeconds: reducer.windowSeconds,
distinctBy: canonicalReference(reducer.distinctBy),
});
case 'duration':
return canonicalObject({
kind: 'duration',
seconds: reducer.seconds,
repeat: reducer.repeat ?? false,
groupBy,
});
case 'periodic':
return canonicalObject({
kind: 'periodic',
intervalSeconds: canonicalExpression(reducer.intervalSeconds),
immediate: reducer.immediate ?? false,
groupBy,
});
case 'derived_scalar':
return canonicalObject({
kind: 'derived_scalar',
value: canonicalExpression(reducer.value),
});
default:
throw new TypeError('Reducers have an unsupported kind.');
}
}
function canonicalMutation(mutation: ClauseMutation): CanonicalJsonValue {
if (!isRecord(mutation)) {
throw new TypeError('Mutations must be typed JSON values.');
}
const entity =
'entity' in mutation && mutation.entity
? canonicalEntitySelector(mutation.entity as EntitySelector)
: undefined;
switch (mutation.kind) {
case 'none':
return { kind: 'none' };
case 'add':
case 'set':
case 'consume':
case 'derive':
return canonicalObject({
kind: mutation.kind,
pool: mutation.pool,
entity,
value: canonicalExpression(mutation.value),
});
case 'clear':
return canonicalObject({ kind: 'clear', pool: mutation.pool, entity });
case 'transfer':
return canonicalObject({
kind: 'transfer',
pool: mutation.pool,
from: canonicalEntitySelector(mutation.from),
to: canonicalEntitySelector(mutation.to),
value:
mutation.value === undefined
? 'all'
: mutation.value === 'all'
? 'all'
: canonicalExpression(mutation.value),
clearSource: mutation.clearSource ?? true,
});
case 'extend_duration':
return canonicalObject({
kind: 'extend_duration',
target: mutation.target,
seconds: canonicalExpression(mutation.seconds),
});
case 'start_cooldown_on_max':
return canonicalObject({
kind: 'start_cooldown_on_max',
stackPool: mutation.stackPool,
cooldownPool: mutation.cooldownPool,
});
default:
throw new TypeError('Mutations have an unsupported kind.');
}
}
function canonicalTargeting(
targeting: MechanicOutcomeTargeting,
): CanonicalJsonValue {
return canonicalObject({
kind: targeting.kind,
population: 'population' in targeting ? targeting.population : undefined,
center: 'center' in targeting ? targeting.center : undefined,
validTargets:
'validTargets' in targeting ? targeting.validTargets : undefined,
radiusMeters: targeting.radiusMeters,
});
}
function canonicalOutcome(outcome: MechanicOutcome): {
[key: string]: CanonicalJsonValue;
} {
// Outcome IDs are generated identities. Every other field is either typed
// behavior or text consumed by deterministic rendering.
return canonicalObject({
label: outcome.label,
phase: outcome.phase,
kind: outcome.kind,
scope: outcome.scope,
value: canonicalExpression(outcome.value),
basis: outcome.basis,
resource: outcome.resource,
delivery: outcome.delivery ?? 'instant',
durationSeconds: outcome.durationSeconds,
combatTiming: outcome.combatTiming ?? 'current',
attributeId: outcome.attributeId,
statePool: outcome.statePool,
perStack: outcome.perStack ?? false,
minStacks: outcome.minStacks,
maxStacks: outcome.maxStacks,
targeting: outcome.targeting
? canonicalTargeting(outcome.targeting)
: undefined,
probabilityPercent: outcome.probabilityPercent,
});
}
function canonicalClause(clause: MechanicClause): {
[key: string]: CanonicalJsonValue;
} {
// Clause IDs and recipe keys are generated/persistence provenance. The
// remaining fields preserve execution and deterministic rendering order.
return canonicalObject({
label: clause.label,
when: clause.when,
if: clause.if ? canonicalPredicate(clause.if) : undefined,
reducer: canonicalReducer(clause.reducer),
cooldownSeconds: clause.cooldownSeconds,
weight:
clause.weight !== undefined
? canonicalExpression(clause.weight)
: undefined,
procChancePercent: clause.procChancePercent,
requiresAssignedAbilityActive: clause.requiresAssignedAbilityActive,
mutations: clause.mutations.map(canonicalMutation),
outcomes: (clause.outcomes ?? []).map(canonicalOutcome),
});
}
/**
* Builds the versioned semantic payload used by the Mechanic Program hash.
*
* Keyed Scenario Inputs and pools are sets and therefore sorted by their
* canonical semantics. Clauses, mutations, predicate members, and outcomes
* stay in source order because order affects execution or rendered text.
*/
export function mechanicProgramSemanticPayload(
input: MechanicProgramHashInput,
): CanonicalMechanicProgram {
const scenarioInputs = stableSemanticSort(
(input.scenarioInputs ?? []).map(canonicalScenarioInput),
);
const pools = stableSemanticSort((input.pools ?? []).map(canonicalPool));
const payload: CanonicalMechanicProgram = {
kind: MECHANIC_PROGRAM_HASH_KIND,
version: MECHANIC_PROGRAM_HASH_VERSION,
name: input.name,
scenarioInputs,
pools,
clauses: input.clauses.map(canonicalClause),
};
if (input.simulationReadiness !== undefined) {
payload.simulationReadiness = input.simulationReadiness;
}
if (input.sourceVariants !== undefined)
payload.sourceVariants = canonicalizeValue(input.sourceVariants);
return payload;
}
/** Returns canonical JSON bytes as a string, without a hidden domain separator. */
export function canonicalMechanicProgramJson(
input: MechanicProgramHashInput,
): string {
return stableJson(canonicalizeValue(mechanicProgramSemanticPayload(input)));
}
async function sha256Utf8(value: string): Promise<string> {
const crypto = globalThis.crypto;
if (!crypto?.subtle) {
throw new Error('Web Crypto SHA-256 is unavailable.');
}
const bytes = new TextEncoder().encode(value);
const digest = await crypto.subtle.digest('SHA-256', bytes);
return Array.from(new Uint8Array(digest), (byte) =>
byte.toString(16).padStart(2, '0'),
).join('');
}
/** Computes the source fingerprint only after the authored contract validates. */
export async function hashMechanicAuthoredSource(
source: MechanicAuthoredSource,
): Promise<MechanicAuthoredFingerprintResult> {
const validation = materializeMechanicAuthoredDescription(source);
if (!validation.ok) return validation;
const payload = mechanicAuthoredFingerprintPayload(source);
if (!payload) {
return {
ok: false,
errors: [
{
code: 'invalid_source',
path: '',
message: 'The validated authored source could not be serialized.',
},
],
};
}
return {
ok: true,
fingerprint: await sha256Utf8(stableJson(canonicalizeValue(payload))),
payload,
};
}
/** Computes lowercase SHA-256 over UTF-8 canonical Mechanic Program JSON. */
export async function hashMechanicProgram(
input: MechanicProgramHashInput,
): Promise<string> {
return sha256Utf8(canonicalMechanicProgramJson(input));
}
/**
* Hashes one owner revision across its explicit ordered program variants.
* Variant labels are presentation metadata; keys, order, and program semantics
* are revision data.
*/
export async function hashMechanicProgramVariants(
input: MechanicProgramVariantsHashInput,
): Promise<string> {
return sha256Utf8(
stableJson(
canonicalizeValue({
kind: MECHANIC_PROGRAM_VARIANTS_HASH_KIND,
version: MECHANIC_PROGRAM_HASH_VERSION,
simulationReadiness: input.simulationReadiness,
variants: input.variants.map((variant) => ({
key: variant.key,
program: mechanicProgramSemanticPayload(variant.program),
})),
}),
),
);
}
const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
function lifecycleAbsent(
reason: Extract<MechanicLifecycleResult, { status: 'absent' }>['reason'],
errors?: string[],
): MechanicLifecycleResult {
return errors?.length
? { status: 'absent', reason, errors }
: { status: 'absent', reason };
}
/**
* Classifies one selected model without ever treating readiness as currency.
* Validation and renderability are checked before currency, so malformed
* records fail closed as absent rather than leaking a stale or current model.
*/
export async function classifyMechanicLifecycle(
input: MechanicLifecycleInput,
): Promise<MechanicLifecycleResult> {
const revision = input.selectedRevision;
if (!revision || !revision.program) {
return lifecycleAbsent('no_selected_revision');
}
const program = revision.program;
let validation;
try {
validation = validateMechanicProgram(program);
} catch {
return lifecycleAbsent('invalid_program', [
'The selected mechanic could not be validated safely.',
]);
}
if (!validation.ok)
return lifecycleAbsent('invalid_program', validation.errors);
if (program.clauses.length === 0) {
return lifecycleAbsent(
revision.simulationReadiness === 'captured_only'
? 'empty_captured_program'
: 'empty_program',
);
}
const rendering = renderPublicMechanicPrograms(
[{ key: 'base', label: 'Base', program }],
{ resolveAttributeLabel: input.resolveAttributeLabel },
);
if (!rendering.ok) {
return lifecycleAbsent(
'unrenderable_program',
rendering.errors.map((error) => error.message),
);
}
if (
!['ready', 'requires_assumptions', 'captured_only'].includes(
revision.simulationReadiness,
)
) {
return { status: 'stale', reason: 'unsupported_contract' };
}
const supportedContractVersion =
input.supportedMechanicContractVersion ?? MECHANIC_PROGRAM_HASH_VERSION;
if (
revision.mechanicContractVersion !== supportedContractVersion ||
!Number.isInteger(revision.mechanicContractVersion) ||
revision.mechanicContractVersion <= 0
) {
return { status: 'stale', reason: 'unsupported_contract' };
}
if (
!SHA256_HEX_PATTERN.test(revision.sourceFingerprint) ||
!SHA256_HEX_PATTERN.test(input.currentSourceFingerprint)
) {
return lifecycleAbsent('invalid_program', [
'The selected revision and authored source require lowercase SHA-256 fingerprints.',
]);
}
if (revision.sourceFingerprint !== input.currentSourceFingerprint) {
return { status: 'stale', reason: 'fingerprint_mismatch' };
}
if (!SHA256_HEX_PATTERN.test(revision.programHash))
return lifecycleAbsent('invalid_program_hash');
let programHash: string;
try {
programHash = await hashMechanicProgram({
...program,
simulationReadiness: revision.simulationReadiness,
...(revision.sourceVariants !== undefined
? { sourceVariants: revision.sourceVariants }
: {}),
});
} catch {
return lifecycleAbsent('hash_unavailable');
}
if (programHash !== revision.programHash) {
return lifecycleAbsent('invalid_program_hash');
}
return {
status: 'current',
fingerprint: input.currentSourceFingerprint,
programHash,
simulationReadiness: revision.simulationReadiness,
};
}
/**
* Classifies a selected owner revision as one unit across every required
* program variant. One malformed or unrenderable variant fails the complete
* revision closed.
*/
export async function classifyMechanicVariantLifecycle(
input: MechanicVariantLifecycleInput,
): Promise<MechanicLifecycleResult> {
const revision = input.selectedRevision;
if (!revision || revision.variants.length === 0) {
return lifecycleAbsent('no_selected_revision');
}
for (const variant of revision.variants) {
let validation;
try {
validation = validateMechanicProgram(variant.program);
} catch {
return lifecycleAbsent('invalid_program', [
`Mechanic variant ${variant.key} could not be validated safely.`,
]);
}
if (!validation.ok) {
return lifecycleAbsent(
'invalid_program',
validation.errors.map((error) => `${variant.key}: ${error}`),
);
}
}
if (revision.variants.every((variant) => variant.program.clauses.length === 0)) {
return lifecycleAbsent(
revision.simulationReadiness === 'captured_only'
? 'empty_captured_program'
: 'empty_program',
);
}
if (revision.variants.some((variant) => variant.program.clauses.length === 0)) {
return lifecycleAbsent('invalid_program', [
'Every mechanic variant must contain the selected revision graph.',
]);
}
const rendering = renderPublicMechanicPrograms(revision.variants, {
resolveAttributeLabel: input.resolveAttributeLabel,
});
if (!rendering.ok) {
return lifecycleAbsent(
'unrenderable_program',
rendering.errors.map((error) => error.message),
);
}
if (
!['ready', 'requires_assumptions', 'captured_only'].includes(
revision.simulationReadiness,
)
) {
return { status: 'stale', reason: 'unsupported_contract' };
}
const supportedContractVersion =
input.supportedMechanicContractVersion ?? MECHANIC_PROGRAM_HASH_VERSION;
if (
revision.mechanicContractVersion !== supportedContractVersion ||
!Number.isInteger(revision.mechanicContractVersion) ||
revision.mechanicContractVersion <= 0
) {
return { status: 'stale', reason: 'unsupported_contract' };
}
if (
!SHA256_HEX_PATTERN.test(revision.sourceFingerprint) ||
!SHA256_HEX_PATTERN.test(input.currentSourceFingerprint)
) {
return lifecycleAbsent('invalid_program', [
'The selected revision and authored source require lowercase SHA-256 fingerprints.',
]);
}
if (revision.sourceFingerprint !== input.currentSourceFingerprint) {
return { status: 'stale', reason: 'fingerprint_mismatch' };
}
if (!SHA256_HEX_PATTERN.test(revision.programHash)) {
return lifecycleAbsent('invalid_program_hash');
}
let programHash: string;
try {
programHash = await hashMechanicProgramVariants({
simulationReadiness: revision.simulationReadiness,
variants: revision.variants,
});
} catch {
return lifecycleAbsent('hash_unavailable');
}
if (programHash !== revision.programHash) {
return lifecycleAbsent('invalid_program_hash');
}
return {
status: 'current',
fingerprint: input.currentSourceFingerprint,
programHash,
simulationReadiness: revision.simulationReadiness,
};
}
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest';
import { evaluateMechanicProgram } from './mechanic.js';
import {
adaptConditionalEffectProgram,
type ConditionalEffectClauseRow,
@@ -912,4 +913,77 @@ describe('conditional-effect persistence adapter', () => {
if: condition,
});
});
it('preserves a variant-value expression in persisted JSON while adapting it to the selected row value', () => {
const sourceExpression = {
op: 'multiply',
left: { ref: { source: 'variant_value' } },
right: {
op: 'add',
left: 1,
right: {
op: 'divide',
left: {
ref: {
source: 'equipment',
path: 'protocolTalentUpgrades',
},
},
right: 5,
},
},
};
const serializedExpression = JSON.stringify(sourceExpression);
const persistedOutcome = outcome({
state_pool_id: null,
value: 7.25,
value_expression_json: serializedExpression,
value_scaling: 'flat',
application_phase: 'on_event',
});
const result = adaptConditionalEffectProgram(
{
rule: rule(),
statePools: [],
clauses: [
clause({
trigger_id: null,
event_kind: 'tick',
parameters_json: '{}',
state_pool_id: null,
mutations_json: '[]',
}),
],
outcomes: [persistedOutcome],
triggers: [],
},
{ variantKey: 'I' },
);
expect(result).toMatchObject({ status: 'READY', errors: [] });
expect(persistedOutcome.value).toBe(7.25);
expect(persistedOutcome.value_expression_json).toBe(serializedExpression);
expect(JSON.parse(String(persistedOutcome.value_expression_json))).toEqual(
sourceExpression,
);
expect(result.program?.clauses[0].outcomes?.[0].value).toEqual({
op: 'multiply',
left: 7.25,
right: sourceExpression.right,
});
if (!result.program) return;
const runtime = evaluateMechanicProgram(
result.program,
[{ kind: 'tick', at: 0 }],
{ mode: 'custom', encounterSeconds: 1 },
undefined,
{ protocolTalentUpgrades: 5 },
);
expect(runtime.status).toBe('OK');
expect(runtime.outcomes[0]).toMatchObject({
outcomeId: 'outcome-1',
value: 14.5,
resolvedValue: 14.5,
});
});
});
+54 -6
View File
@@ -13,6 +13,7 @@ import {
type Predicate,
type Reducer,
type ScenarioInputDefinition,
type ValueReference,
} from './mechanic.js';
type DatabaseValue = string | number | bigint | boolean | null | undefined;
@@ -257,6 +258,55 @@ function isNumericExpression(value: unknown): value is NumericExpression {
);
}
function resolveVariantExpression(
value: unknown,
variantValue: number,
): NumericExpression | null {
if (finite(value)) return value;
if (!object(value)) return null;
if ('ref' in value) {
if (
object(value.ref) &&
value.ref.source === 'variant_value' &&
Object.keys(value.ref).length === 1
) {
return variantValue;
}
return isValueReference(value.ref)
? { ref: value.ref as ValueReference }
: null;
}
if (value.op === 'floor') {
const nested = resolveVariantExpression(value.value, variantValue);
return nested === null ? null : { op: 'floor', value: nested };
}
if (value.op === 'clamp') {
const nested = resolveVariantExpression(value.value, variantValue);
const min = resolveVariantExpression(value.min, variantValue);
const max = resolveVariantExpression(value.max, variantValue);
return nested === null || min === null || max === null
? null
: { op: 'clamp', value: nested, min, max };
}
if (
!['add', 'subtract', 'multiply', 'divide', 'min', 'max'].includes(
String(value.op),
)
) {
return null;
}
const left = resolveVariantExpression(value.left, variantValue);
const right = resolveVariantExpression(value.right, variantValue);
return left === null || right === null
? null
: {
op: value.op as
'add' | 'subtract' | 'multiply' | 'divide' | 'min' | 'max',
left,
right,
};
}
function isPredicate(value: unknown): value is Predicate {
if (!object(value) || typeof value.kind !== 'string') return false;
if (value.kind === 'true') return true;
@@ -673,11 +723,8 @@ function parseOutcome(
) {
errors.push(`${path} has an unsupported application phase.`);
}
let value: NumericExpression = requiredNumber(
row.value,
`${path} value`,
errors,
);
const variantValue = requiredNumber(row.value, `${path} value`, errors);
let value: NumericExpression = variantValue;
if (
row.value_expression_json !== null &&
row.value_expression_json !== undefined &&
@@ -689,7 +736,8 @@ function parseOutcome(
errors,
);
if (parsed.ok) {
if (isNumericExpression(parsed.value)) value = parsed.value;
const resolved = resolveVariantExpression(parsed.value, variantValue);
if (resolved !== null) value = resolved;
else
errors.push(
`${path} value expression is not a valid numeric expression.`,
@@ -0,0 +1,714 @@
import { describe, expect, it } from 'vitest';
import {
renderPublicMechanicPrograms,
type MechanicPublicProgramVariant,
} from './mechanic-public-renderer.js';
import { MECHANIC_EVENT_KINDS } from './mechanic.js';
import type { MechanicProgram } from './mechanic.js';
const baseProgram = (
overrides: Partial<MechanicProgram> = {},
): MechanicProgram => ({
id: 'public-renderer-test',
name: 'Public renderer test',
clauses: [
{
id: 'hit',
label: 'Hit target',
when: 'weapon_hit',
if: {
kind: 'compare',
left: { source: 'event', path: 'values.headshot' },
operator: 'eq',
right: true,
},
reducer: { kind: 'none' },
mutations: [{ kind: 'none' }],
outcomes: [
{
id: 'damage',
label: 'Headshot damage',
phase: 'on_event',
kind: 'direct_damage',
scope: 'target',
value: 12.5,
basis: 'flat',
},
],
},
],
...overrides,
});
const variants = (
...programs: Array<[string, MechanicProgram]>
): MechanicPublicProgramVariant[] =>
programs.map(([key, program]) => ({ key, program }));
const render = (
program: MechanicProgram,
options?: {
resolveAttributeLabel?: (attributeId: string) => string | null | undefined;
},
) => renderPublicMechanicPrograms([{ key: 'base', program }], options);
describe('public mechanic renderer', () => {
it('renders deterministic, readable prose for ordered variants', () => {
const input = variants(
['I', baseProgram()],
['II', baseProgram({ id: 'public-renderer-test-ii' })],
);
expect(renderPublicMechanicPrograms(input)).toEqual({
ok: true,
variants: [
{
key: 'I',
label: 'Tier I',
text: 'Tier I\n\nHit target: When Weapon hit occurs, provided that the event’s Headshot is equal to true. Headshot damage: when this event occurs, deal 12.5 damage to the target immediately.',
},
{
key: 'II',
label: 'Tier II',
text: 'Tier II\n\nHit target: When Weapon hit occurs, provided that the event’s Headshot is equal to true. Headshot damage: when this event occurs, deal 12.5 damage to the target immediately.',
},
],
});
});
it('preserves the supplied order of variants', () => {
const result = renderPublicMechanicPrograms(
variants(
['II', baseProgram({ id: 'tier-ii' })],
['I', baseProgram({ id: 'tier-i' })],
),
);
expect(result.ok && result.variants.map((variant) => variant.key)).toEqual([
'II',
'I',
]);
});
it('renders every event registry label without exposing the script format', () => {
const program = baseProgram({
clauses: MECHANIC_EVENT_KINDS.map((when) => ({
id: when,
when,
label: when,
reducer: { kind: 'none' as const },
mutations: [{ kind: 'none' as const }],
})),
});
const result = render(program);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.variants[0].text).not.toContain('WHEN ');
expect(result.variants[0].text).not.toContain('EVENT.');
expect(result.variants[0].text).not.toContain('{');
for (const clause of program.clauses) {
expect(result.variants[0].text).toContain(
(
{
shot_fired: 'Shot fired',
weapon_hit: 'Weapon hit',
skill_deployed: 'Skill deployed',
signature_ability_deployed: 'Signature Ability deployed',
skill_hit: 'Skill hit',
skill_multishot_triggered: 'Skill Multi-Shot triggered',
agent_hit: 'Agent hit',
health_damage_taken: 'Health damage taken',
damage_dealt: 'Damage dealt',
enemy_killed: 'Enemy killed',
assist: 'Assist',
ally_downed: 'Ally downed',
agent_downed: 'Agent downed',
ally_rescued: 'Ally rescued',
grenade_thrown: 'Grenade thrown',
medical_kit_used: 'Medical Kit used',
healing_applied: 'Healing applied',
extra_health_granted: 'Extra Health granted',
extra_health_changed: 'Extra Health changed',
movement_snapshot: 'Movement snapshot',
proximity_snapshot: 'Proximity snapshot',
firing_started: 'Firing started',
firing_stopped: 'Firing stopped',
reload_started: 'Reload started',
reload_completed: 'Reload completed',
weapon_swapped: 'Weapon swapped',
tick: 'Simulation tick',
} as Record<string, string>
)[clause.when],
);
}
});
it('covers conditions, references, reducers, state, mutations, and outcome metadata', () => {
const program = baseProgram({
scenarioInputs: [
{
key: 'stacks-to-add',
label: 'Stacks to add',
kind: 'number',
defaultValue: 1.25,
bestCaseValue: 2.5,
min: 0,
max: 3,
},
],
pools: [
{
key: 'stacks',
label: 'Momentum stacks',
scope: 'agent',
initial: 0,
min: 0,
max: 4,
bestCaseValue: 3,
expiresAfterSeconds: 8.75,
},
{
key: 'target-mark',
label: 'Target mark',
scope: 'target',
initial: 0,
min: 0,
max: 1,
},
{
key: 'cooldown',
label: 'Momentum cooldown',
scope: 'agent',
initial: 0,
min: 0,
max: 1,
expiresAfterSeconds: 12,
},
],
clauses: [
{
id: 'advanced',
label: 'Build momentum',
when: 'weapon_hit',
if: {
kind: 'all',
predicates: [
{
kind: 'compare',
left: { source: 'event', path: 'values.distanceMeters' },
operator: 'lte',
right: 15.5,
},
{
kind: 'not',
predicate: {
kind: 'exists',
value: { source: 'event', path: 'values.critical' },
},
},
{
kind: 'compare',
left: { source: 'attribute', attributeId: 'firepower' },
operator: 'gte',
right: { source: 'scenario', key: 'stacks-to-add' },
},
],
},
reducer: {
kind: 'count',
threshold: 2,
reset: 'subtract',
groupBy: { source: 'event', path: 'targetId' },
},
cooldownSeconds: 4.5,
weight: {
op: 'clamp',
value: { ref: { source: 'pool', pool: 'stacks' } },
min: 0,
max: 1,
},
procChancePercent: 37.5,
requiresAssignedAbilityActive: true,
mutations: [
{
kind: 'add',
pool: 'stacks',
value: { ref: { source: 'scenario', key: 'stacks-to-add' } },
},
{
kind: 'set',
pool: 'target-mark',
entity: { kind: 'event_target' },
value: 1,
},
{ kind: 'consume', pool: 'stacks', value: 0.5 },
{
kind: 'derive',
pool: 'stacks',
value: { op: 'floor', value: { ref: { source: 'reducer' } } },
},
{
kind: 'transfer',
pool: 'target-mark',
from: { kind: 'event_target' },
to: { kind: 'agent' },
value: 'all',
clearSource: false,
},
{
kind: 'extend_duration',
target: 'assigned_ability',
seconds: 2.25,
},
{
kind: 'start_cooldown_on_max',
stackPool: 'stacks',
cooldownPool: 'cooldown',
},
],
outcomes: [
{
id: 'buff',
label: 'Momentum buff',
phase: 'while_active',
kind: 'attribute_modifier',
scope: 'self',
value: {
op: 'multiply',
left: 2,
right: {
ref: { source: 'attribute', attributeId: 'firepower' },
},
},
basis: 'flat',
attributeId: 'firepower',
statePool: 'stacks',
perStack: true,
minStacks: 1,
maxStacks: 4,
combatTiming: 'current',
probabilityPercent: 88.25,
},
{
id: 'restore',
label: 'Regeneration',
phase: 'after_event',
kind: 'restoration',
scope: 'self_and_allies',
value: 10,
basis: 'max_health_percent',
resource: 'health',
delivery: 'continuous',
durationSeconds: 3.5,
},
{
id: 'cost',
label: 'Ammo cost',
phase: 'on_event',
kind: 'resource_cost',
scope: 'self',
value: 2,
basis: 'flat',
resource: 'ammo',
delivery: 'instant',
},
{
id: 'reload',
label: 'Reload inactive weapon',
phase: 'on_exit',
kind: 'weapon_reload',
scope: 'inactive_weapon',
value: { op: 'add', left: 1.125, right: 0.25 },
basis: 'flat',
},
{
id: 'area',
label: 'Area strike',
phase: 'on_event',
kind: 'direct_damage',
scope: 'target',
value: 15,
basis: 'weapon_base_percent',
targeting: {
kind: 'event_target_area',
center: 'event_target',
validTargets: 'enemies',
radiusMeters: 4,
},
},
{
id: 'marker',
label: 'Marker',
phase: 'on_enter',
kind: 'marker',
scope: 'assigned_ability',
value: 1,
basis: 'flat',
},
],
},
],
});
const result = render(program, {
resolveAttributeLabel: (id) =>
id === 'firepower' ? 'Firepower' : undefined,
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.variants[0].text).toMatchInlineSnapshot(`
"Base
The “Stacks to add” scenario input is a number, from 0, to 3, default 1.25, maximum 2.5.
State “Momentum cooldown” tracks the Agent, starting at 0, from 0 to 1. It expires 12 seconds after it is written. State “Momentum stacks” tracks the Agent, starting at 0, from 0 to 4. The maximum scenario value is 3. It expires 8.75 seconds after it is written. State “Target mark” tracks each target, starting at 0, from 0 to 1.
Build momentum: When Weapon hit occurs, provided that all of these conditions are met: (the event’s Target distance is at most 15.5); (it is not the case that the event’s Critical hit is present); (the Firepower Attribute value is at least the “Stacks to add” scenario input), after 2 matching events grouped by the event’s Target ID while retaining any matches beyond the threshold, only while the assigned ability is active, with a weight of the value of the “Momentum stacks” state for the Agent limited from 0 to 1, with a 37.5% chance to trigger, then unavailable for 4.5 seconds. Add the “Stacks to add” scenario input to the “Momentum stacks” state for the Agent. Set 1 as the “Target mark” state for the event target. Consume 0.5 from the “Momentum stacks” state for the Agent. Derive the whole-number value of the reduced value as the “Momentum stacks” state for the Agent. Transfer all of the “Target mark” state from the event target to the Agent, without clearing the source. Extend the assigned ability by 2.25 seconds. Start the “Momentum cooldown” cooldown when the “Momentum stacks” state reaches its maximum. Momentum buff: while the state is active, modify “Firepower” by the product of 2 and the Firepower Attribute value for the Agent using the “Momentum stacks” state per stack when stacks are from 1 through 4 immediately with a 88.25% chance. Regeneration: after this event, restore a total of 10% of maximum Health to Health for the Agent and allies continuously over 3.5 seconds. Ammo cost: when this event occurs, spend 2 of Ammo from the Agent immediately. Reload inactive weapon: when the state ends, reload the inactive weapon after the sum of 1.125 and 0.25 seconds. Area strike: when this event occurs, deal damage equal to 15% of weapon base damage to the target, affecting valid enemies within 4 meters of the event target immediately. Marker: when the state begins, record a marker of 1 for the assigned ability immediately."
`);
});
it('renders a custom variant label and resolves all attribute references', () => {
const result = renderPublicMechanicPrograms(
[
{
key: 'rank-1',
label: 'Rank 1',
program: baseProgram({
clauses: [
{
...baseProgram().clauses[0],
if: {
kind: 'exists',
value: { source: 'attribute', attributeId: 'armor' },
},
outcomes: [
{
...baseProgram().clauses[0].outcomes![0],
kind: 'attribute_modifier',
attributeId: 'armor',
scope: 'self',
},
],
},
],
}),
},
],
{ resolveAttributeLabel: (id) => (id === 'armor' ? 'Armor' : null) },
);
expect(result).toMatchObject({
ok: true,
variants: [{ key: 'rank-1', label: 'Rank 1' }],
});
if (result.ok) expect(result.variants[0].text).toContain('“Armor”');
});
it('fails closed for an invalid program before attempting to render it', () => {
const invalid = baseProgram({
clauses: [{ ...baseProgram().clauses[0], when: 'not-an-event' as never }],
});
const result = render(invalid);
expect(result).toMatchObject({
ok: false,
errors: [{ code: 'invalid_program', path: 'variants[base]' }],
});
});
it('validates true predicates instead of dropping their structure', () => {
const program = baseProgram({
clauses: [
{
...baseProgram().clauses[0],
if: { kind: 'true', unexpected: true } as never,
},
],
});
const result = render(program);
expect(result).toMatchObject({
ok: false,
errors: [
{
code: 'unsupported_fragment',
path: 'variants[base].clauses[0].if.unexpected',
},
],
});
});
it('rejects overlapping or non-array input shapes', () => {
const result = renderPublicMechanicPrograms({
variants: [{ key: 'base', program: baseProgram() }],
} as never);
expect(result).toMatchObject({
ok: false,
errors: [{ code: 'invalid_program', path: 'variants' }],
});
});
it('rejects combat references outside the combat reference registry', () => {
const result = render(
baseProgram({
clauses: [
{
...baseProgram().clauses[0],
outcomes: [
{
...baseProgram().clauses[0].outcomes![0],
value: {
ref: { source: 'combat', path: 'maxHealth' },
},
},
],
},
],
}),
);
expect(result).toMatchObject({
ok: false,
errors: [
{
code: 'unsupported_fragment',
path: 'variants[base].clauses[0].outcomes[0].value.ref.path',
},
],
});
});
it('fails closed when an Attribute ID cannot be resolved', () => {
const result = render(
baseProgram({
clauses: [
{
...baseProgram().clauses[0],
outcomes: [
{
...baseProgram().clauses[0].outcomes![0],
kind: 'attribute_modifier',
attributeId: 'missing-attribute',
},
],
},
],
}),
{ resolveAttributeLabel: () => undefined },
);
expect(result).toMatchObject({
ok: false,
errors: [
{
code: 'unresolved_attribute',
path: 'variants[base].clauses[0].outcomes[0].attributeId',
},
],
});
});
it('does not render ignored combat timing on flat outcomes', () => {
const program = baseProgram({
clauses: [
{
...baseProgram().clauses[0],
outcomes: [
{
...baseProgram().clauses[0].outcomes![0],
basis: 'flat',
combatTiming: 'pre_event',
},
],
},
],
});
const result = render(program);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.variants[0].text).not.toContain('before this event');
expect(result.variants[0].text).not.toContain('using current values');
}
});
it('fails closed for targeting the runtime does not expand', () => {
const result = render(
baseProgram({
clauses: [
{
...baseProgram().clauses[0],
outcomes: [
{
...baseProgram().clauses[0].outcomes![0],
targeting: {
kind: 'within_radius',
population: 'enemies',
radiusMeters: 4,
},
},
],
},
],
}),
);
expect(result).toMatchObject({
ok: false,
errors: [
{
code: 'unsupported_fragment',
path: 'variants[base].clauses[0].outcomes[0].targeting',
},
],
});
});
it('sorts set-like inputs and pools by semantic key', () => {
const first = baseProgram({
scenarioInputs: [
{
key: 'z-input',
label: 'Z input',
kind: 'toggle',
defaultValue: false,
bestCaseValue: true,
},
{
key: 'a-input',
label: 'A input',
kind: 'toggle',
defaultValue: false,
bestCaseValue: true,
},
],
pools: [
{ key: 'z-pool', label: 'Z pool', scope: 'agent', initial: 0 },
{ key: 'a-pool', label: 'A pool', scope: 'agent', initial: 0 },
],
});
const second = baseProgram({
scenarioInputs: [...first.scenarioInputs!].reverse(),
pools: [...first.pools!].reverse(),
});
const firstResult = render(first);
const secondResult = render(second);
expect(firstResult.ok && secondResult.ok).toBe(true);
if (firstResult.ok && secondResult.ok)
expect(firstResult.variants[0].text).toBe(secondResult.variants[0].text);
});
it('requires renderable labels instead of humanizing generated IDs', () => {
const missingVariantLabel = renderPublicMechanicPrograms([
{ key: 'generated-variant-id', program: baseProgram() },
]);
expect(missingVariantLabel).toMatchObject({
ok: false,
errors: [
{
code: 'unsupported_fragment',
path: 'variants[generated-variant-id].label',
},
],
});
const missingClauseLabel = render(
baseProgram({
clauses: [{ ...baseProgram().clauses[0], label: undefined }],
}),
);
expect(missingClauseLabel).toMatchObject({
ok: false,
errors: [
{
code: 'unsupported_fragment',
path: 'variants[base].clauses[0].label',
},
],
});
const missingOutcomeLabel = render(
baseProgram({
clauses: [
{
...baseProgram().clauses[0],
outcomes: [
{
...baseProgram().clauses[0].outcomes![0],
label: undefined as never,
},
],
},
],
}),
);
expect(missingOutcomeLabel).toMatchObject({
ok: false,
errors: [
{
code: 'unsupported_fragment',
path: 'variants[base].clauses[0].outcomes[0].label',
},
],
});
const missingPoolLabel = render(
baseProgram({
pools: [
{
key: 'generated-pool-id',
label: undefined as never,
scope: 'agent',
initial: 0,
},
],
}),
);
expect(missingPoolLabel).toMatchObject({
ok: false,
errors: [
{ code: 'unsupported_fragment', path: 'variants[base].pools[0].label' },
],
});
});
it('fails closed for unsupported fields instead of leaking them', () => {
const program = baseProgram();
(
program.clauses[0] as MechanicProgram['clauses'][number] & {
script?: string;
}
).script = 'WHEN raw';
const result = render(program);
expect(result).toMatchObject({
ok: false,
errors: [
{
code: 'unsupported_fragment',
path: 'variants[base].clauses[0].script',
},
],
});
});
it('does not round represented numeric values or depend on locale settings', () => {
const program = baseProgram({
clauses: [
{
...baseProgram().clauses[0],
outcomes: [
{ ...baseProgram().clauses[0].outcomes![0], value: 1.23456789 },
],
},
],
});
const result = render(program);
expect(result.ok).toBe(true);
if (result.ok) expect(result.variants[0].text).toContain('1.23456789');
});
});
File diff suppressed because it is too large Load Diff
+269
View File
@@ -19,6 +19,84 @@ const custom = (
inputs,
});
const closeAndPersonalProgram = (
resolvedVariantValue: number,
): MechanicProgram => ({
id: 'close-and-personal-engineering',
name: 'Close and Personal Engineering',
pools: [
{
key: 'eligible-allies',
label: 'Eligible Allies',
scope: 'agent',
initial: 0,
min: 0,
max: 20,
},
],
clauses: [
{
id: 'sample-eligible-allies',
when: 'proximity_snapshot',
reducer: {
kind: 'derived_scalar',
value: {
ref: {
source: 'event',
path: 'values.alliesWithin30MetersWithAgentGrantedBuff',
},
},
},
mutations: [
{
kind: 'derive',
pool: 'eligible-allies',
value: { ref: { source: 'reducer' } },
},
],
},
{
id: 'resolve-engineering',
when: 'tick',
reducer: { kind: 'none' },
mutations: [{ kind: 'none' }],
outcomes: [
{
id: 'engineering',
label: 'Engineering',
phase: 'on_event',
kind: 'attribute_modifier',
scope: 'self',
basis: 'flat',
attributeId: 'engineering',
value: {
op: 'multiply',
left: {
op: 'multiply',
left: { ref: { source: 'pool', pool: 'eligible-allies' } },
right: resolvedVariantValue,
},
right: {
op: 'add',
left: 1,
right: {
op: 'divide',
left: {
ref: {
source: 'equipment',
path: 'protocolTalentUpgrades',
},
},
right: 5,
},
},
},
},
],
},
],
});
describe('deterministic mechanic probabilities and assigned abilities', () => {
it('rolls outcome probability independently with a reproducible seed and preserves a refreshed window', () => {
const program: MechanicProgram = {
@@ -321,6 +399,23 @@ describe('structured mechanic runtime', () => {
});
});
it('advertises the optional non-negative integer proximity count without making snapshots strict', () => {
const definition = MECHANIC_EVENT_REGISTRY.proximity_snapshot;
const countField = definition.fields?.find(
({ path }) => path === 'values.alliesWithin30MetersWithAgentGrantedBuff',
);
expect(definition.strictFields).not.toBe(true);
expect(countField).toEqual({
path: 'values.alliesWithin30MetersWithAgentGrantedBuff',
label: 'Allies within 30 meters with an Agent-granted buff',
type: 'number',
minimum: 0,
integer: true,
});
expect(countField?.required).not.toBe(true);
});
it('advertises imported support and equipment-use trigger events', () => {
expect(MECHANIC_EVENT_REGISTRY.ally_downed).toMatchObject({
key: 'ally_downed',
@@ -1260,6 +1355,104 @@ describe('structured mechanic runtime', () => {
expect(maximum.finalState[0].value).toBe(4);
});
it('preserves an explicit zero clause weight', () => {
const result = evaluateMechanicProgram(
{
id: 'zero-weight',
name: 'Zero weight',
clauses: [
{
id: 'zero-weight-clause',
when: 'agent_hit',
reducer: { kind: 'none' },
weight: 0,
mutations: [],
},
],
},
[{ kind: 'agent_hit', at: 0 }],
custom(1),
);
expect(result.emissions).toHaveLength(1);
expect(result.emissions[0].weight).toBe(0);
expect(result.estimatedActivationCount).toBe(0);
});
it.each([0, 0.5])(
'keeps a weighted reload delay intact at weight %s',
(weight) => {
const result = evaluateMechanicProgram(
{
id: 'weighted-reload',
name: 'Weighted reload',
clauses: [
{
id: 'weighted-reload-clause',
when: 'weapon_hit',
reducer: { kind: 'none' },
weight,
mutations: [],
outcomes: [
{
id: 'reload',
label: 'Reload',
phase: 'on_event',
kind: 'weapon_reload',
scope: 'equipped_weapon',
value: 5,
basis: 'flat',
},
],
},
],
},
[{ kind: 'weapon_hit', at: 1 }],
custom(10),
);
expect(result.outcomes).toHaveLength(1);
expect(result.outcomes[0]).toMatchObject({
at: 6,
weight,
resolvedValue: 5,
appliedValue: 5,
});
},
);
it('preserves a zero weight for maximum-mode passive outcomes', () => {
const result = evaluateMechanicProgram(
{
id: 'zero-weight-maximum',
name: 'Zero weight maximum',
clauses: [
{
id: 'zero-weight-maximum-clause',
label: 'Maximum passive',
when: 'weapon_hit',
reducer: { kind: 'none' },
weight: 0,
mutations: [],
outcomes: [
{
id: 'marker',
label: 'Passive marker',
phase: 'while_active',
kind: 'marker',
scope: 'self',
value: 1,
basis: 'flat',
},
],
},
],
},
[],
{ mode: 'maximum', encounterSeconds: 10 },
);
expect(result.outcomes).toHaveLength(1);
expect(result.outcomes[0]).toMatchObject({ weight: 0, appliedValue: 0 });
});
it('derives proximity stacks directly from a builder-controlled snapshot', () => {
const program: MechanicProgram = {
id: 'nearby-allies',
@@ -1306,6 +1499,7 @@ describe('structured mechanic runtime', () => {
],
custom(),
);
expect(result.status).toBe('OK');
expect(result.finalState[0].value).toBe(2);
const maximum = evaluateMechanicProgram(program, [], {
mode: 'maximum',
@@ -1314,6 +1508,81 @@ describe('structured mechanic runtime', () => {
expect(maximum.finalState[0].value).toBe(3);
});
it.each([
{ count: 0, upgrades: 0, multiplier: 0 },
{ count: 3, upgrades: 0, multiplier: 3 },
{ count: 3, upgrades: 5, multiplier: 6 },
])(
'resolves Close-and-Personal-style Engineering for count $count and $upgrades OS upgrades',
({ count, upgrades, multiplier }) => {
const resolvedVariantValue = 7.25;
const result = evaluateMechanicProgram(
closeAndPersonalProgram(resolvedVariantValue),
[
{
kind: 'proximity_snapshot',
at: 0,
values: {
alliesWithin30MetersWithAgentGrantedBuff: count,
},
},
{ kind: 'tick', at: 1 },
],
custom(),
undefined,
{ protocolTalentUpgrades: upgrades },
);
expect(result.status).toBe('OK');
expect(result.finalState).toContainEqual(
expect.objectContaining({ pool: 'eligible-allies', value: count }),
);
expect(
result.outcomes.find(({ outcomeId }) => outcomeId === 'engineering'),
).toMatchObject({
value: resolvedVariantValue * multiplier,
resolvedValue: resolvedVariantValue * multiplier,
});
},
);
it.each([
{
count: '2',
error:
'Allies within 30 meters with an Agent-granted buff must be a number.',
},
{
count: -1,
error:
'Allies within 30 meters with an Agent-granted buff must be 0 or greater.',
},
{
count: 1.5,
error:
'Allies within 30 meters with an Agent-granted buff must be an integer.',
},
])('rejects invalid proximity ally count $count', ({ count, error }) => {
const result = evaluateMechanicProgram(
closeAndPersonalProgram(7.25),
[
{
kind: 'proximity_snapshot',
at: 0,
values: {
alliesWithin30MetersWithAgentGrantedBuff: count,
},
},
],
custom(),
undefined,
{ protocolTalentUpgrades: 0 },
);
expect(result.status).toBe('INVALID');
expect(result.errors).toContain(`Event 1 (Proximity snapshot) ${error}`);
});
it('shares one movement charge pool across generation and consumption clauses', () => {
const program: MechanicProgram = {
id: 'mobile-charge',
+37 -6
View File
@@ -28,6 +28,13 @@ export const MECHANIC_EVENT_KINDS = [
'tick',
] as const;
export const PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_VALUE_KEY =
'alliesWithin30MetersWithAgentGrantedBuff' as const;
export const PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_FIELD =
`values.${PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_VALUE_KEY}` as const;
export const PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_INPUT =
'allies-within-30m-with-agent-granted-buff' as const;
export type MechanicEventKind = (typeof MECHANIC_EVENT_KINDS)[number];
export type MechanicEventDefinition = {
key: MechanicEventKind;
@@ -39,6 +46,7 @@ export type MechanicEventDefinition = {
type: 'boolean' | 'number' | 'string';
required?: boolean;
minimum?: number;
integer?: boolean;
}[];
strictFields?: boolean;
};
@@ -308,6 +316,15 @@ export const MECHANIC_EVENT_REGISTRY: Readonly<
label: 'Proximity snapshot',
description:
'A sampled count or state for nearby allies, enemies, and Agent-owned buffs.',
fields: [
{
path: PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_FIELD,
label: 'Allies within 30 meters with an Agent-granted buff',
type: 'number',
minimum: 0,
integer: true,
},
],
},
firing_started: {
key: 'firing_started',
@@ -1616,8 +1633,10 @@ function emitOutcomes(
}
const targetIds = outcomeTargetIds(clause, outcome, context);
if (!targetIds) continue;
const emittedAt =
outcome.kind === 'weapon_reload' ? at + Math.max(0, appliedValue) : at;
if (outcome.kind === 'weapon_reload') {
appliedValue = Math.max(0, resolvedValue);
}
const emittedAt = outcome.kind === 'weapon_reload' ? at + appliedValue : at;
for (const targetId of targetIds) {
emissions.push({
clauseId: clause.id,
@@ -2049,6 +2068,13 @@ function validateMechanicEvents(events: MechanicEvent[]) {
) {
errors.push(`${fieldPath} must be ${field.minimum} or greater.`);
}
if (
field.type === 'number' &&
field.integer &&
!Number.isInteger(value)
) {
errors.push(`${fieldPath} must be an integer.`);
}
}
const hasExtraHealth = getPath(event, 'values.hasExtraHealth');
const currentExtraHealth = getPath(event, 'values.currentExtraHealth');
@@ -3091,6 +3117,10 @@ export function evaluateMechanicProgram(
.filter((pool): pool is string => Boolean(pool))
.map((pool) => [pool, stateValue(pool, undefined, context)]),
);
const weight =
clause.weight !== undefined
? clamp(numericValue(clause.weight, context), 0, 1)
: 1;
appendScheduledOutcomes(
outcomes,
emitOutcomes(
@@ -3102,7 +3132,7 @@ export function evaluateMechanicProgram(
},
'after',
0,
1,
weight,
before,
context,
continuousDeliveries,
@@ -3224,9 +3254,10 @@ export function evaluateMechanicProgram(
for (const reduction of reduced) {
if (reduction.at + EPSILON < (cooldowns.get(stateKey) ?? 0)) continue;
const context = { ...baseContext, reducerValue: reduction.value };
const weight = clause.weight
? clamp(numericValue(clause.weight, context), 0, 1)
: 1;
const weight =
clause.weight !== undefined
? clamp(numericValue(clause.weight, context), 0, 1)
: 1;
const relevantPools = new Set(
(clause.outcomes ?? [])
.map((outcome) => outcome.statePool)
+2 -6
View File
@@ -172,10 +172,6 @@
<a class="discord-link-button" class:interaction-pending={discordLinkPending} aria-busy={discordLinkPending} href="/auth/discord?mode=link" onclick={() => discordLinkPending = true}><img src="/discord-symbol.svg" alt="" aria-hidden="true"/><span>Link Discord</span></a>
{/if}
{/if}
<div class="security-summary" aria-label="Multi-factor authentication">
<div><p class="eyebrow">ACCOUNT HARDENING</p><h2>MULTI-FACTOR AUTHENTICATION</h2><small>{account.mfa?.enabled ? 'Authenticator active.' : 'Optional for standard accounts.'}</small></div>
<a class="secondary security-link" href="/account/security">REVIEW SECURITY →</a>
</div>
</div>
{:else}
<div class="account-panel" role="tabpanel">
@@ -187,6 +183,6 @@
</section>
<style>
.owner-account-control{width:100%;min-width:0;padding:12px}.current-avatar{display:grid;grid-template-columns:58px minmax(0,1fr) auto;align-items:center;gap:10px;padding:8px;border:1px solid var(--shd-border);background:#0d1011}.current-avatar>img{width:58px;height:58px;border:1px solid var(--shd-orange);border-radius:50%;object-fit:cover}.current-avatar>div{min-width:0;display:grid;gap:3px}.current-avatar small{color:var(--shd-text-dim);font-size:var(--shd-type-telemetry);font-weight:900;letter-spacing:.7px}.current-avatar strong{overflow:hidden;color:var(--shd-text);font-size:var(--shd-type-supporting);text-overflow:ellipsis;white-space:nowrap}.avatar-edit-trigger{min-height:40px;padding:0 10px}.avatar-editor{display:grid;gap:9px;margin-top:9px;padding-top:9px;border-top:1px solid var(--shd-border)}.account-section-heading{display:flex;align-items:start;justify-content:space-between;gap:8px}.account-section-heading h2{margin-bottom:0}.owner-account-control :global(.image-drop-input){grid-template-columns:58px minmax(0,1fr)}.owner-account-control :global(.image-upload-actions){grid-column:1/-1;grid-template-columns:1fr}.discord-link-button{width:100%;min-height:44px;display:flex;align-items:center;justify-content:center;gap:9px;border:1px solid #6571dc;background:#171a32;color:#fff}.discord-link-button img{width:22px}.provider-unlink-confirm{grid-column:1/-1;display:grid;gap:8px;margin-top:8px;padding-top:8px;border-top:1px solid var(--shd-border)}.provider-unlink-confirm>div{display:grid;grid-template-columns:1fr 1fr;gap:6px}.provider-unlink-confirm button{width:100%;min-height:40px}.security-summary{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-top:18px;padding:14px 0;border-top:1px solid var(--shd-border)}.security-summary h2{margin:2px 0 4px}.security-summary small{color:var(--shd-text-muted)}.security-link{white-space:nowrap;text-decoration:none}
@media(max-width:650px){.current-avatar{grid-template-columns:52px minmax(0,1fr)}.current-avatar>img{width:52px;height:52px}.avatar-edit-trigger{grid-column:1/-1;width:100%;min-height:44px}.security-summary{align-items:stretch;flex-direction:column}.security-link{width:100%;text-align:center}}
.owner-account-control{width:100%;min-width:0;padding:12px}.current-avatar{display:grid;grid-template-columns:58px minmax(0,1fr) auto;align-items:center;gap:10px;padding:8px;border:1px solid var(--shd-border);background:#0d1011}.current-avatar>img{width:58px;height:58px;border:1px solid var(--shd-orange);border-radius:50%;object-fit:cover}.current-avatar>div{min-width:0;display:grid;gap:3px}.current-avatar small{color:var(--shd-text-dim);font-size:var(--shd-type-telemetry);font-weight:900;letter-spacing:.7px}.current-avatar strong{overflow:hidden;color:var(--shd-text);font-size:var(--shd-type-supporting);text-overflow:ellipsis;white-space:nowrap}.avatar-edit-trigger{min-height:40px;padding:0 10px}.avatar-editor{display:grid;gap:9px;margin-top:9px;padding-top:9px;border-top:1px solid var(--shd-border)}.account-section-heading{display:flex;align-items:start;justify-content:space-between;gap:8px}.account-section-heading h2{margin-bottom:0}.owner-account-control :global(.image-drop-input){grid-template-columns:58px minmax(0,1fr)}.owner-account-control :global(.image-upload-actions){grid-column:1/-1;grid-template-columns:1fr}.discord-link-button{width:100%;min-height:44px;display:flex;align-items:center;justify-content:center;gap:9px;border:1px solid #6571dc;background:#171a32;color:#fff}.discord-link-button img{width:22px}.provider-unlink-confirm{grid-column:1/-1;display:grid;gap:8px;margin-top:8px;padding-top:8px;border-top:1px solid var(--shd-border)}.provider-unlink-confirm>div{display:grid;grid-template-columns:1fr 1fr;gap:6px}.provider-unlink-confirm button{width:100%;min-height:40px}
@media(max-width:650px){.current-avatar{grid-template-columns:52px minmax(0,1fr)}.current-avatar>img{width:52px;height:52px}.avatar-edit-trigger{grid-column:1/-1;width:100%;min-height:44px}}
</style>
+38 -6
View File
@@ -7,15 +7,20 @@
import type { DatabaseItem } from '$lib/database/items';
import MarkdownContent from './MarkdownContent.svelte';
import WeaponModSlotIcon from './WeaponModSlotIcon.svelte';
import DatabaseMechanicGroupCard from './database/DatabaseMechanicGroup.svelte';
import DatabaseMechanicStatusBadge from './database/DatabaseMechanicStatusBadge.svelte';
import { databaseMechanicGroupStatus, type DatabaseMechanicGroup } from '$lib/database/items';
let {
item,
hideDiscussionUtility = false,
anchor = true
anchor = true,
detail = false
}: {
item: DatabaseItem & { gameIcon?: GameIconName };
hideDiscussionUtility?: boolean;
anchor?: boolean;
detail?: boolean;
} = $props();
let protocolLevel = $state(1);
let talentUpgrades = $state(0);
@@ -29,6 +34,14 @@
const effect = item.protocolPreview?.talentEffects[Number(raw) - 1];
return effect ? valueWithUnit(effect.baseValue * (1 + talentUpgrades / 5), effect.unit) : placeholder;
});
const mechanicGroups = () => item.mechanicGroups ?? [];
const hasMechanicGroups = () => mechanicGroups().length > 0;
const isSpecializationMechanic = (group: DatabaseMechanicGroup) => group.ownerType === 'specialization_tree_rank';
const hasSpecializationMechanics = () => mechanicGroups().some(isSpecializationMechanic);
const primaryMechanicGroup = () => {
const groups = mechanicGroups();
return groups.length === 1 && !isSpecializationMechanic(groups[0]) ? groups[0] : null;
};
</script>
<article id={anchor ? `database-item-${item.id}` : undefined} class="database-item-card" class:talent-card={item.variant === 'talent'} class:protocol-quality-standard={item.topBorderTone === 'standard'} class:protocol-quality-specialized={item.topBorderTone === 'specialized'} class:protocol-quality-superior={item.topBorderTone === 'superior'} class:protocol-quality-highend={item.topBorderTone === 'highend'}>
@@ -39,7 +52,12 @@
</div>
<div class="database-item-identity">
<small>{item.kicker}</small>
<h2>{item.name}</h2>
<div class="database-item-name-line">
<h2>{item.name}</h2>
{#if primaryMechanicGroup()}
<DatabaseMechanicStatusBadge status={databaseMechanicGroupStatus(primaryMechanicGroup()!)} />
{/if}
</div>
</div>
{#if item.headerBadges?.length || item.headerBadge || item.headerMetaIcon}
<div class="database-header-status">
@@ -53,7 +71,7 @@
{#if item.protocolPreview}
<section class="database-protocol-preview">
<div class="database-protocol-primary"><span>{item.protocolPreview.primaryStat}</span><b>{Number.isFinite(protocolPrimaryValue()) ? valueWithUnit(protocolPrimaryValue(), item.protocolPreview.primaryUnit) : 'NOT CONFIGURED'}</b></div>
{#if item.protocolPreview.talentDescription}
{#if item.protocolPreview.talentDescription && !hasMechanicGroups()}
<div class="database-protocol-talent"><p>{talentDescription()}</p></div>
{/if}
<div class="database-protocol-controls"><label class="database-protocol-level"><span>LVL {protocolLevel}</span><input type="range" min="1" max="50" step="1" bind:value={protocolLevel} aria-label={`${item.name} level`}/></label>{#if item.protocolPreview.talentDescription}<div class="database-protocol-diamonds" role="group" aria-label={`${item.name} talent upgrades`}>{#each [1, 2, 3, 4, 5] as upgrade}<button type="button" class:active={talentUpgrades >= upgrade} aria-label={`Set talent upgrades to ${upgrade}`} aria-pressed={talentUpgrades === upgrade} onclick={() => talentUpgrades = talentUpgrades === upgrade ? 0 : upgrade}>◆</button>{/each}</div>{/if}</div>
@@ -86,15 +104,29 @@
{/each}
</div>
{/if}
{#if item.variant === 'talent'}
{#if hasMechanicGroups() && !hasSpecializationMechanics()}
<div class="database-mechanic-groups">
{#each mechanicGroups() as group (group.id)}
<DatabaseMechanicGroupCard {group} {detail}/>
{/each}
</div>
{/if}
{#if item.variant === 'talent' && !hasMechanicGroups()}
<div class="database-talent-tiers">
<section><span>TIER I</span><p>{item.description ?? 'Description is not available.'}</p></section>
<section><span>TIER II</span><p>{item.secondaryDescription ?? 'Description is not available.'}</p></section>
{#if item.secondaryDescription}<section><span>TIER II</span><p>{item.secondaryDescription}</p></section>{/if}
</div>
{:else if !item.protocolPreview}
{:else if !item.protocolPreview && (!hasMechanicGroups() || hasSpecializationMechanics())}
{#if item.description}<p class:data-description={item.descriptionStyle === 'data'}>{item.description}</p>{/if}
{#if item.secondaryDescription}<p class="secondary-description" class:data-description={item.descriptionStyle === 'data'}>{item.secondaryDescription}</p>{/if}
{/if}
{#if hasSpecializationMechanics()}
<div class="database-mechanic-groups database-specialization-effect-groups">
{#each mechanicGroups().filter(isSpecializationMechanic) as group (group.id)}
<DatabaseMechanicGroupCard {group} {detail} showIdentity/>
{/each}
</div>
{/if}
{#if item.afterLines?.length}
<div class="database-item-lines after-description">{#each item.afterLines as line}<div><span>{line.label}</span><b>{line.value}</b></div>{/each}</div>
{/if}
+4 -3
View File
@@ -18,6 +18,7 @@
let closeButton = $state<HTMLButtonElement | null>(null);
let dialog = $state<HTMLDivElement | null>(null);
const openPreview = async (item: DatabaseRelatedItem, button: HTMLButtonElement) => {
if (!item.preview) return;
selected = item;
trigger = button;
await tick();
@@ -32,8 +33,8 @@
};
const trapDialogFocus = (event: KeyboardEvent) => {
if (event.key !== 'Tab' || !dialog) return;
const focusable = [...dialog.querySelectorAll<HTMLElement>('a[href],button:not(:disabled),[tabindex]:not([tabindex="-1"])')]
.filter((element) => !element.hasAttribute('hidden'));
const focusable = [...dialog.querySelectorAll<HTMLElement>('a[href],button:not(:disabled),input:not([type="hidden"]):not(:disabled),select:not(:disabled),textarea:not(:disabled),[tabindex]:not([tabindex="-1"])')]
.filter((element) => !element.hasAttribute('hidden') && element.getClientRects().length > 0);
const first = focusable[0];
const last = focusable.at(-1);
if (!first || !last) return;
@@ -65,7 +66,7 @@
<div class="database-preview-backdrop" role="presentation" onclick={(event) => { if (event.target === event.currentTarget) void closePreview(); }}>
<div class="database-preview-dialog" bind:this={dialog} role="dialog" aria-modal="true" aria-labelledby={`database-preview-${selected.id}`} tabindex="-1" onkeydown={trapDialogFocus}>
<header><div><small>DATABASE QUICK VIEW</small><strong id={`database-preview-${selected.id}`}>{selected.preview.name}</strong></div><button type="button" bind:this={closeButton} aria-label="Close details" onclick={() => void closePreview()}>×</button></header>
<DatabaseItemCard item={selected.preview}/>
<DatabaseItemCard item={selected.preview} anchor={false} detail/>
</div>
</div>
{/if}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+292 -156
View File
@@ -1,5 +1,16 @@
<script lang="ts">
type Entry = { name: string; kind: 'text' | 'file'; value?: string; fileName?: string; type?: string };
import {
formatMechanicToken,
formatMechanicValue,
normalizePhase2OwnerPreview,
parseProposalPreviewPayload,
safePreviewValue,
isPreviewFieldHidden,
type AuthoredSourcePreview,
type AttachmentPreview,
type MechanicPreviewState,
type ProposalPreviewEntry
} from './ProposalChangePreview.helpers';
let {
module,
@@ -13,8 +24,10 @@
currentSnapshot?: Record<string, unknown> | null;
} = $props();
const entries = $derived(JSON.parse(payload) as Entry[]);
const proposed = $derived(Object.fromEntries(entries.filter((entry) => entry.kind === 'text').map((entry) => [entry.name, entry.value ?? ''])));
const parsedPayload = $derived(parseProposalPreviewPayload(payload));
const entries = $derived(parsedPayload.entries as ProposalPreviewEntry[]);
const proposed = $derived(parsedPayload.fields);
const phase2OwnerPreview = $derived(normalizePhase2OwnerPreview(module, action, payload, currentSnapshot));
const label = (value: string) => value.replace(/([A-Z])/g, ' $1').replaceAll('_', ' ').trim().toUpperCase();
const shown = (value: unknown) => value === null || value === undefined || value === '' ? 'NOT SET' : String(value);
const jsonValue = (value: unknown) => {
@@ -43,16 +56,8 @@
: 'TREE NODE'
);
const specializationRecord = $derived((currentSnapshot?.record ?? null) as Record<string, unknown> | null);
const skillChipRecord = $derived((currentSnapshot?.record ?? null) as Record<string, unknown> | null);
const currentSharedSkillChipProfiles = $derived((Array.isArray(currentSnapshot) ? currentSnapshot : []) as any[]);
const proposedSharedSkillChipProfiles = $derived((jsonValue(proposed.profiles) ?? []) as any[]);
const skillChipFields = $derived([
{ label: 'NAME', current: skillChipRecord?.name, proposed: proposed.name },
{ label: 'SPECIALIZATION ABILITY', current: skillChipRecord?.specialization_ability_id, proposed: proposed.abilityId },
{ label: '2-PIECE ATTRIBUTE', current: (currentSnapshot?.twoPiece as any)?.stat_attribute_id, proposed: proposed.twoPieceStatId },
{ label: '2-PIECE RANGE', current: `${(currentSnapshot?.twoPiece as any)?.min_value ?? '—'} – ${(currentSnapshot?.twoPiece as any)?.max_value ?? '—'}`, proposed: `${proposed.twoPieceMin || '—'} – ${proposed.twoPieceMax || '—'}` },
{ label: '3-PIECE TALENT', current: (currentSnapshot?.talent as any)?.name, proposed: proposed.talentName }
]);
const specializationFields = $derived(
action === 'saveProgression'
? [
@@ -116,23 +121,80 @@
const proposedCalculationStages = $derived((jsonValue(proposed.stagesJson) ?? []) as any[]);
const proposedCalculationProfiles = $derived((jsonValue(proposed.profilesJson) ?? []) as any[]);
const proposedSkillCalculationProfiles = $derived((jsonValue(proposed.skillProfilesJson) ?? []) as any[]);
const phase2Record = $derived((currentSnapshot?.record ?? null) as Record<string, unknown> | null);
const phase2TargetDisplay = (side: 'current' | 'proposed') =>
side === 'current'
? phase2OwnerPreview?.canonicalTargetId
: phase2OwnerPreview?.canonicalTargetId ?? 'ASSIGNED ON APPROVAL';
const phase2HasCurrentTarget = $derived(Boolean(phase2OwnerPreview?.canonicalTargetId));
const ownerIdentityFields = (side: 'current' | 'proposed', family: NonNullable<typeof phase2OwnerPreview>['family']) => {
const value = (key: string) => side === 'current' ? phase2Record?.[key] : proposed[key];
if (family === 'talent') return [
{ label: 'NAME', value: value('name') },
{ label: 'CATEGORY', value: value('category') },
{ label: 'OWNER TYPE', value: side === 'current' ? (currentSnapshot?.authoredSource as any)?.owner?.type : 'talent' },
{ label: 'OWNER ID', value: phase2TargetDisplay(side) }
];
if (family === 'protocol-talent') return [
{ label: 'NAME', value: value('name') },
{ label: 'QUALITY', value: value('quality') },
{ label: 'ATTRIBUTE TYPE', value: side === 'current' ? phase2Record?.primary_attribute_type : proposed.attributeType },
{ label: 'PRIMARY ATTRIBUTE', value: side === 'current' ? (currentSnapshot?.primaryEffect as any)?.stat_attribute_id : proposed.primaryStatId },
{ label: 'TALENT', value: side === 'current' ? (currentSnapshot?.talent as any)?.name : proposed.hasTalent === '1' ? proposed.talentName : 'NOT ASSIGNED' }
];
if (family === 'skill-chip-talent') return [
{ label: 'NAME', value: value('name') },
{ label: 'SPECIALIZATION ABILITY', value: side === 'current' ? phase2Record?.specialization_ability_id : proposed.abilityId },
{ label: '2-PIECE ATTRIBUTE', value: side === 'current' ? (currentSnapshot?.twoPiece as any)?.stat_attribute_id : proposed.twoPieceStatId },
{ label: '2-PIECE RANGE', value: side === 'current' ? `${(currentSnapshot?.twoPiece as any)?.min_value ?? '—'} – ${(currentSnapshot?.twoPiece as any)?.max_value ?? '—'}` : `${proposed.twoPieceMin || '—'} – ${proposed.twoPieceMax || '—'}` },
{ label: '3-PIECE TALENT', value: side === 'current' ? (currentSnapshot?.talent as any)?.name : proposed.hasTalent === '1' ? proposed.talentName : 'NOT ASSIGNED' }
];
if (family === 'specialization-node') return [
{ label: 'NAME', value: value('name') },
{ label: 'FOCUS', value: side === 'current' ? phase2Record?.focus_id : proposed.focusId },
{ label: 'ROW', value: side === 'current' ? phase2Record?.row_number : proposed.rowNumber },
{ label: 'COLUMN', value: side === 'current' ? phase2Record?.column_number : proposed.columnNumber },
{ label: 'MAXIMUM RANK', value: side === 'current' ? phase2Record?.max_rank : proposed.maxRank },
{ label: 'RANK DEFINITIONS', value: side === 'current' ? (currentSnapshot?.ranks as any[])?.length ?? 0 : (jsonValue(proposed.ranksJson) as any[])?.length ?? 0 }
];
return [
{ label: 'NAME', value: value('name') },
{ label: 'SPECIALIZATION', value: side === 'current' ? phase2Record?.specialization_id : proposed.specializationId },
{ label: 'DESCRIPTION TEMPLATE', value: side === 'current' ? phase2Record?.description_template : proposed.descriptionTemplate },
{ label: 'ATTACHMENTS', value: side === 'current' ? (currentSnapshot?.attachments as any[])?.length ?? 0 : phase2OwnerPreview?.proposedAttachments.length ?? 0 }
];
};
const ownerRelationshipRows = (side: 'current' | 'proposed', family: NonNullable<typeof phase2OwnerPreview>['family']) => {
if (family === 'talent') {
if (side === 'proposed') return [`CATEGORY · ${shown(proposed.category)}`, `RECORD ID · ${shown(phase2TargetDisplay(side))}`];
const relationships = (currentSnapshot?.relationships ?? {}) as any;
return [
`WEAPON SCOPE · ${shown(relationships.weaponScope?.scope)}`,
`WEAPON SLOT · ${shown(relationships.weaponSlot?.slot)}`,
`OWNER WEAPON · ${shown(relationships.ownerWeapon?.id)}${relationships.ownerWeapon?.name ? ` · ${relationships.ownerWeapon.name}` : ''}`,
`GEAR TALENTS · ${(relationships.gearTalents ?? []).map((item: any) => item.gear_id).join(', ') || 'NONE'}`,
`WEAPON TALENT OPTIONS · ${(relationships.weaponTalentOptions ?? []).map((item: any) => `${item.weapon_id} · SLOT ${item.talent_slot}`).join(', ') || 'NONE'}`
];
}
if (family === 'protocol-talent') return side === 'current'
? [`PROTOCOL ID · ${shown(phase2TargetDisplay(side))}`, `TALENT ID · ${shown((currentSnapshot?.talent as any)?.id)}`]
: [`PROTOCOL ID · ${shown(phase2TargetDisplay(side))}`, `TALENT · ${proposed.hasTalent === '1' ? shown(proposed.talentName) : 'NOT ASSIGNED'}`];
if (family === 'skill-chip-talent') return side === 'current'
? [`SKILL CHIP SET ID · ${shown(phase2TargetDisplay(side))}`, `TALENT ID · ${shown((currentSnapshot?.talent as any)?.id)}`]
: [`SKILL CHIP SET ID · ${shown(phase2TargetDisplay(side))}`, `TALENT · ${proposed.hasTalent === '1' ? shown(proposed.talentName) : 'NOT ASSIGNED'}`];
if (family === 'specialization-node') return side === 'current'
? [`NODE ID · ${shown(phase2TargetDisplay(side))}`, `FOCUS ID · ${shown(phase2Record?.focus_id)}`]
: [`NODE ID · ${shown(phase2TargetDisplay(side))}`, `FOCUS ID · ${shown(proposed.focusId)}`];
return side === 'current'
? [`COMBAT EFFECT ID · ${shown(phase2TargetDisplay(side))}`, `ATTACHMENT IDS · ${(currentSnapshot?.attachments as any[] ?? []).map((item: any) => item.id).join(', ') || 'NONE'}`]
: [`COMBAT EFFECT ID · ${shown(phase2TargetDisplay(side))}`, `FAN-OUT ATTACHMENTS · ${phase2OwnerPreview?.proposedAttachments.length ?? 0}`];
};
const effectSummary = (effect: any) => {
const target = effect.statId || effect.stat_attribute_id || effect.abilityId || effect.ability_id || effect.label || 'CUSTOM EFFECT';
const value = effect.value === null || effect.value === undefined || effect.value === '' ? '' : `${effect.value}${effect.unit ? ` ${effect.unit}` : ''}`;
return `${target}${value ? ` · ${value}` : ''}`;
};
const conditionalRuleSummary = (effect: any) => {
const rule = effect.conditionalRule ?? {};
const clauses = Array.isArray(rule.clauses) ? rule.clauses : [];
const outcomes = clauses.reduce((total: number, clause: any) =>
total + (Array.isArray(clause.outcomes) ? clause.outcomes.length : 0), 0);
return `${effect.effectId} · ${readableToken(rule.simulationReadiness)} · ${clauses.length} BRANCH${clauses.length === 1 ? '' : 'ES'} · ${outcomes} OUTCOME${outcomes === 1 ? '' : 'S'}`;
};
const readableToken = (value: unknown) => shown(value).replaceAll('_', ' ').toUpperCase();
const storedJson = (value: unknown, fallback: unknown) => {
if (typeof value !== 'string') return value ?? fallback;
try { return JSON.parse(value); } catch { return fallback; }
};
const attackProfileLines = (attack: Record<string, unknown> | null) => {
if (!attack || ('enabled' in attack && !attack.enabled)) return [];
const delivery = String(attack.delivery ?? '').toLowerCase();
@@ -156,90 +218,100 @@
}
return lines;
};
const conditionalRuleLines = (source: unknown) => {
if (!source || typeof source !== 'object' || Array.isArray(source)) return [];
const wrapper = source as Record<string, any>;
const persisted = wrapper.rule && typeof wrapper.rule === 'object';
const rule = persisted ? wrapper.rule : wrapper;
const inputs = persisted
? storedJson(rule.scenario_inputs_json, [])
: rule.scenarioInputs;
const pools = persisted ? wrapper.statePools : rule.pools;
const clauses = persisted ? wrapper.clauses : rule.clauses;
const lines = [
`READINESS · ${readableToken(rule.simulationReadiness ?? rule.simulation_readiness)}`,
`MODEL · ${Array.isArray(inputs) ? inputs.length : 0} SCENARIO INPUTS · ${Array.isArray(pools) ? pools.length : 0} STATE POOLS · ${Array.isArray(clauses) ? clauses.length : 0} BRANCHES`
];
if (Array.isArray(inputs)) {
for (const input of inputs) {
lines.push(`INPUT · ${shown(input.label ?? input.key)} · ${readableToken(input.kind)} · ${readableToken(input.readiness ?? 'ready')}`);
}
}
if (Array.isArray(pools)) {
for (const pool of pools) {
const poolKey = pool.key ?? pool.state_key;
const scope = pool.scope ?? pool.state_scope;
const maximum = pool.max ?? pool.maximum_value;
const expiry = pool.expiresAfterSeconds ?? pool.duration_seconds;
lines.push(`STATE · ${shown(poolKey)} · ${readableToken(scope)} · MAX ${shown(maximum)}${expiry ? ` · EXPIRES ${expiry}s` : ''}`);
}
}
if (Array.isArray(clauses)) {
for (const [index, clause] of clauses.entries()) {
const event = clause.event ?? clause.event_kind;
const recipe = clause.recipeKey ?? clause.recipe_key;
const reducer = persisted
? storedJson(clause.reducer_json, { kind: 'none' })
: clause.reducer;
const mutations = persisted
? storedJson(clause.mutations_json, [])
: clause.mutations;
const branchOutcomes = persisted
? (wrapper.outcomes ?? []).filter((outcome: any) => outcome.clause_id === clause.id)
: clause.outcomes ?? [];
lines.push([
`BRANCH ${index + 1}`,
readableToken(event),
recipe ? `RECIPE ${readableToken(recipe)}` : '',
`REDUCER ${readableToken(reducer?.kind)}`,
clause.cooldownSeconds ?? clause.cooldown_seconds
? `${clause.cooldownSeconds ?? clause.cooldown_seconds}s COOLDOWN`
: '',
`${Array.isArray(mutations) ? mutations.length : 0} MUTATIONS`,
`${branchOutcomes.length} OUTCOMES`
].filter(Boolean).join(' · '));
for (const outcome of branchOutcomes) {
if (persisted) {
lines.push([
`↳ ${readableToken(outcome.variant_key)}`,
readableToken(outcome.application_kind),
readableToken(outcome.effect_scope),
outcome.stat_attribute_id || readableToken(outcome.resource_kind ?? outcome.value_basis),
`${shown(outcome.value)}${outcome.value_expression_json ? ' · EXPRESSION' : ''}`,
readableToken(outcome.application_phase)
].join(' · '));
continue;
}
const variants = outcome.variants && typeof outcome.variants === 'object'
? Object.entries(outcome.variants).map(([variant, configured]: [string, any]) =>
`${readableToken(variant)} ${shown(configured?.value)}${configured?.expression ? ' (EXPRESSION)' : ''}`
).join(' · ')
: 'NO VARIANTS';
lines.push([
`↳ ${shown(outcome.label ?? outcome.key)}`,
readableToken(outcome.kind),
readableToken(outcome.scope),
outcome.attributeId || readableToken(outcome.resource ?? outcome.basis),
variants,
readableToken(outcome.phase)
].join(' · '));
}
}
}
return lines;
};
</script>
{#snippet authoredSourceBlock(source: AuthoredSourcePreview | null)}
{#if source}
<section class="proposal-mechanic-section authored-source-preview">
<header><span>AUTHORED SOURCE · VERSION {shown(source.version)}</span><b>{source.variants.length} ORDERED VARIANTS</b></header>
<div class="proposal-source-template"><span>TEMPLATE</span><p>{source.template}</p></div>
{#if source.specialization}
<div class="proposal-source-identity">
<div><span>RANK DESCRIPTION</span><p>{shown(source.specialization.rankDescription)}</p></div>
<div><span>REUSABLE EFFECT ID</span><p>{shown(source.specialization.effectId)}</p></div>
<div><span>REUSABLE EFFECT TEMPLATE</span><p>{shown(source.specialization.effectTemplate)}</p></div>
</div>
{/if}
<div class="proposal-source-variants">
{#each source.variants as variant, variantIndex}
<article>
<header><span>VARIANT {variantIndex + 1} · {variant.key}</span><b>{variant.slots.length} SLOTS</b></header>
<p class="proposal-materialized-text">{variant.materialized || 'NOT MATERIALIZED'}</p>
{#each variant.slots as slot, slotIndex}
<small>SLOT {slotIndex + 1} · ORDER {slot.order} · {slot.key} = {shown(slot.value)}{slot.unit ? ` · UNIT ${slot.unit}` : ''}{slot.attributeId ? ` · ATTRIBUTE ${slot.attributeId}` : ''}</small>
{:else}<small>NO TEMPLATE SLOTS</small>{/each}
</article>
{:else}<p class="proposal-structured-empty">NO AUTHORED VARIANTS</p>{/each}
</div>
</section>
{/if}
{/snippet}
{#snippet mechanicStateBlock(state: MechanicPreviewState, heading: string)}
<section class="proposal-mechanic-section mechanic-state-preview">
<header><span>{heading}</span><b>{state.selectedRevision ? `REVISION ${shown(state.selectedRevision.revisionNumber)}` : state.modelDraft ? 'MODEL SUBMISSION' : 'NO MODEL SELECTED'}</b></header>
<div class="proposal-model-summary">
<div><span>SELECTION STATE</span><strong>{state.selectedRevision ? formatMechanicToken(state.selectedRevisionStatus) : state.modelDraft ? 'PENDING REVISION' : 'ABSENT'}</strong></div>
<div><span>READINESS</span><strong>{formatMechanicToken((state.selectedRevision ?? state.modelDraft)?.readiness)}</strong></div>
<div><span>SCENARIO INPUTS</span><strong>{(state.selectedRevision ?? state.modelDraft)?.scenarioInputs.length ?? 0}</strong></div>
<div><span>STATE POOLS</span><strong>{(state.selectedRevision ?? state.modelDraft)?.pools.length ?? 0}</strong></div>
<div><span>CLAUSES</span><strong>{(state.selectedRevision ?? state.modelDraft)?.clauses.length ?? 0}</strong></div>
</div>
{#if state.selectedRevision ?? state.modelDraft}
{@const model = (state.selectedRevision ?? state.modelDraft)!}
<div class="proposal-graph-summary">
<section><header><span>SCENARIO INPUTS</span><b>{model.scenarioInputs.length}</b></header>
{#each model.scenarioInputs as input}<p>INPUT · {input.label} · {formatMechanicToken(input.kind)} · {formatMechanicToken(input.readiness)}{input.min !== null || input.max !== null ? ` · RANGE ${shown(input.min)}–${shown(input.max)}` : ''}{input.defaultValue !== null ? ` · DEFAULT ${shown(input.defaultValue)}` : ''}</p>{:else}<p>NO SCENARIO INPUTS</p>{/each}
</section>
<section><header><span>STATE POOLS</span><b>{model.pools.length}</b></header>
{#each model.pools as pool}<p>POOL · {pool.key} · {pool.label} · KIND {formatMechanicToken(pool.stateKind)} · {formatMechanicToken(pool.scope)} · INITIAL {shown(pool.initial)} · RANGE {shown(pool.min)}–{shown(pool.max)}{pool.bestCaseValue !== null ? ` · BEST ${shown(pool.bestCaseValue)}` : ''}{pool.expiresAfterSeconds !== null ? ` · EXPIRES ${shown(pool.expiresAfterSeconds)}s` : ''}</p>{:else}<p>NO STATE POOLS</p>{/each}
</section>
<section><header><span>CLAUSE GRAPH</span><b>{model.clauses.length}</b></header>
{#each model.clauses as clause, clauseIndex}
<article class="proposal-clause">
<p><b>CLAUSE {clauseIndex + 1} · {clause.label}</b> · EVENT {formatMechanicToken(clause.event)}{clause.recipeKey ? ` · RECIPE ${formatMechanicToken(clause.recipeKey)}` : ''} · REDUCER {formatMechanicToken((clause.reducer as any)?.kind)}{clause.cooldownSeconds !== null ? ` · COOLDOWN ${shown(clause.cooldownSeconds)}s` : ''}</p>
<small>CONDITION · {formatMechanicValue(clause.condition)} · MUTATIONS {clause.mutations.length}</small>
{#each clause.mutations as mutation, mutationIndex}<small>MUTATION {mutationIndex + 1} · {formatMechanicValue(mutation)}</small>{/each}
{#each clause.outcomes as outcome, outcomeIndex}
<div class="proposal-outcome"><small>OUTCOME {outcomeIndex + 1} · {outcome.label} · {formatMechanicToken(outcome.kind)} · {formatMechanicToken(outcome.scope)} · {formatMechanicToken(outcome.phase)} · BASIS {formatMechanicToken(outcome.basis)}{outcome.attributeId ? ` · ATTRIBUTE ${outcome.attributeId}` : ''}{outcome.statePool ? ` · POOL ${outcome.statePool}` : ''}{outcome.resource ? ` · RESOURCE ${formatMechanicToken(outcome.resource)}` : ''}{outcome.perStack !== null ? ` · PER STACK ${outcome.perStack ? 'YES' : 'NO'}` : ''}</small>{#each outcome.variants as variant}<small>VARIANT {variant.key} · VALUE {formatMechanicValue(variant.value)}{variant.expression !== null ? ` · EXPRESSION ${formatMechanicValue(variant.expression)}` : ''}</small>{/each}</div>
{/each}
</article>
{:else}<p>NO CLAUSES</p>{/each}
</section>
</div>
{:else}<p class="proposal-structured-empty">NO IMMUTABLE MODEL REVISION IS SELECTED.</p>{/if}
</section>
{/snippet}
{#snippet projectionBlock(state: MechanicPreviewState)}
<section class="proposal-mechanic-section proposal-projection-preview">
<header><span>PUBLIC PROJECTION</span><b>{formatMechanicToken(state.projection.status)}</b></header>
{#if state.projection.variants.length}
<p class="proposal-projection-meta">PROJECTION SOURCE · {state.selectedRevision ? `REVISION ${shown(state.selectedRevision.revisionNumber)}` : 'AUTHORED FALLBACK'}</p>
{#each state.projection.variants as variant}<p class="proposal-projection-variant"><b>{variant.key}</b><span>STATUS {formatMechanicToken(variant.status)} · DISPLAY SOURCE {formatMechanicToken(variant.displaySource)}</span><strong>{variant.text || 'NO PUBLIC TEXT'}</strong></p>{/each}
{:else}<p class="proposal-structured-empty">NO PUBLIC PROJECTION AVAILABLE.</p>{/if}
</section>
{/snippet}
{#snippet mechanicBlocks(state: MechanicPreviewState, heading: string)}
{@render authoredSourceBlock(state.authoredSource)}
{@render mechanicStateBlock(state, heading)}
{@render projectionBlock(state)}
{/snippet}
{#snippet attachmentBlock(attachments: AttachmentPreview[], heading: string)}
<section class="proposal-mechanic-section attachment-preview">
<header><span>{heading}</span><b>{attachments.length} ATTACHMENTS</b></header>
{#each attachments as attachment, attachmentIndex}
<article>
<header><span>ATTACHMENT {attachmentIndex + 1} · {attachment.attachmentId}</span><b>RANK {shown(attachment.rank)} · ORDER {shown(attachment.effectOrder)}</b></header>
<p>NODE ID · {shown(attachment.nodeId)} · COMBAT EFFECT ID · {shown(attachment.effectId)}</p>
{@render mechanicBlocks(attachment.mechanic, 'ATTACHMENT MECHANIC')}
</article>
{:else}<p class="proposal-structured-empty">NO ATTACHMENTS</p>{/each}
</section>
{/snippet}
<section class="proposal-change-preview" aria-label="Proposed data comparison">
<div class="proposal-preview-head">
<div><span>CHANGE PREVIEW</span><small>LIVE REGISTRY COMPARED WITH CONTRIBUTOR SUBMISSION</small></div>
@@ -281,6 +353,42 @@
</div>
</article>
</div>
{:else if phase2OwnerPreview}
<div class="proposal-compare-grid phase2-owner-preview">
<article class="proposal-editor-preview before">
<header><span>CURRENT LIVE · {phase2OwnerPreview.family.toUpperCase()}</span><b>{phase2HasCurrentTarget ? 'BEFORE' : 'NO LIVE RECORD'}</b></header>
{#if phase2HasCurrentTarget}
<div class="proposal-field-summary owner-identity-fields">{#each ownerIdentityFields('current', phase2OwnerPreview.family) as field}<div><span>{field.label}</span><strong>{shown(field.value)}</strong></div>{/each}</div>
<div class="proposal-relationships"><header><span>RELATIONSHIPS</span><b>LIVE</b></header>{#each ownerRelationshipRows('current', phase2OwnerPreview.family) as line}<p>{line}</p>{/each}</div>
{#if ['talent','protocol-talent','skill-chip-talent'].includes(phase2OwnerPreview.family)}
{@render mechanicBlocks(phase2OwnerPreview.currentMechanic, 'MECHANIC MODEL')}
{:else}
{#if phase2OwnerPreview.family === 'specialization-node'}
<div class="proposal-rank-preview">
{#each currentNodeRanks as rank}<section><header><span>RANK {rank.rank}</span><b>{currentNodeEffects.filter((effect) => Number(effect.rank) === Number(rank.rank)).length} STATIC EFFECTS</b></header><p>{shown(rank.description)}</p>{#each currentNodeEffects.filter((effect) => Number(effect.rank) === Number(rank.rank)) as effect}<small>{effectSummary(effect)}</small>{/each}<small>{currentNodeCosts.filter((cost) => Number(cost.rank) === Number(rank.rank)).map((cost) => `${cost.resource_id} × ${cost.quantity}`).join(' · ') || 'CREDITS ONLY'}</small></section>{:else}<p class="proposal-structured-empty">NO RANK DEFINITIONS</p>{/each}
</div>
{/if}
{@render attachmentBlock(phase2OwnerPreview.currentAttachments, phase2OwnerPreview.family === 'combat-effect' ? 'REUSABLE EFFECT FAN-OUT' : 'NODE ATTACHMENTS')}
{/if}
{:else}<div class="proposal-empty-state"><b>NO LIVE {phase2OwnerPreview.family.toUpperCase()} RECORD</b><span>The proposed owner state will be created on approval.</span></div>{/if}
</article>
<article class="proposal-editor-preview after">
<header><span>PROPOSED · {phase2OwnerPreview.family.toUpperCase()}</span><b>AFTER</b></header>
<div class="proposal-field-summary owner-identity-fields">{#each ownerIdentityFields('proposed', phase2OwnerPreview.family) as field}<div><span>{field.label}</span><strong>{shown(field.value)}</strong></div>{/each}</div>
<div class="proposal-relationships"><header><span>RELATIONSHIPS</span><b>PROPOSED</b></header>{#each ownerRelationshipRows('proposed', phase2OwnerPreview.family) as line}<p>{line}</p>{/each}</div>
{#if phase2OwnerPreview.selectionIntent}<p class="proposal-selection-intent">MODEL REQUEST · {formatMechanicToken(phase2OwnerPreview.selectionIntent)}</p>{/if}
{#if ['talent','protocol-talent','skill-chip-talent'].includes(phase2OwnerPreview.family)}
{@render mechanicBlocks(phase2OwnerPreview.proposedMechanic, 'MECHANIC MODEL AFTER APPROVAL')}
{:else}
{#if phase2OwnerPreview.family === 'specialization-node'}
<div class="proposal-rank-preview">
{#each proposedRanks as rank}<section><header><span>RANK {rank.rank}</span><b>{rank.effects?.length ?? 0} STATIC EFFECTS</b></header><p>{shown(rank.description)}</p>{#each rank.effects ?? [] as effect}<small>{effectSummary(effect)}</small>{/each}<small>{Object.entries(rank.costs ?? {}).filter(([, quantity]) => Number(quantity) > 0).map(([resource, quantity]) => `${resource} × ${quantity}`).join(' · ') || 'CREDITS ONLY'}</small></section>{:else}<p class="proposal-structured-empty">NO RANK DEFINITIONS</p>{/each}
</div>
{/if}
{@render attachmentBlock(phase2OwnerPreview.proposedAttachments, phase2OwnerPreview.family === 'combat-effect' ? 'REUSABLE EFFECT FAN-OUT AFTER APPROVAL' : 'NODE ATTACHMENTS AFTER APPROVAL')}
{/if}
</article>
</div>
{:else if module === 'skillchips' && ['savePrimaryProfile','saveSecondaryPool'].includes(action)}
<div class="proposal-compare-grid">
<article class="proposal-editor-preview before">
@@ -292,35 +400,6 @@
<div class="proposal-structured-list">{#each proposedSharedSkillChipProfiles as profile}<p>{profile.statId} · {Object.entries(profile.values ?? {}).map(([quality, range]: [string, any]) => `${quality.toUpperCase()} ${shown(range.min)}–${shown(range.max)}`).join(' · ')}</p>{/each}</div>
</article>
</div>
{:else if module === 'skillchips' && action === 'save'}
<div class="proposal-compare-grid">
<article class="proposal-editor-preview before">
<header><span>CURRENT LIVE · SKILL CHIP</span><b>{skillChipRecord ? 'BEFORE' : 'NO LIVE RECORD'}</b></header>
{#if skillChipRecord}
<div class="proposal-field-summary">
{#each skillChipFields as field}<div><span>{field.label}</span><strong>{shown(field.current)}</strong></div>{/each}
<div><span>3-PIECE TALENT</span><strong>{currentSnapshot?.talent ? 'ASSIGNED' : 'NOT ASSIGNED'}</strong></div>
</div>
<div class="proposal-structured-list">
<header><span>3-PIECE CONDITIONAL MECHANIC</span><b>TYPED RULE</b></header>
{#each conditionalRuleLines(currentSnapshot?.conditional) as line}<p>{line}</p>{:else}<p>NO TYPED RULE CONFIGURED</p>{/each}
</div>
{:else}
<div class="proposal-empty-state"><b>NEW SKILL CHIP</b><span>No live registry record will be replaced.</span></div>
{/if}
</article>
<article class="proposal-editor-preview after">
<header><span>PROPOSED · SKILL CHIP</span><b>AFTER</b></header>
<div class="proposal-field-summary">
{#each skillChipFields as field}<div><span>{field.label}</span><strong>{shown(field.proposed)}</strong></div>{/each}
<div><span>3-PIECE TALENT</span><strong>{proposed.hasTalent === '1' ? 'ASSIGNED' : 'NOT ASSIGNED'}</strong></div>
</div>
<div class="proposal-structured-list">
<header><span>3-PIECE CONDITIONAL MECHANIC</span><b>TYPED RULE</b></header>
{#each conditionalRuleLines(jsonValue(proposed.conditionalRule)) as line}<p>{line}</p>{:else}<p>NO TYPED RULE CONFIGURED</p>{/each}
</div>
</article>
</div>
{:else if module === 'calculations'}
<div class="proposal-compare-grid calculation-proposal-preview">
<article class="proposal-editor-preview before">
@@ -333,7 +412,7 @@
{#if action === 'saveRevision'}<div class="proposal-rank-preview">{#each proposedCalculationStages as stage}<section><header><span>{stage.label}</span><b>{stage.operator?.replaceAll('_',' ').toUpperCase()}</b></header><p>ORDER {stage.displayOrder} · {stage.lockedPosition?.toUpperCase() ?? 'REORDERABLE'}</p></section>{/each}</div>{/if}
</article>
</div>
{:else if module === 'specializations' && ['saveProgression','saveSpecialization','saveFocus','saveAbility','saveCombatEffect','saveFocusAbilities','saveNode'].includes(action)}
{:else if module === 'specializations' && ['saveProgression','saveSpecialization','saveFocus','saveAbility','saveFocusAbilities'].includes(action)}
<div class="proposal-compare-grid specialization-proposal-preview">
<article class="proposal-editor-preview before">
<header><span>CURRENT LIVE · {specializationKind}</span><b>{specializationRecord ? 'BEFORE' : 'NO LIVE RECORD'}</b></header>
@@ -352,12 +431,6 @@
<header><span>INTRINSIC ATTACK PROFILE</span><b>{currentAbilityAttack ? 'CONFIGURED' : 'NONE'}</b></header>
{#each attackProfileLines(currentAbilityAttack) as line}<p>{line}</p>{:else}<p>NO INTRINSIC ATTACK PROFILE</p>{/each}
</div>
{:else if action === 'saveNode'}
<div class="proposal-rank-preview">
{#each currentNodeRanks as rank}
<section><header><span>RANK {rank.rank}</span><b>{currentNodeEffects.filter((effect) => Number(effect.rank) === Number(rank.rank)).length} EFFECTS</b></header><p>{rank.description}</p><small>{currentNodeCosts.filter((cost) => Number(cost.rank) === Number(rank.rank)).map((cost) => `${cost.resource_id} × ${cost.quantity}`).join(' · ') || 'CREDITS ONLY'}</small></section>
{/each}
</div>
{:else if action === 'saveProgression'}
<div class="proposal-rank-preview">
{#each currentRankProfiles as profile}
@@ -385,18 +458,6 @@
<header><span>INTRINSIC ATTACK PROFILE</span><b>{attackProfileLines(proposedAbilityAttack).length ? 'CONFIGURED' : 'NONE'}</b></header>
{#each attackProfileLines(proposedAbilityAttack) as line}<p>{line}</p>{:else}<p>NO INTRINSIC ATTACK PROFILE</p>{/each}
</div>
{:else if action === 'saveNode'}
<div class="proposal-rank-preview">
{#each proposedRanks as rank}
<section>
<header><span>RANK {rank.rank}</span><b>{rank.effects?.length ?? 0} STATIC · {rank.combatEffects?.length ?? 0} CONDITIONAL</b></header>
<p>{rank.description || 'NO RANK DESCRIPTION'}</p>
{#each rank.effects ?? [] as effect}<small>{effectSummary(effect)}</small>{/each}
{#each rank.combatEffects ?? [] as effect}<small>{conditionalRuleSummary(effect)}</small>{/each}
<small>{Object.entries(rank.costs ?? {}).filter(([, quantity]) => Number(quantity) > 0).map(([resource, quantity]) => `${resource} × ${quantity}`).join(' · ') || 'CREDITS ONLY'}</small>
</section>
{/each}
</div>
{:else if action === 'saveProgression'}
<div class="proposal-rank-preview">
{#each [1,2,3] as rank}
@@ -411,19 +472,94 @@
<header><span>PROPOSED {label(module)} RECORD</span><b>AFTER</b></header>
<div class="proposal-field-summary">
{#each entries as entry}
{@const safeValue = entry.kind === 'text' ? safePreviewValue(entry.name, entry.value) : ''}
{#if !isPreviewFieldHidden(entry.name)}
<div>
<span>{label(entry.name)}</span>
{#if entry.kind === 'file'}
<strong>{entry.fileName || 'UPLOADED FILE'}</strong><small>{entry.type || 'FILE EVIDENCE'}</small>
{:else if jsonValue(entry.value)}
<strong>{Array.isArray(jsonValue(entry.value)) ? `${jsonValue(entry.value).length} CONFIGURED ITEMS` : 'CONFIGURED DATA'}</strong>
<small>{entry.value}</small>
{:else if jsonValue(safeValue)}
<strong>{Array.isArray(jsonValue(safeValue)) ? `${jsonValue(safeValue).length} CONFIGURED ITEMS` : 'CONFIGURED DATA'}</strong>
<small>{safeValue}</small>
{:else}
<strong>{shown(entry.value)}</strong>
<strong>{shown(safeValue)}</strong>
{/if}
</div>
{/if}
{/each}
</div>
</div>
{/if}
</section>
<style>
.phase2-owner-preview { align-items: start; }
.owner-identity-fields { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.proposal-relationships,
.proposal-mechanic-section { display: grid; gap: 5px; padding: 0 8px 8px; }
.proposal-relationships > header,
.proposal-mechanic-section > header,
.proposal-source-variants article > header,
.attachment-preview article > header { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 29px; padding: 6px 8px; border: 1px solid var(--shd-border); background: #111415; }
.proposal-relationships > header span,
.proposal-relationships > header b,
.proposal-mechanic-section > header span,
.proposal-mechanic-section > header b,
.proposal-source-variants article > header span,
.proposal-source-variants article > header b,
.attachment-preview article > header span,
.attachment-preview article > header b { font-size: var(--shd-type-telemetry); letter-spacing: .65px; }
.proposal-relationships > header b,
.proposal-mechanic-section > header b,
.proposal-source-variants article > header b,
.attachment-preview article > header b { color: var(--shd-orange); }
.proposal-relationships p,
.proposal-selection-intent,
.proposal-mechanic-section > p,
.proposal-mechanic-section > article > p,
.proposal-source-variants article > small,
.attachment-preview article > p { margin: 0; padding: 6px 8px; border: 1px solid var(--shd-border); color: var(--shd-text-muted); font-size: var(--shd-type-telemetry); overflow-wrap: anywhere; }
.proposal-source-template { display: grid; gap: 4px; padding: 8px; border: 1px solid var(--shd-border); background: #0d0f10; }
.proposal-source-identity { display: grid; gap: 5px; grid-template-columns: repeat(3, minmax(0, 1fr)); }
.proposal-source-identity > div { display: grid; gap: 4px; min-width: 0; padding: 7px 8px; border: 1px solid var(--shd-border); background: #0d0f10; }
.proposal-source-identity span { color: var(--shd-text-muted); font-size: var(--shd-type-telemetry); letter-spacing: .7px; }
.proposal-source-identity p { margin: 0; color: var(--shd-text); font-size: var(--shd-type-supporting); line-height: 1.4; overflow-wrap: anywhere; white-space: pre-wrap; }
.proposal-source-template span,
.proposal-model-summary span,
.proposal-projection-meta,
.proposal-projection-variant span { color: var(--shd-text-muted); font-size: var(--shd-type-telemetry); letter-spacing: .7px; }
.proposal-source-template p,
.proposal-materialized-text { margin: 0; color: var(--shd-text); font-size: var(--shd-type-body); line-height: 1.4; overflow-wrap: anywhere; white-space: pre-wrap; }
.proposal-source-variants,
.proposal-graph-summary { display: grid; gap: 5px; }
.proposal-source-variants article { display: grid; gap: 4px; padding: 5px; border: 1px solid var(--shd-border); background: #0d1011; }
.proposal-source-variants article > small { background: #111415; }
.proposal-model-summary { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 5px; }
.proposal-model-summary > div { display: grid; gap: 4px; min-width: 0; padding: 7px; border: 1px solid var(--shd-border); background: #0d0f10; }
.proposal-model-summary strong { color: var(--shd-text); font-size: var(--shd-type-telemetry); overflow-wrap: anywhere; }
.proposal-graph-summary > section { display: grid; gap: 4px; }
.proposal-graph-summary > section > header { display: flex; justify-content: space-between; gap: 8px; padding: 6px 8px; border: 1px solid var(--shd-border); background: #111415; }
.proposal-graph-summary > section > header span,
.proposal-graph-summary > section > header b { font-size: var(--shd-type-telemetry); letter-spacing: .65px; }
.proposal-graph-summary > section > header b { color: var(--shd-orange); }
.proposal-graph-summary > section > p { margin: 0; padding: 6px 8px; border: 1px solid var(--shd-border); color: var(--shd-text-muted); font-size: var(--shd-type-telemetry); overflow-wrap: anywhere; }
.proposal-clause { display: grid; gap: 3px; padding: 5px; border: 1px solid var(--shd-border); background: #0d1011; }
.proposal-clause > p,
.proposal-clause > small,
.proposal-outcome > small { margin: 0; padding: 5px 6px; border: 1px solid var(--shd-border); color: var(--shd-text-muted); font-size: var(--shd-type-telemetry); overflow-wrap: anywhere; }
.proposal-clause > p { color: var(--shd-text); }
.proposal-outcome { display: grid; gap: 3px; margin-left: 8px; }
.proposal-projection-preview { gap: 5px; }
.proposal-projection-meta { margin: 0; padding: 0 2px; }
.proposal-projection-variant { display: grid; grid-template-columns: 42px 1fr; gap: 5px; margin: 0; padding: 6px; border: 1px solid var(--shd-border); background: #0d0f10; }
.proposal-projection-variant > b { color: var(--shd-orange); font-size: var(--shd-type-telemetry); }
.proposal-projection-variant > strong { grid-column: 1 / -1; color: var(--shd-text); font-size: var(--shd-type-supporting); line-height: 1.4; overflow-wrap: anywhere; }
.attachment-preview { padding-top: 0; }
.attachment-preview > article { display: grid; gap: 5px; padding: 5px; border: 1px solid var(--shd-border); background: #0d1011; }
.attachment-preview > article .proposal-mechanic-section { padding-right: 0; padding-left: 0; }
.proposal-structured-empty { margin: 0; padding: 8px; border: 1px dashed var(--shd-border); color: var(--shd-text-muted); font-size: var(--shd-type-telemetry); text-align: center; }
@media (max-width: 800px) {
.owner-identity-fields, .proposal-model-summary, .proposal-source-identity { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.proposal-model-summary > div:last-child { grid-column: span 2; }
}
</style>
@@ -0,0 +1,60 @@
<script lang="ts">
import {
databaseMechanicGroupDisplaySourceLabel,
databaseMechanicGroupStatus,
databaseMechanicStatusLabel,
type DatabaseMechanicGroup
} from '$lib/database/items';
import DatabaseMechanicStatusBadge from './DatabaseMechanicStatusBadge.svelte';
let {
group,
detail = false,
showIdentity = false
}: {
group: DatabaseMechanicGroup;
detail?: boolean;
showIdentity?: boolean;
} = $props();
const status = $derived(databaseMechanicGroupStatus(group));
const displaySource = $derived(databaseMechanicGroupDisplaySourceLabel(group));
</script>
<section
class="database-mechanic-group"
class:detail
class:specialization-effect={showIdentity}
data-status={status}
aria-label={`${group.label}: ${databaseMechanicStatusLabel(status)}`}
>
{#if showIdentity}
<header class="database-mechanic-group-identity">
<div>
<small>{group.label}</small>
{#if group.context}<strong>{group.context}</strong>{/if}
</div>
<DatabaseMechanicStatusBadge {status}/>
</header>
{:else if group.context}
<p class="database-mechanic-group-context">{group.context}</p>
{/if}
<div class="database-mechanic-variants">
{#each group.variants as variant (variant.label)}
<section class="database-mechanic-variant" data-status={variant.status}>
<div class="database-mechanic-variant-label"><span>{variant.label}</span></div>
<div class="database-mechanic-behavior">
<small>{variant.status === 'modeled' ? 'MODELED BEHAVIOR' : 'AUTHORED DESCRIPTION'}</small>
<p aria-label={variant.behaviorText} title={detail ? undefined : variant.behaviorText}>{variant.behaviorText}</p>
</div>
</section>
{/each}
</div>
{#if detail}
<dl class="database-mechanic-display-source">
<div><dt>DISPLAY SOURCE</dt><dd>{displaySource}</dd></div>
</dl>
{/if}
</section>
@@ -0,0 +1,12 @@
<script lang="ts">
import {
databaseMechanicStatusLabel,
type DatabaseMechanicStatus
} from '$lib/database/items';
let { status }: { status: DatabaseMechanicStatus } = $props();
</script>
<strong class="database-mechanic-status" class:not-modeled={status === 'not_modeled'}>
{databaseMechanicStatusLabel(status)}
</strong>
@@ -0,0 +1,355 @@
<script lang="ts">
import type {
MechanicAuthoredSlot,
MechanicAuthoredVariant,
} from '$lib/calculations/mechanic-authored-description';
export type AuthoredVariantLabel = { key: string; label: string };
let {
template = $bindable(),
variants = $bindable(),
variantLabels,
idPrefix = 'authored-description',
disabled = false,
}: {
template: string;
variants: MechanicAuthoredVariant[];
variantLabels: AuthoredVariantLabel[];
idPrefix?: string;
disabled?: boolean;
} = $props();
const tokenPattern = /\{([^{}]+)\}/g;
const allowedNamedTokens = new Set(['duration', 'max_stacks']);
const tokens = $derived.by(() => {
const ordered: string[] = [];
for (const match of template.matchAll(tokenPattern)) {
if (!ordered.includes(match[1])) ordered.push(match[1]);
}
return ordered;
});
const invalidTokens = $derived(
tokens.filter(
(token) =>
!allowedNamedTokens.has(token) && !/^[1-9]\d*$/.test(token),
),
);
function materialized(
sourceTemplate: string,
slots: MechanicAuthoredSlot[],
) {
const values = new Map(slots.map((slot) => [slot.key, slot.value]));
return sourceTemplate.replace(tokenPattern, (placeholder, token: string) =>
values.get(token) || placeholder,
);
}
function reconcileVariants(
sourceTemplate: string,
sourceVariants: MechanicAuthoredVariant[],
) {
return variantLabels.map((requiredVariant) => {
const existing = sourceVariants.find(
(variant) => variant.key === requiredVariant.key,
);
const existingSlots = new Map(
(existing?.slots ?? []).map((slot) => [slot.key, slot]),
);
const slots = tokens.map((token, order) => ({
...(existingSlots.get(token) ?? { key: token, value: '', order }),
key: token,
order,
}));
return {
key: requiredVariant.key,
materialized: materialized(sourceTemplate, slots),
slots,
};
});
}
function updateTemplate(value: string) {
template = value;
variants = reconcileVariants(value, variants);
}
function updateSlot(variantKey: string, token: string, value: string) {
variants = variants.map((variant) => {
if (variant.key !== variantKey) return variant;
const slots = tokens.map((currentToken, order) => {
const existing = variant.slots.find(
(slot) => slot.key === currentToken,
);
return {
...(existing ?? { key: currentToken, value: '', order }),
key: currentToken,
value: currentToken === token ? value : (existing?.value ?? ''),
order,
};
});
return {
...variant,
slots,
materialized: materialized(template, slots),
};
});
}
function slotValue(variantKey: string, token: string) {
return (
variants
.find((variant) => variant.key === variantKey)
?.slots.find((slot) => slot.key === token)?.value ?? ''
);
}
function preview(variantKey: string) {
return (
variants.find((variant) => variant.key === variantKey)?.materialized ??
template
);
}
</script>
<section class="authored-editor" aria-labelledby={`${idPrefix}-title`}>
<header>
<div>
<p class="eyebrow">PUBLIC FALLBACK SOURCE</p>
<h4 id={`${idPrefix}-title`}>AUTHORED DESCRIPTION</h4>
<p>Define exact public prose independently from combat modeling.</p>
</div>
<span class="variant-count">
{variantLabels.length} {variantLabels.length === 1 ? 'VARIANT' : 'VARIANTS'}
</span>
</header>
<label class="field template-field">
SHARED DESCRIPTION TEMPLATE
<textarea
id={`${idPrefix}-template`}
value={template}
oninput={(event) => updateTemplate(event.currentTarget.value)}
placeholder={'After {1} hits, gain {2}% Weapon Damage for {duration} seconds.'}
{disabled}
required
></textarea>
<small>
Use numbered tokens such as <code>{'{1}'}</code>, plus
<code>{'{duration}'}</code> and <code>{'{max_stacks}'}</code>. Keep fixed
units and Attribute wording in the template. Enter only the numbers that
change by variant below; the combat model assigns Attribute semantics.
</small>
</label>
{#if invalidTokens.length}
<p class="token-error" role="alert">
Unsupported {invalidTokens.length === 1 ? 'token' : 'tokens'}:
{invalidTokens.map((token) => `{${token}}`).join(', ')}
</p>
{/if}
{#if tokens.length}
<div class="matrix-scroll">
<table>
<thead>
<tr>
<th scope="col">AUTHORED VALUE</th>
{#each variantLabels as variant}
<th scope="col">{variant.label}</th>
{/each}
</tr>
</thead>
<tbody>
{#each tokens as token}
<tr>
<th scope="row"><code>{`{${token}}`}</code></th>
{#each variantLabels as variant}
<td>
<label class="sr-only" for={`${idPrefix}-${variant.key}-${token}`}>
{variant.label} value for {`{${token}}`}
</label>
<input
id={`${idPrefix}-${variant.key}-${token}`}
type="number"
step="any"
inputmode="decimal"
value={slotValue(variant.key, token)}
oninput={(event) =>
updateSlot(variant.key, token, event.currentTarget.value)}
{disabled}
required
/>
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
{:else}
<p class="empty-tokens">
Add a supported token to the shared template to define variant values.
</p>
{/if}
<div class="previews">
{#each variantLabels as variant}
<article>
<span>{variant.label} EXACT PREVIEW</span>
<p>{preview(variant.key) || 'Description preview'}</p>
</article>
{/each}
</div>
</section>
<style>
.authored-editor {
border: 1px solid var(--border, #333b44);
background: color-mix(in srgb, var(--surface, #12171d) 94%, transparent);
}
header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
padding: 1rem 1.1rem;
border-bottom: 1px solid var(--border, #333b44);
}
header h4,
header p {
margin: 0;
}
header h4 {
margin-top: 0.2rem;
}
header > div > p:last-child {
margin-top: 0.35rem;
color: var(--muted, #97a3af);
}
.variant-count {
flex: 0 0 auto;
padding: 0.4rem 0.5rem;
border: 1px solid var(--border, #46515c);
color: var(--muted, #a4aeb8);
font-family: var(--font-mono, monospace);
font-size: 0.68rem;
font-weight: 700;
letter-spacing: 0.08em;
}
.template-field {
margin: 1rem 1.1rem 0;
}
.template-field code,
th code {
color: var(--info, #6cb9ed);
}
.matrix-scroll {
margin: 1rem 1.1rem;
overflow-x: auto;
}
table {
width: 100%;
min-width: 34rem;
border-collapse: collapse;
}
th,
td {
border: 1px solid var(--border, #333b44);
padding: 0.55rem;
text-align: left;
}
thead th {
background: var(--surface-dark, #0d1217);
color: var(--muted, #a4aeb8);
font-family: var(--font-mono, monospace);
font-size: 0.68rem;
letter-spacing: 0.08em;
}
tbody th {
width: 10rem;
background: color-mix(in srgb, var(--surface, #12171d) 80%, black);
}
td input {
width: 100%;
min-width: 8rem;
}
.previews {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
gap: 0.75rem;
padding: 0 1.1rem 1.1rem;
}
.previews article {
padding: 0.8rem 0.9rem;
border-left: 3px solid var(--info, #6cb9ed);
background: var(--surface-dark, #0d1217);
}
.previews span {
color: var(--info, #6cb9ed);
font-family: var(--font-mono, monospace);
font-size: 0.68rem;
font-weight: 700;
letter-spacing: 0.08em;
}
.previews p {
margin: 0.4rem 0 0;
white-space: pre-wrap;
}
.token-error,
.empty-tokens {
margin: 1rem 1.1rem;
padding: 0.7rem 0.8rem;
border: 1px solid var(--border, #46515c);
color: var(--muted, #a4aeb8);
font-family: var(--font-mono, monospace);
font-size: 0.75rem;
}
.token-error {
border-color: var(--danger, #b7524c);
color: var(--danger-light, #ff8b84);
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@media (max-width: 40rem) {
header {
align-items: stretch;
flex-direction: column;
}
.variant-count {
align-self: flex-start;
}
}
</style>
@@ -9,15 +9,18 @@
blankConditionalMechanicDraft,
currentHealthPercentBandPredicate,
eventFieldComparisonPredicate,
eventFieldNumericExpression,
mechanicTargetingForMode,
mechanicTargetingMode,
parseConditionalMechanicDraft,
readCurrentHealthPercentBand,
readEventFieldComparison,
readEventFieldNumericExpression,
registeredEventFields,
readStatePoolThreshold,
statePoolThresholdPredicate,
type ConditionalMechanicClauseDraft,
type ConditionalNumericExpression,
type ConditionalMechanicDraftV1,
type ConditionalMechanicOutcomeDraft,
type ConditionalMechanicPoolDraft,
@@ -31,6 +34,7 @@
formatMechanicProgram,
MECHANIC_EVENT_KINDS,
MECHANIC_EVENT_REGISTRY,
PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_FIELD,
type ClauseMutation,
type MechanicOutcomeScope,
type NumericExpression,
@@ -408,6 +412,40 @@
updateClause(index, { reducer });
}
function derivedScalarModel(clause: ConditionalMechanicClauseDraft) {
if (clause.reducer.kind !== 'derived_scalar') return 'static';
if (typeof clause.reducer.value === 'number') return 'static';
return readEventFieldNumericExpression(clause.reducer.value) ? 'event' : 'advanced';
}
function numericEventFields(clause: ConditionalMechanicClauseDraft) {
return registeredEventFields(clause.event).filter((field) => field.type === 'number');
}
function setDerivedScalarModel(clauseIndex: number, model: string) {
const clause = rule.clauses[clauseIndex];
if (clause.reducer.kind !== 'derived_scalar') return;
if (model === 'static') {
updateClause(clauseIndex, { reducer: { kind: 'derived_scalar', value: 1 } });
return;
}
const field = numericEventFields(clause)[0];
if (model === 'event' && field) {
updateClause(clauseIndex, {
reducer: {
kind: 'derived_scalar',
value: eventFieldNumericExpression(field.path)
}
});
}
}
function setDerivedScalarEventField(clauseIndex: number, path: string) {
updateClause(clauseIndex, {
reducer: { kind: 'derived_scalar', value: eventFieldNumericExpression(path) }
});
}
function updateOutcome(clauseIndex: number, outcomeIndex: number, patch: Partial<ConditionalMechanicOutcomeDraft>) {
const outcomes = [...rule.clauses[clauseIndex].outcomes];
outcomes[outcomeIndex] = { ...outcomes[outcomeIndex], ...patch };
@@ -517,6 +555,10 @@
const eventValueOptions = [
{ value: 'values.enemyCount', label: 'ENEMY COUNT' },
{ value: 'values.allyCount', label: 'ALLY COUNT' },
{
value: PROXIMITY_AGENT_GRANTED_BUFF_ALLY_COUNT_FIELD,
label: 'AGENT-BUFFED ALLIES ≤30M'
},
{ value: 'values.magazineRemaining', label: 'ROUNDS LEFT' },
{ value: 'values.magazinePercent', label: 'MAGAZINE %' },
{ value: 'values.distanceMeters', label: 'DISTANCE' }
@@ -534,10 +576,10 @@
};
}
function protocolUpgradeExpression(value: number): NumericExpression {
function protocolUpgradeExpression(): ConditionalNumericExpression {
return {
op: 'multiply',
left: value,
left: { ref: { source: 'variant_value' } },
right: {
op: 'add',
left: 1,
@@ -578,17 +620,17 @@
typeof expression === 'object'
&& 'op' in expression
&& expression.op === 'multiply'
&& typeof expression.left === 'number'
&& typeof expression.right === 'object'
) {
if ('ref' in expression.right) {
if (typeof expression.left === 'number' && 'ref' in expression.right) {
if (expression.right.ref.source === 'event') return 'event';
if (expression.right.ref.source === 'scenario') return 'scenario';
if (expression.right.ref.source === 'reducer') return 'reducer';
if (expression.right.ref.source === 'attribute') return 'attribute_value';
}
if (
'op' in expression.right
typeof expression.left === 'number'
&& 'op' in expression.right
&& expression.right.op === 'divide'
&& typeof expression.right.left === 'object'
&& 'ref' in expression.right.left
@@ -596,7 +638,13 @@
&& expression.right.right === 100
) return 'attribute';
if (
'op' in expression.right
(typeof expression.left === 'number'
|| (
typeof expression.left === 'object'
&& 'ref' in expression.left
&& expression.left.ref.source === 'variant_value'
))
&& 'op' in expression.right
&& expression.right.op === 'add'
&& typeof expression.right.right === 'object'
&& 'op' in expression.right.right
@@ -657,7 +705,7 @@
model: OutcomeValueModel,
value: number,
reference = ''
): NumericExpression | undefined {
): ConditionalNumericExpression | undefined {
if (model === 'event') return referenceExpression('event', reference || 'values.enemyCount', value);
if (model === 'attribute') return reference
? attributePercentExpression(value, reference)
@@ -671,7 +719,7 @@
if (model === 'reducer') {
return { op: 'multiply', left: value, right: { ref: { source: 'reducer' } } };
}
if (model === 'protocol_upgrades') return protocolUpgradeExpression(value);
if (model === 'protocol_upgrades') return protocolUpgradeExpression();
return undefined;
}
@@ -698,7 +746,7 @@
updateOutcome(clauseIndex, outcomeIndex, { variants });
}
function replaceExpressionBase(expression: NumericExpression, value: number): NumericExpression {
function replaceExpressionBase(expression: ConditionalNumericExpression, value: number): ConditionalNumericExpression {
const model = outcomeValueModel({
key: 'temporary',
label: 'Temporary',
@@ -743,7 +791,7 @@
if (model === 'reducer') {
return { op: 'multiply', left: value, right: { ref: { source: 'reducer' } } };
}
if (model === 'protocol_upgrades') return protocolUpgradeExpression(value);
if (model === 'protocol_upgrades') return protocolUpgradeExpression();
return expression;
}
@@ -802,7 +850,7 @@
updateClause(clauseIndex, { mutations });
}
function updateMutation(clauseIndex: number, mutationIndex: number, kind: 'add' | 'set' | 'consume' | 'clear', pool?: string, value?: number) {
function updateMutation(clauseIndex: number, mutationIndex: number, kind: 'add' | 'set' | 'consume' | 'derive' | 'clear', pool?: string, value?: number) {
const mutations = [...rule.clauses[clauseIndex].mutations];
const current = mutations[mutationIndex];
const nextPool = pool ?? ('pool' in current ? current.pool : rule.pools[0]?.key ?? '');
@@ -812,7 +860,9 @@
: undefined;
mutations[mutationIndex] = kind === 'clear'
? { kind, pool: nextPool, entity }
: { kind, pool: nextPool, value: value ?? ('value' in current && typeof current.value === 'number' ? current.value : 1), entity };
: kind === 'derive'
? { kind, pool: nextPool, value: { ref: { source: 'reducer' } }, entity }
: { kind, pool: nextPool, value: value ?? ('value' in current && typeof current.value === 'number' ? current.value : 1), entity };
updateClause(clauseIndex, { mutations });
}
@@ -1134,7 +1184,29 @@
{:else if clause.reducer.kind === 'periodic'}
<label class="field">INTERVAL · SECONDS<input type="number" min="0.01" step="any" value={typeof clause.reducer.intervalSeconds === 'number' ? clause.reducer.intervalSeconds : 1} oninput={(event) => setReducerNumber(clauseIndex,'intervalSeconds',event.currentTarget.value)}/></label>
{:else if clause.reducer.kind === 'derived_scalar'}
<label class="field">DERIVED VALUE<input type="number" step="any" value={typeof clause.reducer.value === 'number' ? clause.reducer.value : 1} oninput={(event) => setReducerNumber(clauseIndex,'value',event.currentTarget.value)}/></label>
<SegmentedChoice
legend="DERIVED VALUE SOURCE"
name={`${idPrefix}-derived-source-${clauseIndex}`}
options={[
{value:'static',label:'STATIC'},
{value:'event',label:'EVENT FIELD',disabled:numericEventFields(clause).length === 0},
...(derivedScalarModel(clause) === 'advanced' ? [{value:'advanced',label:'ADVANCED',disabled:true}] : [])
]}
value={derivedScalarModel(clause)}
onchange={(values) => setDerivedScalarModel(clauseIndex,values[0])}
/>
{#if derivedScalarModel(clause) === 'event'}
<SegmentedChoice
legend="NUMERIC EVENT FIELD"
name={`${idPrefix}-derived-event-${clauseIndex}`}
options={numericEventFields(clause).map((field) => ({value:field.path,label:field.label.toUpperCase()}))}
value={readEventFieldNumericExpression(clause.reducer.value) ?? ''}
columns={Math.min(3,numericEventFields(clause).length)}
onchange={(values) => setDerivedScalarEventField(clauseIndex,values[0])}
/>
{:else if derivedScalarModel(clause) === 'static'}
<label class="field">DERIVED VALUE<input type="number" step="any" value={typeof clause.reducer.value === 'number' ? clause.reducer.value : 1} oninput={(event) => setReducerNumber(clauseIndex,'value',event.currentTarget.value)}/></label>
{/if}
{/if}
</div>
@@ -1159,9 +1231,9 @@
<SegmentedChoice
legend="OPERATION"
name={`${idPrefix}-mutation-kind-${clauseIndex}-${mutationIndex}`}
options={[{value:'add',label:'ADD'},{value:'set',label:'SET'},{value:'consume',label:'CONSUME'},{value:'clear',label:'CLEAR'}]}
value={mutation.kind === 'none' || mutation.kind === 'derive' || mutation.kind === 'transfer' ? 'add' : mutation.kind}
onchange={(values) => updateMutation(clauseIndex,mutationIndex,values[0] as 'add'|'set'|'consume'|'clear')}
options={[{value:'add',label:'ADD'},{value:'set',label:'SET'},{value:'consume',label:'CONSUME'},{value:'derive',label:'DERIVED VALUE'},{value:'clear',label:'CLEAR'}]}
value={mutation.kind === 'none' || mutation.kind === 'transfer' ? 'add' : mutation.kind}
onchange={(values) => updateMutation(clauseIndex,mutationIndex,values[0] as 'add'|'set'|'consume'|'derive'|'clear')}
/>
<SegmentedChoice
legend="STATE POOL"
@@ -1169,10 +1241,12 @@
options={rule.pools.map((pool) => ({value:pool.key,label:pool.label.toUpperCase()}))}
value={'pool' in mutation ? mutation.pool : rule.pools[0]?.key ?? ''}
columns={Math.min(4,Math.max(1,rule.pools.length))}
onchange={(values) => updateMutation(clauseIndex,mutationIndex,mutation.kind === 'clear' ? 'clear' : mutation.kind === 'set' || mutation.kind === 'consume' ? mutation.kind : 'add',values[0])}
onchange={(values) => updateMutation(clauseIndex,mutationIndex,mutation.kind === 'clear' ? 'clear' : mutation.kind === 'derive' ? 'derive' : mutation.kind === 'set' || mutation.kind === 'consume' ? mutation.kind : 'add',values[0])}
/>
{#if mutation.kind !== 'clear'}
{#if mutation.kind !== 'clear' && mutation.kind !== 'derive'}
<label class="field">VALUE<input type="number" step="any" value={'value' in mutation && typeof mutation.value === 'number' ? mutation.value : 1} oninput={(event) => updateMutation(clauseIndex,mutationIndex,mutation.kind === 'set' || mutation.kind === 'consume' ? mutation.kind : 'add',undefined,Number(event.currentTarget.value))}/></label>
{:else if mutation.kind === 'derive'}
<div class="branch-readout"><span>VALUE</span><strong>DERIVED SCALAR</strong></div>
{/if}
{#if 'pool' in mutation && rule.pools.find((pool) => pool.key === mutation.pool)?.scope === 'target'}
<SegmentedChoice
+60
View File
@@ -0,0 +1,60 @@
import { describe, expect, it } from 'vitest';
import {
databaseMechanicGroupDisplaySourceLabel,
databaseMechanicGroupStatus,
databaseMechanicStatusLabel,
type DatabaseMechanicGroup,
} from './items';
const group = (
variants: DatabaseMechanicGroup['variants'],
): DatabaseMechanicGroup => ({
id: 'owner-1',
ownerType: 'talent',
label: 'Weapon Talent',
variants,
});
describe('database mechanic presentation', () => {
it('uses one modeled status and display source for a fully modeled owner', () => {
const value = group([
{
label: 'Tier I',
behaviorText: 'Gain 10% Weapon Damage.',
status: 'modeled',
displaySource: 'model',
},
{
label: 'Tier II',
behaviorText: 'Gain 20% Weapon Damage.',
status: 'modeled',
displaySource: 'model',
},
]);
expect(databaseMechanicGroupStatus(value)).toBe('modeled');
expect(databaseMechanicStatusLabel(databaseMechanicGroupStatus(value))).toBe('MODELED');
expect(databaseMechanicGroupDisplaySourceLabel(value)).toBe('MODELED BEHAVIOR');
});
it('falls back to the neutral public status when an owner is incomplete', () => {
const value = group([
{
label: 'Tier I',
behaviorText: 'Gain 10% Weapon Damage.',
status: 'modeled',
displaySource: 'model',
},
{
label: 'Tier II',
behaviorText: 'Gain 20% Weapon Damage.',
status: 'not_modeled',
displaySource: 'authored',
},
]);
expect(databaseMechanicGroupStatus(value)).toBe('not_modeled');
expect(databaseMechanicStatusLabel(databaseMechanicGroupStatus(value))).toBe('NOT MODELED');
expect(databaseMechanicGroupDisplaySourceLabel(value)).toBe('AUTHORED DESCRIPTION');
});
});
+48
View File
@@ -2,6 +2,53 @@ import type { GameIconName } from '$lib/game-icons';
import type { GameDataTargetType } from '$lib/game-data-targets';
export type DatabaseBadge = { label: string; tone?: string };
/** Public, serializable mechanic presentation for one source owner. */
export type DatabaseMechanicOwnerType =
| 'talent'
| 'os_protocol_talent'
| 'skill_chip_talent'
| 'specialization_tree_rank';
export type DatabaseMechanicStatus = 'modeled' | 'not_modeled';
export type DatabaseMechanicDisplaySource = 'model' | 'authored';
export type DatabaseMechanicVariant = {
label: string;
behaviorText: string;
status: DatabaseMechanicStatus;
displaySource: DatabaseMechanicDisplaySource;
};
export type DatabaseMechanicGroup = {
/** Stable owner identity for keyed rendering and deep-linkable detail. */
id: string;
ownerType: DatabaseMechanicOwnerType;
label: string;
context?: string;
variants: DatabaseMechanicVariant[];
};
export const databaseMechanicStatusLabel = (status: DatabaseMechanicStatus) =>
status === 'modeled' ? 'MODELED' : 'NOT MODELED';
/** A complete public owner projection has one status across its variants. */
export const databaseMechanicGroupStatus = (
group: DatabaseMechanicGroup,
): DatabaseMechanicStatus =>
group.variants.length > 0 &&
group.variants.every((variant) => variant.status === 'modeled')
? 'modeled'
: 'not_modeled';
export const databaseMechanicGroupDisplaySourceLabel = (
group: DatabaseMechanicGroup,
) =>
databaseMechanicGroupStatus(group) === 'modeled'
? 'MODELED BEHAVIOR'
: 'AUTHORED DESCRIPTION';
export const isDatabaseMechanicStatus = (
value: unknown,
): value is DatabaseMechanicStatus =>
value === 'modeled' || value === 'not_modeled';
export type DatabaseMeter = { label: string; value: number };
export type DatabaseWeaponModSlot = {
slot: string;
@@ -43,6 +90,7 @@ export type DatabaseItem = {
afterLines?: DatabaseFact[];
iconGroups?: DatabaseIconGroup[];
weaponModSlots?: DatabaseWeaponModSlot[];
mechanicGroups?: DatabaseMechanicGroup[];
description?: string;
secondaryDescription?: string;
descriptionStyle?: 'prose' | 'data';
@@ -94,7 +94,7 @@ describe('AI mechanic authoring prompt', () => {
}),
);
expect(AI_MECHANIC_PROMPT_VERSION).toBe(10);
expect(AI_MECHANIC_PROMPT_VERSION).toBe(11);
expect(input.canonicalCatalog.grammar.outcome.optional).toEqual(
expect.arrayContaining(['delivery', 'durationSeconds']),
);
@@ -136,7 +136,7 @@ describe('AI mechanic authoring prompt', () => {
]),
);
expect(AI_MECHANIC_AUTHORING_INSTRUCTIONS).toContain(
'Prompt contract version: 10',
'Prompt contract version: 11',
);
const advertised = structuredClone(
@@ -185,7 +185,7 @@ describe('AI mechanic authoring prompt', () => {
expect(parsed.ok).toBe(true);
});
it('advertises the canonical Extra Health change event contract in version 10', () => {
it('advertises the canonical Extra Health change event contract in version 11', () => {
const input = JSON.parse(
buildAiMechanicAuthoringInput({
request,
@@ -196,9 +196,9 @@ describe('AI mechanic authoring prompt', () => {
}),
);
expect(AI_MECHANIC_PROMPT_VERSION).toBe(10);
expect(AI_MECHANIC_PROMPT_VERSION).toBe(11);
expect(AI_MECHANIC_AUTHORING_INSTRUCTIONS).toContain(
'Prompt contract version: 10',
'Prompt contract version: 11',
);
expect(input.canonicalCatalog.events).toContainEqual({
key: 'extra_health_changed',
@@ -325,7 +325,7 @@ describe('AI mechanic authoring prompt', () => {
expect(parsed.ok).toBe(true);
});
it('advertises reproducible outcome and clause proc probabilities in version 10', () => {
it('advertises reproducible outcome and clause proc probabilities in version 11', () => {
const input = JSON.parse(
buildAiMechanicAuthoringInput({
request,
@@ -336,7 +336,7 @@ describe('AI mechanic authoring prompt', () => {
}),
);
expect(AI_MECHANIC_PROMPT_VERSION).toBe(10);
expect(AI_MECHANIC_PROMPT_VERSION).toBe(11);
expect(input.canonicalCatalog.grammar.clause.optional).toEqual(
expect.arrayContaining([
'procChancePercent',
@@ -489,4 +489,62 @@ describe('AI mechanic authoring prompt', () => {
});
expect(parsed.ok).toBe(true);
});
it('advertises draft variant-value scaling and the typed proximity input in version 11', () => {
const input = JSON.parse(
buildAiMechanicAuthoringInput({
request: {
...request,
context: {
...request.context,
sourceName: 'Close and Personal',
sourceDescription:
'Increase Weapon Damage by (1)% plus (2)% for each nearby ally with a buff granted by you.',
},
},
attributes: [],
events: [MECHANIC_EVENT_REGISTRY.proximity_snapshot],
actions: [],
recipeKeys: [],
}),
);
const grammar = input.canonicalCatalog.grammar;
const proximityEvent = input.canonicalCatalog.events[0];
expect(AI_MECHANIC_PROMPT_VERSION).toBe(11);
expect(AI_MECHANIC_AUTHORING_INSTRUCTIONS).toContain(
'Prompt contract version: 11',
);
expect(grammar.valueReferences).toContain('variant_value');
expect(grammar.draftOutcomeExpressionReferences).toEqual(['variant_value']);
expect(grammar.referenceShapes).toContainEqual({
ref: { source: 'variant_value' },
});
expect(proximityEvent.fields).toContainEqual({
path: 'values.alliesWithin30MetersWithAgentGrantedBuff',
label: 'Allies within 30 meters with an Agent-granted buff',
type: 'number',
minimum: 0,
integer: true,
});
expect(proximityEvent.strictFields).toBeUndefined();
expect(AI_MECHANIC_AUTHORING_INSTRUCTIONS).toEqual(
expect.stringContaining('unresolved numbered source placeholder'),
);
expect(AI_MECHANIC_AUTHORING_INSTRUCTIONS).toEqual(
expect.stringContaining('{ref:{source:"variant_value"}}'),
);
expect(input.examplesAndRules).toEqual(
expect.arrayContaining([
expect.stringContaining('only inside an outcome variant expression'),
expect.stringContaining('outcome variants[variantKey].value'),
expect.stringContaining(
'{ref:{source:"event",path:"values.alliesWithin30MetersWithAgentGrantedBuff"}}',
),
expect.stringContaining(
'{key:"allies-within-30m-with-agent-granted-buff"',
),
expect.stringContaining('readiness:"ready",min:0'),
]),
);
});
});
+11 -1
View File
@@ -3,7 +3,7 @@ import { CONDITIONAL_MECHANIC_OUTCOME_CAPABILITIES } from '$lib/calculations/mec
import { MECHANIC_COMBAT_REFERENCE_REGISTRY } from '$lib/calculations/mechanic';
import type { AiMechanicAttribute } from './mechanic-authoring-context';
export const AI_MECHANIC_PROMPT_VERSION = 10;
export const AI_MECHANIC_PROMPT_VERSION = 11;
const mechanicsGrammar = {
version: 1,
@@ -83,6 +83,7 @@ const mechanicsGrammar = {
'attribute',
'reducer',
'pool',
'variant_value',
],
combatReferences: MECHANIC_COMBAT_REFERENCE_REGISTRY,
numericExpressionOperators: [
@@ -95,7 +96,9 @@ const mechanicsGrammar = {
'clamp',
'floor',
],
draftOutcomeExpressionReferences: ['variant_value'],
referenceShapes: [
{ ref: { source: 'variant_value' } },
{ ref: { source: 'event', path: 'values.distanceMeters' } },
{ ref: { source: 'scenario', key: 'input-key' } },
{ ref: { source: 'combat', path: 'currentHealth', timing: 'current' } },
@@ -498,6 +501,7 @@ Security and scope:
- Use only the supplied event, action, recipe, attribute, scope, reference, expression, reducer, mutation, and outcome catalogs.
- Never invent an Attribute ID, event, field path, source variant, or runtime behavior.
- Ask focused questions when different answers would change the calculation. Do not guess material cadence, duration, target, stacking, reset, scope, damage basis, or value behavior.
- An unresolved numbered source placeholder is a material missing value. Ask the human for the exact numeric value for every affected source variant; never infer or guess it.
- If the behavior cannot be represented by the supplied grammar, return capability_gap with implementation-ready developer changes.
Response rules:
@@ -507,6 +511,7 @@ Response rules:
- All keys must be stable lower-case identifiers using letters, digits, dashes, or underscores and beginning with a letter.
- A draft must define exactly the supplied value variants for every outcome.
- The numeric variant value is the human-facing base value. Use expression only when runtime scaling or a live event/scenario/equipment value changes it.
- Put each clarified placeholder answer in the corresponding outcome variant value as its human-facing value. When that value participates in a runtime expression, reference it exactly as {ref:{source:"variant_value"}}; never duplicate the numeric literal in the expression. variant_value is draft-only and valid only inside an outcome variant expression.
- Use attribute_modifier only with an exact supplied Attribute ID.
- Use direct_damage, restoration, or resource_cost rather than a fabricated Attribute when that is the actual mechanic.
- Keep assumptions explicit. Use warnings for representable limitations that do not require code changes.
@@ -551,9 +556,14 @@ export function buildAiMechanicAuthoringInput(input: {
'A target-scoped pool owns an independent value and expiry timer for each entity. Bind hit-created target state with entity:{kind:"event_target"}; do not collapse different enemies into one Agent-scoped pool.',
'Writing a target-scoped pool refreshes only that target entity timer. An on_exit outcome runs when that entity expires and uses the entity previous state for stack bands and perStack multiplication, even though the stored pool value has already reset.',
'When an outcome value is exactly a live Attribute amount, use the Attribute reference directly as the variant expression. Divide by 100 only when a displayed percentage is being used as a multiplier.',
'variant_value is draft-only and may appear only inside an outcome variant expression, with the exact shape {ref:{source:"variant_value"}}. It resolves to that same variant object’s human-facing numeric value at runtime.',
'If source wording contains an unresolved numbered placeholder such as {1} or {2}, return clarification_required and ask for the exact numeric answer for every affected source variant. Never guess a placeholder value.',
'After clarification, put each answer in the corresponding outcome variants[variantKey].value. If a runtime-scaled expression uses that answer, reference {ref:{source:"variant_value"}} rather than duplicating the numeric literal.',
'A weapon_hit may compare values.aiming with true only when the wording requires aiming down sights at hit resolution. Missing aiming evidence does not match; do not replace it with a scenario assumption.',
'An explosion centered on the hit target uses target-scoped direct_damage with targeting kind event_target_area, center event_target, validTargets enemies, and the stated positive radiusMeters. The runtime applies one equal damage emission to each authoritative valid enemy at or inside the radius. Do not use legacy within_radius metadata for explosion damage.',
'Precise Trauma is representable as one target-scoped stack pool with a one-second expiry: body shots add one stack, headshots add two, and one on_exit direct-damage outcome uses the expiring target previous stack count. This models the stated one-second debuff without inventing generic repeated target ticks.',
'For proximity_snapshot, the optional values.alliesWithin30MetersWithAgentGrantedBuff field is a non-negative integer count of distinct allied Agents at or within 30 meters who possess at least one buff granted by the source Agent. Multiple qualifying buffs on one ally still count that ally once. Read it with {ref:{source:"event",path:"values.alliesWithin30MetersWithAgentGrantedBuff"}}.',
'When loadout timelines must supply values.alliesWithin30MetersWithAgentGrantedBuff, define the ready numeric scenario input exactly as {key:"allies-within-30m-with-agent-granted-buff",label:"Allies within 30 meters with an Agent-granted buff",kind:"number",readiness:"ready",min:0}. The loadout timeline copies that resolved count into each proximity_snapshot event, and runtime event validation rejects non-integers.',
'OS Protocol upgrade scaling may use equipment.protocolTalentUpgrades only when allowProtocolUpgradeScaling is true.',
'Assigned-ability scope may be used only when allowAssignedAbility is true.',
'When allowAssignedAbility is true, a kill or assist that must occur while the source item\'s assigned ability is active uses enemy_killed or assist with {source:"event",path:"values.assignedAbilityActive"} compared to true. This field is optional on the event; a missing value does not match.',
@@ -1,191 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { connect, type Database } from '@tursodatabase/database';
const mocks = vi.hoisted(() => ({
audit: vi.fn(async () => undefined),
unlink: vi.fn(async () => undefined),
avatarDirectory: vi.fn(() => '/tmp/account-deletion-avatars'),
}));
vi.mock('$lib/server/audit', () => ({ recordIsacAudit: mocks.audit }));
vi.mock('node:fs/promises', () => ({ unlink: mocks.unlink }));
vi.mock('$lib/server/avatars', () => ({
avatarStorageDirectory: mocks.avatarDirectory,
}));
vi.mock('$lib/agents', () => ({
displayNameKey: (value: string) => value.toLowerCase(),
}));
import {
LastAdministratorDeletionError,
softDeleteAccount,
} from './account-deletion';
async function createDatabase(): Promise<Database> {
const database = await connect(':memory:');
await database.exec(`
CREATE TABLE users(
id TEXT PRIMARY KEY, username TEXT NOT NULL, login_username TEXT,
password_hash TEXT, discord_id TEXT, role TEXT NOT NULL
);
INSERT INTO users VALUES('user-1','agent','agent','hash','discord','user');
CREATE TABLE user_profiles(
user_id TEXT PRIMARY KEY, display_name TEXT, display_name_key TEXT,
bio_markdown TEXT NOT NULL DEFAULT '', is_public INTEGER NOT NULL DEFAULT 1,
bio_updated_at TEXT, updated_at TEXT
);
INSERT INTO user_profiles(user_id,display_name) VALUES('user-1','Agent');
CREATE TABLE user_avatars(user_id TEXT PRIMARY KEY, source TEXT, value TEXT);
CREATE TABLE avatar_reviews(
id TEXT PRIMARY KEY, user_id TEXT, status TEXT, reviewed_at TEXT
);
INSERT INTO user_avatars(user_id,source,value)
VALUES('user-1','upload','11111111-1111-4111-8111-111111111111.webp');
CREATE TABLE user_status(user_id TEXT PRIMARY KEY, blocked_at TEXT, banned_until TEXT);
CREATE TABLE deleted_accounts(
user_id TEXT PRIMARY KEY, original_username TEXT, deleted_at TEXT,
deleted_by TEXT, reason TEXT
);
CREATE TABLE sessions(id TEXT PRIMARY KEY, user_id TEXT);
CREATE TABLE magic_link_tokens(id TEXT PRIMARY KEY, user_id TEXT);
CREATE TABLE webauthn_challenges(id TEXT PRIMARY KEY, user_id TEXT);
CREATE TABLE passkeys(id TEXT PRIMARY KEY, user_id TEXT);
CREATE TABLE user_emails(id TEXT PRIMARY KEY, user_id TEXT);
CREATE TABLE oauth_states(id TEXT PRIMARY KEY, user_id TEXT);
CREATE TABLE discord_profiles(user_id TEXT PRIMARY KEY);
CREATE TABLE user_roles(user_id TEXT, role_id TEXT);
CREATE TABLE user_permissions(user_id TEXT, permission_id TEXT);
CREATE TABLE login_events(id TEXT PRIMARY KEY, user_id TEXT);
CREATE TABLE mfa_totp_factors(
id TEXT PRIMARY KEY, user_id TEXT, state TEXT, encrypted_secret TEXT,
encryption_key_id TEXT, revoked_at TEXT
);
CREATE TABLE mfa_recovery_codes(
id TEXT PRIMARY KEY, user_id TEXT, code_hash TEXT,
consumed_at TEXT, revoked_at TEXT
);
CREATE TABLE authentication_transactions(
id TEXT PRIMARY KEY, user_id TEXT, consumed_at TEXT
);
INSERT INTO mfa_totp_factors VALUES('factor-1','user-1','pending','mfa1.old','old-key',NULL);
INSERT INTO mfa_recovery_codes VALUES('recovery-1','user-1','hash',NULL,NULL);
INSERT INTO authentication_transactions VALUES('tx-1','user-1',NULL);
`);
return database;
}
describe('account deletion MFA erasure', () => {
let database: Database;
beforeEach(async () => {
database = await createDatabase();
mocks.audit.mockReset();
mocks.audit.mockResolvedValue(undefined);
mocks.unlink.mockReset();
mocks.unlink.mockResolvedValue(undefined);
});
afterEach(async () => database.close());
it('purges pending MFA transactions, recovery codes, and factor material', async () => {
expect(
await softDeleteAccount(database, 'user-1', 'admin-1', 'request', true),
).toBe(true);
expect(mocks.unlink).toHaveBeenCalledWith(
'/tmp/account-deletion-avatars/11111111-1111-4111-8111-111111111111.webp',
);
for (const table of [
'mfa_totp_factors',
'mfa_recovery_codes',
'authentication_transactions',
]) {
const row = await (
await database.prepare(
`SELECT COUNT(*) AS count FROM ${table} WHERE user_id=?`,
)
).get('user-1');
expect(Number(row?.count)).toBe(0);
}
const user = await (
await database.prepare(
'SELECT username,password_hash,discord_id FROM users WHERE id=?',
)
).get('user-1');
expect(user).toMatchObject({
username: 'deleted-agent-user-1',
password_hash: null,
discord_id: null,
});
});
it('rolls back all deletion and MFA erasure when audit recording fails', async () => {
mocks.audit.mockRejectedValueOnce(new Error('audit unavailable'));
await expect(
softDeleteAccount(database, 'user-1', 'admin-1', 'request', true),
).rejects.toThrow('audit unavailable');
expect(mocks.unlink).not.toHaveBeenCalled();
const user = await (
await database.prepare(
'SELECT username,password_hash FROM users WHERE id=?',
)
).get('user-1');
expect(user).toMatchObject({ username: 'agent', password_hash: 'hash' });
const factor = await (
await database.prepare(
'SELECT encrypted_secret,state FROM mfa_totp_factors WHERE id=?',
)
).get('factor-1');
expect(factor).toMatchObject({
encrypted_secret: 'mfa1.old',
state: 'pending',
});
const deleted = await (
await database.prepare('SELECT 1 FROM deleted_accounts WHERE user_id=?')
).get('user-1');
expect(deleted).toBeUndefined();
});
it('does not clean the avatar when a transaction mutation fails', async () => {
await database.exec('DROP TABLE user_permissions');
await expect(
softDeleteAccount(database, 'user-1', 'admin-1', 'request', true),
).rejects.toThrow();
expect(mocks.unlink).not.toHaveBeenCalled();
const user = await (
await database.prepare('SELECT username FROM users WHERE id=?')
).get('user-1');
expect(user?.username).toBe('agent');
});
it('preserves committed deletion when post-commit avatar cleanup fails', async () => {
mocks.unlink.mockRejectedValueOnce(new Error('unlink failed'));
const log = vi.spyOn(console, 'error').mockImplementation(() => undefined);
expect(
await softDeleteAccount(database, 'user-1', 'admin-1', 'request'),
).toBe(true);
expect(log).toHaveBeenCalledWith(
'[account-deletion] committed deletion; uploaded avatar cleanup failed.',
{ userId: 'user-1' },
);
const user = await (
await database.prepare('SELECT username FROM users WHERE id=?')
).get('user-1');
expect(user?.username).toBe('deleted-agent-user-1');
log.mockRestore();
});
it('rejects deletion of the sole active canonical administrator', async () => {
await database.exec(
"INSERT INTO user_roles(user_id,role_id) VALUES('user-1','role-admin')",
);
await expect(
softDeleteAccount(database, 'user-1', 'user-1', 'request'),
).rejects.toBeInstanceOf(LastAdministratorDeletionError);
const deleted = await (
await database.prepare('SELECT 1 FROM deleted_accounts WHERE user_id=?')
).get('user-1');
expect(deleted).toBeUndefined();
});
});
+106 -199
View File
@@ -1,24 +1,7 @@
import type { Database } from '@tursodatabase/database';
import { randomBytes } from 'node:crypto';
import { unlink } from 'node:fs/promises';
import path from 'node:path';
import { avatarStorageDirectory } from '$lib/server/avatars';
import { randomUUID } from 'node:crypto';
import { deleteUploadedAvatar } from '$lib/server/avatars';
import { displayNameKey } from '$lib/agents';
import { recordIsacAudit } from '$lib/server/audit';
import {
countActiveFullAdministrators,
isFullAdministrator,
} from './bootstrap';
const AVATAR_FILE_PATTERN = /^[0-9a-f-]{36}\.webp$/i;
type AvatarCleanup = { key: string } | { invalid: true } | null;
export class LastAdministratorDeletionError extends Error {
constructor() {
super('The final active full administrator cannot be deleted.');
this.name = 'LastAdministratorDeletionError';
}
}
export async function softDeleteAccount(
database: Database,
@@ -27,189 +10,113 @@ export async function softDeleteAccount(
reason: string | null,
purgeSecurityData = false,
): Promise<boolean> {
const deletion = database.transactionAsync(async (transaction) => {
const user = await (
await transaction.prepare(`
SELECT users.username,users.login_username,user_profiles.display_name,
user_status.blocked_at,user_status.banned_until,deleted_accounts.deleted_at
FROM users LEFT JOIN user_profiles ON user_profiles.user_id=users.id
LEFT JOIN user_status ON user_status.user_id=users.id
LEFT JOIN deleted_accounts ON deleted_accounts.user_id=users.id
WHERE users.id=?
`)
).get(userId);
if (!user || user.deleted_at) return false;
const now = new Date().toISOString();
const targetIsActive =
!user.blocked_at &&
(!user.banned_until || String(user.banned_until) <= now);
if (
targetIsActive &&
(await isFullAdministrator(transaction as unknown as Database, userId)) &&
(await countActiveFullAdministrators(
transaction as unknown as Database,
new Date(now),
)) <= 1
const user = await (
await database.prepare(`
SELECT users.username,users.login_username,user_profiles.display_name,deleted_accounts.deleted_at
FROM users LEFT JOIN user_profiles ON user_profiles.user_id=users.id
LEFT JOIN deleted_accounts ON deleted_accounts.user_id=users.id
WHERE users.id=?
`)
).get(userId);
if (!user || user.deleted_at) return false;
const now = new Date().toISOString();
const deletedUsername = `deleted-agent-${userId.slice(0, 12)}`;
const deletedDisplayName = `Deleted Agent ${userId.replaceAll('-', '').slice(0, 8)}`;
await (
await database.prepare(
'INSERT INTO deleted_accounts(user_id,original_username,deleted_at,deleted_by,reason) VALUES(?,?,?,?,?)',
)
throw new LastAdministratorDeletionError();
const deletedUsername = `deleted-agent-${userId.slice(0, 12)}`;
const deletedDisplayName = `Deleted Agent ${userId.replaceAll('-', '').slice(0, 8)}`;
).run(
userId,
purgeSecurityData
? deletedUsername
: String(user.login_username ?? user.username),
now,
deletedBy,
reason,
);
await (
await database.prepare(
`UPDATE users SET username=?,login_username=NULL,password_hash=NULL,discord_id=NULL,role='user' WHERE id=?`,
)
).run(deletedUsername, userId);
await (
await database.prepare(
`INSERT INTO user_profiles(user_id,display_name,display_name_key,bio_markdown,is_public,bio_updated_at,updated_at)
VALUES(?,?,?,?,0,?,?)
ON CONFLICT(user_id) DO UPDATE SET
display_name=excluded.display_name,
display_name_key=excluded.display_name_key,
bio_markdown='',
is_public=0,
bio_updated_at=excluded.bio_updated_at,
updated_at=excluded.updated_at`,
)
).run(
userId,
deletedDisplayName,
displayNameKey(deletedDisplayName),
'',
now,
now,
);
await (
await database.prepare('DELETE FROM sessions WHERE user_id=?')
).run(userId);
await (
await database.prepare('DELETE FROM magic_link_tokens WHERE user_id=?')
).run(userId);
await (
await database.prepare('DELETE FROM webauthn_challenges WHERE user_id=?')
).run(userId);
await (
await database.prepare('DELETE FROM passkeys WHERE user_id=?')
).run(userId);
await (
await database.prepare('DELETE FROM user_emails WHERE user_id=?')
).run(userId);
await (
await database.prepare('DELETE FROM oauth_states WHERE user_id=?')
).run(userId);
await (
await database.prepare('DELETE FROM discord_profiles WHERE user_id=?')
).run(userId);
await (
await database.prepare('DELETE FROM user_roles WHERE user_id=?')
).run(userId);
await (
await database.prepare('DELETE FROM user_permissions WHERE user_id=?')
).run(userId);
await deleteUploadedAvatar(database, userId);
if (purgeSecurityData) {
await (
await transaction.prepare(
'INSERT INTO deleted_accounts(user_id,original_username,deleted_at,deleted_by,reason) VALUES(?,?,?,?,?)',
)
).run(
userId,
purgeSecurityData
? deletedUsername
: String(user.login_username ?? user.username),
now,
deletedBy,
reason,
);
await (
await transaction.prepare(
`UPDATE users SET username=?,login_username=NULL,password_hash=NULL,discord_id=NULL,role='user' WHERE id=?`,
)
).run(deletedUsername, userId);
await (
await transaction.prepare(
`INSERT INTO user_profiles(user_id,display_name,display_name_key,bio_markdown,is_public,bio_updated_at,updated_at)
VALUES(?,?,?,?,0,?,?)
ON CONFLICT(user_id) DO UPDATE SET
display_name=excluded.display_name,
display_name_key=excluded.display_name_key,
bio_markdown='',
is_public=0,
bio_updated_at=excluded.bio_updated_at,
updated_at=excluded.updated_at`,
)
).run(
userId,
deletedDisplayName,
displayNameKey(deletedDisplayName),
'',
now,
now,
);
const avatar = await (
await transaction.prepare(
'SELECT source,value FROM user_avatars WHERE user_id=? LIMIT 1',
)
).get(userId);
const avatarCleanup: AvatarCleanup =
avatar?.source === 'upload'
? typeof avatar.value === 'string' &&
AVATAR_FILE_PATTERN.test(avatar.value)
? { key: avatar.value }
: { invalid: true }
: null;
await (
await transaction.prepare('DELETE FROM user_avatars WHERE user_id=?')
await database.prepare('DELETE FROM login_events WHERE user_id=?')
).run(userId);
await (
await transaction.prepare(
"UPDATE avatar_reviews SET status='removed',reviewed_at=COALESCE(reviewed_at,?) WHERE user_id=? AND status='pending'",
)
).run(now, userId);
await (
await transaction.prepare('DELETE FROM sessions WHERE user_id=?')
).run(userId);
await (
await transaction.prepare('DELETE FROM magic_link_tokens WHERE user_id=?')
).run(userId);
await (
await transaction.prepare(
'DELETE FROM webauthn_challenges WHERE user_id=?',
)
).run(userId);
await (
await transaction.prepare('DELETE FROM passkeys WHERE user_id=?')
).run(userId);
await (
await transaction.prepare('DELETE FROM user_emails WHERE user_id=?')
).run(userId);
await (
await transaction.prepare('DELETE FROM oauth_states WHERE user_id=?')
).run(userId);
await (
await transaction.prepare('DELETE FROM discord_profiles WHERE user_id=?')
).run(userId);
await (
await transaction.prepare('DELETE FROM user_roles WHERE user_id=?')
).run(userId);
await (
await transaction.prepare('DELETE FROM user_permissions WHERE user_id=?')
).run(userId);
// Overwrite ciphertext and key metadata before deleting factor rows.
await (
await transaction.prepare(
"UPDATE mfa_totp_factors SET state='revoked',encrypted_secret=?,encryption_key_id='erased',revoked_at=? WHERE user_id=?",
)
).run(`erased:${randomBytes(32).toString('base64url')}`, now, userId);
await (
await transaction.prepare('DELETE FROM mfa_totp_factors WHERE user_id=?')
).run(userId);
await (
await transaction.prepare(
'DELETE FROM mfa_recovery_codes WHERE user_id=?',
)
).run(userId);
await (
await transaction.prepare(
'DELETE FROM authentication_transactions WHERE user_id=?',
)
).run(userId);
if (purgeSecurityData) {
await (
await transaction.prepare('DELETE FROM login_events WHERE user_id=?')
).run(userId);
}
await recordIsacAudit({
actorId: deletedBy,
category: 'user_access',
action: 'account.soft_deleted',
entityId: userId,
before: purgeSecurityData
? { purgedAtOwnerRequest: true }
: {
username: user.username,
displayName: user.display_name,
},
after: {
username: deletedUsername,
displayName: 'Deleted Agent',
reason,
securityDataPurged: purgeSecurityData,
mfaFactorsPurged: true,
recoveryCodesPurged: true,
authenticationTransactionsPurged: true,
},
database: transaction as unknown as Database,
createdAt: now,
});
return { deleted: true, avatarCleanup };
});
const committed = await deletion.immediate();
if (!committed) return false;
if (committed.avatarCleanup) {
try {
if ('invalid' in committed.avatarCleanup)
throw new Error('invalid avatar storage key');
await unlink(
path.join(avatarStorageDirectory(), committed.avatarCleanup.key),
);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
console.error(
'[account-deletion] committed deletion; uploaded avatar cleanup failed.',
{ userId: userId.slice(0, 200) },
);
}
}
}
await (
await database.prepare(
'INSERT INTO audit_log(id,actor_id,entity_type,entity_id,action,before_json,after_json,created_at) VALUES(?,?,?,?,?,?,?,?)',
)
).run(
randomUUID(),
deletedBy,
'user_access',
userId,
'account.soft_deleted',
purgeSecurityData
? JSON.stringify({ purgedAtOwnerRequest: true })
: JSON.stringify({
username: user.username,
displayName: user.display_name,
}),
JSON.stringify({
username: deletedUsername,
displayName: 'Deleted Agent',
reason,
securityDataPurged: purgeSecurityData,
}),
now,
);
return true;
}
@@ -1,338 +0,0 @@
import { dev } from '$app/environment';
import { getDatabase } from '$lib/server/database';
import type { Database } from '@tursodatabase/database';
import type { Cookies } from '@sveltejs/kit';
import { createHash, randomBytes, randomUUID } from 'node:crypto';
export const AUTHENTICATION_TRANSACTION_COOKIE = 'shd_auth_tx';
export const AUTHENTICATION_TRANSACTION_COOKIE_PATH = '/auth/two-factor';
export const AUTHENTICATION_TRANSACTION_SECONDS = 5 * 60;
export const AUTHENTICATION_TRANSACTION_ATTEMPT_LIMIT = 5;
export const AUTHENTICATION_TRANSACTION_PROVIDERS = [
'password',
'discord',
'magic_link',
'passkey',
] as const;
export type AuthenticationTransactionProvider =
(typeof AUTHENTICATION_TRANSACTION_PROVIDERS)[number];
export type AuthenticationTransactionKind = 'login' | 'step_up';
export type AuthenticationTransactionDatabase = Pick<
Database,
'prepare' | 'transactionAsync'
>;
export type AuthenticationTransactionTransaction = Pick<Database, 'prepare'>;
export type AuthenticationTransaction = {
id: string;
userId: string;
provider: AuthenticationTransactionProvider | null;
kind: AuthenticationTransactionKind;
returnPath: string;
requiredAal: 2;
attemptCount: number;
expiresAt: string;
};
type AuthenticationTransactionRow = {
id: string;
user_id: string;
provider: AuthenticationTransactionProvider | null;
kind: AuthenticationTransactionKind;
return_path: string;
required_aal: 2;
attempt_count: number;
expires_at: string;
consumed_at: string | null;
};
export class AuthenticationTransactionError extends Error {
constructor(message = 'Unable to create the authentication transaction.') {
super(message);
this.name = 'AuthenticationTransactionError';
}
}
function hashToken(token: string): string {
return createHash('sha256').update(token, 'utf8').digest('hex');
}
function databaseOrDefault(
database?: AuthenticationTransactionDatabase,
): Promise<AuthenticationTransactionDatabase> {
return database
? Promise.resolve(database)
: (getDatabase() as Promise<AuthenticationTransactionDatabase>);
}
function nowDate(value: Date | string | number | undefined): Date {
const date =
value instanceof Date ? new Date(value) : new Date(value ?? Date.now());
if (!Number.isFinite(date.getTime()))
throw new AuthenticationTransactionError();
return date;
}
/** Accept only a same-origin path, never an absolute or protocol-relative URL. */
export function validateAuthenticationReturnPath(value: string): string | null {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.length > 2048 ||
!value.startsWith('/') ||
value.startsWith('//') ||
value.includes('\\') ||
value.includes('#') ||
/[\u0000-\u001f\u007f]/u.test(value)
)
return null;
try {
const decoded = decodeURIComponent(value);
if (
decoded.startsWith('//') ||
decoded.includes('\\') ||
/[\u0000-\u001f\u007f]/u.test(decoded)
)
return null;
const parsed = new URL(value, 'https://shd.invalid');
if (
parsed.origin !== 'https://shd.invalid' ||
!parsed.pathname.startsWith('/')
)
return null;
} catch {
return null;
}
return value;
}
function cookieOptions() {
return {
path: AUTHENTICATION_TRANSACTION_COOKIE_PATH,
httpOnly: true,
sameSite: 'lax' as const,
secure: !dev,
maxAge: AUTHENTICATION_TRANSACTION_SECONDS,
};
}
export function clearAuthenticationTransactionCookie(cookies: Cookies): void {
cookies.delete(AUTHENTICATION_TRANSACTION_COOKIE, {
path: AUTHENTICATION_TRANSACTION_COOKIE_PATH,
});
}
function fromRow(row: AuthenticationTransactionRow): AuthenticationTransaction {
return {
id: String(row.id),
userId: String(row.user_id),
provider: row.provider ?? null,
kind: row.kind,
returnPath: String(row.return_path),
requiredAal: 2,
attemptCount: Number(row.attempt_count),
expiresAt: String(row.expires_at),
};
}
export async function createAuthenticationTransaction(
cookies: Cookies,
databaseInput: AuthenticationTransactionDatabase | undefined,
options: {
userId: string;
kind: AuthenticationTransactionKind;
provider?: AuthenticationTransactionProvider | null;
returnPath: string;
now?: Date | string | number;
},
): Promise<AuthenticationTransaction> {
const returnPath = validateAuthenticationReturnPath(options.returnPath);
if (
!options.userId ||
!returnPath ||
(options.kind === 'login' && !options.provider)
)
throw new AuthenticationTransactionError();
const database = await databaseOrDefault(databaseInput);
const now = nowDate(options.now);
const createdAt = now.toISOString();
const expiresAt = new Date(
now.getTime() + AUTHENTICATION_TRANSACTION_SECONDS * 1000,
).toISOString();
const id = randomUUID();
const token = randomBytes(32).toString('base64url');
await (
await database.prepare(
`INSERT INTO authentication_transactions(
id,token_hash,user_id,provider,kind,return_path,required_aal,attempt_count,expires_at,created_at
) VALUES(?,?,?,?,?,?,?,?,?,?)`,
)
).run(
id,
hashToken(token),
options.userId,
options.provider ?? null,
options.kind,
returnPath,
2,
0,
expiresAt,
createdAt,
);
cookies.set(AUTHENTICATION_TRANSACTION_COOKIE, token, cookieOptions());
return {
id,
userId: options.userId,
provider: options.provider ?? null,
kind: options.kind,
returnPath,
requiredAal: 2,
attemptCount: 0,
expiresAt,
};
}
export const beginAuthenticationTransaction = createAuthenticationTransaction;
export async function getAuthenticationTransaction(
cookies: Cookies,
databaseInput?: AuthenticationTransactionDatabase,
nowValue?: Date | string | number,
): Promise<AuthenticationTransaction | null> {
const token = cookies.get(AUTHENTICATION_TRANSACTION_COOKIE);
if (!token) return null;
const now = nowDate(nowValue).toISOString();
const database = await databaseOrDefault(databaseInput);
const row = (await (
await database.prepare(
`SELECT id,user_id,provider,kind,return_path,required_aal,attempt_count,expires_at,consumed_at
FROM authentication_transactions
WHERE token_hash=? AND consumed_at IS NULL AND expires_at>? AND attempt_count<?`,
)
).get(hashToken(token), now, AUTHENTICATION_TRANSACTION_ATTEMPT_LIMIT)) as
AuthenticationTransactionRow | undefined;
if (!row) {
clearAuthenticationTransactionCookie(cookies);
return null;
}
return fromRow(row);
}
/** Atomically account for one failed factor attempt. */
export async function recordAuthenticationAttempt(
cookies: Cookies,
databaseInput?: AuthenticationTransactionDatabase,
nowValue?: Date | string | number,
): Promise<{ accepted: boolean; attemptCount: number; locked: boolean }> {
const token = cookies.get(AUTHENTICATION_TRANSACTION_COOKIE);
if (!token) return { accepted: false, attemptCount: 0, locked: false };
const database = await databaseOrDefault(databaseInput);
const now = nowDate(nowValue).toISOString();
const attempt = database.transactionAsync(async (transaction) => {
const row = (await (
await transaction.prepare(
'SELECT id,attempt_count FROM authentication_transactions WHERE token_hash=? AND consumed_at IS NULL AND expires_at>? AND attempt_count<?',
)
).get(hashToken(token), now, AUTHENTICATION_TRANSACTION_ATTEMPT_LIMIT)) as
{ id: string; attempt_count: number } | undefined;
if (!row) return null;
const updated = await (
await transaction.prepare(
'UPDATE authentication_transactions SET attempt_count=attempt_count+1 WHERE id=? AND consumed_at IS NULL AND attempt_count<?',
)
).run(row.id, AUTHENTICATION_TRANSACTION_ATTEMPT_LIMIT);
return updated.changes === 1 ? Number(row.attempt_count) + 1 : null;
});
const attemptCount = await attempt.immediate();
if (attemptCount === null) {
clearAuthenticationTransactionCookie(cookies);
return { accepted: false, attemptCount: 0, locked: true };
}
return {
accepted: true,
attemptCount,
locked: false,
};
}
/**
* Load a transaction while the caller's immediate transaction holds the
* write claim. The conditional consume must happen before that transaction
* commits.
*/
export async function claimAuthenticationTransactionInTransaction(
transaction: AuthenticationTransactionTransaction,
cookies: Cookies,
nowValue?: Date | string | number,
): Promise<AuthenticationTransaction | null> {
const token = cookies.get(AUTHENTICATION_TRANSACTION_COOKIE);
if (!token) return null;
const now = nowDate(nowValue).toISOString();
const row = (await (
await transaction.prepare(
`SELECT id,user_id,provider,kind,return_path,required_aal,attempt_count,expires_at,consumed_at
FROM authentication_transactions
WHERE token_hash=? AND consumed_at IS NULL AND expires_at>? AND attempt_count<?`,
)
).get(hashToken(token), now, AUTHENTICATION_TRANSACTION_ATTEMPT_LIMIT)) as
AuthenticationTransactionRow | undefined;
return row ? fromRow(row) : null;
}
/** Conditionally consume a transaction already loaded in this transaction. */
export async function consumeAuthenticationTransactionInTransaction(
transaction: AuthenticationTransactionTransaction,
cookies: Cookies,
transactionId: string,
nowValue?: Date | string | number,
): Promise<boolean> {
const token = cookies.get(AUTHENTICATION_TRANSACTION_COOKIE);
if (!token) return false;
const now = nowDate(nowValue).toISOString();
const consumed = await (
await transaction.prepare(
`UPDATE authentication_transactions SET consumed_at=?
WHERE id=? AND token_hash=? AND consumed_at IS NULL AND expires_at>? AND attempt_count<?`,
)
).run(
now,
transactionId,
hashToken(token),
now,
AUTHENTICATION_TRANSACTION_ATTEMPT_LIMIT,
);
return consumed.changes === 1;
}
/** Consume a transaction in one conditional write; replay cannot succeed. */
export async function consumeAuthenticationTransaction(
cookies: Cookies,
databaseInput?: AuthenticationTransactionDatabase,
nowValue?: Date | string | number,
): Promise<AuthenticationTransaction | null> {
const token = cookies.get(AUTHENTICATION_TRANSACTION_COOKIE);
if (!token) return null;
const database = await databaseOrDefault(databaseInput);
const now = nowDate(nowValue).toISOString();
const consume = database.transactionAsync(async (transaction) => {
const row = await claimAuthenticationTransactionInTransaction(
transaction,
cookies,
now,
);
if (!row) return null;
const consumed = await consumeAuthenticationTransactionInTransaction(
transaction,
cookies,
row.id,
now,
);
return consumed ? row : null;
});
const result = await consume.immediate();
clearAuthenticationTransactionCookie(cookies);
return result;
}
export const consumeAuthTransaction = consumeAuthenticationTransaction;
@@ -1,182 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { connect, type Database } from '@tursodatabase/database';
const mocks = vi.hoisted(() => ({
audit: vi.fn(),
}));
vi.mock('$lib/server/audit', () => ({
recordIsacAudit: mocks.audit,
}));
import { applyAuthorityChange } from './authority-change';
import type { AuthUser } from './session';
const operator = {
id: 'operator-1',
aal: 2,
authLevel: 2,
aal2VerifiedAt: new Date().toISOString(),
} as AuthUser;
async function createDatabase(): Promise<Database> {
const database = await connect(':memory:');
await database.exec(`
CREATE TABLE users(id TEXT PRIMARY KEY, role TEXT NOT NULL);
CREATE TABLE roles(id TEXT PRIMARY KEY);
CREATE TABLE permissions(id TEXT PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE role_permissions(role_id TEXT, permission_id TEXT);
CREATE TABLE user_roles(user_id TEXT, role_id TEXT, PRIMARY KEY(user_id,role_id));
CREATE TABLE user_permissions(user_id TEXT, permission_id TEXT);
CREATE TABLE user_status(user_id TEXT PRIMARY KEY, blocked_at TEXT, banned_until TEXT);
CREATE TABLE deleted_accounts(user_id TEXT PRIMARY KEY);
CREATE TABLE sessions(id TEXT PRIMARY KEY, user_id TEXT);
CREATE TABLE mfa_totp_factors(id TEXT PRIMARY KEY, user_id TEXT, state TEXT);
CREATE TABLE mfa_recovery_codes(id TEXT PRIMARY KEY, user_id TEXT, consumed_at TEXT, revoked_at TEXT);
INSERT INTO users VALUES('operator-1','user'),('target-1','user');
INSERT INTO roles VALUES('role-admin'),('role-user');
INSERT INTO permissions VALUES('permission-system-admin','system.admin'),('permission-users-view','users.view');
INSERT INTO role_permissions VALUES('role-admin','permission-system-admin'),('role-user','permission-users-view');
INSERT INTO user_roles VALUES('operator-1','role-admin');
INSERT INTO mfa_totp_factors VALUES('operator-factor','operator-1','active');
INSERT INTO sessions VALUES('target-session','target-1');
`);
return database;
}
const access = (roleIds: string[], permissionIds: string[]) => ({
roleIds,
permissionIds,
});
describe('shared authority changes', () => {
let database: Database;
beforeEach(async () => {
database = await createDatabase();
mocks.audit.mockReset();
mocks.audit.mockResolvedValue(undefined);
});
afterEach(async () => database.close());
it('cannot revert an administrator grant by removing the final active authority', async () => {
await expect(
applyAuthorityChange({
database,
operator,
targetId: 'operator-1',
...access([], []),
expectedCurrent: access(['role-admin'], []),
}),
).rejects.toMatchObject({ status: 409 });
const role = await (
await database.prepare('SELECT role_id FROM user_roles WHERE user_id=?')
).get('operator-1');
expect(role.role_id).toBe('role-admin');
});
it('requires an MFA-ready target when reversion restores administrator authority', async () => {
await expect(
applyAuthorityChange({
database,
operator,
targetId: 'target-1',
...access(['role-admin'], []),
expectedCurrent: access([], []),
}),
).rejects.toMatchObject({ status: 400 });
const role = await (
await database.prepare('SELECT role_id FROM user_roles WHERE user_id=?')
).get('target-1');
expect(role).toBeUndefined();
});
it('requires recent AAL2 authentication for administrator reversion', async () => {
await database.exec(`
INSERT INTO mfa_totp_factors VALUES('target-factor','target-1','active');
INSERT INTO mfa_recovery_codes VALUES('target-code','target-1',NULL,NULL);
`);
await expect(
applyAuthorityChange({
database,
operator: {
...operator,
aal2VerifiedAt: new Date(Date.now() - 11 * 60_000).toISOString(),
} as never,
targetId: 'target-1',
...access(['role-admin'], []),
expectedCurrent: access([], []),
}),
).rejects.toMatchObject({ status: 403 });
});
it('revokes sessions and appends reversion audit evidence in the transaction', async () => {
await database.exec(`
INSERT INTO mfa_totp_factors VALUES('target-factor','target-1','active');
INSERT INTO mfa_recovery_codes VALUES('target-code','target-1',NULL,NULL);
`);
const result = await applyAuthorityChange({
database,
operator,
targetId: 'target-1',
...access(['role-admin'], []),
expectedCurrent: access([], []),
audit: {
actorId: 'operator-1',
category: 'audit_control',
action: 'audit.reverted',
entityId: 'event-1',
before: access([], []),
after: {
originalEventId: 'event-1',
restored: access(['role-admin'], []),
},
},
});
expect(result.after).toEqual(access(['role-admin'], []));
expect(
await (
await database.prepare('SELECT COUNT(*) AS count FROM sessions')
).get(),
).toMatchObject({ count: 0 });
expect(mocks.audit).toHaveBeenCalledWith(
expect.objectContaining({
action: 'audit.reverted',
entityId: 'event-1',
database,
}),
);
});
it('rolls back authority and session changes when audit append fails', async () => {
await database.exec(`
INSERT INTO mfa_totp_factors VALUES('target-factor','target-1','active');
INSERT INTO mfa_recovery_codes VALUES('target-code','target-1',NULL,NULL);
`);
mocks.audit.mockRejectedValueOnce(new Error('audit failed'));
await expect(
applyAuthorityChange({
database,
operator,
targetId: 'target-1',
...access(['role-admin'], []),
expectedCurrent: access([], []),
}),
).rejects.toThrow('audit failed');
const role = await (
await database.prepare('SELECT role_id FROM user_roles WHERE user_id=?')
).get('target-1');
const sessions = await (
await database.prepare('SELECT COUNT(*) AS count FROM sessions')
).get();
expect(role).toBeUndefined();
expect(Number(sessions.count)).toBe(1);
});
});
-272
View File
@@ -1,272 +0,0 @@
import type { Database } from '@tursodatabase/database';
import type { AuthUser } from './session';
import { hasRecentAal2, RECENT_AAL2_WINDOW_MS } from './authorization';
import { recordIsacAudit } from '$lib/server/audit';
import {
countActiveFullAdministrators,
hasActiveTotpFactor,
isFullAdministrator,
isMfaReady,
} from './bootstrap';
export type AuthoritySnapshot = {
roleIds: string[];
permissionIds: string[];
};
type AuditValue = Record<string, unknown> | unknown[] | null;
export type AuthorityAudit = {
actorId: string;
category: string;
action: string;
entityId: string;
before?: AuditValue;
after?: AuditValue;
};
export type AuthorityChangeInput = {
database: Database;
operator: AuthUser;
targetId: string;
roleIds: string[];
permissionIds: string[];
expectedCurrent?: AuthoritySnapshot;
audit?: AuthorityAudit;
};
export type AuthorityChangeResult = {
before: AuthoritySnapshot;
after: AuthoritySnapshot;
sessionsRevoked: number;
};
export class AuthorityChangeError extends Error {
readonly status: 400 | 403 | 404 | 409;
constructor(status: 400 | 403 | 404 | 409, message: string) {
super(message);
this.name = 'AuthorityChangeError';
this.status = status;
}
}
const sorted = (values: string[]) => [...values].sort();
function sameSnapshot(
left: AuthoritySnapshot,
right: AuthoritySnapshot,
): boolean {
return (
JSON.stringify({
roleIds: sorted(left.roleIds),
permissionIds: sorted(left.permissionIds),
}) ===
JSON.stringify({
roleIds: sorted(right.roleIds),
permissionIds: sorted(right.permissionIds),
})
);
}
function isRecentAal2(user: AuthUser): boolean {
return hasRecentAal2(user, Date.now());
}
export async function applyAuthorityChange(
input: AuthorityChangeInput,
): Promise<AuthorityChangeResult> {
const database = input.database;
await database.exec('BEGIN IMMEDIATE');
let transactionOpen = true;
const rollback = async () => {
if (!transactionOpen) return;
transactionOpen = false;
await database.exec('ROLLBACK');
};
try {
const operatorIsFullAdministrator =
(await isFullAdministrator(database, input.operator.id)) &&
input.operator.aal === 2 &&
(await hasActiveTotpFactor(database, input.operator.id));
const target = await (
await database.prepare('SELECT id FROM users WHERE id=?')
).get(input.targetId);
if (!target) throw new AuthorityChangeError(404, 'User not found.');
const roleIds = [...new Set(input.roleIds.map(String))];
const permissionIds = [...new Set(input.permissionIds.map(String))];
const validRoles = roleIds.length
? Number(
(
await (
await database.prepare(
`SELECT COUNT(*) AS count FROM roles WHERE id IN (${roleIds.map(() => '?').join(',')})`,
)
).get(...roleIds)
)?.count,
)
: 0;
const validPermissionRows = permissionIds.length
? await (
await database.prepare(
`SELECT id,name FROM permissions WHERE id IN (${permissionIds.map(() => '?').join(',')})`,
)
).all(...permissionIds)
: [];
if (
validRoles !== roleIds.length ||
validPermissionRows.length !== permissionIds.length
)
throw new AuthorityChangeError(
400,
'One or more access selections are invalid.',
);
const before: AuthoritySnapshot = {
roleIds: (
await (
await database.prepare(
'SELECT role_id FROM user_roles WHERE user_id=? ORDER BY role_id',
)
).all(input.targetId)
).map((row) => String(row.role_id)),
permissionIds: (
await (
await database.prepare(
'SELECT permission_id FROM user_permissions WHERE user_id=? ORDER BY permission_id',
)
).all(input.targetId)
).map((row) => String(row.permission_id)),
};
if (input.expectedCurrent && !sameSnapshot(before, input.expectedCurrent))
throw new AuthorityChangeError(
409,
'The user’s access changed after this event. Reversion was blocked.',
);
const currentRoleSystemAdmin = Boolean(
await (
await database.prepare(`
SELECT 1
FROM user_roles
JOIN role_permissions ON role_permissions.role_id=user_roles.role_id
JOIN permissions ON permissions.id=role_permissions.permission_id
WHERE user_roles.user_id=? AND permissions.name='system.admin'
LIMIT 1
`)
).get(input.targetId),
);
const currentDirectSystemAdmin = before.permissionIds.includes(
'permission-system-admin',
);
const currentSystemAdmin =
currentRoleSystemAdmin || currentDirectSystemAdmin;
const requestedDirectSystemAdmin = validPermissionRows.some(
(permission) => String(permission.name) === 'system.admin',
);
const requestedRoleSystemAdmin = Boolean(
roleIds.length &&
(await (
await database.prepare(`
SELECT 1
FROM role_permissions
JOIN permissions ON permissions.id=role_permissions.permission_id
WHERE role_permissions.role_id IN (${roleIds.map(() => '?').join(',')})
AND permissions.name='system.admin'
LIMIT 1
`)
).get(...roleIds)),
);
const requestedSystemAdmin =
requestedDirectSystemAdmin || requestedRoleSystemAdmin;
const requestedCanonicalAdministrator = roleIds.includes('role-admin');
const targetIsFullAdministrator = await isFullAdministrator(
database,
input.targetId,
);
const targetHadAdministratorAuthority =
targetIsFullAdministrator || before.roleIds.includes('role-admin');
const changesAdministratorAccess =
targetIsFullAdministrator ||
currentSystemAdmin !== requestedSystemAdmin ||
currentDirectSystemAdmin !== requestedDirectSystemAdmin ||
requestedCanonicalAdministrator !== before.roleIds.includes('role-admin');
if (changesAdministratorAccess && !operatorIsFullAdministrator)
throw new AuthorityChangeError(
403,
'Only a full administrator can grant, remove, or modify administrator access.',
);
if (changesAdministratorAccess && !isRecentAal2(input.operator))
throw new AuthorityChangeError(
403,
`Recent AAL2 authentication is required for administrator changes within ${RECENT_AAL2_WINDOW_MS / 60_000} minutes.`,
);
if (
(requestedSystemAdmin || requestedCanonicalAdministrator) &&
(!targetHadAdministratorAuthority ||
(requestedDirectSystemAdmin && !currentDirectSystemAdmin)) &&
!(await isMfaReady(database, input.targetId))
)
throw new AuthorityChangeError(
400,
'The target must have an active TOTP factor and an unused recovery code before receiving administrator authority.',
);
await (
await database.prepare('DELETE FROM user_roles WHERE user_id=?')
).run(input.targetId);
await (
await database.prepare('DELETE FROM user_permissions WHERE user_id=?')
).run(input.targetId);
for (const roleId of roleIds)
await (
await database.prepare(
'INSERT INTO user_roles(user_id,role_id) VALUES(?,?)',
)
).run(input.targetId, roleId);
for (const permissionId of permissionIds)
await (
await database.prepare(
'INSERT INTO user_permissions(user_id,permission_id) VALUES(?,?)',
)
).run(input.targetId, permissionId);
let sessionsRevoked = 0;
if (changesAdministratorAccess) {
const revoked = await (
await database.prepare('DELETE FROM sessions WHERE user_id=?')
).run(input.targetId);
sessionsRevoked = Number(revoked.changes ?? 0);
}
if ((await countActiveFullAdministrators(database)) < 1)
throw new AuthorityChangeError(
409,
'The final active full administrator cannot lose administrator access.',
);
const after: AuthoritySnapshot = { roleIds, permissionIds };
const audit = input.audit ?? {
actorId: input.operator.id,
category: 'user_access',
action: 'access.updated',
entityId: input.targetId,
before,
after,
};
await recordIsacAudit({
...audit,
before: audit.before === undefined ? before : audit.before,
after: audit.after === undefined ? after : audit.after,
database,
});
await database.exec('COMMIT');
transactionOpen = false;
return { before, after, sessionsRevoked };
} catch (error) {
await rollback();
throw error;
}
}
-78
View File
@@ -1,78 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
database: { prepare: vi.fn() },
isFullAdministrator: vi.fn(),
hasActiveTotpFactor: vi.fn(),
isMfaReady: vi.fn(),
}));
vi.mock('$lib/server/database', () => ({
getDatabase: vi.fn(async () => mocks.database),
}));
vi.mock('./bootstrap', () => ({
isFullAdministrator: mocks.isFullAdministrator,
hasActiveTotpFactor: mocks.hasActiveTotpFactor,
isMfaReady: mocks.isMfaReady,
}));
import {
getPermissions,
hasRecentAal2,
requireRecentAal2,
} from './authorization';
const user = (aal: 1 | 2, aal2VerifiedAt: string | null = null) =>
({
id: 'user-1',
aal,
authLevel: aal,
aal2VerifiedAt,
}) as never;
describe('privileged authorization assurance', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.isFullAdministrator.mockResolvedValue(false);
mocks.hasActiveTotpFactor.mockResolvedValue(false);
mocks.database.prepare.mockResolvedValue({
all: vi.fn(async () => [
{ name: 'system.admin' },
{ name: 'users.view' },
]),
});
});
it('does not turn an AAL1 or unenrolled administrator into wildcard access', async () => {
mocks.isFullAdministrator.mockResolvedValue(true);
const permissions = await getPermissions(user(1));
expect(permissions).toContain('users.view');
expect(permissions).toContain('isac.access');
expect(permissions).not.toContain('*');
expect(permissions).not.toContain('system.admin');
});
it('requires both canonical administration, active TOTP, and AAL2 for wildcard access', async () => {
mocks.isFullAdministrator.mockResolvedValue(true);
mocks.hasActiveTotpFactor.mockResolvedValue(true);
const permissions = await getPermissions(user(2));
expect(permissions).toEqual(['*']);
});
it('does not treat a direct system.admin grant as unrestricted access', async () => {
const permissions = await getPermissions(user(2));
expect(permissions).toContain('users.view');
expect(permissions).not.toContain('*');
expect(permissions).not.toContain('system.admin');
});
it('recognizes only AAL2 evidence from the last ten minutes', () => {
const now = Date.parse('2026-08-07T12:00:00.000Z');
expect(hasRecentAal2(user(1, '2026-08-07T11:59:00.000Z'), now)).toBe(false);
expect(hasRecentAal2(user(2, '2026-08-07T11:59:00.000Z'), now)).toBe(true);
expect(hasRecentAal2(user(2, '2026-08-07T11:49:59.999Z'), now)).toBe(false);
expect(() =>
requireRecentAal2(user(1, '2026-08-07T11:59:00.000Z'), now),
).toThrow();
});
});
+5 -73
View File
@@ -1,13 +1,6 @@
import { getDatabase } from '$lib/server/database';
import type { AuthUser } from './session';
import { error } from '@sveltejs/kit';
import {
hasActiveTotpFactor,
isFullAdministrator,
isMfaReady,
} from './bootstrap';
export const RECENT_AAL2_WINDOW_MS = 10 * 60 * 1000;
const REGISTERED_AGENT_PERMISSIONS = [
'isac.access',
@@ -17,14 +10,8 @@ const REGISTERED_AGENT_PERMISSIONS = [
export async function getPermissions(user: AuthUser | null): Promise<string[]> {
if (!user) return [];
if (user.role === 'admin') return ['*'];
const database = await getDatabase();
const canonicalAdministrator = await isFullAdministrator(database, user.id);
if (
canonicalAdministrator &&
user.aal === 2 &&
(await hasActiveTotpFactor(database, user.id))
)
return ['*'];
const rows = await (
await database.prepare(`
SELECT permissions.name FROM permissions
@@ -40,12 +27,10 @@ export async function getPermissions(user: AuthUser | null): Promise<string[]> {
const permissions = [
...new Set([
...REGISTERED_AGENT_PERMISSIONS,
...rows
.map((row) => String(row.name))
.filter((permission) => permission !== 'system.admin'),
...rows.map((row) => String(row.name)),
]),
];
return permissions;
return permissions.includes('system.admin') ? ['*'] : permissions;
}
export async function hasPermission(
@@ -82,60 +67,7 @@ export async function requireDataView(
return user;
}
export async function requireAdmin(user: AuthUser | null): Promise<AuthUser> {
export function requireAdmin(user: AuthUser | null): asserts user is AuthUser {
if (!user) error(401, 'Sign in required');
const database = await getDatabase();
if (!(await isFullAdministrator(database, user.id)))
error(403, 'Administrator permission required');
if (!(await hasActiveTotpFactor(database, user.id)))
error(403, 'Administrator MFA enrollment required');
requireAal2(user);
return user;
}
export function hasAal2(user: AuthUser | null): boolean {
return user?.aal === 2;
}
export function hasRecentAal2(
user: AuthUser | null,
now = Date.now(),
): boolean {
if (!hasAal2(user) || !user?.aal2VerifiedAt) return false;
const verifiedAt = Date.parse(user.aal2VerifiedAt);
return (
Number.isFinite(verifiedAt) &&
verifiedAt <= now &&
now - verifiedAt <= RECENT_AAL2_WINDOW_MS
);
}
export function requireAal2(user: AuthUser | null): AuthUser {
if (!user) error(401, 'Sign in required');
if (!hasAal2(user)) error(403, 'AAL2 authentication required');
return user;
}
export function requireRecentAal2(
user: AuthUser | null,
now = Date.now(),
): AuthUser {
if (!user) error(401, 'Sign in required');
if (!hasRecentAal2(user, now))
error(403, 'Recent AAL2 authentication required');
return user;
}
export async function isAdministratorMfaReady(
user: AuthUser | null,
): Promise<boolean> {
if (!user) return false;
return isMfaReady(await getDatabase(), user.id);
}
export async function targetCanReceiveAdministratorAuthority(
database: Parameters<typeof isMfaReady>[0],
userId: string,
): Promise<boolean> {
return isMfaReady(database, userId);
if (user.role !== 'admin') error(403, 'Administrator permission required');
}
+13 -84
View File
@@ -1,91 +1,20 @@
import type { Database } from '@tursodatabase/database';
/**
* Returns whether the account has the canonical unrestricted administrator
* relationship. The role column is a legacy projection and is not authority.
* Direct system.admin grants are intentionally not treated as full
* administration; they cannot bootstrap or escalate an account.
* Atomically promotes the authenticated user when no administrator exists.
* The conditional UPDATE ensures concurrent first sign-ins cannot both win.
*/
export async function isFullAdministrator(
export async function ensureBootstrapAdmin(
database: Database,
userId: string,
): Promise<boolean> {
const row = await (
await database.prepare(`
SELECT 1
FROM users
WHERE users.id=?
AND EXISTS (
SELECT 1
FROM user_roles
WHERE user_roles.user_id=users.id
AND user_roles.role_id='role-admin'
)
LIMIT 1
`)
).get(userId);
return Boolean(row);
}
/** Count active accounts holding the canonical unrestricted relationship. */
export async function countActiveFullAdministrators(
database: Database,
now = new Date(),
): Promise<number> {
const row = await (
await database.prepare(`
SELECT COUNT(DISTINCT users.id) AS count
FROM users
LEFT JOIN user_status ON user_status.user_id=users.id
LEFT JOIN deleted_accounts ON deleted_accounts.user_id=users.id
WHERE deleted_accounts.user_id IS NULL
AND user_status.blocked_at IS NULL
AND (
user_status.banned_until IS NULL
OR user_status.banned_until<=?
)
AND EXISTS (
SELECT 1 FROM user_roles
WHERE user_roles.user_id=users.id AND user_roles.role_id='role-admin'
)
`)
).get(now.toISOString());
const count = Number(row?.count);
if (!Number.isSafeInteger(count) || count < 0)
throw new Error('Unable to determine active administrator count.');
return count;
}
export async function hasActiveTotpFactor(
database: Database,
userId: string,
): Promise<boolean> {
const row = await (
await database.prepare(
"SELECT 1 FROM mfa_totp_factors WHERE user_id=? AND state='active' LIMIT 1",
)
).get(userId);
return Boolean(row);
}
export async function hasUnusedRecoveryCode(
database: Database,
userId: string,
): Promise<boolean> {
const row = await (
await database.prepare(
'SELECT 1 FROM mfa_recovery_codes WHERE user_id=? AND consumed_at IS NULL AND revoked_at IS NULL LIMIT 1',
)
).get(userId);
return Boolean(row);
}
export async function isMfaReady(
database: Database,
userId: string,
): Promise<boolean> {
return (
(await hasActiveTotpFactor(database, userId)) &&
(await hasUnusedRecoveryCode(database, userId))
);
): Promise<void> {
const promote = await database.prepare(`
UPDATE users
SET role = 'admin'
WHERE id = ?
AND NOT EXISTS (
SELECT 1 FROM users WHERE role = 'admin'
)
`);
await promote.run(userId);
}
-227
View File
@@ -1,227 +0,0 @@
import { env } from '$env/dynamic/private';
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
export const MFA_TOTP_PARAMETERS = {
algorithm: 'SHA1',
digits: 6,
periodSeconds: 30,
} as const;
const ENVELOPE_VERSION = 'mfa1';
const KEY_BYTES = 32;
const IV_BYTES = 12;
const TAG_BYTES = 16;
export type MfaEncryptionKey = {
id: string;
key: Buffer;
};
export class MfaCryptoError extends Error {
constructor() {
super('Unable to protect the MFA secret.');
this.name = 'MfaCryptoError';
}
}
export type DecryptedTotpSecret = {
secret: Buffer;
keyId: string;
needsRewrap: boolean;
};
type TotpAadContext = {
factorId: string;
userId: string;
};
function isCanonicalBase64Url(value: string): boolean {
if (!/^[A-Za-z0-9_-]+$/.test(value)) return false;
try {
const decoded = Buffer.from(value, 'base64url');
return (
decoded.length === KEY_BYTES && decoded.toString('base64url') === value
);
} catch {
return false;
}
}
/** Parse the app-only keyring. No fallback or generated key is permitted. */
export function parseMfaTotpEncryptionKeys(raw: string): MfaEncryptionKey[] {
const entries = raw.split(',').map((entry) => entry.trim());
if (
entries.length < 1 ||
entries.length > 3 ||
entries.some((entry) => !entry)
)
throw new MfaCryptoError();
const ids = new Set<string>();
const encodedKeys = new Set<string>();
const keys: MfaEncryptionKey[] = [];
for (const entry of entries) {
const separator = entry.indexOf(':');
const id = separator > 0 ? entry.slice(0, separator) : '';
const encoded = separator > 0 ? entry.slice(separator + 1) : '';
if (
!/^[A-Za-z0-9_-]{1,64}$/.test(id) ||
encoded.length !== 43 ||
!isCanonicalBase64Url(encoded) ||
ids.has(id) ||
encodedKeys.has(encoded)
)
throw new MfaCryptoError();
ids.add(id);
encodedKeys.add(encoded);
keys.push({ id, key: Buffer.from(encoded, 'base64url') });
}
return keys;
}
export function getMfaTotpEncryptionKeys(): MfaEncryptionKey[] {
const raw = env.MFA_TOTP_ENCRYPTION_KEYS?.trim();
if (!raw) throw new MfaCryptoError();
return parseMfaTotpEncryptionKeys(raw);
}
function aadFor({ factorId, userId }: TotpAadContext): Buffer {
if (!factorId || !userId) throw new MfaCryptoError();
return Buffer.from(
JSON.stringify({
version: ENVELOPE_VERSION,
factorId,
userId,
algorithm: MFA_TOTP_PARAMETERS.algorithm,
digits: MFA_TOTP_PARAMETERS.digits,
periodSeconds: MFA_TOTP_PARAMETERS.periodSeconds,
}),
'utf8',
);
}
function activeKey(keys: MfaEncryptionKey[]): MfaEncryptionKey {
const key = keys[0];
if (!key || key.key.length !== KEY_BYTES) throw new MfaCryptoError();
return key;
}
function envelopePart(value: Buffer): string {
return value.toString('base64url');
}
function decodeEnvelope(envelope: string): {
keyId: string;
iv: Buffer;
ciphertext: Buffer;
tag: Buffer;
} {
const parts = envelope.split('.');
if (parts.length !== 5 || parts[0] !== ENVELOPE_VERSION)
throw new MfaCryptoError();
const [, keyId, encodedIv, encodedCiphertext, encodedTag] = parts;
if (
!/^[A-Za-z0-9_-]{1,64}$/.test(keyId) ||
!encodedIv ||
!encodedCiphertext ||
!encodedTag
)
throw new MfaCryptoError();
try {
const iv = Buffer.from(encodedIv, 'base64url');
const ciphertext = Buffer.from(encodedCiphertext, 'base64url');
const tag = Buffer.from(encodedTag, 'base64url');
if (
iv.length !== IV_BYTES ||
ciphertext.length !== 20 ||
tag.length !== TAG_BYTES ||
iv.toString('base64url') !== encodedIv ||
ciphertext.toString('base64url') !== encodedCiphertext ||
tag.toString('base64url') !== encodedTag
)
throw new MfaCryptoError();
return { keyId, iv, ciphertext, tag };
} catch {
throw new MfaCryptoError();
}
}
function keyById(keys: MfaEncryptionKey[], id: string): MfaEncryptionKey {
const key = keys.find((candidate) => candidate.id === id);
if (!key || key.key.length !== KEY_BYTES) throw new MfaCryptoError();
return key;
}
export function encryptTotpSecret(
context: TotpAadContext & { secret: Uint8Array },
keys: MfaEncryptionKey[] = getMfaTotpEncryptionKeys(),
): string {
try {
if (context.secret.length !== 20) throw new MfaCryptoError();
const key = activeKey(keys);
const iv = randomBytes(IV_BYTES);
const cipher = createCipheriv('aes-256-gcm', key.key, iv);
cipher.setAAD(aadFor(context));
const ciphertext = Buffer.concat([
cipher.update(context.secret),
cipher.final(),
]);
const tag = cipher.getAuthTag();
return [
ENVELOPE_VERSION,
key.id,
envelopePart(iv),
envelopePart(ciphertext),
envelopePart(tag),
].join('.');
} catch (error) {
if (error instanceof MfaCryptoError) throw error;
throw new MfaCryptoError();
}
}
export function decryptTotpSecret(
context: TotpAadContext & { envelope: string },
keys: MfaEncryptionKey[] = getMfaTotpEncryptionKeys(),
): DecryptedTotpSecret {
try {
const envelope = decodeEnvelope(context.envelope);
const key = keyById(keys, envelope.keyId);
const decipher = createDecipheriv('aes-256-gcm', key.key, envelope.iv);
decipher.setAAD(aadFor(context));
decipher.setAuthTag(envelope.tag);
const secret = Buffer.concat([
decipher.update(envelope.ciphertext),
decipher.final(),
]);
if (secret.length !== 20) throw new MfaCryptoError();
return {
secret,
keyId: key.id,
needsRewrap: key.id !== activeKey(keys).id,
};
} catch (error) {
if (error instanceof MfaCryptoError) throw error;
throw new MfaCryptoError();
}
}
export function rewrapTotpSecret(
context: TotpAadContext & { envelope: string },
keys: MfaEncryptionKey[] = getMfaTotpEncryptionKeys(),
): { envelope: string; previousKeyId: string; activeKeyId: string } {
const decrypted = decryptTotpSecret(context, keys);
const active = activeKey(keys);
return {
envelope: encryptTotpSecret(
{
factorId: context.factorId,
userId: context.userId,
secret: decrypted.secret,
},
keys,
),
previousKeyId: decrypted.keyId,
activeKeyId: active.id,
};
}
-397
View File
@@ -1,397 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { connect, type Database } from '@tursodatabase/database';
import { Secret } from 'otpauth';
const { keyA, keyB } = vi.hoisted(() => ({
keyA: Buffer.alloc(32, 0x11).toString('base64url'),
keyB: Buffer.alloc(32, 0x22).toString('base64url'),
}));
vi.mock('$env/dynamic/private', () => ({
env: {
MFA_TOTP_ENCRYPTION_KEYS: `active:${keyA},retained:${keyB}`,
},
}));
import {
decryptTotpSecret,
encryptTotpSecret,
parseMfaTotpEncryptionKeys,
rewrapTotpSecret,
MfaCryptoError,
} from './mfa-crypto';
import {
beginTotpEnrollment,
generateTotpCode,
verifyTotpFactor,
} from './mfa-totp';
import {
consumeRecoveryCode,
formatRecoveryCode,
issueRecoveryCodes,
normalizeRecoveryCode,
} from './mfa-recovery';
import {
consumeAuthenticationTransaction,
createAuthenticationTransaction,
getAuthenticationTransaction,
recordAuthenticationAttempt,
validateAuthenticationReturnPath,
} from './authentication-transactions';
const now = new Date('2026-08-07T12:00:00.000Z');
function cookieJar() {
const values = new Map<string, string>();
return {
values,
get: (name: string) => values.get(name),
set: vi.fn((name: string, value: string) => values.set(name, value)),
delete: vi.fn((name: string) => values.delete(name)),
};
}
async function mfaDatabase(userId = 'user-1'): Promise<Database> {
const database = await connect(':memory:');
await database.exec(`
CREATE TABLE users (id TEXT PRIMARY KEY);
INSERT INTO users(id) VALUES ('${userId}');
CREATE TABLE mfa_totp_factors (
id TEXT PRIMARY KEY, user_id TEXT NOT NULL, state TEXT NOT NULL,
encrypted_secret TEXT NOT NULL, encryption_key_id TEXT NOT NULL,
issuer TEXT NOT NULL, account_label TEXT NOT NULL, algorithm TEXT NOT NULL,
digits INTEGER NOT NULL, period_seconds INTEGER NOT NULL,
last_counter INTEGER, failed_attempts INTEGER NOT NULL DEFAULT 0,
locked_until TEXT, expires_at TEXT, created_at TEXT NOT NULL,
activated_at TEXT, revoked_at TEXT
);
CREATE TABLE mfa_recovery_codes (
id TEXT PRIMARY KEY, user_id TEXT NOT NULL, code_hash TEXT NOT NULL,
created_at TEXT NOT NULL, consumed_at TEXT, revoked_at TEXT
);
`);
return database;
}
async function transactionDatabase(): Promise<Database> {
const database = await connect(':memory:');
await database.exec(`
CREATE TABLE authentication_transactions (
id TEXT PRIMARY KEY, token_hash TEXT NOT NULL UNIQUE, user_id TEXT NOT NULL,
provider TEXT, kind TEXT NOT NULL, return_path TEXT NOT NULL, required_aal INTEGER NOT NULL,
attempt_count INTEGER NOT NULL, expires_at TEXT NOT NULL, consumed_at TEXT,
created_at TEXT NOT NULL
);
`);
return database;
}
afterEach(() => vi.restoreAllMocks());
describe('MFA encryption foundation', () => {
it('rejects malformed keyrings and reports rotation without exposing keys', () => {
expect(() => parseMfaTotpEncryptionKeys('')).toThrow(MfaCryptoError);
expect(() => parseMfaTotpEncryptionKeys(`one:${keyA},two:${keyA}`)).toThrow(
MfaCryptoError,
);
expect(() =>
parseMfaTotpEncryptionKeys(`one:${keyA}=,two:${keyB}`),
).toThrow(MfaCryptoError);
const secret = Buffer.alloc(20, 0x33);
const oldKeys = parseMfaTotpEncryptionKeys(`old:${keyB},active:${keyA}`);
const envelope = encryptTotpSecret(
{ factorId: 'factor-1', userId: 'user-1', secret },
oldKeys,
);
const decrypted = decryptTotpSecret(
{ factorId: 'factor-1', userId: 'user-1', envelope },
parseMfaTotpEncryptionKeys(`active:${keyA},old:${keyB}`),
);
expect(decrypted.secret).toEqual(secret);
expect(decrypted.needsRewrap).toBe(true);
const rewrapped = rewrapTotpSecret(
{ factorId: 'factor-1', userId: 'user-1', envelope },
parseMfaTotpEncryptionKeys(`active:${keyA},old:${keyB}`),
);
expect(rewrapped.previousKeyId).toBe('old');
expect(rewrapped.activeKeyId).toBe('active');
expect(() =>
decryptTotpSecret(
{ factorId: 'factor-2', userId: 'user-1', envelope },
oldKeys,
),
).toThrow(MfaCryptoError);
expect(() =>
decryptTotpSecret(
{ factorId: 'factor-1', userId: 'user-1', envelope: `${envelope}x` },
oldKeys,
),
).toThrow(MfaCryptoError);
});
});
describe('TOTP factors', () => {
let database: Database;
beforeEach(async () => {
database = await mfaDatabase();
});
afterEach(async () => database.close());
it('uses the one-period window and atomically rejects counter replay', async () => {
const enrollment = await beginTotpEnrollment(database, {
userId: 'user-1',
now,
});
const secret = Secret.fromBase32(enrollment.secretBase32).bytes;
const nextPeriodCode = generateTotpCode(secret, now.getTime() + 30_000);
const verified = await verifyTotpFactor(database, {
userId: 'user-1',
factorId: enrollment.factorId,
token: nextPeriodCode,
now,
});
expect(verified.status).toBe('verified');
const replay = await verifyTotpFactor(database, {
userId: 'user-1',
factorId: enrollment.factorId,
token: nextPeriodCode,
now,
});
expect(replay.status).toBe('replayed');
});
it('locks after five failures and expires pending enrollment', async () => {
const enrollment = await beginTotpEnrollment(database, {
userId: 'user-1',
now,
});
for (let attempt = 0; attempt < 5; attempt += 1) {
await verifyTotpFactor(database, {
userId: 'user-1',
factorId: enrollment.factorId,
token: '000000',
now,
});
}
const locked = await verifyTotpFactor(database, {
userId: 'user-1',
factorId: enrollment.factorId,
token: '000000',
now,
});
expect(locked.status).toBe('locked');
const expired = await verifyTotpFactor(database, {
userId: 'user-1',
factorId: enrollment.factorId,
token: '000000',
now: new Date(now.getTime() + 11 * 60_000),
});
expect(expired.status).toBe('expired');
});
it('rewraps a verified factor under the active encryption key atomically', async () => {
const secret = Buffer.alloc(20, 0x44);
const factorId = 'factor-old-key';
const oldEnvelope = encryptTotpSecret(
{ factorId, userId: 'user-1', secret },
parseMfaTotpEncryptionKeys(`retained:${keyB},active:${keyA}`),
);
await (
await database.prepare(
`INSERT INTO mfa_totp_factors(
id,user_id,state,encrypted_secret,encryption_key_id,issuer,account_label,
algorithm,digits,period_seconds,failed_attempts,created_at,activated_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`,
)
).run(
factorId,
'user-1',
'active',
oldEnvelope,
'retained',
'SHD.build',
'user-1',
'SHA1',
6,
30,
0,
now.toISOString(),
now.toISOString(),
);
const result = await verifyTotpFactor(database, {
userId: 'user-1',
factorId,
token: generateTotpCode(secret, now.getTime()),
now,
});
expect(result).toMatchObject({
status: 'verified',
needsRewrap: true,
keyId: 'retained',
});
const row = await (
await database.prepare(
'SELECT encrypted_secret,encryption_key_id FROM mfa_totp_factors WHERE id=?',
)
).get(factorId);
expect(row.encryption_key_id).toBe('active');
expect(row.encrypted_secret).not.toBe(oldEnvelope);
expect(
decryptTotpSecret(
{
factorId,
userId: 'user-1',
envelope: String(row.encrypted_secret),
},
parseMfaTotpEncryptionKeys(`active:${keyA},retained:${keyB}`),
).secret,
).toEqual(secret);
});
});
describe('recovery codes', () => {
let database: Database;
beforeEach(async () => {
database = await mfaDatabase();
});
afterEach(async () => database.close());
it('issues ten formatted codes and consumes one atomically', async () => {
const issued = await issueRecoveryCodes(database, {
userId: 'user-1',
now,
});
expect(issued.codes).toHaveLength(10);
expect(issued.codes[0]).toMatch(/^[0-9A-F]{4}(?:-[0-9A-F]{4}){7}$/);
expect(normalizeRecoveryCode(issued.codes[0])).toHaveLength(32);
expect(formatRecoveryCode(normalizeRecoveryCode(issued.codes[0])!)).toBe(
issued.codes[0],
);
expect(
await consumeRecoveryCode(database, {
userId: 'user-1',
code: issued.codes[0],
now,
}),
).toBe(true);
expect(
await consumeRecoveryCode(database, {
userId: 'user-1',
code: issued.codes[0],
now,
}),
).toBe(false);
});
it('revokes unused codes when regenerated', async () => {
await issueRecoveryCodes(database, { userId: 'user-1', now });
await issueRecoveryCodes(database, {
userId: 'user-1',
now: new Date(now.getTime() + 1_000),
});
const revoked = await (
await database.prepare(
'SELECT COUNT(*) AS count FROM mfa_recovery_codes WHERE revoked_at IS NOT NULL',
)
).get();
expect(Number(revoked.count)).toBe(10);
});
});
describe('authentication transactions', () => {
let database: Database;
beforeEach(async () => {
database = await transactionDatabase();
});
afterEach(async () => database.close());
it('enforces local return paths, five attempts, and one-time consumption', async () => {
expect(validateAuthenticationReturnPath('/builder?tab=weapons')).toBe(
'/builder?tab=weapons',
);
expect(
validateAuthenticationReturnPath('https://evil.example/'),
).toBeNull();
expect(validateAuthenticationReturnPath('//evil.example')).toBeNull();
expect(validateAuthenticationReturnPath('/%2F%2Fevil.example')).toBeNull();
const cookies = cookieJar();
const transaction = await createAuthenticationTransaction(
cookies as never,
database,
{
userId: 'user-1',
kind: 'login',
provider: 'password',
returnPath: '/builder',
now,
},
);
expect(cookies.set).toHaveBeenCalledWith(
'shd_auth_tx',
expect.any(String),
expect.objectContaining({
path: '/auth/two-factor',
httpOnly: true,
sameSite: 'lax',
maxAge: 300,
}),
);
expect(transaction.provider).toBe('password');
const stored = await (
await database.prepare(
'SELECT token_hash FROM authentication_transactions',
)
).get();
expect(String(stored.token_hash)).not.toBe(
cookies.values.get('shd_auth_tx'),
);
for (let attempt = 0; attempt < 5; attempt += 1) {
expect(
(await recordAuthenticationAttempt(cookies as never, database, now))
.accepted,
).toBe(true);
}
expect(
await getAuthenticationTransaction(cookies as never, database, now),
).toBeNull();
const secondCookies = cookieJar();
const second = await createAuthenticationTransaction(
secondCookies as never,
database,
{
userId: 'user-1',
kind: 'step_up',
returnPath: '/account/security',
now,
},
);
const consumed = await consumeAuthenticationTransaction(
secondCookies as never,
database,
now,
);
expect(consumed).toMatchObject({
id: second.id,
kind: 'step_up',
requiredAal: 2,
});
expect(
await consumeAuthenticationTransaction(
secondCookies as never,
database,
now,
),
).toBeNull();
});
});
-157
View File
@@ -1,157 +0,0 @@
import { getDatabase } from '$lib/server/database';
import type { Database } from '@tursodatabase/database';
import { createHash, randomBytes, randomUUID } from 'node:crypto';
export const RECOVERY_CODE_COUNT = 10;
export const RECOVERY_CODE_BYTES = 16;
const RECOVERY_CODE_DOMAIN = 'shd.build:mfa-recovery-code:v1';
export type RecoveryDatabase = Pick<Database, 'prepare' | 'transactionAsync'>;
export type RecoveryTransaction = Pick<Database, 'prepare'>;
export class RecoveryCodeError extends Error {
constructor(message = 'Unable to process recovery codes.') {
super(message);
this.name = 'RecoveryCodeError';
}
}
export type IssuedRecoveryCodes = {
codes: string[];
createdAt: string;
};
function databaseOrDefault(
database?: RecoveryDatabase,
): Promise<RecoveryDatabase> {
return database
? Promise.resolve(database)
: (getDatabase() as Promise<RecoveryDatabase>);
}
function timestamp(value: Date | string | number | undefined): string {
const date =
value instanceof Date ? new Date(value) : new Date(value ?? Date.now());
if (!Number.isFinite(date.getTime())) throw new RecoveryCodeError();
return date.toISOString();
}
/** Return the canonical code used for hashing, or null for malformed input. */
export function normalizeRecoveryCode(input: string): string | null {
if (typeof input !== 'string') return null;
const normalized = input
.normalize('NFKC')
.replace(/[\s-]+/gu, '')
.toUpperCase();
return /^[0-9A-F]{32}$/.test(normalized) ? normalized : null;
}
/** Add display separators without changing the canonical validation format. */
export function formatRecoveryCode(canonicalCode: string): string {
const normalized = normalizeRecoveryCode(canonicalCode);
if (!normalized) throw new RecoveryCodeError();
return normalized.match(/.{1,4}/g)?.join('-') ?? normalized;
}
export function generateRecoveryCode(): { canonical: string; display: string } {
const canonical = randomBytes(RECOVERY_CODE_BYTES)
.toString('hex')
.toUpperCase();
return { canonical, display: formatRecoveryCode(canonical) };
}
export function hashRecoveryCode(userId: string, code: string): string {
const normalized = normalizeRecoveryCode(code);
if (!userId || !normalized) throw new RecoveryCodeError();
return createHash('sha256')
.update(RECOVERY_CODE_DOMAIN, 'utf8')
.update('\0', 'utf8')
.update(userId, 'utf8')
.update('\0', 'utf8')
.update(normalized, 'utf8')
.digest('hex');
}
export async function issueRecoveryCodesInTransaction(
transaction: RecoveryTransaction,
options: { userId: string; now?: Date | string | number },
): Promise<IssuedRecoveryCodes> {
if (!options.userId) throw new RecoveryCodeError();
const createdAt = timestamp(options.now);
const generated = Array.from(
{ length: RECOVERY_CODE_COUNT },
generateRecoveryCode,
);
await (
await transaction.prepare(
'UPDATE mfa_recovery_codes SET revoked_at=? WHERE user_id=? AND consumed_at IS NULL AND revoked_at IS NULL',
)
).run(createdAt, options.userId);
for (const code of generated) {
await (
await transaction.prepare(
'INSERT INTO mfa_recovery_codes(id,user_id,code_hash,created_at) VALUES(?,?,?,?)',
)
).run(
randomUUID(),
options.userId,
hashRecoveryCode(options.userId, code.canonical),
createdAt,
);
}
return { codes: generated.map((code) => code.display), createdAt };
}
export async function issueRecoveryCodes(
databaseInput: RecoveryDatabase | undefined,
options: { userId: string; now?: Date | string | number },
): Promise<IssuedRecoveryCodes> {
if (!options.userId) throw new RecoveryCodeError();
const database = await databaseOrDefault(databaseInput);
const issued = database.transactionAsync(async (transaction) => {
return issueRecoveryCodesInTransaction(transaction, options);
});
return await issued.immediate();
}
export const regenerateRecoveryCodes = issueRecoveryCodes;
export async function consumeRecoveryCode(
databaseInput: RecoveryDatabase | undefined,
options: { userId: string; code: string; now?: Date | string | number },
): Promise<boolean> {
const normalized = normalizeRecoveryCode(options.code);
if (!normalized || !options.userId) return false;
const database = await databaseOrDefault(databaseInput);
const consumed = database.transactionAsync((transaction) =>
consumeRecoveryCodeInTransaction(transaction, {
...options,
code: normalized,
}),
);
return await consumed.immediate();
}
/** Consume one recovery code using the caller's transaction. */
export async function consumeRecoveryCodeInTransaction(
transaction: RecoveryTransaction,
options: { userId: string; code: string; now?: Date | string | number },
): Promise<boolean> {
const normalized = normalizeRecoveryCode(options.code);
if (!normalized || !options.userId) return false;
const consumedAt = timestamp(options.now);
const result = await (
await transaction.prepare(
`UPDATE mfa_recovery_codes
SET consumed_at=?
WHERE user_id=? AND code_hash=? AND consumed_at IS NULL AND revoked_at IS NULL`,
)
).run(
consumedAt,
options.userId,
hashRecoveryCode(options.userId, normalized),
);
return result.changes === 1;
}
export const useRecoveryCode = consumeRecoveryCode;
-416
View File
@@ -1,416 +0,0 @@
import { getDatabase } from '$lib/server/database';
import type { Database } from '@tursodatabase/database';
import { randomBytes, randomUUID } from 'node:crypto';
import { Secret, TOTP } from 'otpauth';
import {
decryptTotpSecret,
encryptTotpSecret,
getMfaTotpEncryptionKeys,
MFA_TOTP_PARAMETERS,
rewrapTotpSecret,
} from './mfa-crypto';
export const TOTP_ISSUER = 'SHD.build';
export const TOTP_SECRET_BYTES = 20;
export const TOTP_WINDOW = 1;
export const TOTP_PENDING_SECONDS = 10 * 60;
export const TOTP_FAILURE_LIMIT = 5;
export const TOTP_LOCK_SECONDS = 5 * 60;
export type TotpDatabase = Pick<Database, 'prepare' | 'transactionAsync'>;
export type TotpTransaction = Pick<Database, 'prepare'>;
export class TotpServiceError extends Error {
constructor(message = 'Unable to process the TOTP factor.') {
super(message);
this.name = 'TotpServiceError';
}
}
export type TotpEnrollment = {
factorId: string;
secretBase32: string;
provisioningUri: string;
expiresAt: string;
replacedFactorId?: string;
};
export type TotpEnrollmentOptions = {
userId: string;
accountLabel?: string;
now?: Date | string | number;
replaceActive?: boolean;
};
export type TotpVerificationResult =
| {
status: 'verified';
counter: number;
needsRewrap: boolean;
keyId: string;
}
| {
status: 'invalid' | 'replayed' | 'expired';
lockedUntil: string | null;
}
| {
status: 'locked';
lockedUntil: string;
};
export type TotpVerificationOptions = {
userId: string;
factorId: string;
token: string;
now?: Date | string | number;
};
type TotpFactorRow = {
id: string;
user_id: string;
state: 'pending' | 'active' | 'revoked';
encrypted_secret: string;
encryption_key_id: string;
issuer: string;
account_label: string;
last_counter: number | null;
failed_attempts: number;
locked_until: string | null;
expires_at: string | null;
};
function databaseOrDefault(database?: TotpDatabase): Promise<TotpDatabase> {
return database
? Promise.resolve(database)
: (getDatabase() as Promise<TotpDatabase>);
}
function asTimestamp(value: Date | string | number | undefined): Date {
const result =
value instanceof Date
? new Date(value.getTime())
: new Date(value ?? Date.now());
if (!Number.isFinite(result.getTime())) throw new TotpServiceError();
return result;
}
function toSecret(secret: Uint8Array): Secret {
if (secret.length !== TOTP_SECRET_BYTES) throw new TotpServiceError();
const bytes = Uint8Array.from(secret);
return new Secret({ buffer: bytes.buffer as ArrayBuffer });
}
function totpFor(secret: Uint8Array, label: string): TOTP {
return new TOTP({
issuer: TOTP_ISSUER,
label,
issuerInLabel: true,
secret: toSecret(secret),
algorithm: MFA_TOTP_PARAMETERS.algorithm,
digits: MFA_TOTP_PARAMETERS.digits,
period: MFA_TOTP_PARAMETERS.periodSeconds,
});
}
export function generateTotpSecret(): Buffer {
return randomBytes(TOTP_SECRET_BYTES);
}
export function generateTotpCode(
secret: Uint8Array,
timestamp = Date.now(),
): string {
return totpFor(secret, TOTP_ISSUER).generate({ timestamp });
}
export function validateTotpCode(
secret: Uint8Array,
token: string,
timestamp = Date.now(),
): number | null {
if (!/^\d{6}$/.test(token)) return null;
return totpFor(secret, TOTP_ISSUER).validate({
token,
timestamp,
window: TOTP_WINDOW,
});
}
export function totpCounter(timestamp = Date.now()): number {
return TOTP.counter({
period: MFA_TOTP_PARAMETERS.periodSeconds,
timestamp,
});
}
function provisioningUri(secret: Uint8Array, label: string): string {
return totpFor(secret, label).toString();
}
export async function beginTotpEnrollmentInTransaction(
transaction: TotpTransaction,
options: TotpEnrollmentOptions,
): Promise<TotpEnrollment> {
if (!options.userId || options.userId.length > 200)
throw new TotpServiceError();
const now = asTimestamp(options.now);
const nowIso = now.toISOString();
const expiresAt = new Date(
now.getTime() + TOTP_PENDING_SECONDS * 1000,
).toISOString();
const factorId = randomUUID();
const accountLabel = (options.accountLabel ?? options.userId).trim();
if (!accountLabel || accountLabel.length > 200) throw new TotpServiceError();
const secret = generateTotpSecret();
const keys = getMfaTotpEncryptionKeys();
const encryptedSecret = encryptTotpSecret(
{ factorId, userId: options.userId, secret },
keys,
);
const current = (await (
await transaction.prepare(
"SELECT id,state,expires_at FROM mfa_totp_factors WHERE user_id=? AND state IN ('pending','active')",
)
).all(options.userId)) as Array<{
id: string;
state: 'pending' | 'active';
expires_at: string | null;
}>;
const pending = current.find((row) => row.state === 'pending');
if (pending && (!pending.expires_at || pending.expires_at <= nowIso)) {
await (
await transaction.prepare(
"UPDATE mfa_totp_factors SET state='revoked',revoked_at=? WHERE id=? AND user_id=? AND state='pending'",
)
).run(nowIso, pending.id, options.userId);
} else if (pending) {
throw new TotpServiceError();
}
const active = current.find((row) => row.state === 'active');
if (active && !options.replaceActive) throw new TotpServiceError();
await (
await transaction.prepare(
`INSERT INTO mfa_totp_factors(
id,user_id,state,encrypted_secret,encryption_key_id,issuer,account_label,
algorithm,digits,period_seconds,failed_attempts,expires_at,created_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`,
)
).run(
factorId,
options.userId,
'pending',
encryptedSecret,
keys[0].id,
TOTP_ISSUER,
accountLabel,
MFA_TOTP_PARAMETERS.algorithm,
MFA_TOTP_PARAMETERS.digits,
MFA_TOTP_PARAMETERS.periodSeconds,
0,
expiresAt,
nowIso,
);
return {
factorId,
secretBase32: toSecret(secret).base32,
provisioningUri: provisioningUri(secret, accountLabel),
expiresAt,
...(active ? { replacedFactorId: active.id } : {}),
};
}
export async function beginTotpEnrollment(
databaseInput: TotpDatabase | undefined,
options: TotpEnrollmentOptions,
): Promise<TotpEnrollment> {
const database = await databaseOrDefault(databaseInput);
const insert = database.transactionAsync(
async (transaction) =>
await beginTotpEnrollmentInTransaction(transaction, options),
);
return await insert.immediate();
}
export const startTotpEnrollment = beginTotpEnrollment;
function lockedUntilDate(row: TotpFactorRow, now: Date): string | null {
if (!row.locked_until) return null;
return new Date(row.locked_until) > now ? row.locked_until : null;
}
export async function verifyTotpFactorInTransaction(
transaction: TotpTransaction,
options: TotpVerificationOptions,
pendingOnly = false,
activatePending = true,
): Promise<TotpVerificationResult> {
const now = asTimestamp(options.now);
const nowIso = now.toISOString();
const lockUntil = new Date(
now.getTime() + TOTP_LOCK_SECONDS * 1000,
).toISOString();
const row = (await (
await transaction.prepare(
'SELECT id,user_id,state,encrypted_secret,encryption_key_id,issuer,account_label,last_counter,failed_attempts,locked_until,expires_at FROM mfa_totp_factors WHERE id=? AND user_id=? LIMIT 1',
)
).get(options.factorId, options.userId)) as TotpFactorRow | undefined;
if (
!row ||
row.state === 'revoked' ||
(pendingOnly && row.state !== 'pending')
)
return { status: 'invalid', lockedUntil: null } as const;
if (
row.state === 'pending' &&
(!row.expires_at || row.expires_at <= nowIso)
) {
await (
await transaction.prepare(
"UPDATE mfa_totp_factors SET state='revoked',revoked_at=? WHERE id=? AND state='pending'",
)
).run(nowIso, row.id);
return { status: 'expired', lockedUntil: null } as const;
}
const existingLock = lockedUntilDate(row, now);
if (existingLock)
return { status: 'locked', lockedUntil: existingLock } as const;
let decrypted;
try {
decrypted = decryptTotpSecret(
{
factorId: row.id,
userId: row.user_id,
envelope: row.encrypted_secret,
},
getMfaTotpEncryptionKeys(),
);
} catch {
throw new TotpServiceError();
}
const delta = validateTotpCode(
decrypted.secret,
options.token,
now.getTime(),
);
const currentCounter = totpCounter(now.getTime());
const matchedCounter = delta === null ? null : currentCounter + delta;
if (matchedCounter !== null) {
const update =
pendingOnly && !activatePending
? `UPDATE mfa_totp_factors
SET last_counter=?,failed_attempts=0,locked_until=NULL
WHERE id=? AND user_id=? AND state='pending'
AND (last_counter IS NULL OR last_counter<?)
AND (locked_until IS NULL OR locked_until<=?)`
: `UPDATE mfa_totp_factors
SET last_counter=?,failed_attempts=0,locked_until=NULL,
state=CASE WHEN state='pending' THEN 'active' ELSE state END,
expires_at=CASE WHEN state='pending' THEN NULL ELSE expires_at END,
activated_at=CASE WHEN state='pending' THEN ? ELSE activated_at END
WHERE id=? AND user_id=? AND state IN ('pending','active')
AND (last_counter IS NULL OR last_counter<?)
AND (locked_until IS NULL OR locked_until<=?)`;
const updated = await (
await transaction.prepare(update)
).run(
...(pendingOnly && !activatePending
? [matchedCounter, row.id, options.userId, matchedCounter, nowIso]
: [
matchedCounter,
nowIso,
row.id,
options.userId,
matchedCounter,
nowIso,
]),
);
if (updated.changes === 1) {
if (decrypted.needsRewrap) {
const rewrapped = rewrapTotpSecret(
{
factorId: row.id,
userId: row.user_id,
envelope: row.encrypted_secret,
},
getMfaTotpEncryptionKeys(),
);
const rewrappedRow = await (
await transaction.prepare(
`UPDATE mfa_totp_factors
SET encrypted_secret=?,encryption_key_id=?
WHERE id=? AND user_id=? AND state IN ('pending','active')`,
)
).run(
rewrapped.envelope,
rewrapped.activeKeyId,
row.id,
options.userId,
);
if (rewrappedRow.changes !== 1) throw new TotpServiceError();
}
return {
status: 'verified',
counter: matchedCounter,
needsRewrap: decrypted.needsRewrap,
keyId: decrypted.keyId,
} as const;
}
return { status: 'replayed', lockedUntil: null } as const;
}
const failedAttempts =
row.locked_until && row.locked_until <= nowIso
? 1
: row.failed_attempts + 1;
const locked = failedAttempts >= TOTP_FAILURE_LIMIT;
await (
await transaction.prepare(
`UPDATE mfa_totp_factors
SET failed_attempts=?,locked_until=?
WHERE id=? AND user_id=? AND state IN ('pending','active')
AND (locked_until IS NULL OR locked_until<=?)`,
)
).run(
failedAttempts,
locked ? lockUntil : null,
row.id,
options.userId,
nowIso,
);
return {
status: 'invalid',
lockedUntil: locked ? lockUntil : null,
} as const;
}
export async function verifyTotpFactor(
databaseInput: TotpDatabase | undefined,
options: TotpVerificationOptions,
): Promise<TotpVerificationResult> {
const database = await databaseOrDefault(databaseInput);
const verify = database.transactionAsync((transaction) =>
verifyTotpFactorInTransaction(transaction, options),
);
return await verify.immediate();
}
export const verifyTotp = verifyTotpFactor;
export async function revokeTotpFactor(
databaseInput: TotpDatabase | undefined,
options: { userId: string; factorId: string; now?: Date | string | number },
): Promise<boolean> {
const database = await databaseOrDefault(databaseInput);
const now = asTimestamp(options.now).toISOString();
const result = await (
await database.prepare(
"UPDATE mfa_totp_factors SET state='revoked',revoked_at=? WHERE id=? AND user_id=? AND state IN ('pending','active')",
)
).run(now, options.factorId, options.userId);
return result.changes === 1;
}
@@ -1,104 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
database: { prepare: vi.fn() },
hasActiveTotpFactor: vi.fn(),
isFullAdministrator: vi.fn(),
createAuthenticationTransaction: vi.fn(),
createSession: vi.fn(),
recordLogin: vi.fn(),
}));
vi.mock('./bootstrap', () => ({
hasActiveTotpFactor: mocks.hasActiveTotpFactor,
isFullAdministrator: mocks.isFullAdministrator,
}));
vi.mock('./authentication-transactions', () => ({
createAuthenticationTransaction: mocks.createAuthenticationTransaction,
}));
vi.mock('./session', () => ({
createSession: mocks.createSession,
recordLogin: mocks.recordLogin,
}));
import { completePrimaryAuthentication } from './primary-authentication';
const providers = ['password', 'magic_link', 'discord', 'passkey'] as const;
describe('primary authentication completion', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.database.prepare.mockResolvedValue({
get: vi.fn(async () => ({ id: 'user-1' })),
});
mocks.hasActiveTotpFactor.mockResolvedValue(true);
mocks.isFullAdministrator.mockResolvedValue(false);
mocks.createAuthenticationTransaction.mockResolvedValue({
id: 'tx-1',
userId: 'user-1',
provider: 'password',
kind: 'login',
returnPath: '/account',
requiredAal: 2,
attemptCount: 0,
expiresAt: '2026-08-07T12:05:00.000Z',
});
mocks.createSession.mockResolvedValue('session-1');
});
it.each(providers)(
'cannot bypass active MFA after %s verification',
async (provider) => {
const result = await completePrimaryAuthentication({
database: mocks.database as never,
cookies: {} as never,
userId: 'user-1',
provider,
returnPath: '/account',
});
expect(result).toMatchObject({
kind: 'mfa',
redirectTo: '/auth/two-factor',
});
expect(mocks.createSession).not.toHaveBeenCalled();
expect(mocks.createAuthenticationTransaction).toHaveBeenCalledWith(
{},
mocks.database,
expect.objectContaining({
userId: 'user-1',
kind: 'login',
provider,
}),
);
expect(mocks.recordLogin).toHaveBeenCalledWith(
'user-1',
provider,
false,
expect.objectContaining({
failureReason: 'mfa_required',
riskFlags: ['primary_authenticated_mfa_required'],
}),
);
},
);
it('gives an unenrolled administrator only an enrollment session', async () => {
mocks.hasActiveTotpFactor.mockResolvedValue(false);
mocks.isFullAdministrator.mockResolvedValue(true);
const result = await completePrimaryAuthentication({
database: mocks.database as never,
cookies: {} as never,
userId: 'user-1',
provider: 'password',
});
expect(result).toMatchObject({
kind: 'session',
aal: 1,
redirectTo: '/account/security?required=admin',
});
expect(mocks.createAuthenticationTransaction).not.toHaveBeenCalled();
});
});
@@ -1,120 +0,0 @@
import type { Database } from '@tursodatabase/database';
import type { Cookies } from '@sveltejs/kit';
import { hasActiveTotpFactor, isFullAdministrator } from './bootstrap';
import {
createAuthenticationTransaction,
type AuthenticationTransaction,
} from './authentication-transactions';
import { createSession, recordLogin, type SessionAuthLevel } from './session';
export type PrimaryAuthenticationProvider =
'password' | 'discord' | 'magic_link' | 'passkey';
export class PrimaryAuthenticationError extends Error {
readonly code: 'account_restricted' | 'account_missing';
constructor(code: 'account_restricted' | 'account_missing') {
super('This account is not permitted to sign in.');
this.name = 'PrimaryAuthenticationError';
this.code = code;
}
}
export type PrimaryAuthenticationResult =
| {
kind: 'session';
sessionId: string;
aal: SessionAuthLevel;
redirectTo: string;
}
| {
kind: 'mfa';
transaction: AuthenticationTransaction;
redirectTo: '/auth/two-factor';
};
export type CompletePrimaryAuthenticationInput = {
database: Database;
cookies: Cookies;
userId: string;
provider: PrimaryAuthenticationProvider;
request?: Request;
getClientAddress?: () => string;
credentialId?: string | null;
returnPath?: string;
};
/**
* Completes a verified password, email, Discord, or passkey identity. This is
* the only primary-auth path allowed to create a session. Accounts with an
* active TOTP factor receive an opaque MFA transaction instead.
*/
export async function completePrimaryAuthentication(
input: CompletePrimaryAuthenticationInput,
): Promise<PrimaryAuthenticationResult> {
const status = await (
await input.database.prepare(`
SELECT users.id,user_status.blocked_at,user_status.banned_until,
deleted_accounts.deleted_at
FROM users
LEFT JOIN user_status ON user_status.user_id=users.id
LEFT JOIN deleted_accounts ON deleted_accounts.user_id=users.id
WHERE users.id=?
`)
).get(input.userId);
const banned =
typeof status?.banned_until === 'string' &&
new Date(status.banned_until) > new Date();
if (!status) throw new PrimaryAuthenticationError('account_missing');
if (status.deleted_at || status.blocked_at || banned) {
await recordLogin(input.userId, input.provider, false, {
request: input.request,
getClientAddress: input.getClientAddress,
credentialId: input.credentialId,
failureReason: 'account_restricted',
});
throw new PrimaryAuthenticationError('account_restricted');
}
const activeFactor = await hasActiveTotpFactor(input.database, input.userId);
const fullAdministrator = await isFullAdministrator(
input.database,
input.userId,
);
if (!activeFactor) {
const sessionId = await createSession(input.cookies, input.userId, {
aal: 1,
});
const redirectTo = fullAdministrator
? '/account/security?required=admin'
: (input.returnPath ?? '/account');
await recordLogin(input.userId, input.provider, true, {
request: input.request,
getClientAddress: input.getClientAddress,
credentialId: input.credentialId,
sessionId,
aal: 1,
});
return { kind: 'session', sessionId, aal: 1, redirectTo };
}
const transaction = await createAuthenticationTransaction(
input.cookies,
input.database,
{
userId: input.userId,
kind: 'login',
provider: input.provider,
returnPath: input.returnPath ?? '/account',
},
);
await recordLogin(input.userId, input.provider, false, {
request: input.request,
getClientAddress: input.getClientAddress,
credentialId: input.credentialId,
failureReason: 'mfa_required',
riskFlags: ['primary_authenticated_mfa_required'],
aal: 1,
});
return { kind: 'mfa', transaction, redirectTo: '/auth/two-factor' };
}
-103
View File
@@ -1,103 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { connect, type Database } from '@tursodatabase/database';
const mocks = vi.hoisted(() => ({ database: null as Database | null }));
vi.mock('$lib/server/database', () => ({
getDatabase: vi.fn(async () => mocks.database),
}));
vi.mock('$lib/avatar', () => ({
avatarUrl: vi.fn(() => '/missing-item-icon.svg'),
}));
import { createSession, getSessionUser } from './session';
function cookieJar() {
const values = new Map<string, string>();
return {
values,
get: (name: string) => values.get(name),
set: vi.fn((name: string, value: string) => values.set(name, value)),
delete: vi.fn((name: string) => values.delete(name)),
};
}
async function createDatabase(): Promise<Database> {
const database = await connect(':memory:');
await database.exec(`
CREATE TABLE users (
id TEXT PRIMARY KEY, username TEXT NOT NULL, login_username TEXT,
role TEXT NOT NULL, discord_id TEXT
);
CREATE TABLE user_profiles (
user_id TEXT PRIMARY KEY, display_name TEXT, public_slug TEXT
);
CREATE TABLE user_avatars (
user_id TEXT PRIMARY KEY, source TEXT, value TEXT, updated_at TEXT
);
CREATE TABLE user_status (
user_id TEXT PRIMARY KEY, last_active_at TEXT, blocked_at TEXT,
banned_until TEXT, updated_at TEXT NOT NULL DEFAULT ''
);
CREATE TABLE deleted_accounts (user_id TEXT PRIMARY KEY, deleted_at TEXT);
CREATE TABLE sessions (
id TEXT PRIMARY KEY, user_id TEXT NOT NULL, token_hash TEXT NOT NULL,
expires_at TEXT NOT NULL, created_at TEXT NOT NULL, aal INTEGER NOT NULL,
aal_verified_at TEXT NOT NULL, aal2_verified_at TEXT
);
INSERT INTO users(id,username,login_username,role,discord_id)
VALUES ('user-1','agent','agent','user',NULL);
INSERT INTO user_profiles(user_id,display_name,public_slug)
VALUES ('user-1','Agent','agent');
`);
return database;
}
describe('session AAL foundation', () => {
let database: Database;
beforeEach(async () => {
database = await createDatabase();
mocks.database = database;
});
afterEach(async () => {
mocks.database = null;
await database.close();
});
it('preserves legacy AAL1 calls and supports AAL2 metadata', async () => {
const aal2Cookies = cookieJar();
await createSession(aal2Cookies as never, 'user-1', { aal: 2 });
const row = await (
await database.prepare(
'SELECT token_hash,aal,aal_verified_at,aal2_verified_at FROM sessions',
)
).get();
expect(row.aal).toBe(2);
expect(row.aal_verified_at).toBeTruthy();
expect(row.aal2_verified_at).toBeTruthy();
expect(String(row.token_hash)).not.toBe(
aal2Cookies.values.get('shd_session'),
);
const user = await getSessionUser(aal2Cookies as never);
expect(user).toMatchObject({
id: 'user-1',
aal: 2,
authLevel: 2,
aalVerifiedAt: expect.any(String),
aal2VerifiedAt: expect.any(String),
});
const aal1Cookies = cookieJar();
await createSession(aal1Cookies as never, 'user-1');
const aal1 = await (
await database.prepare(
'SELECT aal,aal2_verified_at FROM sessions ORDER BY created_at DESC LIMIT 1',
)
).get();
expect(aal1.aal).toBe(1);
expect(aal1.aal2_verified_at).toBeNull();
});
});
+19 -138
View File
@@ -1,6 +1,5 @@
import { dev } from '$app/environment';
import { getDatabase } from '$lib/server/database';
import type { Database } from '@tursodatabase/database';
import type { Cookies } from '@sveltejs/kit';
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { avatarUrl } from '$lib/avatar';
@@ -17,27 +16,6 @@ export type AuthUser = {
role: string;
discordLinked: boolean;
avatarUrl: string;
/** Server-only authentication assurance metadata; no raw token is exposed. */
aal: 1 | 2;
authLevel: 1 | 2;
sessionCreatedAt: string;
aalVerifiedAt: string;
aal2VerifiedAt: string | null;
};
export type SessionAuthLevel = 1 | 2;
export type SessionTransaction = Pick<Database, 'prepare'>;
export type PendingSession = {
sessionId: string;
token: string;
};
export type CreateSessionOptions = {
aal?: SessionAuthLevel;
authLevel?: SessionAuthLevel;
aalVerifiedAt?: Date | string;
aal2VerifiedAt?: Date | string | null;
};
type LoginRequestContext = {
@@ -47,43 +25,23 @@ type LoginRequestContext = {
credentialId?: string | null;
sessionId?: string | null;
riskFlags?: string[] | null;
aal?: SessionAuthLevel;
aal2VerifiedAt?: string | null;
};
function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
function sessionCookieOptions() {
return {
path: '/',
httpOnly: true,
sameSite: 'lax' as const,
secure: !dev,
maxAge: SESSION_SECONDS,
};
}
export function setSessionCookie(cookies: Cookies, token: string): void {
cookies.set(COOKIE_NAME, token, sessionCookieOptions());
}
export async function createSessionInTransaction(
transaction: SessionTransaction,
export async function createSession(
cookies: Cookies,
userId: string,
options: CreateSessionOptions = {},
): Promise<PendingSession> {
): Promise<string> {
const database = await getDatabase();
const token = randomBytes(32).toString('base64url');
const sessionId = randomUUID();
const now = new Date();
const expiresAt = new Date(now.getTime() + SESSION_SECONDS * 1000);
const aal = options.authLevel ?? options.aal ?? 1;
const aalVerifiedAt = new Date(options.aalVerifiedAt ?? now).toISOString();
const aal2VerifiedAt =
aal === 2 ? new Date(options.aal2VerifiedAt ?? now).toISOString() : null;
const insert = await transaction.prepare(
'INSERT INTO sessions (id, user_id, token_hash, expires_at, created_at, aal, aal_verified_at, aal2_verified_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
const insert = await database.prepare(
'INSERT INTO sessions (id, user_id, token_hash, expires_at, created_at) VALUES (?, ?, ?, ?, ?)',
);
await insert.run(
@@ -92,67 +50,16 @@ export async function createSessionInTransaction(
hashToken(token),
expiresAt.toISOString(),
now.toISOString(),
aal,
aalVerifiedAt,
aal2VerifiedAt,
);
return { sessionId, token };
}
export async function createSession(
cookies: Cookies,
userId: string,
options: CreateSessionOptions = {},
): Promise<string> {
const database = await getDatabase();
const operation = database.transactionAsync((transaction) =>
createSessionInTransaction(transaction, userId, options),
);
const session = await operation.immediate();
setSessionCookie(cookies, session.token);
return session.sessionId;
}
/** Upgrade the current cookie-backed session without exposing or reissuing its token. */
export async function upgradeSessionToAal2InTransaction(
transaction: SessionTransaction,
cookies: Cookies,
userId: string,
verifiedAt = new Date(),
): Promise<string | null> {
const token = cookies.get(COOKIE_NAME);
if (!token) return null;
const result = await (
await transaction.prepare(`
UPDATE sessions
SET aal=2,aal_verified_at=?,aal2_verified_at=?
WHERE token_hash=? AND user_id=? AND expires_at>?
`)
).run(
verifiedAt.toISOString(),
verifiedAt.toISOString(),
hashToken(token),
userId,
new Date().toISOString(),
);
if (result.changes !== 1) return null;
const row = await (
await transaction.prepare('SELECT id FROM sessions WHERE token_hash=?')
).get(hashToken(token));
return row?.id ? String(row.id) : null;
}
export async function upgradeSessionToAal2(
cookies: Cookies,
userId: string,
verifiedAt = new Date(),
): Promise<string | null> {
const database = await getDatabase();
const operation = database.transactionAsync((transaction) =>
upgradeSessionToAal2InTransaction(transaction, cookies, userId, verifiedAt),
);
return await operation.immediate();
cookies.set(COOKIE_NAME, token, {
path: '/',
httpOnly: true,
sameSite: 'lax',
secure: !dev,
maxAge: SESSION_SECONDS,
});
return sessionId;
}
function describeClient(userAgent: string) {
@@ -203,23 +110,6 @@ export async function recordLogin(
context: LoginRequestContext = {},
): Promise<void> {
const database = await getDatabase();
await recordLoginInTransaction(
database,
userId,
provider,
succeeded,
context,
);
await purgeExpiredLoginMetadata();
}
export async function recordLoginInTransaction(
transaction: SessionTransaction,
userId: string | null,
provider: 'password' | 'discord' | 'magic_link' | 'passkey',
succeeded: boolean,
context: LoginRequestContext = {},
): Promise<void> {
const userAgent =
context.request?.headers.get('user-agent')?.slice(0, 1000) ?? null;
const headers = context.request?.headers;
@@ -244,10 +134,10 @@ export async function recordLoginInTransaction(
/* unavailable in some development adapters */
}
await (
await transaction.prepare(`INSERT INTO login_events(id,user_id,provider,succeeded,ip_address,user_agent,
await database.prepare(`INSERT INTO login_events(id,user_id,provider,succeeded,ip_address,user_agent,
client_name,operating_system,device_type,location_country,location_region,location_city,
failure_reason,risk_flags,credential_id,session_id,aal,aal2_verified_at,created_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`)
failure_reason,risk_flags,credential_id,session_id,created_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`)
).run(
randomUUID(),
userId,
@@ -265,10 +155,9 @@ export async function recordLoginInTransaction(
riskFlags.length ? riskFlags.join(',') : null,
context.credentialId ?? null,
context.sessionId ?? null,
context.aal ?? (succeeded ? 1 : null),
context.aal2VerifiedAt ?? null,
new Date().toISOString(),
);
await purgeExpiredLoginMetadata();
}
export async function getSessionUser(
@@ -284,9 +173,7 @@ export async function getSessionUser(
users.role, users.discord_id, user_avatars.source AS avatar_source,
user_avatars.value AS avatar_value, user_avatars.updated_at AS avatar_updated_at,
user_status.last_active_at,user_status.blocked_at,user_status.banned_until,
deleted_accounts.deleted_at,
sessions.aal,sessions.aal_verified_at,sessions.aal2_verified_at,
sessions.created_at AS session_created_at
deleted_accounts.deleted_at
FROM sessions
JOIN users ON users.id = sessions.user_id
LEFT JOIN user_profiles ON user_profiles.user_id=users.id
@@ -337,12 +224,6 @@ export async function getSessionUser(
String(user.id),
user.avatar_updated_at,
),
aal: Number(user.aal) === 2 ? 2 : 1,
authLevel: Number(user.aal) === 2 ? 2 : 1,
sessionCreatedAt: String(user.session_created_at),
aalVerifiedAt: String(user.aal_verified_at),
aal2VerifiedAt:
typeof user.aal2_verified_at === 'string' ? user.aal2_verified_at : null,
};
}
@@ -0,0 +1,127 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Database } from '@tursodatabase/database';
import type { MechanicRuntimeSelection } from './mechanic-runtime-selection';
const mocks = vi.hoisted(() => ({
loadSelections: vi.fn(),
}));
vi.mock('./mechanic-runtime-selection', async (importOriginal) => ({
...(await importOriginal<typeof import('./mechanic-runtime-selection')>()),
loadSelectedMechanicRuntimesForOwnerReferences: mocks.loadSelections,
}));
import { loadBuildMechanicRuntimes } from './build-mechanic-runtime';
import { mechanicRuntimeOwnerReferenceKey } from './mechanic-runtime-selection';
const runtime = (sourceId: string): MechanicRuntimeSelection => ({
owner: { type: 'talent', id: sourceId, scope: 'standard', hasTierII: true },
sourceId,
sourceFingerprint: 'a'.repeat(64),
revisionId: `${sourceId}-revision`,
revisionNumber: 1,
simulationReadiness: 'ready',
scenarioInputs: [],
variants: [
{
key: 'base',
label: 'BASE',
program: { id: `mechanic-runtime:${sourceId}:base`, name: sourceId, clauses: [] },
},
],
});
function emptyDatabase() {
return {} as Database;
}
describe('Build mechanic runtime hydration', () => {
beforeEach(() => {
mocks.loadSelections.mockReset();
});
it('maps every owner family through the selected-runtime reader using attachment ownership', async () => {
const database = emptyDatabase();
const selections = new Map<string, MechanicRuntimeSelection | null>([
[
mechanicRuntimeOwnerReferenceKey({
type: 'talent',
id: 'talent-1',
}),
runtime('talent-source'),
],
[
mechanicRuntimeOwnerReferenceKey({
type: 'os_protocol_talent',
id: 'protocol-talent-1',
}),
runtime('protocol-source'),
],
[
mechanicRuntimeOwnerReferenceKey({
type: 'skill_chip_talent',
id: 'chip-talent-1',
}),
runtime('chip-source'),
],
[
mechanicRuntimeOwnerReferenceKey({
type: 'specialization_tree_rank',
id: 'attachment-1',
}),
runtime('attachment-source'),
],
]);
mocks.loadSelections.mockResolvedValueOnce(selections);
const hydrated = await loadBuildMechanicRuntimes(database, {
talentIds: ['talent-1', 'not-authored'],
protocolTalentIds: ['protocol-talent-1'],
skillChipTalentIds: ['chip-talent-1'],
specializationAttachmentIds: ['attachment-1'],
});
expect(mocks.loadSelections).toHaveBeenCalledWith(database, [
{ type: 'talent', id: 'talent-1' },
{ type: 'talent', id: 'not-authored' },
{ type: 'os_protocol_talent', id: 'protocol-talent-1' },
{ type: 'skill_chip_talent', id: 'chip-talent-1' },
{ type: 'specialization_tree_rank', id: 'attachment-1' },
]);
expect(hydrated).toMatchObject({
talents: {
'talent-1': { sourceId: 'talent-source' },
'not-authored': null,
},
protocolTalents: {
'protocol-talent-1': { sourceId: 'protocol-source' },
},
skillChipTalents: { 'chip-talent-1': { sourceId: 'chip-source' } },
specializationAttachments: {
'attachment-1': { sourceId: 'attachment-source' },
},
});
expect(
hydrated.specializationAttachments['combat-effect-reusable'],
).toBeUndefined();
expect(JSON.parse(JSON.stringify(hydrated))).toEqual(hydrated);
});
it('returns null capabilities when no selected source can be loaded', async () => {
const database = emptyDatabase();
const hydrated = await loadBuildMechanicRuntimes(database, {
talentIds: ['talent-1'],
protocolTalentIds: ['protocol-talent-1'],
skillChipTalentIds: ['chip-talent-1'],
specializationAttachmentIds: ['attachment-1'],
});
expect(hydrated).toEqual({
talents: { 'talent-1': null },
protocolTalents: { 'protocol-talent-1': null },
skillChipTalents: { 'chip-talent-1': null },
specializationAttachments: { 'attachment-1': null },
});
expect(mocks.loadSelections).toHaveBeenCalledOnce();
});
});

Some files were not shown because too many files have changed in this diff Show More