Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
904cb073a2 | ||
|
|
fe06b90117 | ||
|
|
e5213248a8 | ||
|
|
1fba43272a | ||
|
|
18e13ca80c | ||
|
|
8c021c134f | ||
|
|
29d26bd036 |
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -42,3 +42,6 @@ tmp/
|
||||
# Python caches
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
.pi
|
||||
.mesh
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -115,21 +115,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 +263,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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -142,6 +142,10 @@ describe('container runtime startup', () => {
|
||||
{ key: 'APP_ORIGIN', value: 'https://exported.invalid' },
|
||||
{ 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 },
|
||||
@@ -220,6 +224,7 @@ describe('container runtime startup', () => {
|
||||
APP_ORIGIN: 'https://stage.shd.build',
|
||||
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,
|
||||
|
||||
+34
-11
@@ -2390,9 +2390,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 +2406,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 +2432,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 +2491,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 +2518,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
|
||||
|
||||
@@ -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
|
||||
|
||||
+43
-13
@@ -638,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.
|
||||
@@ -707,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.
|
||||
@@ -800,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
|
||||
@@ -896,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
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"worktree": {
|
||||
"setup": "npm install"
|
||||
}
|
||||
}
|
||||
@@ -14,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',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dev } from '$app/environment';
|
||||
import { json, type Handle, type HandleServerError } from '@sveltejs/kit';
|
||||
import { stringify } from 'devalue';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
@@ -15,6 +16,15 @@ import {
|
||||
} from '$lib/server/data-moderation';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
// THROWAWAY PROTOTYPE: fixture-only review must not open the shared database.
|
||||
if (
|
||||
dev &&
|
||||
event.url.pathname === '/database' &&
|
||||
event.url.searchParams.get('prototype') === 'model-status'
|
||||
) {
|
||||
return resolve(event);
|
||||
}
|
||||
|
||||
if (
|
||||
event.url.pathname === '/admin' ||
|
||||
event.url.pathname.startsWith('/admin/')
|
||||
|
||||
@@ -176,6 +176,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;
|
||||
|
||||
@@ -7,6 +7,8 @@ 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,
|
||||
@@ -803,6 +805,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({
|
||||
|
||||
@@ -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([
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
}),
|
||||
),
|
||||
})),
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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.`,
|
||||
|
||||
@@ -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',
|
||||
@@ -1306,6 +1401,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 +1410,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',
|
||||
|
||||
@@ -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',
|
||||
@@ -2049,6 +2066,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');
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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'),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,10 +1,26 @@
|
||||
import { dev } from '$app/environment';
|
||||
import { getSessionUser } from '$lib/server/auth/session';
|
||||
import { hasPermission } from '$lib/server/auth/authorization';
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
import { notificationSummary } from '$lib/server/notifications';
|
||||
import { getSiteAccessSettings } from '$lib/server/site-access';
|
||||
|
||||
export const load: LayoutServerLoad = async ({ cookies }) => {
|
||||
export const load: LayoutServerLoad = async ({ cookies, url }) => {
|
||||
// THROWAWAY PROTOTYPE: fixture-only review must not open the shared database.
|
||||
if (dev && url.pathname === '/database' && url.searchParams.get('prototype') === 'model-status') {
|
||||
return {
|
||||
user: null,
|
||||
isacAccess: false,
|
||||
notifications: { unread: 0 },
|
||||
siteAccess: {
|
||||
comingSoonEnabled: false,
|
||||
accountCreationEnabled: true,
|
||||
sections: { news: true, database: true, builds: true, guides: true, builder: true },
|
||||
updatedAt: 'prototype'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const user = await getSessionUser(cookies);
|
||||
return {
|
||||
user,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { dev } from '$app/environment';
|
||||
import { getDatabase } from '$lib/server/database';
|
||||
import { getRegistrySearch } from '$lib/server/pagination';
|
||||
import { databaseCategories } from '$lib/database/categories';
|
||||
@@ -16,6 +17,11 @@ const tables = {
|
||||
} as const;
|
||||
|
||||
export const load: PageServerLoad = async ({ url }) => {
|
||||
// THROWAWAY PROTOTYPE: avoid opening the shared database for fixture-only review.
|
||||
if (dev && url.searchParams.get('prototype') === 'model-status') {
|
||||
return { registries: [], total: 0, search: '', searchResults: [] };
|
||||
}
|
||||
|
||||
const database = await getDatabase();
|
||||
const { search, pattern } = getRegistrySearch(url);
|
||||
const counts = await Promise.all(
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
<script lang="ts">
|
||||
import { dev } from '$app/environment';
|
||||
import { page } from '$app/state';
|
||||
import ModelStatusPrototype from './ModelStatusPrototype.prototype.svelte';
|
||||
import type { PrototypeVariant } from './model-status.prototype';
|
||||
|
||||
let { data } = $props();
|
||||
const onlineRegistries = $derived(data.registries.filter((registry) => registry.count > 0).length);
|
||||
const prototypeVariant = $derived.by<PrototypeVariant | null>(() => {
|
||||
if (!dev || page.url.searchParams.get('prototype') !== 'model-status') return null;
|
||||
const variant = page.url.searchParams.get('variant');
|
||||
return variant === 'A' || variant === 'B' || variant === 'C' ? variant : null;
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
@@ -8,6 +18,9 @@
|
||||
<meta name="description" content="Community-maintained The Division Resurgence attributes, talents, brands, gear, weapons, mods, protocols, skill chips, and specializations data."/>
|
||||
</svelte:head>
|
||||
|
||||
{#if prototypeVariant}
|
||||
<ModelStatusPrototype variant={prototypeVariant} />
|
||||
{:else}
|
||||
<main class="page community-index-page">
|
||||
<header class="catalogue-hero community-index-hero">
|
||||
<div><p class="eyebrow"><span></span> ISAC PUBLIC ARCHIVE</p><h1>RESURGENCE <em>DATABASE.</em></h1><p>Explore equipment, talents, modifications, and gameplay effects from The Division Resurgence.</p></div>
|
||||
@@ -54,3 +67,4 @@
|
||||
{/each}
|
||||
</section>
|
||||
</main>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<script lang="ts">
|
||||
import ModelStatusPrototypeSwitcher from './ModelStatusPrototypeSwitcher.prototype.svelte';
|
||||
import ModelStatusVariantA from './ModelStatusVariantA.prototype.svelte';
|
||||
import ModelStatusVariantB from './ModelStatusVariantB.prototype.svelte';
|
||||
import ModelStatusVariantC from './ModelStatusVariantC.prototype.svelte';
|
||||
import type { PrototypeVariant } from './model-status.prototype';
|
||||
|
||||
let { variant }: { variant: PrototypeVariant } = $props();
|
||||
</script>
|
||||
|
||||
<!-- THROWAWAY PROTOTYPE: three issue #5 variants on the existing /database route. -->
|
||||
<main class="page model-status-prototype">
|
||||
{#if variant === 'A'}
|
||||
<ModelStatusVariantA />
|
||||
{:else if variant === 'B'}
|
||||
<ModelStatusVariantB />
|
||||
{:else}
|
||||
<ModelStatusVariantC />
|
||||
{/if}
|
||||
</main>
|
||||
<ModelStatusPrototypeSwitcher current={variant} />
|
||||
@@ -0,0 +1,45 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { page } from '$app/state';
|
||||
import { onMount } from 'svelte';
|
||||
import { prototypeVariantNames, type PrototypeVariant } from './model-status.prototype';
|
||||
|
||||
let { current }: { current: PrototypeVariant } = $props();
|
||||
const variants: PrototypeVariant[] = ['A', 'B', 'C'];
|
||||
|
||||
const cycle = (direction: -1 | 1) => {
|
||||
const currentIndex = variants.indexOf(current);
|
||||
const next = variants[(currentIndex + direction + variants.length) % variants.length];
|
||||
const params = new URLSearchParams(page.url.searchParams);
|
||||
params.set('prototype', 'model-status');
|
||||
params.set('variant', next);
|
||||
void goto(`${page.url.pathname}?${params.toString()}${page.url.hash}`, {
|
||||
keepFocus: true,
|
||||
noScroll: true,
|
||||
replaceState: true
|
||||
});
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
const handleKeydown = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
|
||||
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
|
||||
if (event.target instanceof HTMLElement && event.target.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])')) return;
|
||||
event.preventDefault();
|
||||
cycle(event.key === 'ArrowLeft' ? -1 : 1);
|
||||
};
|
||||
window.addEventListener('keydown', handleKeydown);
|
||||
return () => window.removeEventListener('keydown', handleKeydown);
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- THROWAWAY PROTOTYPE: development-only variant switcher for issue #5. -->
|
||||
<nav class="prototype-switcher" aria-label="Model status prototype variants">
|
||||
<button type="button" onclick={() => cycle(-1)} aria-label="Show previous prototype variant">←</button>
|
||||
<strong aria-live="polite" title={prototypeVariantNames[current]} aria-label={`Variant ${current}: ${prototypeVariantNames[current]}`}>{current}</strong>
|
||||
<button type="button" onclick={() => cycle(1)} aria-label="Show next prototype variant">→</button>
|
||||
</nav>
|
||||
|
||||
<style>
|
||||
.prototype-switcher{position:fixed;z-index:1000;right:14px;bottom:14px;display:grid;grid-template-columns:36px 34px 36px;height:36px;border:1px solid var(--shd-border-strong);box-shadow:0 7px 20px #000a;background:var(--shd-bg);color:var(--shd-text)}.prototype-switcher button{display:grid;place-items:center;border:0;background:var(--shd-surface-raised);color:var(--shd-orange);font:800 17px/1 var(--shd-font-mono);cursor:pointer}.prototype-switcher button:first-child{border-right:1px solid var(--shd-border)}.prototype-switcher button:last-child{border-left:1px solid var(--shd-border)}.prototype-switcher button:hover{background:var(--shd-surface-active);color:var(--shd-orange-hover)}.prototype-switcher button:active{transform:translateY(1px);filter:brightness(.82)}.prototype-switcher button:focus-visible{position:relative;z-index:1;outline:2px solid var(--shd-focus-ring);outline-offset:2px}.prototype-switcher>strong{display:grid;place-items:center;color:var(--shd-text);font:900 12px/1 var(--shd-font-mono);letter-spacing:.6px}@media(max-width:520px){.prototype-switcher{right:8px;bottom:8px}}@media(prefers-reduced-motion:reduce){.prototype-switcher button{transition:none}}
|
||||
</style>
|
||||
@@ -0,0 +1,78 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
modelStatusFixtures,
|
||||
publicBehavior,
|
||||
publicStatus
|
||||
} from './model-status.prototype';
|
||||
|
||||
const quickViewFixtures = [modelStatusFixtures[0], modelStatusFixtures[3]];
|
||||
</script>
|
||||
|
||||
<!-- THROWAWAY PROTOTYPE: issue #5, variant A. -->
|
||||
<div class="prototype-a">
|
||||
<header class="prototype-heading">
|
||||
<div>
|
||||
<p><span></span> DEVELOPMENT PROTOTYPE · ISSUE #5 · VARIANT A</p>
|
||||
<h1>MODELING <em>STATUS.</em></h1>
|
||||
</div>
|
||||
<p>Integrated card hierarchy keeps the public state in the identity header and gives behavior one primary reading block.</p>
|
||||
</header>
|
||||
|
||||
<section aria-labelledby="a-card-heading">
|
||||
<header class="surface-heading">
|
||||
<div><span>01 / CARD PRESENTATION</span><h2 id="a-card-heading">DATABASE CARDS</h2></div>
|
||||
<small>ALL MECHANIC OWNERS · PUBLIC STATE ONLY</small>
|
||||
</header>
|
||||
<div class="card-grid">
|
||||
{#each modelStatusFixtures as fixture}
|
||||
<article class="model-card">
|
||||
<header>
|
||||
<div><small>{fixture.owner}</small><h3>{fixture.name}</h3><span>{fixture.context}</span></div>
|
||||
<strong class:not-modeled={publicStatus(fixture) === 'NOT MODELED'}>{publicStatus(fixture)}</strong>
|
||||
</header>
|
||||
<div class="behavior-block">
|
||||
<small>{publicStatus(fixture) === 'MODELED' ? 'MODELED BEHAVIOR' : 'AUTHORED DESCRIPTION'}</small>
|
||||
<p>{publicBehavior(fixture)}</p>
|
||||
</div>
|
||||
<footer><span>READ-ONLY FIXTURE</span><b>VIEW DETAILS →</b></footer>
|
||||
</article>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="a-detail-heading">
|
||||
<header class="surface-heading">
|
||||
<div><span>02 / DETAIL PRESENTATION</span><h2 id="a-detail-heading">QUICK VIEW</h2></div>
|
||||
<small>MODELED TEXT FIRST · AUTHORED FALLBACK WHEN NOT MODELED</small>
|
||||
</header>
|
||||
<div class="quick-view">
|
||||
{#each quickViewFixtures as fixture}
|
||||
<article>
|
||||
<header><div><small>{fixture.owner}</small><h3>{fixture.name}</h3></div><strong class:not-modeled={publicStatus(fixture) === 'NOT MODELED'}>{publicStatus(fixture)}</strong></header>
|
||||
<div><span>BEHAVIOR</span><p>{publicBehavior(fixture)}</p></div>
|
||||
<dl><div><dt>RECORD</dt><dd>{fixture.context}</dd></div><div><dt>DISPLAY SOURCE</dt><dd>{publicStatus(fixture) === 'MODELED' ? 'Modeled behavior' : 'Authored description'}</dd></div></dl>
|
||||
</article>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="a-search-heading">
|
||||
<header class="surface-heading">
|
||||
<div><span>03 / GLOBAL SEARCH PRESENTATION</span><h2 id="a-search-heading">SEARCH RESULTS</h2></div>
|
||||
<small>{modelStatusFixtures.length} FIXTURE MATCHES</small>
|
||||
</header>
|
||||
<div class="search-results">
|
||||
{#each modelStatusFixtures as fixture}
|
||||
<div class="search-result">
|
||||
<small>{fixture.owner}</small><strong>{fixture.name}</strong><span>{publicBehavior(fixture)}</span><b class:not-modeled={publicStatus(fixture) === 'NOT MODELED'}>{publicStatus(fixture)}</b>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.prototype-a{display:grid;gap:28px;padding:20px 0 110px}.prototype-heading{min-height:150px;display:grid;grid-template-columns:minmax(0,1fr) minmax(280px,420px);align-items:end;gap:24px;padding:24px;border:1px solid var(--shd-border);border-top:2px solid var(--shd-orange);background:var(--shd-surface)}.prototype-heading p{margin:0;color:var(--shd-text-muted);font:var(--shd-type-supporting)/1.5 var(--shd-font-editorial)}.prototype-heading>div>p{color:var(--shd-orange);font:900 var(--shd-type-telemetry)/1 var(--shd-font-sans);letter-spacing:1px}.prototype-heading>div>p span{display:inline-block;width:22px;border-top:2px solid currentColor;vertical-align:middle}.prototype-heading h1{margin:10px 0 0;font-size:clamp(34px,5vw,64px);line-height:.9;letter-spacing:-1px}.prototype-heading h1 em{color:var(--shd-orange);font-style:normal}.prototype-a>section{display:grid;gap:10px}.surface-heading{min-height:46px;display:flex;align-items:end;justify-content:space-between;gap:16px;padding-bottom:9px;border-bottom:1px solid var(--shd-border)}.surface-heading>div{display:flex;align-items:baseline;gap:12px}.surface-heading span,.surface-heading small{color:var(--shd-text-muted);font-size:var(--shd-type-telemetry);font-weight:800;letter-spacing:.8px}.surface-heading h2{margin:0;font-size:20px;letter-spacing:.6px}.card-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.model-card{min-width:0;display:flex;flex-direction:column;border:1px solid var(--shd-border);border-top:2px solid var(--shd-border-strong);background:var(--shd-surface)}.model-card>header{min-height:92px;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:start;gap:10px;padding:14px;border-bottom:1px solid var(--shd-border)}.model-card header small,.quick-view header small{display:block;margin-bottom:6px;color:var(--shd-text-muted);font-size:var(--shd-type-telemetry);font-weight:900;letter-spacing:.8px}.model-card h3,.quick-view h3{margin:0;font-size:18px;line-height:1.05}.model-card header span{display:block;margin-top:7px;color:var(--shd-text-dim);font-size:var(--shd-type-telemetry)}.model-card header strong,.quick-view header strong,.search-result b{padding:5px 7px;border:1px solid var(--shd-success);color:var(--shd-success);font-size:10px;line-height:1;letter-spacing:.7px;white-space:nowrap}.model-card header strong.not-modeled,.quick-view header strong.not-modeled,.search-result b.not-modeled{border-color:var(--shd-border-strong);color:var(--shd-text-muted)}.behavior-block{flex:1;margin:12px;padding:12px;border-left:2px solid var(--shd-success);background:var(--shd-model-surface)}.model-card:has(.not-modeled) .behavior-block{border-left-color:var(--shd-text-dim)}.behavior-block small{color:var(--shd-text-dim);font-size:10px;font-weight:900;letter-spacing:.9px}.behavior-block p{margin:7px 0 0;color:var(--shd-text);font:var(--shd-type-supporting)/1.5 var(--shd-font-editorial)}.model-card>footer{display:flex;justify-content:space-between;gap:10px;padding:10px 12px;border-top:1px solid var(--shd-border-soft);color:var(--shd-text-dim);font-size:10px;font-weight:900;letter-spacing:.6px}.model-card>footer b{color:var(--shd-orange)}.quick-view{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.quick-view>article{border:1px solid var(--shd-border);background:var(--shd-surface-raised)}.quick-view article>header{display:flex;align-items:start;justify-content:space-between;gap:16px;padding:16px;border-bottom:1px solid var(--shd-border)}.quick-view article>div{padding:18px 16px}.quick-view article>div span{color:var(--shd-text-muted);font-size:10px;font-weight:900;letter-spacing:1px}.quick-view article>div p{max-width:62ch;margin:8px 0 0;font:18px/1.55 var(--shd-font-editorial)}.quick-view dl{display:grid;grid-template-columns:1fr 1fr;margin:0;border-top:1px solid var(--shd-border)}.quick-view dl>div{padding:10px 16px;border-left:1px solid var(--shd-border)}.quick-view dl>div:first-child{border-left:0}.quick-view dt{color:var(--shd-text-dim);font-size:10px;font-weight:900;letter-spacing:.8px}.quick-view dd{margin:4px 0 0;color:var(--shd-text-muted);font-size:var(--shd-type-telemetry)}.search-results{border:1px solid var(--shd-border);background:var(--shd-model-surface)}.search-result{display:grid;grid-template-columns:190px minmax(150px,.7fr) minmax(260px,1.6fr) auto;align-items:center;gap:12px;min-height:58px;padding:8px 12px;border-top:1px solid var(--shd-border-soft)}.search-result:first-child{border-top:0}.search-result>small{color:var(--shd-orange);font-size:var(--shd-type-telemetry);font-weight:900;letter-spacing:.5px}.search-result>strong{font-size:var(--shd-type-supporting)}.search-result>span{color:var(--shd-text-muted);font:var(--shd-type-telemetry)/1.4 var(--shd-font-editorial)}
|
||||
@media(max-width:1000px){.card-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.search-result{grid-template-columns:minmax(140px,.7fr) minmax(0,1fr) auto}.search-result>small{grid-column:1/-1}.search-result>span{grid-column:2}}
|
||||
@media(max-width:700px){.prototype-heading,.quick-view,.card-grid{grid-template-columns:1fr}.prototype-heading{align-items:start}.surface-heading{align-items:start}.surface-heading>div{display:grid;gap:4px}.surface-heading>small{display:none}.search-result{grid-template-columns:1fr auto}.search-result>small,.search-result>span{grid-column:1/-1}}
|
||||
</style>
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -502,16 +502,12 @@ export const load: PageServerLoad = async ({ params, url, cookies }) => {
|
||||
case 'skill-chips':
|
||||
countSql = `SELECT COUNT(*) AS total FROM skill_chip_sets item WHERE item.active=1${searchClause}`;
|
||||
rowsSql = `SELECT item.*,bonus.min_value,bonus.max_value,attributes.name AS bonus_stat,attributes.unit AS bonus_unit,
|
||||
talents.name AS talent_name,abilities.name AS ability_name,specializations.name AS specialization_name,
|
||||
(SELECT COUNT(*) FROM skill_chip_primary_options) AS primary_count,
|
||||
(SELECT COUNT(*) FROM skill_chip_secondary_options) AS secondary_count,
|
||||
talents.name AS talent_name,talents.description_template AS talent_description,
|
||||
icons.updated_at AS icon_updated_at,render.id AS render_id,render.updated_at AS render_updated_at
|
||||
FROM skill_chip_sets item
|
||||
LEFT JOIN skill_chip_two_piece_bonuses bonus ON bonus.skill_chip_set_id=item.id
|
||||
LEFT JOIN stat_attributes attributes ON attributes.id=bonus.stat_attribute_id
|
||||
LEFT JOIN skill_chip_talents talents ON talents.skill_chip_set_id=item.id
|
||||
LEFT JOIN specialization_abilities abilities ON abilities.id=item.specialization_ability_id
|
||||
LEFT JOIN specializations ON specializations.id=abilities.specialization_id
|
||||
LEFT JOIN game_data_icons icons ON icons.entity_type='skill_chip' AND icons.entity_id=item.id
|
||||
LEFT JOIN managed_images render ON render.source_entity_type='skill_chip_render' AND render.source_entity_id=item.id
|
||||
WHERE item.active=1${searchClause}
|
||||
@@ -1035,23 +1031,12 @@ export const load: PageServerLoad = async ({ params, url, cookies }) => {
|
||||
iconUrl: iconUrl('skill_chip', row.id, row.icon_updated_at),
|
||||
badges: [{ label: 'SUPERIOR' }, { label: 'HIGH-END' }],
|
||||
facts: [
|
||||
{
|
||||
label: 'SPECIALIZATION ABILITY',
|
||||
value: row.ability_name
|
||||
? `${row.ability_name} · ${row.specialization_name}`
|
||||
: 'UNASSIGNED',
|
||||
},
|
||||
{
|
||||
label: '2-PIECE BONUS',
|
||||
value: row.bonus_stat
|
||||
? `${row.bonus_stat} · ${range(row.min_value, row.max_value, row.bonus_unit)}`
|
||||
: 'NOT CONFIGURED',
|
||||
},
|
||||
{ label: 'PRIMARY POOL', value: `${row.primary_count} OPTIONS` },
|
||||
{
|
||||
label: 'SECONDARY POOL',
|
||||
value: `${row.secondary_count} OPTIONS`,
|
||||
},
|
||||
],
|
||||
lines: [
|
||||
{
|
||||
@@ -1059,6 +1044,9 @@ export const load: PageServerLoad = async ({ params, url, cookies }) => {
|
||||
value: list(row.talent_name, 'NOT CONFIGURED'),
|
||||
},
|
||||
],
|
||||
description: row.talent_description
|
||||
? String(row.talent_description)
|
||||
: undefined,
|
||||
};
|
||||
case 'specializations':
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// THROWAWAY PROTOTYPE for issue #5. Fixture lifecycle data must never become a public API.
|
||||
export type PrototypeVariant = 'A' | 'B' | 'C';
|
||||
export type PublicModelStatus = 'MODELED' | 'NOT MODELED';
|
||||
|
||||
type MechanicLifecycle =
|
||||
'ready' | 'requires_assumptions' | 'captured_only' | 'absent';
|
||||
|
||||
export type ModelStatusFixture = {
|
||||
id: string;
|
||||
owner:
|
||||
| 'Talent'
|
||||
| 'OS Protocol Talent'
|
||||
| 'Skill Chip Talent'
|
||||
| 'Specialization tree-rank effect';
|
||||
name: string;
|
||||
context: string;
|
||||
internal: {
|
||||
lifecycle: MechanicLifecycle;
|
||||
current: boolean;
|
||||
};
|
||||
modeledText?: string;
|
||||
authoredText: string;
|
||||
};
|
||||
|
||||
export const modelStatusFixtures: ModelStatusFixture[] = [
|
||||
{
|
||||
id: 'talent-ready',
|
||||
owner: 'Talent',
|
||||
name: 'Predatory Advance',
|
||||
context: 'Weapon Talent · Tier I',
|
||||
internal: { lifecycle: 'ready', current: true },
|
||||
modeledText:
|
||||
'On enemy kill: gain +15% Weapon Damage for 10 s. Refreshes and stacks up to 3 times.',
|
||||
authoredText:
|
||||
'Killing an enemy grants 15% weapon damage for 10s. Stacks up to 3 times.',
|
||||
},
|
||||
{
|
||||
id: 'protocol-assumptions',
|
||||
owner: 'OS Protocol Talent',
|
||||
name: 'Emergency Weave',
|
||||
context: 'Superior OS Protocol · Talent',
|
||||
internal: { lifecycle: 'requires_assumptions', current: true },
|
||||
modeledText:
|
||||
'When armor breaks: restore 20% Armor over 5 s. Cooldown: 20 s.',
|
||||
authoredText:
|
||||
'When armor is broken, restore 20% armor over 5s. Cooldown: 20s.',
|
||||
},
|
||||
{
|
||||
id: 'chip-captured',
|
||||
owner: 'Skill Chip Talent',
|
||||
name: 'Rapid Instruction',
|
||||
context: 'Tactical Skill Chip Set · 3-piece talent',
|
||||
internal: { lifecycle: 'captured_only', current: true },
|
||||
modeledText: 'After skill use: gain +8% Skill Haste for 12 s.',
|
||||
authoredText: 'Using a skill grants 8% Skill Haste for 12s.',
|
||||
},
|
||||
{
|
||||
id: 'specialization-absent',
|
||||
owner: 'Specialization tree-rank effect',
|
||||
name: 'Perfect Cadence · Rank 3',
|
||||
context: 'Sharpshooter · Precision branch',
|
||||
internal: { lifecycle: 'absent', current: true },
|
||||
authoredText:
|
||||
'After reaching 5 hits without missing, your next shot deals 25% increased damage.',
|
||||
},
|
||||
{
|
||||
id: 'talent-stale',
|
||||
owner: 'Talent',
|
||||
name: 'Measured Focus',
|
||||
context: 'Gear Talent · Tier II',
|
||||
internal: { lifecycle: 'ready', current: false },
|
||||
modeledText:
|
||||
'After a headshot: gain +8% Critical Hit Damage for 8 s, stacking up to 3 times.',
|
||||
authoredText:
|
||||
'Headshots grant 10% Critical Hit Damage for 8s. Stacks up to 4 times.',
|
||||
},
|
||||
];
|
||||
|
||||
export const publicStatus = (fixture: ModelStatusFixture): PublicModelStatus =>
|
||||
fixture.internal.current && fixture.internal.lifecycle !== 'absent'
|
||||
? 'MODELED'
|
||||
: 'NOT MODELED';
|
||||
|
||||
export const publicBehavior = (fixture: ModelStatusFixture): string =>
|
||||
publicStatus(fixture) === 'MODELED' && fixture.modeledText
|
||||
? fixture.modeledText
|
||||
: fixture.authoredText;
|
||||
|
||||
export const prototypeVariantNames = {
|
||||
A: 'Integrated card hierarchy',
|
||||
B: 'Evidence rail',
|
||||
C: 'Registry rows',
|
||||
} satisfies Record<PrototypeVariant, string>;
|
||||
@@ -1 +0,0 @@
|
||||
3.12
|
||||
@@ -1,24 +0,0 @@
|
||||
# Copy this file to $XDG_CONFIG_HOME/shd-capture/config.toml and adjust local limits.
|
||||
# The utility reads the OpenAI key from the named environment variable only.
|
||||
|
||||
[server]
|
||||
# Only loopback IP literals are valid: 127.0.0.1 or ::1.
|
||||
host = "127.0.0.1"
|
||||
port = 8765
|
||||
|
||||
[lifecycle]
|
||||
# One local process owns this instance name and releases its runtime lock on shutdown.
|
||||
instance_name = "shd-capture"
|
||||
lock_timeout_seconds = 5
|
||||
shutdown_timeout_seconds = 30
|
||||
|
||||
[limits]
|
||||
max_image_bytes = 33554432
|
||||
max_video_bytes = 4294967296
|
||||
max_queue_items = 64
|
||||
max_ocr_text_characters = 20000
|
||||
|
||||
[openai]
|
||||
# Set this name in the process environment. Do not put the key in this file.
|
||||
api_key_env = "OPENAI_API_KEY"
|
||||
model = "gpt-4.1-mini"
|
||||
@@ -1,133 +0,0 @@
|
||||
# Game Data Capture Contracts
|
||||
|
||||
RG-1 freezes contract version 1 for the taxonomy, workflow states, evidence
|
||||
model, archive manifest, and ISAC handoff boundary. The approved GDC-001
|
||||
mod-family change extends version 1 with `weapon_mod` and `gear_mod`.
|
||||
|
||||
## Files
|
||||
|
||||
- `domain-contract-v1.json` lists every family/view pair, record type, Gear
|
||||
slot, abstention reason, state, and allowed transition.
|
||||
- `screenshot-classification.schema.json` validates one hierarchical screen
|
||||
classification.
|
||||
- `evidence-archive-manifest-v1.schema.json` validates a private evidence
|
||||
archive manifest.
|
||||
- `isac-handoff-v1.schema.json` validates a bounded draft handoff for
|
||||
authenticated ISAC intake.
|
||||
- `examples/classification/` contains one valid and one invalid classification
|
||||
for each family, including Weapon Mod, Gear Mod, and explicit `unknown`
|
||||
abstention.
|
||||
- `examples/archive/` and `examples/handoff/` exercise each versioned document
|
||||
schema.
|
||||
|
||||
The schemas use JSON Schema Draft 2020-12, internal `$ref` values, standard
|
||||
formats, and no implementation-specific keywords. Python `jsonschema` and
|
||||
TypeScript validators such as Ajv can compile the files without model
|
||||
conversion. Consumers must reject a document unless `schema_version` equals the
|
||||
schema's `const` value. Consumers must also run semantic reference validation
|
||||
because JSON Schema cannot prove that an ID points to an item in another array.
|
||||
|
||||
## Mod Screen Semantics
|
||||
|
||||
Repository source data and editors establish `weapon_mod` and `gear_mod` as
|
||||
separate canonical aggregates. Each family currently supports only the `detail`
|
||||
view and its same-named record type. A Mod classification never sets the
|
||||
six-slot `gear_slot` field. A Weapon Mod detail screenshot may provide evidence
|
||||
for item-owned slot, primary quality ranges, compatibility, Mod Effects, exotic
|
||||
Attributes, and weapon-lock data. A Gear Mod detail screenshot may provide
|
||||
evidence for its item-owned primary quality ranges. These fields and
|
||||
relationships are not separate screen views or record types.
|
||||
|
||||
Each mod family has one global canonical secondary Attribute pool configured
|
||||
outside individual item details. The pool stores Level 1 and Level 20 minimum
|
||||
and maximum ranges for Specialized, Superior, and High-end quality. Capacity is
|
||||
zero for Standard, one for Specialized, and two each for Superior and High-end.
|
||||
A secondary roll visible on an item-detail screenshot is evidence for that
|
||||
observed item instance; it does not establish a pool option, canonical range
|
||||
endpoint, or family-wide capacity.
|
||||
|
||||
The `record_types` array still supports composite screens. No repository
|
||||
evidence establishes another independent canonical record type on a Weapon Mod
|
||||
or Gear Mod detail screen, so these two mappings each contain one record type. A
|
||||
classifier must use `unknown` with an abstention reason for another Mod view, an
|
||||
ambiguous family, or unsupported content.
|
||||
|
||||
## Skill Chip Screen Semantics
|
||||
|
||||
The implemented Skill Chip model assigns each definition to one specialization
|
||||
ability. Each set owns one 2-piece bonus and may own one 3-piece Talent. One
|
||||
shared fixed primary profile serves every definition: Skill Duration, Skill
|
||||
Radius, Skill Cooldown Recovery, and Skill Intensity each store direct minimum
|
||||
and maximum values for Standard, Specialized, Superior, and High-end. These
|
||||
primary values apply to the assigned ability. Current Agent and combat totals
|
||||
exclude them and present them as `NOT YET DEFINED`.
|
||||
|
||||
One shared secondary Attribute pool also serves every definition. Its entries
|
||||
store direct minimum and maximum values for Specialized, Superior, and High-end.
|
||||
Secondary capacity is zero for Standard, one for Specialized, and two each for
|
||||
Superior and High-end. Skill Chips have no item levels, so workers must not
|
||||
infer level curves or level-based endpoints from Skill Chip evidence.
|
||||
|
||||
Every equipped quality counts toward the two-piece threshold. Only equipped
|
||||
High-end chips increase `h` in `minimum + (maximum - minimum) * h / 3`, where
|
||||
`h` ranges from zero through three. The unchanged version 1 contract vocabulary
|
||||
uses `skill_chip_roll_pool` for captured roll-profile evidence. Handoff
|
||||
consumers must map that evidence to the shared primary profile or shared
|
||||
secondary pool and must not attach either profile to an individual definition.
|
||||
The JSON schemas remain unchanged.
|
||||
|
||||
## Version Decision
|
||||
|
||||
The approved additive taxonomy change remains schema version 1. The document
|
||||
shapes, trust boundary, bounds, and meanings of every existing value are
|
||||
unchanged, and all existing version 1 labels and documents remain valid. This
|
||||
utility and its payloads are prototype formats; no production-stable archive or
|
||||
handoff version has been declared. A version increment would force a document
|
||||
migration without representing a structural or semantic break.
|
||||
|
||||
Consumers must update their closed version 1 vocabularies before they accept Mod
|
||||
labels. Older consumers reject the new values, which keeps the boundary fail
|
||||
closed. Existing stored labels need validation against the revised vocabulary
|
||||
but no value rewrite. The capture-label UI, storage regression coverage,
|
||||
classifier, extraction dispatch, evidence export, and ISAC adapter mappings must
|
||||
consume both families and their exact `detail`/record-type pairs before their
|
||||
respective gates can pass. This contract change does not alter those downstream
|
||||
implementations.
|
||||
|
||||
## Evidence Rules
|
||||
|
||||
Capture workers store source text, a normalized value, confidence, engine
|
||||
identity, an image digest, a bounded region, and append-only correction history
|
||||
for each evidence value. A null normalized value requires a `missing_reason`. A
|
||||
present normalized value requires a null `missing_reason`. Each correction's
|
||||
`before` state must match the preceding `after` state. Timestamps must increase,
|
||||
and the final `after` state must match the current evidence value.
|
||||
|
||||
Workers record the configured item shown on screen under `observed_instances`,
|
||||
including visible values and any applicable quality, tier, upgrade state, or
|
||||
level. Skill Chip observations omit item level because Skill Chips have none.
|
||||
Workers place proposed reusable definitions under `canonical_candidates` and
|
||||
handoff `records`. For Weapon Mods, Gear Mods, and Skill Chips, item-detail
|
||||
evidence remains separate from each family’s shared canonical profiles. A worker
|
||||
must not copy an observed roll, relationship, mechanic, range endpoint, option
|
||||
list, or secondary capacity into a canonical candidate unless evidence
|
||||
establishes that canonical claim.
|
||||
|
||||
## Trust Boundary
|
||||
|
||||
Archive and handoff documents contain content hashes and logical artifact IDs.
|
||||
They exclude host paths and credentials. The handoff declares
|
||||
`mutation_authority: "none"`. Importing or inspecting it grants no permission
|
||||
and performs no mutation. An authenticated ISAC action must revalidate each
|
||||
draft and preserve contributor moderation and audit behavior.
|
||||
|
||||
Archive images and handoff images allow at most 64 MiB. Private archive videos
|
||||
allow at most 16 GiB, matching the configured capture ceiling. Schema validation
|
||||
enforces media-specific byte limits. Semantic validation enforces unique entity
|
||||
and correction IDs, local references, evidence artifact hashes, correction
|
||||
chains, and normalized image bounds.
|
||||
|
||||
The contracts assign explicit states or reasons to cancellation, resource
|
||||
exhaustion, ambiguous classification, unsupported content, and extraction
|
||||
failure. Recovery requires a listed transition. Unknown transitions and future
|
||||
schema versions fail closed.
|
||||
@@ -1,173 +0,0 @@
|
||||
{
|
||||
"contract_version": 1,
|
||||
"families": {
|
||||
"weapon": {
|
||||
"gear_slot": false,
|
||||
"views": {
|
||||
"detail": ["weapon", "weapon_talent"],
|
||||
"blueprint": ["weapon", "weapon_talent"],
|
||||
"crafting": ["weapon"],
|
||||
"stat_range": ["weapon"],
|
||||
"talent_grid": ["weapon_talent"],
|
||||
"augmentation": ["weapon_augmentation_profile"]
|
||||
}
|
||||
},
|
||||
"gear": {
|
||||
"gear_slot": true,
|
||||
"views": {
|
||||
"detail": ["gear", "brand_set"],
|
||||
"blueprint": ["gear", "brand_set"],
|
||||
"talent": ["gear_talent"],
|
||||
"augmentation": ["gear_augmentation_profile"]
|
||||
}
|
||||
},
|
||||
"skill_chip": {
|
||||
"gear_slot": false,
|
||||
"views": {
|
||||
"detail": ["skill_chip_set", "skill_chip_roll_pool"],
|
||||
"set_bonus": ["skill_chip_set_bonus"],
|
||||
"talent": ["skill_chip_talent"]
|
||||
}
|
||||
},
|
||||
"os_protocol": {
|
||||
"gear_slot": false,
|
||||
"views": {
|
||||
"detail": ["os_protocol"],
|
||||
"secondary_profile": ["os_protocol_secondary_profile"],
|
||||
"talent": ["os_protocol_talent"]
|
||||
}
|
||||
},
|
||||
"specialization": {
|
||||
"gear_slot": false,
|
||||
"views": {
|
||||
"overview": ["specialization"],
|
||||
"details": ["specialization"],
|
||||
"ability": ["specialization_ability"],
|
||||
"focus_details": ["specialization_focus"],
|
||||
"focus_tree": ["specialization_focus", "specialization_tree_node"],
|
||||
"rank_details": ["specialization_tree_rank"]
|
||||
}
|
||||
},
|
||||
"weapon_mod": {
|
||||
"gear_slot": false,
|
||||
"views": {
|
||||
"detail": ["weapon_mod"]
|
||||
}
|
||||
},
|
||||
"gear_mod": {
|
||||
"gear_slot": false,
|
||||
"views": {
|
||||
"detail": ["gear_mod"]
|
||||
}
|
||||
},
|
||||
"unknown": {
|
||||
"gear_slot": false,
|
||||
"views": { "unknown": [] }
|
||||
}
|
||||
},
|
||||
"gear_slots": [
|
||||
"Mask",
|
||||
"Gloves",
|
||||
"Backpack",
|
||||
"Body Armor",
|
||||
"Holster",
|
||||
"Knee Pads"
|
||||
],
|
||||
"abstention_reasons": [
|
||||
"low_confidence",
|
||||
"ambiguous_family",
|
||||
"ambiguous_view",
|
||||
"unsupported_family",
|
||||
"unsupported_view",
|
||||
"insufficient_visual_evidence",
|
||||
"occluded",
|
||||
"corrupt_image",
|
||||
"resource_limit",
|
||||
"cancelled"
|
||||
],
|
||||
"missing_reasons": [
|
||||
"not_visible",
|
||||
"occluded",
|
||||
"unreadable",
|
||||
"not_present_on_screen",
|
||||
"unsupported",
|
||||
"ambiguous",
|
||||
"extraction_failed",
|
||||
"not_applicable",
|
||||
"redacted"
|
||||
],
|
||||
"states": {
|
||||
"capture": {
|
||||
"received": ["spooling", "deduplicated", "failed", "cancelled"],
|
||||
"spooling": ["stored", "failed", "cancelled"],
|
||||
"stored": ["queued", "failed"],
|
||||
"deduplicated": [],
|
||||
"queued": [],
|
||||
"failed": ["spooling", "cancelled"],
|
||||
"cancelled": []
|
||||
},
|
||||
"job": {
|
||||
"queued": ["running", "cancelled"],
|
||||
"running": ["succeeded", "retry_wait", "failed", "cancelled"],
|
||||
"retry_wait": ["queued", "failed", "cancelled"],
|
||||
"succeeded": [],
|
||||
"failed": ["queued"],
|
||||
"cancelled": []
|
||||
},
|
||||
"extraction": {
|
||||
"pending": ["local_processing", "cancelled"],
|
||||
"local_processing": [
|
||||
"candidate_ready",
|
||||
"fallback_pending",
|
||||
"abstained",
|
||||
"failed",
|
||||
"cancelled"
|
||||
],
|
||||
"fallback_pending": ["fallback_processing", "cancelled"],
|
||||
"fallback_processing": [
|
||||
"candidate_ready",
|
||||
"abstained",
|
||||
"failed",
|
||||
"cancelled"
|
||||
],
|
||||
"candidate_ready": [],
|
||||
"abstained": [],
|
||||
"failed": ["pending"],
|
||||
"cancelled": []
|
||||
},
|
||||
"grouping": {
|
||||
"ungrouped": ["proposed", "cancelled"],
|
||||
"proposed": ["grouped", "rejected", "cancelled"],
|
||||
"grouped": ["split", "superseded"],
|
||||
"split": ["superseded"],
|
||||
"superseded": [],
|
||||
"rejected": ["ungrouped"],
|
||||
"cancelled": []
|
||||
},
|
||||
"review": {
|
||||
"pending": ["in_review", "cancelled"],
|
||||
"in_review": ["changes_requested", "approved", "rejected", "cancelled"],
|
||||
"changes_requested": ["in_review", "rejected", "cancelled"],
|
||||
"approved": ["in_review"],
|
||||
"rejected": ["in_review"],
|
||||
"cancelled": []
|
||||
},
|
||||
"export": {
|
||||
"not_requested": ["queued"],
|
||||
"queued": ["building", "cancelled"],
|
||||
"building": ["ready", "failed", "cancelled"],
|
||||
"ready": ["expired"],
|
||||
"failed": ["queued", "cancelled"],
|
||||
"cancelled": [],
|
||||
"expired": ["queued"]
|
||||
},
|
||||
"error": {
|
||||
"open": ["retryable", "terminal", "dismissed"],
|
||||
"retryable": ["retrying", "terminal", "dismissed"],
|
||||
"retrying": ["recovered", "retryable", "terminal"],
|
||||
"recovered": [],
|
||||
"terminal": ["dismissed"],
|
||||
"dismissed": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,924 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://shd.build/schemas/game-data-capture/evidence-archive-manifest-v1.json",
|
||||
"title": "Game data capture evidence archive manifest v1",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"schema_version",
|
||||
"archive_id",
|
||||
"created_at",
|
||||
"generator",
|
||||
"artifacts",
|
||||
"captures",
|
||||
"screens",
|
||||
"jobs",
|
||||
"extractions",
|
||||
"groups",
|
||||
"reviews",
|
||||
"exports",
|
||||
"errors",
|
||||
"evidence_values",
|
||||
"observed_instances",
|
||||
"canonical_candidates"
|
||||
],
|
||||
"properties": {
|
||||
"schema_version": { "const": 1 },
|
||||
"archive_id": { "$ref": "#/$defs/id" },
|
||||
"created_at": { "$ref": "#/$defs/timestamp" },
|
||||
"generator": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["name", "version", "policy_version"],
|
||||
"properties": {
|
||||
"name": { "type": "string", "minLength": 1, "maxLength": 100 },
|
||||
"version": { "type": "string", "minLength": 1, "maxLength": 50 },
|
||||
"policy_version": { "type": "string", "minLength": 1, "maxLength": 50 }
|
||||
}
|
||||
},
|
||||
"artifacts": {
|
||||
"type": "array",
|
||||
"maxItems": 10000,
|
||||
"items": { "$ref": "#/$defs/artifact" }
|
||||
},
|
||||
"captures": {
|
||||
"type": "array",
|
||||
"maxItems": 10000,
|
||||
"items": { "$ref": "#/$defs/capture" }
|
||||
},
|
||||
"screens": {
|
||||
"type": "array",
|
||||
"maxItems": 10000,
|
||||
"items": { "$ref": "#/$defs/screen" }
|
||||
},
|
||||
"jobs": {
|
||||
"type": "array",
|
||||
"maxItems": 20000,
|
||||
"items": { "$ref": "#/$defs/job" }
|
||||
},
|
||||
"extractions": {
|
||||
"type": "array",
|
||||
"maxItems": 20000,
|
||||
"items": { "$ref": "#/$defs/extraction" }
|
||||
},
|
||||
"groups": {
|
||||
"type": "array",
|
||||
"maxItems": 10000,
|
||||
"items": { "$ref": "#/$defs/group" }
|
||||
},
|
||||
"reviews": {
|
||||
"type": "array",
|
||||
"maxItems": 10000,
|
||||
"items": { "$ref": "#/$defs/review" }
|
||||
},
|
||||
"exports": {
|
||||
"type": "array",
|
||||
"maxItems": 1000,
|
||||
"items": { "$ref": "#/$defs/export" }
|
||||
},
|
||||
"errors": {
|
||||
"type": "array",
|
||||
"maxItems": 20000,
|
||||
"items": { "$ref": "#/$defs/error" }
|
||||
},
|
||||
"evidence_values": {
|
||||
"type": "array",
|
||||
"maxItems": 100000,
|
||||
"items": { "$ref": "#/$defs/evidenceValue" }
|
||||
},
|
||||
"observed_instances": {
|
||||
"type": "array",
|
||||
"maxItems": 20000,
|
||||
"items": { "$ref": "#/$defs/observedInstance" }
|
||||
},
|
||||
"canonical_candidates": {
|
||||
"type": "array",
|
||||
"maxItems": 20000,
|
||||
"items": { "$ref": "#/$defs/canonicalCandidate" }
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
|
||||
},
|
||||
"sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" },
|
||||
"timestamp": { "type": "string", "format": "date-time", "maxLength": 40 },
|
||||
"family": {
|
||||
"enum": [
|
||||
"weapon",
|
||||
"gear",
|
||||
"skill_chip",
|
||||
"os_protocol",
|
||||
"specialization",
|
||||
"weapon_mod",
|
||||
"gear_mod",
|
||||
"unknown"
|
||||
]
|
||||
},
|
||||
"recordType": {
|
||||
"enum": [
|
||||
"weapon",
|
||||
"weapon_talent",
|
||||
"weapon_augmentation_profile",
|
||||
"gear",
|
||||
"brand_set",
|
||||
"gear_talent",
|
||||
"gear_augmentation_profile",
|
||||
"skill_chip_set",
|
||||
"skill_chip_set_bonus",
|
||||
"skill_chip_roll_pool",
|
||||
"skill_chip_talent",
|
||||
"os_protocol",
|
||||
"os_protocol_secondary_profile",
|
||||
"os_protocol_talent",
|
||||
"specialization",
|
||||
"specialization_focus",
|
||||
"specialization_ability",
|
||||
"specialization_tree_node",
|
||||
"specialization_tree_rank",
|
||||
"weapon_mod",
|
||||
"gear_mod"
|
||||
]
|
||||
},
|
||||
"missingReason": {
|
||||
"enum": [
|
||||
"not_visible",
|
||||
"occluded",
|
||||
"unreadable",
|
||||
"not_present_on_screen",
|
||||
"unsupported",
|
||||
"ambiguous",
|
||||
"extraction_failed",
|
||||
"not_applicable",
|
||||
"redacted"
|
||||
]
|
||||
},
|
||||
"jsonValue": {
|
||||
"oneOf": [
|
||||
{ "type": "null" },
|
||||
{ "type": "boolean" },
|
||||
{ "type": "number" },
|
||||
{ "type": "string", "maxLength": 8192 },
|
||||
{
|
||||
"type": "array",
|
||||
"maxItems": 500,
|
||||
"items": { "$ref": "#/$defs/jsonValue" }
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"maxProperties": 500,
|
||||
"additionalProperties": { "$ref": "#/$defs/jsonValue" }
|
||||
}
|
||||
]
|
||||
},
|
||||
"sourceEngine": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["kind", "engine_id", "engine_version"],
|
||||
"properties": {
|
||||
"kind": {
|
||||
"enum": [
|
||||
"local_ocr",
|
||||
"openai_vision",
|
||||
"classifier",
|
||||
"manual",
|
||||
"video_decoder"
|
||||
]
|
||||
},
|
||||
"engine_id": { "type": "string", "minLength": 1, "maxLength": 100 },
|
||||
"engine_version": { "type": "string", "minLength": 1, "maxLength": 100 }
|
||||
}
|
||||
},
|
||||
"region": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["coordinate_space", "x", "y", "width", "height"],
|
||||
"properties": {
|
||||
"coordinate_space": { "const": "normalized" },
|
||||
"x": { "type": "number", "minimum": 0, "maximum": 1 },
|
||||
"y": { "type": "number", "minimum": 0, "maximum": 1 },
|
||||
"width": { "type": "number", "exclusiveMinimum": 0, "maximum": 1 },
|
||||
"height": { "type": "number", "exclusiveMinimum": 0, "maximum": 1 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["coordinate_space", "x", "y", "width", "height"],
|
||||
"properties": {
|
||||
"coordinate_space": { "const": "pixels" },
|
||||
"x": { "type": "integer", "minimum": 0, "maximum": 100000 },
|
||||
"y": { "type": "integer", "minimum": 0, "maximum": 100000 },
|
||||
"width": { "type": "integer", "minimum": 1, "maximum": 100000 },
|
||||
"height": { "type": "integer", "minimum": 1, "maximum": 100000 }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueState": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["raw_text", "normalized_value", "missing_reason"],
|
||||
"properties": {
|
||||
"raw_text": { "type": ["string", "null"], "maxLength": 8192 },
|
||||
"normalized_value": { "$ref": "#/$defs/jsonValue" },
|
||||
"missing_reason": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/missingReason" }]
|
||||
}
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"normalized_value": { "type": "null" },
|
||||
"missing_reason": { "$ref": "#/$defs/missingReason" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"normalized_value": { "not": { "type": "null" } },
|
||||
"missing_reason": { "type": "null" }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"correction": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"correction_id",
|
||||
"corrected_at",
|
||||
"actor",
|
||||
"reason",
|
||||
"before",
|
||||
"after"
|
||||
],
|
||||
"properties": {
|
||||
"correction_id": { "$ref": "#/$defs/id" },
|
||||
"corrected_at": { "$ref": "#/$defs/timestamp" },
|
||||
"actor": { "enum": ["local_user", "system_reprocess"] },
|
||||
"reason": { "type": "string", "minLength": 1, "maxLength": 1000 },
|
||||
"before": { "$ref": "#/$defs/valueState" },
|
||||
"after": { "$ref": "#/$defs/valueState" }
|
||||
}
|
||||
},
|
||||
"evidenceValue": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"evidence_id",
|
||||
"field_path",
|
||||
"raw_text",
|
||||
"normalized_value",
|
||||
"missing_reason",
|
||||
"confidence",
|
||||
"source_engine",
|
||||
"image_artifact_id",
|
||||
"image_sha256",
|
||||
"region",
|
||||
"correction_history"
|
||||
],
|
||||
"properties": {
|
||||
"evidence_id": { "$ref": "#/$defs/id" },
|
||||
"field_path": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_.-]{1,256}$"
|
||||
},
|
||||
"raw_text": { "type": ["string", "null"], "maxLength": 8192 },
|
||||
"normalized_value": { "$ref": "#/$defs/jsonValue" },
|
||||
"missing_reason": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/missingReason" }]
|
||||
},
|
||||
"confidence": { "type": "number", "minimum": 0, "maximum": 1 },
|
||||
"source_engine": { "$ref": "#/$defs/sourceEngine" },
|
||||
"image_artifact_id": { "$ref": "#/$defs/id" },
|
||||
"image_sha256": { "$ref": "#/$defs/sha256" },
|
||||
"region": { "$ref": "#/$defs/region" },
|
||||
"correction_history": {
|
||||
"type": "array",
|
||||
"maxItems": 100,
|
||||
"items": { "$ref": "#/$defs/correction" }
|
||||
}
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"normalized_value": { "type": "null" },
|
||||
"missing_reason": { "$ref": "#/$defs/missingReason" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"normalized_value": { "not": { "type": "null" } },
|
||||
"missing_reason": { "type": "null" }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"fieldClaim": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"path",
|
||||
"value",
|
||||
"missing_reason",
|
||||
"evidence_refs",
|
||||
"uncertainty_note"
|
||||
],
|
||||
"properties": {
|
||||
"path": { "type": "string", "pattern": "^[A-Za-z0-9_.-]{1,256}$" },
|
||||
"value": { "$ref": "#/$defs/jsonValue" },
|
||||
"missing_reason": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/missingReason" }]
|
||||
},
|
||||
"evidence_refs": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 100,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
},
|
||||
"uncertainty_note": { "type": ["string", "null"], "maxLength": 2000 }
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"value": { "type": "null" },
|
||||
"missing_reason": { "$ref": "#/$defs/missingReason" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"value": { "not": { "type": "null" } },
|
||||
"missing_reason": { "type": "null" }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"classification": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"family",
|
||||
"view",
|
||||
"gear_slot",
|
||||
"record_types",
|
||||
"confidence",
|
||||
"abstention_reason"
|
||||
],
|
||||
"properties": {
|
||||
"family": { "$ref": "#/$defs/family" },
|
||||
"view": { "type": "string" },
|
||||
"gear_slot": { "type": ["string", "null"] },
|
||||
"record_types": {
|
||||
"type": "array",
|
||||
"uniqueItems": true,
|
||||
"maxItems": 8,
|
||||
"items": { "$ref": "#/$defs/recordType" }
|
||||
},
|
||||
"confidence": { "type": "number", "minimum": 0, "maximum": 1 },
|
||||
"abstention_reason": { "type": ["string", "null"] }
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "weapon" },
|
||||
"view": {
|
||||
"enum": [
|
||||
"detail",
|
||||
"blueprint",
|
||||
"crafting",
|
||||
"stat_range",
|
||||
"talent_grid",
|
||||
"augmentation"
|
||||
]
|
||||
},
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"enum": [
|
||||
"weapon",
|
||||
"weapon_talent",
|
||||
"weapon_augmentation_profile"
|
||||
]
|
||||
}
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "gear" },
|
||||
"view": {
|
||||
"enum": ["detail", "blueprint", "talent", "augmentation"]
|
||||
},
|
||||
"gear_slot": {
|
||||
"enum": [
|
||||
"Mask",
|
||||
"Gloves",
|
||||
"Backpack",
|
||||
"Body Armor",
|
||||
"Holster",
|
||||
"Knee Pads"
|
||||
]
|
||||
},
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"enum": [
|
||||
"gear",
|
||||
"brand_set",
|
||||
"gear_talent",
|
||||
"gear_augmentation_profile"
|
||||
]
|
||||
}
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "skill_chip" },
|
||||
"view": { "enum": ["detail", "set_bonus", "talent"] },
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"enum": [
|
||||
"skill_chip_set",
|
||||
"skill_chip_set_bonus",
|
||||
"skill_chip_roll_pool",
|
||||
"skill_chip_talent"
|
||||
]
|
||||
}
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "os_protocol" },
|
||||
"view": { "enum": ["detail", "secondary_profile", "talent"] },
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"enum": [
|
||||
"os_protocol",
|
||||
"os_protocol_secondary_profile",
|
||||
"os_protocol_talent"
|
||||
]
|
||||
}
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "specialization" },
|
||||
"view": {
|
||||
"enum": [
|
||||
"overview",
|
||||
"details",
|
||||
"ability",
|
||||
"focus_details",
|
||||
"focus_tree",
|
||||
"rank_details"
|
||||
]
|
||||
},
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"enum": [
|
||||
"specialization",
|
||||
"specialization_focus",
|
||||
"specialization_ability",
|
||||
"specialization_tree_node",
|
||||
"specialization_tree_rank"
|
||||
]
|
||||
}
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "weapon_mod" },
|
||||
"view": { "const": "detail" },
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"maxItems": 1,
|
||||
"items": { "const": "weapon_mod" }
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "gear_mod" },
|
||||
"view": { "const": "detail" },
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"maxItems": 1,
|
||||
"items": { "const": "gear_mod" }
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "unknown" },
|
||||
"view": { "const": "unknown" },
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": { "maxItems": 0 },
|
||||
"abstention_reason": {
|
||||
"enum": [
|
||||
"low_confidence",
|
||||
"ambiguous_family",
|
||||
"ambiguous_view",
|
||||
"unsupported_family",
|
||||
"unsupported_view",
|
||||
"insufficient_visual_evidence",
|
||||
"occluded",
|
||||
"corrupt_image",
|
||||
"resource_limit",
|
||||
"cancelled"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"artifact": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"artifact_id",
|
||||
"sha256",
|
||||
"media_type",
|
||||
"byte_size",
|
||||
"sensitivity",
|
||||
"parent_artifact_id",
|
||||
"video_timestamp_ms"
|
||||
],
|
||||
"properties": {
|
||||
"artifact_id": { "$ref": "#/$defs/id" },
|
||||
"sha256": { "$ref": "#/$defs/sha256" },
|
||||
"media_type": {
|
||||
"enum": [
|
||||
"image/png",
|
||||
"image/webp",
|
||||
"image/avif",
|
||||
"video/mp4",
|
||||
"video/webm",
|
||||
"video/x-matroska"
|
||||
]
|
||||
},
|
||||
"byte_size": { "type": "integer", "minimum": 1 },
|
||||
"sensitivity": { "const": "private" },
|
||||
"parent_artifact_id": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/id" }]
|
||||
},
|
||||
"video_timestamp_ms": {
|
||||
"type": ["integer", "null"],
|
||||
"minimum": 0,
|
||||
"maximum": 86400000
|
||||
}
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"media_type": { "enum": ["image/png", "image/webp", "image/avif"] },
|
||||
"byte_size": { "maximum": 67108864 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"media_type": {
|
||||
"enum": ["video/mp4", "video/webm", "video/x-matroska"]
|
||||
},
|
||||
"byte_size": { "maximum": 17179869184 }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"capture": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"capture_id",
|
||||
"artifact_id",
|
||||
"state",
|
||||
"received_at",
|
||||
"failure_reason"
|
||||
],
|
||||
"properties": {
|
||||
"capture_id": { "$ref": "#/$defs/id" },
|
||||
"artifact_id": { "$ref": "#/$defs/id" },
|
||||
"state": {
|
||||
"enum": [
|
||||
"received",
|
||||
"spooling",
|
||||
"stored",
|
||||
"deduplicated",
|
||||
"queued",
|
||||
"failed",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"received_at": { "$ref": "#/$defs/timestamp" },
|
||||
"failure_reason": { "type": ["string", "null"], "maxLength": 2000 }
|
||||
}
|
||||
},
|
||||
"screen": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"screen_id",
|
||||
"artifact_id",
|
||||
"classified_at",
|
||||
"classification"
|
||||
],
|
||||
"properties": {
|
||||
"screen_id": { "$ref": "#/$defs/id" },
|
||||
"artifact_id": { "$ref": "#/$defs/id" },
|
||||
"classified_at": { "$ref": "#/$defs/timestamp" },
|
||||
"classification": { "$ref": "#/$defs/classification" }
|
||||
}
|
||||
},
|
||||
"job": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"job_id",
|
||||
"kind",
|
||||
"state",
|
||||
"attempt",
|
||||
"max_attempts",
|
||||
"last_error_id"
|
||||
],
|
||||
"properties": {
|
||||
"job_id": { "$ref": "#/$defs/id" },
|
||||
"kind": {
|
||||
"enum": [
|
||||
"classify",
|
||||
"ocr",
|
||||
"vision_fallback",
|
||||
"frame_extract",
|
||||
"export"
|
||||
]
|
||||
},
|
||||
"state": {
|
||||
"enum": [
|
||||
"queued",
|
||||
"running",
|
||||
"retry_wait",
|
||||
"succeeded",
|
||||
"failed",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"attempt": { "type": "integer", "minimum": 0, "maximum": 20 },
|
||||
"max_attempts": { "type": "integer", "minimum": 1, "maximum": 20 },
|
||||
"last_error_id": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/id" }]
|
||||
}
|
||||
}
|
||||
},
|
||||
"extraction": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"extraction_id",
|
||||
"screen_id",
|
||||
"state",
|
||||
"evidence_refs",
|
||||
"abstention_reason"
|
||||
],
|
||||
"properties": {
|
||||
"extraction_id": { "$ref": "#/$defs/id" },
|
||||
"screen_id": { "$ref": "#/$defs/id" },
|
||||
"state": {
|
||||
"enum": [
|
||||
"pending",
|
||||
"local_processing",
|
||||
"fallback_pending",
|
||||
"fallback_processing",
|
||||
"candidate_ready",
|
||||
"abstained",
|
||||
"failed",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"evidence_refs": {
|
||||
"type": "array",
|
||||
"maxItems": 1000,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
},
|
||||
"abstention_reason": { "type": ["string", "null"], "maxLength": 100 }
|
||||
}
|
||||
},
|
||||
"group": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["group_id", "state", "screen_ids", "supersedes_group_ids"],
|
||||
"properties": {
|
||||
"group_id": { "$ref": "#/$defs/id" },
|
||||
"state": {
|
||||
"enum": [
|
||||
"ungrouped",
|
||||
"proposed",
|
||||
"grouped",
|
||||
"split",
|
||||
"superseded",
|
||||
"rejected",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"screen_ids": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 100,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
},
|
||||
"supersedes_group_ids": {
|
||||
"type": "array",
|
||||
"maxItems": 100,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"review": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["review_id", "candidate_id", "state", "updated_at", "note"],
|
||||
"properties": {
|
||||
"review_id": { "$ref": "#/$defs/id" },
|
||||
"candidate_id": { "$ref": "#/$defs/id" },
|
||||
"state": {
|
||||
"enum": [
|
||||
"pending",
|
||||
"in_review",
|
||||
"changes_requested",
|
||||
"approved",
|
||||
"rejected",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"updated_at": { "$ref": "#/$defs/timestamp" },
|
||||
"note": { "type": ["string", "null"], "maxLength": 4000 }
|
||||
}
|
||||
},
|
||||
"export": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["export_id", "state", "artifact_id", "failure_reason"],
|
||||
"properties": {
|
||||
"export_id": { "$ref": "#/$defs/id" },
|
||||
"state": {
|
||||
"enum": [
|
||||
"not_requested",
|
||||
"queued",
|
||||
"building",
|
||||
"ready",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"expired"
|
||||
]
|
||||
},
|
||||
"artifact_id": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/id" }]
|
||||
},
|
||||
"failure_reason": { "type": ["string", "null"], "maxLength": 2000 }
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["error_id", "state", "code", "message", "retry_after"],
|
||||
"properties": {
|
||||
"error_id": { "$ref": "#/$defs/id" },
|
||||
"state": {
|
||||
"enum": [
|
||||
"open",
|
||||
"retryable",
|
||||
"retrying",
|
||||
"recovered",
|
||||
"terminal",
|
||||
"dismissed"
|
||||
]
|
||||
},
|
||||
"code": {
|
||||
"enum": [
|
||||
"cancelled",
|
||||
"resource_limit",
|
||||
"timeout",
|
||||
"invalid_input",
|
||||
"engine_failure",
|
||||
"storage_failure",
|
||||
"network_failure",
|
||||
"schema_rejected",
|
||||
"unsupported",
|
||||
"ambiguous"
|
||||
]
|
||||
},
|
||||
"message": { "type": "string", "minLength": 1, "maxLength": 2000 },
|
||||
"retry_after": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/timestamp" }]
|
||||
}
|
||||
}
|
||||
},
|
||||
"observedContext": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["level", "quality", "tier", "upgrade_state"],
|
||||
"properties": {
|
||||
"level": { "$ref": "#/$defs/fieldClaim" },
|
||||
"quality": { "$ref": "#/$defs/fieldClaim" },
|
||||
"tier": { "$ref": "#/$defs/fieldClaim" },
|
||||
"upgrade_state": { "$ref": "#/$defs/fieldClaim" }
|
||||
}
|
||||
},
|
||||
"observedInstance": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"instance_id",
|
||||
"family",
|
||||
"source_screen_ids",
|
||||
"observed_context",
|
||||
"fields"
|
||||
],
|
||||
"properties": {
|
||||
"instance_id": { "$ref": "#/$defs/id" },
|
||||
"family": { "$ref": "#/$defs/family" },
|
||||
"source_screen_ids": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 100,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
},
|
||||
"observed_context": { "$ref": "#/$defs/observedContext" },
|
||||
"fields": {
|
||||
"type": "array",
|
||||
"maxItems": 1000,
|
||||
"items": { "$ref": "#/$defs/fieldClaim" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"canonicalCandidate": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"candidate_id",
|
||||
"record_type",
|
||||
"source_instance_ids",
|
||||
"evidence_refs",
|
||||
"fields",
|
||||
"completeness",
|
||||
"relationship_status",
|
||||
"mechanic_status"
|
||||
],
|
||||
"properties": {
|
||||
"candidate_id": { "$ref": "#/$defs/id" },
|
||||
"record_type": { "$ref": "#/$defs/recordType" },
|
||||
"source_instance_ids": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 100,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
},
|
||||
"evidence_refs": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 1000,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
},
|
||||
"fields": {
|
||||
"type": "array",
|
||||
"maxItems": 1000,
|
||||
"items": { "$ref": "#/$defs/fieldClaim" }
|
||||
},
|
||||
"completeness": { "enum": ["complete", "incomplete", "unsupported"] },
|
||||
"relationship_status": {
|
||||
"enum": ["evidenced", "unresolved", "unsupported", "not_applicable"]
|
||||
},
|
||||
"mechanic_status": {
|
||||
"enum": ["evidenced", "unresolved", "unsupported", "not_applicable"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"schema_version": 2,
|
||||
"archive_id": "future-archive"
|
||||
}
|
||||
@@ -1,282 +0,0 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"archive_id": "archive-001",
|
||||
"created_at": "2026-07-31T12:00:00Z",
|
||||
"generator": {
|
||||
"name": "game-data-capture",
|
||||
"version": "0.1.0",
|
||||
"policy_version": "1"
|
||||
},
|
||||
"artifacts": [
|
||||
{
|
||||
"artifact_id": "image-001",
|
||||
"sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"media_type": "image/png",
|
||||
"byte_size": 2048,
|
||||
"sensitivity": "private",
|
||||
"parent_artifact_id": null,
|
||||
"video_timestamp_ms": null
|
||||
}
|
||||
],
|
||||
"captures": [
|
||||
{
|
||||
"capture_id": "capture-001",
|
||||
"artifact_id": "image-001",
|
||||
"state": "queued",
|
||||
"received_at": "2026-07-31T11:59:55Z",
|
||||
"failure_reason": null
|
||||
}
|
||||
],
|
||||
"screens": [
|
||||
{
|
||||
"screen_id": "screen-001",
|
||||
"artifact_id": "image-001",
|
||||
"classified_at": "2026-07-31T11:59:57Z",
|
||||
"classification": {
|
||||
"family": "weapon",
|
||||
"view": "detail",
|
||||
"gear_slot": null,
|
||||
"record_types": ["weapon", "weapon_talent"],
|
||||
"confidence": 0.97,
|
||||
"abstention_reason": null
|
||||
}
|
||||
}
|
||||
],
|
||||
"jobs": [],
|
||||
"extractions": [],
|
||||
"groups": [],
|
||||
"reviews": [
|
||||
{
|
||||
"review_id": "review-001",
|
||||
"candidate_id": "candidate-001",
|
||||
"state": "approved",
|
||||
"updated_at": "2026-07-31T12:00:00Z",
|
||||
"note": "Name verified against the image."
|
||||
}
|
||||
],
|
||||
"exports": [],
|
||||
"errors": [],
|
||||
"evidence_values": [
|
||||
{
|
||||
"evidence_id": "evidence-name",
|
||||
"field_path": "weapon.name",
|
||||
"raw_text": "LVOA-C",
|
||||
"normalized_value": "LVOA-C",
|
||||
"missing_reason": null,
|
||||
"confidence": 0.99,
|
||||
"source_engine": {
|
||||
"kind": "local_ocr",
|
||||
"engine_id": "fixture-ocr",
|
||||
"engine_version": "1"
|
||||
},
|
||||
"image_artifact_id": "image-001",
|
||||
"image_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"region": {
|
||||
"coordinate_space": "normalized",
|
||||
"x": 0.1,
|
||||
"y": 0.1,
|
||||
"width": 0.3,
|
||||
"height": 0.08
|
||||
},
|
||||
"correction_history": []
|
||||
},
|
||||
{
|
||||
"evidence_id": "evidence-level",
|
||||
"field_path": "observed.level",
|
||||
"raw_text": "20",
|
||||
"normalized_value": 20,
|
||||
"missing_reason": null,
|
||||
"confidence": 0.98,
|
||||
"source_engine": {
|
||||
"kind": "local_ocr",
|
||||
"engine_id": "fixture-ocr",
|
||||
"engine_version": "1"
|
||||
},
|
||||
"image_artifact_id": "image-001",
|
||||
"image_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"region": {
|
||||
"coordinate_space": "pixels",
|
||||
"x": 50,
|
||||
"y": 50,
|
||||
"width": 80,
|
||||
"height": 30
|
||||
},
|
||||
"correction_history": []
|
||||
},
|
||||
{
|
||||
"evidence_id": "evidence-quality",
|
||||
"field_path": "observed.quality",
|
||||
"raw_text": "High-end",
|
||||
"normalized_value": "High-end",
|
||||
"missing_reason": null,
|
||||
"confidence": 0.96,
|
||||
"source_engine": {
|
||||
"kind": "local_ocr",
|
||||
"engine_id": "fixture-ocr",
|
||||
"engine_version": "1"
|
||||
},
|
||||
"image_artifact_id": "image-001",
|
||||
"image_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"region": {
|
||||
"coordinate_space": "pixels",
|
||||
"x": 50,
|
||||
"y": 85,
|
||||
"width": 140,
|
||||
"height": 30
|
||||
},
|
||||
"correction_history": []
|
||||
},
|
||||
{
|
||||
"evidence_id": "evidence-tier",
|
||||
"field_path": "observed.tier",
|
||||
"raw_text": "T1",
|
||||
"normalized_value": 1,
|
||||
"missing_reason": null,
|
||||
"confidence": 0.97,
|
||||
"source_engine": {
|
||||
"kind": "local_ocr",
|
||||
"engine_id": "fixture-ocr",
|
||||
"engine_version": "1"
|
||||
},
|
||||
"image_artifact_id": "image-001",
|
||||
"image_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"region": {
|
||||
"coordinate_space": "pixels",
|
||||
"x": 200,
|
||||
"y": 85,
|
||||
"width": 60,
|
||||
"height": 30
|
||||
},
|
||||
"correction_history": []
|
||||
},
|
||||
{
|
||||
"evidence_id": "evidence-upgrade",
|
||||
"field_path": "observed.upgrade_state",
|
||||
"raw_text": null,
|
||||
"normalized_value": null,
|
||||
"missing_reason": "not_visible",
|
||||
"confidence": 0,
|
||||
"source_engine": {
|
||||
"kind": "manual",
|
||||
"engine_id": "review",
|
||||
"engine_version": "1"
|
||||
},
|
||||
"image_artifact_id": "image-001",
|
||||
"image_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"region": {
|
||||
"coordinate_space": "normalized",
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 1,
|
||||
"height": 1
|
||||
},
|
||||
"correction_history": []
|
||||
},
|
||||
{
|
||||
"evidence_id": "evidence-damage",
|
||||
"field_path": "observed.damage",
|
||||
"raw_text": "12,400",
|
||||
"normalized_value": 12400,
|
||||
"missing_reason": null,
|
||||
"confidence": 1,
|
||||
"source_engine": {
|
||||
"kind": "manual",
|
||||
"engine_id": "review",
|
||||
"engine_version": "1"
|
||||
},
|
||||
"image_artifact_id": "image-001",
|
||||
"image_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"region": {
|
||||
"coordinate_space": "pixels",
|
||||
"x": 300,
|
||||
"y": 200,
|
||||
"width": 160,
|
||||
"height": 40
|
||||
},
|
||||
"correction_history": [
|
||||
{
|
||||
"correction_id": "correction-001",
|
||||
"corrected_at": "2026-07-31T12:00:00Z",
|
||||
"actor": "local_user",
|
||||
"reason": "Corrected a missing zero.",
|
||||
"before": {
|
||||
"raw_text": "1,240",
|
||||
"normalized_value": 1240,
|
||||
"missing_reason": null
|
||||
},
|
||||
"after": {
|
||||
"raw_text": "12,400",
|
||||
"normalized_value": 12400,
|
||||
"missing_reason": null
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"observed_instances": [
|
||||
{
|
||||
"instance_id": "instance-001",
|
||||
"family": "weapon",
|
||||
"source_screen_ids": ["screen-001"],
|
||||
"observed_context": {
|
||||
"level": {
|
||||
"path": "observed.level",
|
||||
"value": 20,
|
||||
"missing_reason": null,
|
||||
"evidence_refs": ["evidence-level"],
|
||||
"uncertainty_note": null
|
||||
},
|
||||
"quality": {
|
||||
"path": "observed.quality",
|
||||
"value": "High-end",
|
||||
"missing_reason": null,
|
||||
"evidence_refs": ["evidence-quality"],
|
||||
"uncertainty_note": null
|
||||
},
|
||||
"tier": {
|
||||
"path": "observed.tier",
|
||||
"value": 1,
|
||||
"missing_reason": null,
|
||||
"evidence_refs": ["evidence-tier"],
|
||||
"uncertainty_note": null
|
||||
},
|
||||
"upgrade_state": {
|
||||
"path": "observed.upgrade_state",
|
||||
"value": null,
|
||||
"missing_reason": "not_visible",
|
||||
"evidence_refs": ["evidence-upgrade"],
|
||||
"uncertainty_note": "The screen does not show an upgrade indicator."
|
||||
}
|
||||
},
|
||||
"fields": [
|
||||
{
|
||||
"path": "observed.damage",
|
||||
"value": 12400,
|
||||
"missing_reason": null,
|
||||
"evidence_refs": ["evidence-damage"],
|
||||
"uncertainty_note": "This is the configured level-20 instance value, not a canonical range endpoint."
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"canonical_candidates": [
|
||||
{
|
||||
"candidate_id": "candidate-001",
|
||||
"record_type": "weapon",
|
||||
"source_instance_ids": ["instance-001"],
|
||||
"evidence_refs": ["evidence-name"],
|
||||
"fields": [
|
||||
{
|
||||
"path": "weapon.name",
|
||||
"value": "LVOA-C",
|
||||
"missing_reason": null,
|
||||
"evidence_refs": ["evidence-name"],
|
||||
"uncertainty_note": null
|
||||
}
|
||||
],
|
||||
"completeness": "incomplete",
|
||||
"relationship_status": "unresolved",
|
||||
"mechanic_status": "not_applicable"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "gear",
|
||||
"view": "detail",
|
||||
"gear_slot": "Vest",
|
||||
"record_types": ["gear"],
|
||||
"confidence": 0.95,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "gear",
|
||||
"view": "talent",
|
||||
"gear_slot": "Body Armor",
|
||||
"record_types": ["gear_talent"],
|
||||
"confidence": 0.95,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "gear_mod",
|
||||
"view": "detail",
|
||||
"gear_slot": "Mask",
|
||||
"record_types": ["gear_mod"],
|
||||
"confidence": 0.95,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "gear_mod",
|
||||
"view": "detail",
|
||||
"gear_slot": null,
|
||||
"record_types": ["gear_mod"],
|
||||
"confidence": 0.95,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "os_protocol",
|
||||
"view": "secondary_profile",
|
||||
"gear_slot": null,
|
||||
"record_types": ["os_protocol_secondary_profile"],
|
||||
"confidence": 1.3,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "os_protocol",
|
||||
"view": "secondary_profile",
|
||||
"gear_slot": null,
|
||||
"record_types": ["os_protocol_secondary_profile"],
|
||||
"confidence": 0.93,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "skill_chip",
|
||||
"view": "detail",
|
||||
"gear_slot": null,
|
||||
"record_types": ["weapon"],
|
||||
"confidence": 0.94,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "skill_chip",
|
||||
"view": "set_bonus",
|
||||
"gear_slot": null,
|
||||
"record_types": ["skill_chip_set_bonus"],
|
||||
"confidence": 0.94,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "specialization",
|
||||
"view": "focus_tree",
|
||||
"gear_slot": null,
|
||||
"record_types": ["specialization_tree_node"],
|
||||
"confidence": 0.91,
|
||||
"abstention_reason": "ambiguous_view"
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "specialization",
|
||||
"view": "focus_tree",
|
||||
"gear_slot": null,
|
||||
"record_types": ["specialization_focus", "specialization_tree_node"],
|
||||
"confidence": 0.91,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "unknown",
|
||||
"view": "unknown",
|
||||
"gear_slot": null,
|
||||
"record_types": ["weapon"],
|
||||
"confidence": 0.22,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "unknown",
|
||||
"view": "unknown",
|
||||
"gear_slot": null,
|
||||
"record_types": [],
|
||||
"confidence": 0.22,
|
||||
"abstention_reason": "low_confidence"
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "weapon",
|
||||
"view": "talent",
|
||||
"gear_slot": null,
|
||||
"record_types": ["weapon"],
|
||||
"confidence": 0.9,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "weapon",
|
||||
"view": "detail",
|
||||
"gear_slot": null,
|
||||
"record_types": ["weapon", "weapon_talent"],
|
||||
"confidence": 0.97,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "weapon_mod",
|
||||
"view": "effect",
|
||||
"gear_slot": null,
|
||||
"record_types": ["weapon_mod"],
|
||||
"confidence": 0.96,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"family": "weapon_mod",
|
||||
"view": "detail",
|
||||
"gear_slot": null,
|
||||
"record_types": ["weapon_mod"],
|
||||
"confidence": 0.96,
|
||||
"abstention_reason": null
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"schema_version": 2,
|
||||
"handoff_id": "future-handoff"
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"handoff_id": "handoff-001",
|
||||
"created_at": "2026-07-31T12:05:00Z",
|
||||
"source_archive": {
|
||||
"archive_id": "archive-001",
|
||||
"manifest_sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
|
||||
"schema_version": 1
|
||||
},
|
||||
"trust_boundary": {
|
||||
"intended_destination": "authenticated_isac_intake",
|
||||
"mutation_authority": "none",
|
||||
"requires_authenticated_action": true,
|
||||
"preserves_moderation": true,
|
||||
"creates_audit_events": false
|
||||
},
|
||||
"source_artifacts": [
|
||||
{
|
||||
"artifact_id": "image-001",
|
||||
"sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"media_type": "image/png",
|
||||
"byte_size": 2048
|
||||
}
|
||||
],
|
||||
"evidence_values": [
|
||||
{
|
||||
"evidence_id": "evidence-name",
|
||||
"field_path": "weapon.name",
|
||||
"raw_text": "LVOA-C",
|
||||
"normalized_value": "LVOA-C",
|
||||
"missing_reason": null,
|
||||
"confidence": 0.99,
|
||||
"source_engine": {
|
||||
"kind": "local_ocr",
|
||||
"engine_id": "fixture-ocr",
|
||||
"engine_version": "1"
|
||||
},
|
||||
"image_artifact_id": "image-001",
|
||||
"image_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"region": {
|
||||
"coordinate_space": "normalized",
|
||||
"x": 0.1,
|
||||
"y": 0.1,
|
||||
"width": 0.3,
|
||||
"height": 0.08
|
||||
},
|
||||
"correction_history": []
|
||||
}
|
||||
],
|
||||
"records": [
|
||||
{
|
||||
"handoff_record_id": "handoff-record-001",
|
||||
"record_type": "weapon",
|
||||
"intent": "create_draft",
|
||||
"target_id": null,
|
||||
"review_state": "approved",
|
||||
"source_candidate_ids": ["candidate-001"],
|
||||
"observed_instance_ids": ["instance-001"],
|
||||
"fields": [
|
||||
{
|
||||
"path": "weapon.name",
|
||||
"value": "LVOA-C",
|
||||
"missing_reason": null,
|
||||
"evidence_refs": ["evidence-name"],
|
||||
"uncertainty_note": null
|
||||
}
|
||||
],
|
||||
"relationships": {
|
||||
"status": "unresolved",
|
||||
"evidence_refs": [],
|
||||
"note": "ISAC must resolve and validate canonical relationships before submission."
|
||||
},
|
||||
"mechanics": {
|
||||
"status": "not_applicable",
|
||||
"evidence_refs": [],
|
||||
"note": null
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,412 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://shd.build/schemas/game-data-capture/isac-handoff-v1.json",
|
||||
"title": "Authenticated ISAC draft handoff v1",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"schema_version",
|
||||
"handoff_id",
|
||||
"created_at",
|
||||
"source_archive",
|
||||
"trust_boundary",
|
||||
"source_artifacts",
|
||||
"evidence_values",
|
||||
"records"
|
||||
],
|
||||
"properties": {
|
||||
"schema_version": { "const": 1 },
|
||||
"handoff_id": { "$ref": "#/$defs/id" },
|
||||
"created_at": { "$ref": "#/$defs/timestamp" },
|
||||
"source_archive": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["archive_id", "manifest_sha256", "schema_version"],
|
||||
"properties": {
|
||||
"archive_id": { "$ref": "#/$defs/id" },
|
||||
"manifest_sha256": { "$ref": "#/$defs/sha256" },
|
||||
"schema_version": { "const": 1 }
|
||||
}
|
||||
},
|
||||
"trust_boundary": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"intended_destination",
|
||||
"mutation_authority",
|
||||
"requires_authenticated_action",
|
||||
"preserves_moderation",
|
||||
"creates_audit_events"
|
||||
],
|
||||
"properties": {
|
||||
"intended_destination": { "const": "authenticated_isac_intake" },
|
||||
"mutation_authority": { "const": "none" },
|
||||
"requires_authenticated_action": { "const": true },
|
||||
"preserves_moderation": { "const": true },
|
||||
"creates_audit_events": { "const": false }
|
||||
}
|
||||
},
|
||||
"source_artifacts": {
|
||||
"type": "array",
|
||||
"maxItems": 10000,
|
||||
"items": { "$ref": "#/$defs/sourceArtifact" }
|
||||
},
|
||||
"evidence_values": {
|
||||
"type": "array",
|
||||
"maxItems": 100000,
|
||||
"items": { "$ref": "#/$defs/evidenceValue" }
|
||||
},
|
||||
"records": {
|
||||
"type": "array",
|
||||
"maxItems": 20000,
|
||||
"items": { "$ref": "#/$defs/handoffRecord" }
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"
|
||||
},
|
||||
"sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" },
|
||||
"timestamp": { "type": "string", "format": "date-time", "maxLength": 40 },
|
||||
"recordType": {
|
||||
"enum": [
|
||||
"weapon",
|
||||
"weapon_talent",
|
||||
"weapon_augmentation_profile",
|
||||
"gear",
|
||||
"brand_set",
|
||||
"gear_talent",
|
||||
"gear_augmentation_profile",
|
||||
"skill_chip_set",
|
||||
"skill_chip_set_bonus",
|
||||
"skill_chip_roll_pool",
|
||||
"skill_chip_talent",
|
||||
"os_protocol",
|
||||
"os_protocol_secondary_profile",
|
||||
"os_protocol_talent",
|
||||
"specialization",
|
||||
"specialization_focus",
|
||||
"specialization_ability",
|
||||
"specialization_tree_node",
|
||||
"specialization_tree_rank",
|
||||
"weapon_mod",
|
||||
"gear_mod"
|
||||
]
|
||||
},
|
||||
"missingReason": {
|
||||
"enum": [
|
||||
"not_visible",
|
||||
"occluded",
|
||||
"unreadable",
|
||||
"not_present_on_screen",
|
||||
"unsupported",
|
||||
"ambiguous",
|
||||
"extraction_failed",
|
||||
"not_applicable",
|
||||
"redacted"
|
||||
]
|
||||
},
|
||||
"jsonValue": {
|
||||
"oneOf": [
|
||||
{ "type": "null" },
|
||||
{ "type": "boolean" },
|
||||
{ "type": "number" },
|
||||
{ "type": "string", "maxLength": 8192 },
|
||||
{
|
||||
"type": "array",
|
||||
"maxItems": 500,
|
||||
"items": { "$ref": "#/$defs/jsonValue" }
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"maxProperties": 500,
|
||||
"additionalProperties": { "$ref": "#/$defs/jsonValue" }
|
||||
}
|
||||
]
|
||||
},
|
||||
"sourceEngine": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["kind", "engine_id", "engine_version"],
|
||||
"properties": {
|
||||
"kind": {
|
||||
"enum": [
|
||||
"local_ocr",
|
||||
"openai_vision",
|
||||
"classifier",
|
||||
"manual",
|
||||
"video_decoder"
|
||||
]
|
||||
},
|
||||
"engine_id": { "type": "string", "minLength": 1, "maxLength": 100 },
|
||||
"engine_version": { "type": "string", "minLength": 1, "maxLength": 100 }
|
||||
}
|
||||
},
|
||||
"region": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["coordinate_space", "x", "y", "width", "height"],
|
||||
"properties": {
|
||||
"coordinate_space": { "const": "normalized" },
|
||||
"x": { "type": "number", "minimum": 0, "maximum": 1 },
|
||||
"y": { "type": "number", "minimum": 0, "maximum": 1 },
|
||||
"width": { "type": "number", "exclusiveMinimum": 0, "maximum": 1 },
|
||||
"height": { "type": "number", "exclusiveMinimum": 0, "maximum": 1 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["coordinate_space", "x", "y", "width", "height"],
|
||||
"properties": {
|
||||
"coordinate_space": { "const": "pixels" },
|
||||
"x": { "type": "integer", "minimum": 0, "maximum": 100000 },
|
||||
"y": { "type": "integer", "minimum": 0, "maximum": 100000 },
|
||||
"width": { "type": "integer", "minimum": 1, "maximum": 100000 },
|
||||
"height": { "type": "integer", "minimum": 1, "maximum": 100000 }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueState": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["raw_text", "normalized_value", "missing_reason"],
|
||||
"properties": {
|
||||
"raw_text": { "type": ["string", "null"], "maxLength": 8192 },
|
||||
"normalized_value": { "$ref": "#/$defs/jsonValue" },
|
||||
"missing_reason": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/missingReason" }]
|
||||
}
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"normalized_value": { "type": "null" },
|
||||
"missing_reason": { "$ref": "#/$defs/missingReason" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"normalized_value": { "not": { "type": "null" } },
|
||||
"missing_reason": { "type": "null" }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"correction": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"correction_id",
|
||||
"corrected_at",
|
||||
"actor",
|
||||
"reason",
|
||||
"before",
|
||||
"after"
|
||||
],
|
||||
"properties": {
|
||||
"correction_id": { "$ref": "#/$defs/id" },
|
||||
"corrected_at": { "$ref": "#/$defs/timestamp" },
|
||||
"actor": { "enum": ["local_user", "system_reprocess"] },
|
||||
"reason": { "type": "string", "minLength": 1, "maxLength": 1000 },
|
||||
"before": { "$ref": "#/$defs/valueState" },
|
||||
"after": { "$ref": "#/$defs/valueState" }
|
||||
}
|
||||
},
|
||||
"evidenceValue": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"evidence_id",
|
||||
"field_path",
|
||||
"raw_text",
|
||||
"normalized_value",
|
||||
"missing_reason",
|
||||
"confidence",
|
||||
"source_engine",
|
||||
"image_artifact_id",
|
||||
"image_sha256",
|
||||
"region",
|
||||
"correction_history"
|
||||
],
|
||||
"properties": {
|
||||
"evidence_id": { "$ref": "#/$defs/id" },
|
||||
"field_path": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_.-]{1,256}$"
|
||||
},
|
||||
"raw_text": { "type": ["string", "null"], "maxLength": 8192 },
|
||||
"normalized_value": { "$ref": "#/$defs/jsonValue" },
|
||||
"missing_reason": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/missingReason" }]
|
||||
},
|
||||
"confidence": { "type": "number", "minimum": 0, "maximum": 1 },
|
||||
"source_engine": { "$ref": "#/$defs/sourceEngine" },
|
||||
"image_artifact_id": { "$ref": "#/$defs/id" },
|
||||
"image_sha256": { "$ref": "#/$defs/sha256" },
|
||||
"region": { "$ref": "#/$defs/region" },
|
||||
"correction_history": {
|
||||
"type": "array",
|
||||
"maxItems": 100,
|
||||
"items": { "$ref": "#/$defs/correction" }
|
||||
}
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"normalized_value": { "type": "null" },
|
||||
"missing_reason": { "$ref": "#/$defs/missingReason" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"normalized_value": { "not": { "type": "null" } },
|
||||
"missing_reason": { "type": "null" }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"fieldClaim": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"path",
|
||||
"value",
|
||||
"missing_reason",
|
||||
"evidence_refs",
|
||||
"uncertainty_note"
|
||||
],
|
||||
"properties": {
|
||||
"path": { "type": "string", "pattern": "^[A-Za-z0-9_.-]{1,256}$" },
|
||||
"value": { "$ref": "#/$defs/jsonValue" },
|
||||
"missing_reason": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/missingReason" }]
|
||||
},
|
||||
"evidence_refs": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 100,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
},
|
||||
"uncertainty_note": { "type": ["string", "null"], "maxLength": 2000 }
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"value": { "type": "null" },
|
||||
"missing_reason": { "$ref": "#/$defs/missingReason" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"value": { "not": { "type": "null" } },
|
||||
"missing_reason": { "type": "null" }
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"sourceArtifact": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["artifact_id", "sha256", "media_type", "byte_size"],
|
||||
"properties": {
|
||||
"artifact_id": { "$ref": "#/$defs/id" },
|
||||
"sha256": { "$ref": "#/$defs/sha256" },
|
||||
"media_type": { "enum": ["image/png", "image/webp", "image/avif"] },
|
||||
"byte_size": { "type": "integer", "minimum": 1, "maximum": 67108864 }
|
||||
}
|
||||
},
|
||||
"evidenceSection": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["status", "evidence_refs", "note"],
|
||||
"properties": {
|
||||
"status": {
|
||||
"enum": ["evidenced", "unresolved", "unsupported", "not_applicable"]
|
||||
},
|
||||
"evidence_refs": {
|
||||
"type": "array",
|
||||
"maxItems": 1000,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
},
|
||||
"note": { "type": ["string", "null"], "maxLength": 4000 }
|
||||
}
|
||||
},
|
||||
"handoffRecord": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"handoff_record_id",
|
||||
"record_type",
|
||||
"intent",
|
||||
"target_id",
|
||||
"review_state",
|
||||
"source_candidate_ids",
|
||||
"observed_instance_ids",
|
||||
"fields",
|
||||
"relationships",
|
||||
"mechanics"
|
||||
],
|
||||
"properties": {
|
||||
"handoff_record_id": { "$ref": "#/$defs/id" },
|
||||
"record_type": { "$ref": "#/$defs/recordType" },
|
||||
"intent": { "enum": ["create_draft", "update_draft", "abstain"] },
|
||||
"target_id": {
|
||||
"oneOf": [{ "type": "null" }, { "$ref": "#/$defs/id" }]
|
||||
},
|
||||
"review_state": { "enum": ["approved", "abstained"] },
|
||||
"source_candidate_ids": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 100,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
},
|
||||
"observed_instance_ids": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 100,
|
||||
"uniqueItems": true,
|
||||
"items": { "$ref": "#/$defs/id" }
|
||||
},
|
||||
"fields": {
|
||||
"type": "array",
|
||||
"maxItems": 1000,
|
||||
"items": { "$ref": "#/$defs/fieldClaim" }
|
||||
},
|
||||
"relationships": { "$ref": "#/$defs/evidenceSection" },
|
||||
"mechanics": { "$ref": "#/$defs/evidenceSection" }
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"intent": { "const": "create_draft" },
|
||||
"target_id": { "const": null },
|
||||
"review_state": { "const": "approved" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"intent": { "const": "update_draft" },
|
||||
"target_id": { "$ref": "#/$defs/id" },
|
||||
"review_state": { "const": "approved" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"intent": { "const": "abstain" },
|
||||
"target_id": { "const": null },
|
||||
"review_state": { "const": "abstained" },
|
||||
"fields": { "maxItems": 0 }
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://shd.build/schemas/game-data-capture/screenshot-classification-v1.json",
|
||||
"title": "Screenshot classification v1",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"family",
|
||||
"view",
|
||||
"gear_slot",
|
||||
"record_types",
|
||||
"confidence",
|
||||
"abstention_reason"
|
||||
],
|
||||
"properties": {
|
||||
"family": {
|
||||
"enum": [
|
||||
"weapon",
|
||||
"gear",
|
||||
"skill_chip",
|
||||
"os_protocol",
|
||||
"specialization",
|
||||
"weapon_mod",
|
||||
"gear_mod",
|
||||
"unknown"
|
||||
]
|
||||
},
|
||||
"view": { "type": "string" },
|
||||
"gear_slot": { "type": ["string", "null"] },
|
||||
"record_types": {
|
||||
"type": "array",
|
||||
"uniqueItems": true,
|
||||
"maxItems": 8,
|
||||
"items": { "type": "string" }
|
||||
},
|
||||
"confidence": { "type": "number", "minimum": 0, "maximum": 1 },
|
||||
"abstention_reason": { "type": ["string", "null"] }
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "weapon" },
|
||||
"view": {
|
||||
"enum": [
|
||||
"detail",
|
||||
"blueprint",
|
||||
"crafting",
|
||||
"stat_range",
|
||||
"talent_grid",
|
||||
"augmentation"
|
||||
]
|
||||
},
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"enum": ["weapon", "weapon_talent", "weapon_augmentation_profile"]
|
||||
}
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "gear" },
|
||||
"view": { "enum": ["detail", "blueprint", "talent", "augmentation"] },
|
||||
"gear_slot": {
|
||||
"enum": [
|
||||
"Mask",
|
||||
"Gloves",
|
||||
"Backpack",
|
||||
"Body Armor",
|
||||
"Holster",
|
||||
"Knee Pads"
|
||||
]
|
||||
},
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"enum": [
|
||||
"gear",
|
||||
"brand_set",
|
||||
"gear_talent",
|
||||
"gear_augmentation_profile"
|
||||
]
|
||||
}
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "skill_chip" },
|
||||
"view": { "enum": ["detail", "set_bonus", "talent"] },
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"enum": [
|
||||
"skill_chip_set",
|
||||
"skill_chip_set_bonus",
|
||||
"skill_chip_roll_pool",
|
||||
"skill_chip_talent"
|
||||
]
|
||||
}
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "os_protocol" },
|
||||
"view": { "enum": ["detail", "secondary_profile", "talent"] },
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"enum": [
|
||||
"os_protocol",
|
||||
"os_protocol_secondary_profile",
|
||||
"os_protocol_talent"
|
||||
]
|
||||
}
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "specialization" },
|
||||
"view": {
|
||||
"enum": [
|
||||
"overview",
|
||||
"details",
|
||||
"ability",
|
||||
"focus_details",
|
||||
"focus_tree",
|
||||
"rank_details"
|
||||
]
|
||||
},
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"enum": [
|
||||
"specialization",
|
||||
"specialization_focus",
|
||||
"specialization_ability",
|
||||
"specialization_tree_node",
|
||||
"specialization_tree_rank"
|
||||
]
|
||||
}
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "weapon_mod" },
|
||||
"view": { "const": "detail" },
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"maxItems": 1,
|
||||
"items": { "const": "weapon_mod" }
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "gear_mod" },
|
||||
"view": { "const": "detail" },
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": {
|
||||
"minItems": 1,
|
||||
"maxItems": 1,
|
||||
"items": { "const": "gear_mod" }
|
||||
},
|
||||
"abstention_reason": { "const": null }
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"family": { "const": "unknown" },
|
||||
"view": { "const": "unknown" },
|
||||
"gear_slot": { "const": null },
|
||||
"record_types": { "maxItems": 0 },
|
||||
"abstention_reason": {
|
||||
"enum": [
|
||||
"low_confidence",
|
||||
"ambiguous_family",
|
||||
"ambiguous_view",
|
||||
"unsupported_family",
|
||||
"unsupported_view",
|
||||
"insufficient_visual_evidence",
|
||||
"occluded",
|
||||
"corrupt_image",
|
||||
"resource_limit",
|
||||
"cancelled"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
-- Additive utility-local schema. Migration content is fingerprinted at application time.
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
filename TEXT NOT NULL UNIQUE,
|
||||
checksum TEXT NOT NULL,
|
||||
applied_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE blobs (
|
||||
sha256 TEXT PRIMARY KEY CHECK(length(sha256) = 64),
|
||||
byte_size INTEGER NOT NULL CHECK(byte_size > 0),
|
||||
media_type TEXT NOT NULL CHECK(length(media_type) <= 100),
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE captures (
|
||||
capture_id TEXT PRIMARY KEY,
|
||||
blob_sha256 TEXT NOT NULL REFERENCES blobs(sha256) ON DELETE RESTRICT,
|
||||
state TEXT NOT NULL,
|
||||
received_at TEXT NOT NULL,
|
||||
receipt_token TEXT NOT NULL UNIQUE,
|
||||
failure_reason TEXT,
|
||||
revision INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE jobs (
|
||||
job_id TEXT PRIMARY KEY,
|
||||
capture_id TEXT REFERENCES captures(capture_id) ON DELETE RESTRICT,
|
||||
kind TEXT NOT NULL CHECK(length(kind) <= 100),
|
||||
state TEXT NOT NULL,
|
||||
attempt INTEGER NOT NULL DEFAULT 0 CHECK(attempt >= 0 AND attempt <= 20),
|
||||
max_attempts INTEGER NOT NULL CHECK(max_attempts BETWEEN 1 AND 20),
|
||||
lease_owner TEXT, lease_expires_at TEXT, last_error_id TEXT,
|
||||
revision INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX jobs_available ON jobs(state, lease_expires_at);
|
||||
CREATE TABLE ocr_runs (
|
||||
run_id TEXT PRIMARY KEY, capture_id TEXT NOT NULL REFERENCES captures(capture_id),
|
||||
engine_id TEXT NOT NULL, engine_version TEXT NOT NULL, created_at TEXT NOT NULL,
|
||||
state TEXT NOT NULL, payload_json TEXT NOT NULL CHECK(length(payload_json) <= 1000000)
|
||||
);
|
||||
CREATE TABLE regions (
|
||||
region_id TEXT PRIMARY KEY, run_id TEXT NOT NULL REFERENCES ocr_runs(run_id),
|
||||
region_json TEXT NOT NULL CHECK(length(region_json) <= 10000), created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE classifications (
|
||||
classification_id TEXT PRIMARY KEY, run_id TEXT NOT NULL REFERENCES ocr_runs(run_id),
|
||||
classification_json TEXT NOT NULL CHECK(length(classification_json) <= 10000), created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE extraction_candidates (
|
||||
candidate_id TEXT PRIMARY KEY, run_id TEXT NOT NULL REFERENCES ocr_runs(run_id),
|
||||
candidate_json TEXT NOT NULL CHECK(length(candidate_json) <= 1000000), created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE routing_decisions (
|
||||
decision_id TEXT PRIMARY KEY, candidate_id TEXT REFERENCES extraction_candidates(candidate_id),
|
||||
decision_json TEXT NOT NULL CHECK(length(decision_json) <= 10000), created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE review_events (
|
||||
event_id TEXT PRIMARY KEY, candidate_id TEXT REFERENCES extraction_candidates(candidate_id),
|
||||
event_json TEXT NOT NULL CHECK(length(event_json) <= 10000), created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE lineage (
|
||||
lineage_id TEXT PRIMARY KEY, child_id TEXT NOT NULL, parent_id TEXT NOT NULL,
|
||||
relation TEXT NOT NULL CHECK(length(relation) <= 100), created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE exports (
|
||||
export_id TEXT PRIMARY KEY, state TEXT NOT NULL, manifest_json TEXT NOT NULL CHECK(length(manifest_json) <= 1000000), created_at TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE runtime_failures (
|
||||
failure_id TEXT PRIMARY KEY, subject_type TEXT NOT NULL, subject_id TEXT NOT NULL,
|
||||
code TEXT NOT NULL, message TEXT NOT NULL CHECK(length(message) <= 512), created_at TEXT NOT NULL
|
||||
);
|
||||
@@ -1,38 +0,0 @@
|
||||
-- Durable browser-corpus projections and append-only review evidence.
|
||||
CREATE TABLE capture_labels (
|
||||
capture_id TEXT PRIMARY KEY REFERENCES captures(capture_id) ON DELETE RESTRICT,
|
||||
classification_json TEXT NOT NULL CHECK(length(classification_json) BETWEEN 2 AND 4096),
|
||||
revision INTEGER NOT NULL DEFAULT 0 CHECK(revision >= 0),
|
||||
labeled_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE capture_label_evidence (
|
||||
evidence_id INTEGER PRIMARY KEY,
|
||||
capture_id TEXT NOT NULL REFERENCES captures(capture_id) ON DELETE RESTRICT,
|
||||
replaced_revision INTEGER NOT NULL CHECK(replaced_revision >= 0),
|
||||
classification_json TEXT NOT NULL CHECK(length(classification_json) BETWEEN 2 AND 4096),
|
||||
replaced_at TEXT NOT NULL,
|
||||
UNIQUE(capture_id, replaced_revision)
|
||||
);
|
||||
CREATE INDEX capture_label_evidence_capture ON capture_label_evidence(capture_id, evidence_id);
|
||||
CREATE INDEX captures_blob_sha256 ON captures(blob_sha256);
|
||||
CREATE INDEX jobs_capture_id ON jobs(capture_id);
|
||||
CREATE INDEX ocr_runs_capture_id ON ocr_runs(capture_id);
|
||||
CREATE INDEX runtime_failures_capture_subject ON runtime_failures(subject_type, subject_id);
|
||||
CREATE INDEX lineage_child_id ON lineage(child_id);
|
||||
CREATE INDEX lineage_parent_id ON lineage(parent_id);
|
||||
CREATE TABLE capture_rejections (
|
||||
rejection_id INTEGER PRIMARY KEY,
|
||||
capture_id TEXT NOT NULL UNIQUE REFERENCES captures(capture_id) ON DELETE RESTRICT,
|
||||
rejected_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE capture_deletion_intents (
|
||||
blob_sha256 TEXT PRIMARY KEY REFERENCES blobs(sha256) ON DELETE RESTRICT,
|
||||
capture_id TEXT NOT NULL UNIQUE CHECK(length(capture_id) BETWEEN 8 AND 64),
|
||||
byte_size INTEGER NOT NULL CHECK(byte_size > 0 AND byte_size <= 67108864),
|
||||
capture_state TEXT NOT NULL CHECK(length(capture_state) BETWEEN 1 AND 32),
|
||||
received_at TEXT NOT NULL CHECK(length(received_at) BETWEEN 1 AND 40),
|
||||
receipt_token TEXT NOT NULL UNIQUE CHECK(length(receipt_token) BETWEEN 1 AND 128),
|
||||
failure_reason TEXT,
|
||||
revision INTEGER NOT NULL CHECK(revision >= 0),
|
||||
created_at TEXT NOT NULL CHECK(length(created_at) BETWEEN 1 AND 40)
|
||||
);
|
||||
@@ -1,51 +0,0 @@
|
||||
[build-system]
|
||||
requires = ["hatchling==1.27.0"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "shd-game-data-capture"
|
||||
version = "0.1.0"
|
||||
description = "Local, privacy-preserving game-data capture utility contracts."
|
||||
requires-python = ">=3.12,<3.13"
|
||||
license = { text = "UNLICENSED" }
|
||||
authors = [{ name = "SHD.build" }]
|
||||
dependencies = [
|
||||
"fastapi==0.115.12",
|
||||
"jinja2==3.1.6",
|
||||
"python-multipart==0.0.20",
|
||||
"uvicorn==0.34.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
shd-capture = "game_data_capture.cli:main"
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"httpx==0.28.1",
|
||||
"jsonschema==4.25.1",
|
||||
"mypy==1.15.0",
|
||||
"pytest==8.3.5",
|
||||
"ruff==0.11.0",
|
||||
"types-jsonschema==4.25.1.20251009",
|
||||
]
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/game_data_capture"]
|
||||
|
||||
[tool.ruff]
|
||||
target-version = "py312"
|
||||
line-length = 100
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
mypy_path = ["src"]
|
||||
warn_unreachable = true
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["src"]
|
||||
addopts = "-ra"
|
||||
@@ -1,6 +0,0 @@
|
||||
"""Contracts for the local SHD.build game-data capture utility.
|
||||
|
||||
Importing this package does not inspect the environment or initialize runtime resources.
|
||||
"""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -1,6 +0,0 @@
|
||||
"""Module entry point for ``python -m game_data_capture``."""
|
||||
|
||||
from .cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,163 +0,0 @@
|
||||
"""CLI contracts for the capture utility."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
from game_data_capture.config import AppConfig, ConfigError, ServerConfig, load_config
|
||||
from game_data_capture.doctor import doctor_as_dict, run_doctor
|
||||
from game_data_capture.paths import PathConfigurationError, RuntimePaths, resolve_runtime_paths
|
||||
from game_data_capture.runtime import CaptureRuntime, RuntimeFailure
|
||||
|
||||
EXIT_OK = 0
|
||||
EXIT_CONFIG_ERROR = 2
|
||||
EXIT_UNIMPLEMENTED = 3
|
||||
EXIT_RUNTIME_ERROR = 4
|
||||
|
||||
|
||||
def _add_config_argument(parser: argparse.ArgumentParser) -> None:
|
||||
parser.add_argument("--config", type=Path, help="absolute path to a TOML configuration file")
|
||||
|
||||
|
||||
def _port_argument(raw_value: str) -> int:
|
||||
try:
|
||||
port = int(raw_value)
|
||||
except ValueError as error:
|
||||
raise argparse.ArgumentTypeError("port must be an integer from 1024 to 65535") from error
|
||||
if not 1024 <= port <= 65535:
|
||||
raise argparse.ArgumentTypeError("port must be an integer from 1024 to 65535")
|
||||
return port
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
"""Build the stable command surface without initializing runtime resources."""
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="shd-capture", description="Local SHD.build game-data capture"
|
||||
)
|
||||
subcommands = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
doctor = subcommands.add_parser("doctor", help="report local prerequisite status")
|
||||
_add_config_argument(doctor)
|
||||
doctor.add_argument("--json", action="store_true", help="emit JSON diagnostics")
|
||||
|
||||
serve = subcommands.add_parser("serve", help="start the localhost review service")
|
||||
_add_config_argument(serve)
|
||||
serve.add_argument("--host", help="loopback IP literal override")
|
||||
serve.add_argument("--port", type=_port_argument, help="TCP port override")
|
||||
|
||||
watch = subcommands.add_parser("watch", help="watch the Wayland clipboard for images")
|
||||
_add_config_argument(watch)
|
||||
watch_modes = watch.add_mutually_exclusive_group()
|
||||
watch_modes.add_argument("--arm", action="store_true", help="arm live clipboard capture")
|
||||
watch_modes.add_argument(
|
||||
"--dry-run", action="store_true", help="validate the capture runtime plan"
|
||||
)
|
||||
|
||||
ingest_image = subcommands.add_parser("ingest-image", help="stage one image for capture")
|
||||
_add_config_argument(ingest_image)
|
||||
ingest_image.add_argument("image", type=Path)
|
||||
|
||||
import_video = subcommands.add_parser("import-video", help="stage a video for frame extraction")
|
||||
_add_config_argument(import_video)
|
||||
import_video.add_argument("video", type=Path)
|
||||
|
||||
export = subcommands.add_parser("export", help="write a versioned ISAC handoff")
|
||||
_add_config_argument(export)
|
||||
export.add_argument("destination", type=Path)
|
||||
|
||||
verify = subcommands.add_parser("verify", help="verify an evidence archive")
|
||||
_add_config_argument(verify)
|
||||
verify.add_argument("archive", type=Path)
|
||||
|
||||
evaluate = subcommands.add_parser("eval", help="evaluate local OCR and classification")
|
||||
_add_config_argument(evaluate)
|
||||
evaluate.add_argument("corpus", type=Path)
|
||||
|
||||
purge = subcommands.add_parser("purge", help="purge retained local data")
|
||||
_add_config_argument(purge)
|
||||
purge.add_argument("--confirm", action="store_true", help="confirm a future destructive purge")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def _load_cli_config(config_path: Path | None) -> tuple[AppConfig, RuntimePaths]:
|
||||
paths = resolve_runtime_paths()
|
||||
return load_config(config_path=config_path, paths=paths), paths
|
||||
|
||||
|
||||
def _doctor(arguments: argparse.Namespace) -> int:
|
||||
config, paths = _load_cli_config(arguments.config)
|
||||
diagnostics = doctor_as_dict(run_doctor(config, paths))
|
||||
if arguments.json:
|
||||
print(json.dumps(diagnostics, separators=(",", ":"), sort_keys=True))
|
||||
else:
|
||||
for diagnostic in diagnostics:
|
||||
print(f"{diagnostic['name']}: {diagnostic['status']} ({diagnostic['detail']})")
|
||||
return EXIT_OK
|
||||
|
||||
|
||||
def _serve_contract(arguments: argparse.Namespace) -> int:
|
||||
config, paths = _load_cli_config(arguments.config)
|
||||
host = arguments.host if arguments.host is not None else config.server.host
|
||||
port = arguments.port if arguments.port is not None else config.server.port
|
||||
configured = replace(config, server=ServerConfig(host=host, port=port))
|
||||
CaptureRuntime(configured, paths).serve()
|
||||
return EXIT_OK
|
||||
|
||||
|
||||
def _unimplemented(command: str) -> int:
|
||||
print(
|
||||
f"{command}: subsystem is not implemented; requires gdc-runtime-integration",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return EXIT_UNIMPLEMENTED
|
||||
|
||||
|
||||
def _watch(arguments: argparse.Namespace) -> int:
|
||||
config, paths = _load_cli_config(arguments.config)
|
||||
if not arguments.arm and not arguments.dry_run:
|
||||
return _unimplemented("watch")
|
||||
runtime = CaptureRuntime(config, paths)
|
||||
if arguments.dry_run:
|
||||
runtime.validate_plan()
|
||||
print("watch dry-run: capture runtime plan is valid")
|
||||
return EXIT_OK
|
||||
runtime.watch()
|
||||
return EXIT_OK
|
||||
|
||||
|
||||
def _ingest_image(arguments: argparse.Namespace) -> int:
|
||||
config, paths = _load_cli_config(arguments.config)
|
||||
CaptureRuntime(config, paths).ingest_image(arguments.image)
|
||||
print("image capture stored")
|
||||
return EXIT_OK
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
"""Run one CLI command and return a stable process exit status."""
|
||||
|
||||
parser = build_parser()
|
||||
arguments = parser.parse_args(argv)
|
||||
try:
|
||||
if arguments.command == "doctor":
|
||||
return _doctor(arguments)
|
||||
if arguments.command == "serve":
|
||||
return _serve_contract(arguments)
|
||||
if arguments.command == "watch":
|
||||
return _watch(arguments)
|
||||
if arguments.command == "ingest-image":
|
||||
return _ingest_image(arguments)
|
||||
_load_cli_config(arguments.config)
|
||||
return _unimplemented(arguments.command)
|
||||
except (ConfigError, PathConfigurationError) as error:
|
||||
print(f"configuration error: {error}", file=sys.stderr)
|
||||
return EXIT_CONFIG_ERROR
|
||||
except RuntimeFailure:
|
||||
print("capture runtime failed", file=sys.stderr)
|
||||
return EXIT_RUNTIME_ERROR
|
||||
@@ -1,216 +0,0 @@
|
||||
"""Typed, bounded configuration for the capture runtime.
|
||||
|
||||
Configuration parsing reads an explicit TOML file only when a caller invokes
|
||||
``load_config``. Importing this module has no filesystem or environment effects.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import os
|
||||
import re
|
||||
import tomllib
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from game_data_capture.paths import RuntimePaths, resolve_runtime_paths
|
||||
|
||||
_ENVIRONMENT_NAME = re.compile(r"^[A-Z_][A-Z0-9_]{0,63}$")
|
||||
|
||||
|
||||
class ConfigError(ValueError):
|
||||
"""A bounded, safe-to-display configuration error."""
|
||||
|
||||
|
||||
def _error(field_name: str, constraint: str) -> ConfigError:
|
||||
return ConfigError(f"Invalid configuration: {field_name} {constraint}.")
|
||||
|
||||
|
||||
def _bounded_int(value: object, field_name: str, minimum: int, maximum: int) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or not minimum <= value <= maximum:
|
||||
raise _error(field_name, f"must be an integer from {minimum} to {maximum}")
|
||||
return value
|
||||
|
||||
|
||||
def _mapping(value: object, field_name: str) -> Mapping[str, object]:
|
||||
if not isinstance(value, dict) or not all(isinstance(key, str) for key in value):
|
||||
raise _error(field_name, "must be a table")
|
||||
return value
|
||||
|
||||
|
||||
def _only_keys(section: Mapping[str, object], section_name: str, allowed: set[str]) -> None:
|
||||
if set(section) - allowed:
|
||||
raise _error(section_name, "contains an unsupported setting")
|
||||
|
||||
|
||||
def _string(value: object, field_name: str, maximum: int) -> str:
|
||||
if not isinstance(value, str) or not value or len(value) > maximum:
|
||||
raise _error(field_name, f"must be a non-empty string up to {maximum} characters")
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ServerConfig:
|
||||
host: str = "127.0.0.1"
|
||||
port: int = 8765
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
try:
|
||||
address = ipaddress.ip_address(self.host)
|
||||
except ValueError as error:
|
||||
raise _error("server.host", "must be a loopback IP literal") from error
|
||||
if not address.is_loopback:
|
||||
raise _error("server.host", "must be a loopback IP literal")
|
||||
_bounded_int(self.port, "server.port", 1024, 65535)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class LifecycleConfig:
|
||||
"""One-instance settings consumed later by the runtime integration layer."""
|
||||
|
||||
instance_name: str = "shd-capture"
|
||||
lock_timeout_seconds: int = 5
|
||||
shutdown_timeout_seconds: int = 30
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,31}", self.instance_name):
|
||||
raise _error(
|
||||
"lifecycle.instance_name", "must use lowercase letters, digits, and hyphens"
|
||||
)
|
||||
_bounded_int(self.lock_timeout_seconds, "lifecycle.lock_timeout_seconds", 0, 60)
|
||||
_bounded_int(self.shutdown_timeout_seconds, "lifecycle.shutdown_timeout_seconds", 1, 300)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CaptureLimits:
|
||||
max_image_bytes: int = 32 * 1024 * 1024
|
||||
max_video_bytes: int = 4 * 1024 * 1024 * 1024
|
||||
max_queue_items: int = 64
|
||||
max_ocr_text_characters: int = 20_000
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_bounded_int(self.max_image_bytes, "limits.max_image_bytes", 1, 64 * 1024 * 1024)
|
||||
_bounded_int(self.max_video_bytes, "limits.max_video_bytes", 1, 16 * 1024 * 1024 * 1024)
|
||||
_bounded_int(self.max_queue_items, "limits.max_queue_items", 1, 256)
|
||||
_bounded_int(self.max_ocr_text_characters, "limits.max_ocr_text_characters", 1, 100_000)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OpenAIConfig:
|
||||
api_key_env: str = "OPENAI_API_KEY"
|
||||
model: str = "gpt-4.1-mini"
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not _ENVIRONMENT_NAME.fullmatch(self.api_key_env):
|
||||
raise _error("openai.api_key_env", "must be an environment variable name")
|
||||
_string(self.model, "openai.model", 128)
|
||||
|
||||
def is_configured(self, environment: Mapping[str, str] | None = None) -> bool:
|
||||
env = os.environ if environment is None else environment
|
||||
return bool(env.get(self.api_key_env))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AppConfig:
|
||||
server: ServerConfig = field(default_factory=ServerConfig)
|
||||
lifecycle: LifecycleConfig = field(default_factory=LifecycleConfig)
|
||||
limits: CaptureLimits = field(default_factory=CaptureLimits)
|
||||
openai: OpenAIConfig = field(default_factory=OpenAIConfig)
|
||||
|
||||
|
||||
def _section(document: Mapping[str, object], name: str, allowed: set[str]) -> Mapping[str, object]:
|
||||
value = document.get(name, {})
|
||||
section = _mapping(value, name)
|
||||
_only_keys(section, name, allowed)
|
||||
return section
|
||||
|
||||
|
||||
def parse_config(document: Mapping[str, object]) -> AppConfig:
|
||||
"""Parse a TOML-shaped mapping with an allowlist of configuration keys."""
|
||||
|
||||
_only_keys(document, "root", {"server", "lifecycle", "limits", "openai"})
|
||||
server = _section(document, "server", {"host", "port"})
|
||||
lifecycle = _section(
|
||||
document, "lifecycle", {"instance_name", "lock_timeout_seconds", "shutdown_timeout_seconds"}
|
||||
)
|
||||
limits = _section(
|
||||
document,
|
||||
"limits",
|
||||
{"max_image_bytes", "max_video_bytes", "max_queue_items", "max_ocr_text_characters"},
|
||||
)
|
||||
openai = _section(document, "openai", {"api_key_env", "model"})
|
||||
|
||||
return AppConfig(
|
||||
server=ServerConfig(
|
||||
host=_string(server.get("host", "127.0.0.1"), "server.host", 64),
|
||||
port=_bounded_int(server.get("port", 8765), "server.port", 1024, 65535),
|
||||
),
|
||||
lifecycle=LifecycleConfig(
|
||||
instance_name=_string(
|
||||
lifecycle.get("instance_name", "shd-capture"), "lifecycle.instance_name", 32
|
||||
),
|
||||
lock_timeout_seconds=_bounded_int(
|
||||
lifecycle.get("lock_timeout_seconds", 5), "lifecycle.lock_timeout_seconds", 0, 60
|
||||
),
|
||||
shutdown_timeout_seconds=_bounded_int(
|
||||
lifecycle.get("shutdown_timeout_seconds", 30),
|
||||
"lifecycle.shutdown_timeout_seconds",
|
||||
1,
|
||||
300,
|
||||
),
|
||||
),
|
||||
limits=CaptureLimits(
|
||||
max_image_bytes=_bounded_int(
|
||||
limits.get("max_image_bytes", 32 * 1024 * 1024),
|
||||
"limits.max_image_bytes",
|
||||
1,
|
||||
64 * 1024 * 1024,
|
||||
),
|
||||
max_video_bytes=_bounded_int(
|
||||
limits.get("max_video_bytes", 4 * 1024 * 1024 * 1024),
|
||||
"limits.max_video_bytes",
|
||||
1,
|
||||
16 * 1024 * 1024 * 1024,
|
||||
),
|
||||
max_queue_items=_bounded_int(
|
||||
limits.get("max_queue_items", 64), "limits.max_queue_items", 1, 256
|
||||
),
|
||||
max_ocr_text_characters=_bounded_int(
|
||||
limits.get("max_ocr_text_characters", 20_000),
|
||||
"limits.max_ocr_text_characters",
|
||||
1,
|
||||
100_000,
|
||||
),
|
||||
),
|
||||
openai=OpenAIConfig(
|
||||
api_key_env=_string(
|
||||
openai.get("api_key_env", "OPENAI_API_KEY"), "openai.api_key_env", 64
|
||||
),
|
||||
model=_string(openai.get("model", "gpt-4.1-mini"), "openai.model", 128),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def load_config(config_path: Path | None = None, paths: RuntimePaths | None = None) -> AppConfig:
|
||||
"""Read optional TOML configuration from the XDG config location.
|
||||
|
||||
An absent file selects safe defaults. Parse failures intentionally omit source values and paths.
|
||||
"""
|
||||
|
||||
selected_path = (
|
||||
config_path if config_path is not None else (paths or resolve_runtime_paths()).config_file
|
||||
)
|
||||
if not selected_path.is_absolute() or len(str(selected_path)) > 240:
|
||||
raise _error("config path", "must be an absolute path within 240 characters")
|
||||
if not selected_path.exists():
|
||||
return AppConfig()
|
||||
try:
|
||||
with selected_path.open("rb") as handle:
|
||||
document: Any = tomllib.load(handle)
|
||||
except (OSError, tomllib.TOMLDecodeError) as error:
|
||||
raise _error("config file", "could not be read") from error
|
||||
if not isinstance(document, dict):
|
||||
raise _error("root", "must be a table")
|
||||
return parse_config(document)
|
||||
@@ -1,84 +0,0 @@
|
||||
"""Side-effect-limited local diagnostics for capture prerequisites."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import shutil
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import asdict, dataclass
|
||||
from os import environ
|
||||
|
||||
from game_data_capture.config import AppConfig
|
||||
from game_data_capture.paths import (
|
||||
PathConfigurationError,
|
||||
RuntimePaths,
|
||||
prepare_private_directories,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Diagnostic:
|
||||
name: str
|
||||
status: str
|
||||
detail: str
|
||||
|
||||
|
||||
def _executable_diagnostic(name: str) -> Diagnostic:
|
||||
return Diagnostic(
|
||||
name=name,
|
||||
status="available" if shutil.which(name) else "unavailable",
|
||||
detail="executable found on PATH" if shutil.which(name) else "executable not found on PATH",
|
||||
)
|
||||
|
||||
|
||||
def _gpu_diagnostic(environment: Mapping[str, str]) -> Diagnostic:
|
||||
configured_provider = environment.get("GDC_OCR_PROVIDER")
|
||||
if configured_provider:
|
||||
return Diagnostic(
|
||||
"gpu_provider", "unknown", "provider configured; runtime probe is deferred"
|
||||
)
|
||||
if importlib.util.find_spec("torch") is not None:
|
||||
return Diagnostic(
|
||||
"gpu_provider", "unknown", "torch is installed; runtime probe is deferred"
|
||||
)
|
||||
return Diagnostic("gpu_provider", "unknown", "no provider selected; runtime probe is deferred")
|
||||
|
||||
|
||||
def _storage_diagnostic(paths: RuntimePaths) -> Diagnostic:
|
||||
try:
|
||||
prepare_private_directories(paths)
|
||||
except (OSError, PathConfigurationError):
|
||||
return Diagnostic(
|
||||
"storage_permissions", "unavailable", "private XDG directories are not usable"
|
||||
)
|
||||
return Diagnostic(
|
||||
"storage_permissions", "available", "private XDG directories use owner-only access"
|
||||
)
|
||||
|
||||
|
||||
def run_doctor(
|
||||
config: AppConfig, paths: RuntimePaths, environment: Mapping[str, str] | None = None
|
||||
) -> tuple[Diagnostic, ...]:
|
||||
"""Inspect local prerequisites without launching processes or making network calls."""
|
||||
|
||||
env = environ if environment is None else environment
|
||||
return (
|
||||
_executable_diagnostic("niri"),
|
||||
_executable_diagnostic("wl-paste"),
|
||||
_executable_diagnostic("ffmpeg"),
|
||||
_gpu_diagnostic(env),
|
||||
_storage_diagnostic(paths),
|
||||
Diagnostic(
|
||||
"openai",
|
||||
"configured" if config.openai.is_configured(env) else "missing",
|
||||
"environment variable is present"
|
||||
if config.openai.is_configured(env)
|
||||
else "environment variable is absent",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def doctor_as_dict(diagnostics: tuple[Diagnostic, ...]) -> list[dict[str, str]]:
|
||||
"""Return diagnostics in a serialization-ready form without paths or secret values."""
|
||||
|
||||
return [asdict(diagnostic) for diagnostic in diagnostics]
|
||||
@@ -1,43 +0,0 @@
|
||||
"""Side-effect-free domain contracts for the game data capture utility."""
|
||||
|
||||
from .state_machines import InvalidStateTransition, StateMachine, require_transition
|
||||
from .taxonomy import (
|
||||
ABSTENTION_REASONS,
|
||||
GEAR_SLOTS,
|
||||
RECORD_TYPES_BY_VIEW,
|
||||
SCREEN_VIEWS,
|
||||
AbstentionReason,
|
||||
Family,
|
||||
GearSlot,
|
||||
RecordType,
|
||||
)
|
||||
from .validation import (
|
||||
ContractValidationError,
|
||||
ensure_supported_version,
|
||||
validate_archive_document,
|
||||
validate_archive_references,
|
||||
validate_classification,
|
||||
validate_handoff_document,
|
||||
validate_handoff_references,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ABSTENTION_REASONS",
|
||||
"GEAR_SLOTS",
|
||||
"RECORD_TYPES_BY_VIEW",
|
||||
"SCREEN_VIEWS",
|
||||
"AbstentionReason",
|
||||
"ContractValidationError",
|
||||
"Family",
|
||||
"GearSlot",
|
||||
"InvalidStateTransition",
|
||||
"RecordType",
|
||||
"StateMachine",
|
||||
"ensure_supported_version",
|
||||
"require_transition",
|
||||
"validate_archive_document",
|
||||
"validate_archive_references",
|
||||
"validate_classification",
|
||||
"validate_handoff_document",
|
||||
"validate_handoff_references",
|
||||
]
|
||||
@@ -1,149 +0,0 @@
|
||||
"""Typed Python views of the portable contract structures."""
|
||||
|
||||
import typing
|
||||
|
||||
type JsonValue = None | bool | int | float | str | list[JsonValue] | dict[str, JsonValue]
|
||||
type MissingReason = typing.Literal[
|
||||
"not_visible",
|
||||
"occluded",
|
||||
"unreadable",
|
||||
"not_present_on_screen",
|
||||
"unsupported",
|
||||
"ambiguous",
|
||||
"extraction_failed",
|
||||
"not_applicable",
|
||||
"redacted",
|
||||
]
|
||||
type ScreenshotFamily = typing.Literal[
|
||||
"weapon",
|
||||
"gear",
|
||||
"skill_chip",
|
||||
"os_protocol",
|
||||
"specialization",
|
||||
"weapon_mod",
|
||||
"gear_mod",
|
||||
"unknown",
|
||||
]
|
||||
type CanonicalRecordType = typing.Literal[
|
||||
"weapon",
|
||||
"weapon_talent",
|
||||
"weapon_augmentation_profile",
|
||||
"gear",
|
||||
"brand_set",
|
||||
"gear_talent",
|
||||
"gear_augmentation_profile",
|
||||
"skill_chip_set",
|
||||
"skill_chip_set_bonus",
|
||||
"skill_chip_roll_pool",
|
||||
"skill_chip_talent",
|
||||
"os_protocol",
|
||||
"os_protocol_secondary_profile",
|
||||
"os_protocol_talent",
|
||||
"specialization",
|
||||
"specialization_focus",
|
||||
"specialization_ability",
|
||||
"specialization_tree_node",
|
||||
"specialization_tree_rank",
|
||||
"weapon_mod",
|
||||
"gear_mod",
|
||||
]
|
||||
|
||||
|
||||
class SourceEngine(typing.TypedDict):
|
||||
kind: typing.Literal["local_ocr", "openai_vision", "classifier", "manual", "video_decoder"]
|
||||
engine_id: str
|
||||
engine_version: str
|
||||
|
||||
|
||||
class NormalizedRegion(typing.TypedDict):
|
||||
coordinate_space: typing.Literal["normalized"]
|
||||
x: float
|
||||
y: float
|
||||
width: float
|
||||
height: float
|
||||
|
||||
|
||||
class PixelRegion(typing.TypedDict):
|
||||
coordinate_space: typing.Literal["pixels"]
|
||||
x: int
|
||||
y: int
|
||||
width: int
|
||||
height: int
|
||||
|
||||
|
||||
type BoundingRegion = NormalizedRegion | PixelRegion
|
||||
|
||||
|
||||
class ValueState(typing.TypedDict):
|
||||
raw_text: str | None
|
||||
normalized_value: JsonValue
|
||||
missing_reason: MissingReason | None
|
||||
|
||||
|
||||
class Correction(typing.TypedDict):
|
||||
correction_id: str
|
||||
corrected_at: str
|
||||
actor: typing.Literal["local_user", "system_reprocess"]
|
||||
reason: str
|
||||
before: ValueState
|
||||
after: ValueState
|
||||
|
||||
|
||||
class EvidenceValue(ValueState):
|
||||
evidence_id: str
|
||||
field_path: str
|
||||
confidence: float
|
||||
source_engine: SourceEngine
|
||||
image_artifact_id: str
|
||||
image_sha256: str
|
||||
region: BoundingRegion
|
||||
correction_history: list[Correction]
|
||||
|
||||
|
||||
class FieldClaim(typing.TypedDict):
|
||||
path: str
|
||||
value: JsonValue
|
||||
missing_reason: MissingReason | None
|
||||
evidence_refs: list[str]
|
||||
uncertainty_note: str | None
|
||||
|
||||
|
||||
class ScreenshotClassification(typing.TypedDict):
|
||||
family: ScreenshotFamily
|
||||
view: str
|
||||
gear_slot: (
|
||||
typing.Literal["Mask", "Gloves", "Backpack", "Body Armor", "Holster", "Knee Pads"] | None
|
||||
)
|
||||
record_types: list[CanonicalRecordType]
|
||||
confidence: float
|
||||
abstention_reason: str | None
|
||||
|
||||
|
||||
class ObservedContext(typing.TypedDict):
|
||||
level: FieldClaim
|
||||
quality: FieldClaim
|
||||
tier: FieldClaim
|
||||
upgrade_state: FieldClaim
|
||||
|
||||
|
||||
class ObservedItemInstance(typing.TypedDict):
|
||||
"""Values shown for one configured item; they are not reusable definitions."""
|
||||
|
||||
instance_id: str
|
||||
family: ScreenshotFamily
|
||||
source_screen_ids: list[str]
|
||||
observed_context: ObservedContext
|
||||
fields: list[FieldClaim]
|
||||
|
||||
|
||||
class CanonicalDefinitionCandidate(typing.TypedDict):
|
||||
"""Evidence-backed reusable claims, kept separate from the observed item."""
|
||||
|
||||
candidate_id: str
|
||||
record_type: CanonicalRecordType
|
||||
source_instance_ids: list[str]
|
||||
evidence_refs: list[str]
|
||||
fields: list[FieldClaim]
|
||||
completeness: typing.Literal["complete", "incomplete", "unsupported"]
|
||||
relationship_status: typing.Literal["evidenced", "unresolved", "unsupported", "not_applicable"]
|
||||
mechanic_status: typing.Literal["evidenced", "unresolved", "unsupported", "not_applicable"]
|
||||
@@ -1,214 +0,0 @@
|
||||
"""Trust-boundary ports. Implementations belong to downstream tasks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from math import isfinite
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ResourceBudget:
|
||||
deadline_monotonic: float | None
|
||||
max_input_bytes: int
|
||||
max_output_bytes: int
|
||||
max_items: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
limits: tuple[tuple[str, object], ...] = (
|
||||
("max_input_bytes", self.max_input_bytes),
|
||||
("max_output_bytes", self.max_output_bytes),
|
||||
("max_items", self.max_items),
|
||||
)
|
||||
for name, value in limits:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
||||
raise ValueError(f"{name} must be a non-negative integer")
|
||||
deadline: object = self.deadline_monotonic
|
||||
if deadline is not None:
|
||||
if isinstance(deadline, bool) or not isinstance(deadline, int | float):
|
||||
raise ValueError("deadline_monotonic must be a finite number or null")
|
||||
if not isfinite(deadline):
|
||||
raise ValueError("deadline_monotonic must be finite or null")
|
||||
|
||||
|
||||
class CancellationToken(Protocol):
|
||||
def is_cancelled(self) -> bool: ...
|
||||
|
||||
def raise_if_cancelled(self) -> None: ...
|
||||
|
||||
|
||||
class Clock(Protocol):
|
||||
def now_utc(self) -> datetime: ...
|
||||
|
||||
def monotonic(self) -> float: ...
|
||||
|
||||
|
||||
class IdGenerator(Protocol):
|
||||
def new_id(self) -> str: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class BlobReceipt:
|
||||
sha256: str
|
||||
byte_size: int
|
||||
media_type: str
|
||||
|
||||
|
||||
class BlobStorage(Protocol):
|
||||
"""Stores immutable bytes by digest without exposing filesystem paths."""
|
||||
|
||||
def put(
|
||||
self,
|
||||
chunks: Iterable[bytes],
|
||||
*,
|
||||
expected_sha256: str | None,
|
||||
media_type: str,
|
||||
budget: ResourceBudget,
|
||||
cancellation: CancellationToken,
|
||||
) -> BlobReceipt: ...
|
||||
|
||||
def read(
|
||||
self,
|
||||
sha256: str,
|
||||
*,
|
||||
budget: ResourceBudget,
|
||||
cancellation: CancellationToken,
|
||||
) -> Iterable[bytes]: ...
|
||||
|
||||
def exists(self, sha256: str) -> bool: ...
|
||||
|
||||
|
||||
class Repository[RecordT](Protocol):
|
||||
def get(self, record_id: str) -> RecordT | None: ...
|
||||
|
||||
def add(self, record: RecordT) -> None: ...
|
||||
|
||||
def replace(self, record: RecordT, *, expected_revision: int) -> None: ...
|
||||
|
||||
|
||||
type CaptureRepository = Repository[object]
|
||||
type JobRepository = Repository[object]
|
||||
type ExtractionRepository = Repository[object]
|
||||
type GroupingRepository = Repository[object]
|
||||
type ReviewRepository = Repository[object]
|
||||
type ExportRepository = Repository[object]
|
||||
type ErrorRepository = Repository[object]
|
||||
|
||||
|
||||
class UnitOfWork(Protocol):
|
||||
captures: CaptureRepository
|
||||
jobs: JobRepository
|
||||
extractions: ExtractionRepository
|
||||
groupings: GroupingRepository
|
||||
reviews: ReviewRepository
|
||||
exports: ExportRepository
|
||||
errors: ErrorRepository
|
||||
|
||||
def commit(self) -> None: ...
|
||||
|
||||
def rollback(self) -> None: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ImageInput:
|
||||
artifact_id: str
|
||||
sha256: str
|
||||
media_type: str
|
||||
byte_size: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class EngineResult:
|
||||
engine_id: str
|
||||
engine_version: str
|
||||
payload: Mapping[str, object]
|
||||
|
||||
|
||||
class OcrEngine(Protocol):
|
||||
def extract(
|
||||
self,
|
||||
image: ImageInput,
|
||||
*,
|
||||
regions: Sequence[Mapping[str, int | float | str]],
|
||||
budget: ResourceBudget,
|
||||
cancellation: CancellationToken,
|
||||
) -> EngineResult: ...
|
||||
|
||||
|
||||
class VisionFallback(Protocol):
|
||||
"""Accepts bounded artifacts and never receives credentials in a request."""
|
||||
|
||||
def extract(
|
||||
self,
|
||||
images: Sequence[ImageInput],
|
||||
*,
|
||||
response_schema: Mapping[str, object],
|
||||
request_fingerprint: str,
|
||||
budget: ResourceBudget,
|
||||
cancellation: CancellationToken,
|
||||
) -> EngineResult: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SubprocessRequest:
|
||||
tool: SubprocessTool
|
||||
arguments: tuple[str, ...]
|
||||
environment: Mapping[SubprocessEnvironmentKey, str]
|
||||
stdin: bytes | None
|
||||
budget: ResourceBudget
|
||||
|
||||
|
||||
class SubprocessTool(StrEnum):
|
||||
WL_PASTE = "wl-paste"
|
||||
FFMPEG = "ffmpeg"
|
||||
FFPROBE = "ffprobe"
|
||||
|
||||
|
||||
class SubprocessEnvironmentKey(StrEnum):
|
||||
WAYLAND_DISPLAY = "WAYLAND_DISPLAY"
|
||||
XDG_RUNTIME_DIR = "XDG_RUNTIME_DIR"
|
||||
PATH = "PATH"
|
||||
HOME = "HOME"
|
||||
LANG = "LANG"
|
||||
LC_ALL = "LC_ALL"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SubprocessResult:
|
||||
return_code: int
|
||||
stdout: bytes
|
||||
stderr: bytes
|
||||
timed_out: bool
|
||||
cancelled: bool
|
||||
|
||||
|
||||
class SubprocessRunner(Protocol):
|
||||
"""Runs an argument array without a shell and with an explicit environment."""
|
||||
|
||||
def run(
|
||||
self,
|
||||
request: SubprocessRequest,
|
||||
*,
|
||||
cancellation: CancellationToken,
|
||||
) -> SubprocessResult: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FrameScore:
|
||||
timestamp_ms: int
|
||||
stability: float
|
||||
sharpness: float
|
||||
ui_coverage: float
|
||||
|
||||
|
||||
class FrameScorer(Protocol):
|
||||
def score(
|
||||
self,
|
||||
frames: Sequence[ImageInput],
|
||||
*,
|
||||
budget: ResourceBudget,
|
||||
cancellation: CancellationToken,
|
||||
) -> Sequence[FrameScore]: ...
|
||||
@@ -1,211 +0,0 @@
|
||||
"""State vocabularies and allowed transitions for recoverable workflows."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from types import MappingProxyType
|
||||
from typing import Final
|
||||
|
||||
|
||||
class CaptureState(StrEnum):
|
||||
RECEIVED = "received"
|
||||
SPOOLING = "spooling"
|
||||
STORED = "stored"
|
||||
DEDUPLICATED = "deduplicated"
|
||||
QUEUED = "queued"
|
||||
FAILED = "failed"
|
||||
CANCELLED = "cancelled"
|
||||
|
||||
|
||||
class JobState(StrEnum):
|
||||
QUEUED = "queued"
|
||||
RUNNING = "running"
|
||||
RETRY_WAIT = "retry_wait"
|
||||
SUCCEEDED = "succeeded"
|
||||
FAILED = "failed"
|
||||
CANCELLED = "cancelled"
|
||||
|
||||
|
||||
class ExtractionState(StrEnum):
|
||||
PENDING = "pending"
|
||||
LOCAL_PROCESSING = "local_processing"
|
||||
FALLBACK_PENDING = "fallback_pending"
|
||||
FALLBACK_PROCESSING = "fallback_processing"
|
||||
CANDIDATE_READY = "candidate_ready"
|
||||
ABSTAINED = "abstained"
|
||||
FAILED = "failed"
|
||||
CANCELLED = "cancelled"
|
||||
|
||||
|
||||
class GroupingState(StrEnum):
|
||||
UNGROUPED = "ungrouped"
|
||||
PROPOSED = "proposed"
|
||||
GROUPED = "grouped"
|
||||
SPLIT = "split"
|
||||
SUPERSEDED = "superseded"
|
||||
REJECTED = "rejected"
|
||||
CANCELLED = "cancelled"
|
||||
|
||||
|
||||
class ReviewState(StrEnum):
|
||||
PENDING = "pending"
|
||||
IN_REVIEW = "in_review"
|
||||
CHANGES_REQUESTED = "changes_requested"
|
||||
APPROVED = "approved"
|
||||
REJECTED = "rejected"
|
||||
CANCELLED = "cancelled"
|
||||
|
||||
|
||||
class ExportState(StrEnum):
|
||||
NOT_REQUESTED = "not_requested"
|
||||
QUEUED = "queued"
|
||||
BUILDING = "building"
|
||||
READY = "ready"
|
||||
FAILED = "failed"
|
||||
CANCELLED = "cancelled"
|
||||
EXPIRED = "expired"
|
||||
|
||||
|
||||
class ErrorState(StrEnum):
|
||||
OPEN = "open"
|
||||
RETRYABLE = "retryable"
|
||||
RETRYING = "retrying"
|
||||
RECOVERED = "recovered"
|
||||
TERMINAL = "terminal"
|
||||
DISMISSED = "dismissed"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StateMachine:
|
||||
name: str
|
||||
transitions: Mapping[str, frozenset[str]]
|
||||
|
||||
def allows(self, current: str, target: str) -> bool:
|
||||
return target in self.transitions.get(current, frozenset())
|
||||
|
||||
|
||||
def _machine(name: str, transitions: dict[str, set[str]]) -> StateMachine:
|
||||
return StateMachine(
|
||||
name=name,
|
||||
transitions=MappingProxyType(
|
||||
{state: frozenset(targets) for state, targets in transitions.items()}
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
STATE_MACHINES: Final[Mapping[str, StateMachine]] = MappingProxyType(
|
||||
{
|
||||
"capture": _machine(
|
||||
"capture",
|
||||
{
|
||||
"received": {"spooling", "deduplicated", "failed", "cancelled"},
|
||||
"spooling": {"stored", "failed", "cancelled"},
|
||||
"stored": {"queued", "failed"},
|
||||
"deduplicated": set(),
|
||||
"queued": set(),
|
||||
"failed": {"spooling", "cancelled"},
|
||||
"cancelled": set(),
|
||||
},
|
||||
),
|
||||
"job": _machine(
|
||||
"job",
|
||||
{
|
||||
"queued": {"running", "cancelled"},
|
||||
"running": {"succeeded", "retry_wait", "failed", "cancelled"},
|
||||
"retry_wait": {"queued", "failed", "cancelled"},
|
||||
"succeeded": set(),
|
||||
"failed": {"queued"},
|
||||
"cancelled": set(),
|
||||
},
|
||||
),
|
||||
"extraction": _machine(
|
||||
"extraction",
|
||||
{
|
||||
"pending": {"local_processing", "cancelled"},
|
||||
"local_processing": {
|
||||
"candidate_ready",
|
||||
"fallback_pending",
|
||||
"abstained",
|
||||
"failed",
|
||||
"cancelled",
|
||||
},
|
||||
"fallback_pending": {"fallback_processing", "cancelled"},
|
||||
"fallback_processing": {
|
||||
"candidate_ready",
|
||||
"abstained",
|
||||
"failed",
|
||||
"cancelled",
|
||||
},
|
||||
"candidate_ready": set(),
|
||||
"abstained": set(),
|
||||
"failed": {"pending"},
|
||||
"cancelled": set(),
|
||||
},
|
||||
),
|
||||
"grouping": _machine(
|
||||
"grouping",
|
||||
{
|
||||
"ungrouped": {"proposed", "cancelled"},
|
||||
"proposed": {"grouped", "rejected", "cancelled"},
|
||||
"grouped": {"split", "superseded"},
|
||||
"split": {"superseded"},
|
||||
"superseded": set(),
|
||||
"rejected": {"ungrouped"},
|
||||
"cancelled": set(),
|
||||
},
|
||||
),
|
||||
"review": _machine(
|
||||
"review",
|
||||
{
|
||||
"pending": {"in_review", "cancelled"},
|
||||
"in_review": {
|
||||
"changes_requested",
|
||||
"approved",
|
||||
"rejected",
|
||||
"cancelled",
|
||||
},
|
||||
"changes_requested": {"in_review", "rejected", "cancelled"},
|
||||
"approved": {"in_review"},
|
||||
"rejected": {"in_review"},
|
||||
"cancelled": set(),
|
||||
},
|
||||
),
|
||||
"export": _machine(
|
||||
"export",
|
||||
{
|
||||
"not_requested": {"queued"},
|
||||
"queued": {"building", "cancelled"},
|
||||
"building": {"ready", "failed", "cancelled"},
|
||||
"ready": {"expired"},
|
||||
"failed": {"queued", "cancelled"},
|
||||
"cancelled": set(),
|
||||
"expired": {"queued"},
|
||||
},
|
||||
),
|
||||
"error": _machine(
|
||||
"error",
|
||||
{
|
||||
"open": {"retryable", "terminal", "dismissed"},
|
||||
"retryable": {"retrying", "terminal", "dismissed"},
|
||||
"retrying": {"recovered", "retryable", "terminal"},
|
||||
"recovered": set(),
|
||||
"terminal": {"dismissed"},
|
||||
"dismissed": set(),
|
||||
},
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class InvalidStateTransition(ValueError):
|
||||
"""Raised when a caller attempts a transition absent from the contract."""
|
||||
|
||||
|
||||
def require_transition(machine_name: str, current: str, target: str) -> None:
|
||||
machine = STATE_MACHINES.get(machine_name)
|
||||
if machine is None:
|
||||
raise InvalidStateTransition(f"Unknown state machine: {machine_name}")
|
||||
if current not in machine.transitions:
|
||||
raise InvalidStateTransition(f"Unknown {machine_name} state: {current}")
|
||||
if not machine.allows(current, target):
|
||||
raise InvalidStateTransition(f"Invalid {machine_name} transition: {current} -> {target}")
|
||||
@@ -1,130 +0,0 @@
|
||||
"""Frozen screenshot taxonomy and canonical record vocabulary for contract v1."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from enum import StrEnum
|
||||
from types import MappingProxyType
|
||||
from typing import Final
|
||||
|
||||
|
||||
class Family(StrEnum):
|
||||
WEAPON = "weapon"
|
||||
GEAR = "gear"
|
||||
SKILL_CHIP = "skill_chip"
|
||||
OS_PROTOCOL = "os_protocol"
|
||||
SPECIALIZATION = "specialization"
|
||||
WEAPON_MOD = "weapon_mod"
|
||||
GEAR_MOD = "gear_mod"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class GearSlot(StrEnum):
|
||||
MASK = "Mask"
|
||||
GLOVES = "Gloves"
|
||||
BACKPACK = "Backpack"
|
||||
BODY_ARMOR = "Body Armor"
|
||||
HOLSTER = "Holster"
|
||||
KNEE_PADS = "Knee Pads"
|
||||
|
||||
|
||||
class AbstentionReason(StrEnum):
|
||||
LOW_CONFIDENCE = "low_confidence"
|
||||
AMBIGUOUS_FAMILY = "ambiguous_family"
|
||||
AMBIGUOUS_VIEW = "ambiguous_view"
|
||||
UNSUPPORTED_FAMILY = "unsupported_family"
|
||||
UNSUPPORTED_VIEW = "unsupported_view"
|
||||
INSUFFICIENT_VISUAL_EVIDENCE = "insufficient_visual_evidence"
|
||||
OCCLUDED = "occluded"
|
||||
CORRUPT_IMAGE = "corrupt_image"
|
||||
RESOURCE_LIMIT = "resource_limit"
|
||||
CANCELLED = "cancelled"
|
||||
|
||||
|
||||
class RecordType(StrEnum):
|
||||
WEAPON = "weapon"
|
||||
WEAPON_TALENT = "weapon_talent"
|
||||
WEAPON_AUGMENTATION_PROFILE = "weapon_augmentation_profile"
|
||||
GEAR = "gear"
|
||||
BRAND_SET = "brand_set"
|
||||
GEAR_TALENT = "gear_talent"
|
||||
GEAR_AUGMENTATION_PROFILE = "gear_augmentation_profile"
|
||||
SKILL_CHIP_SET = "skill_chip_set"
|
||||
SKILL_CHIP_SET_BONUS = "skill_chip_set_bonus"
|
||||
SKILL_CHIP_ROLL_POOL = "skill_chip_roll_pool"
|
||||
SKILL_CHIP_TALENT = "skill_chip_talent"
|
||||
OS_PROTOCOL = "os_protocol"
|
||||
OS_PROTOCOL_SECONDARY_PROFILE = "os_protocol_secondary_profile"
|
||||
OS_PROTOCOL_TALENT = "os_protocol_talent"
|
||||
SPECIALIZATION = "specialization"
|
||||
SPECIALIZATION_FOCUS = "specialization_focus"
|
||||
SPECIALIZATION_ABILITY = "specialization_ability"
|
||||
SPECIALIZATION_TREE_NODE = "specialization_tree_node"
|
||||
SPECIALIZATION_TREE_RANK = "specialization_tree_rank"
|
||||
WEAPON_MOD = "weapon_mod"
|
||||
GEAR_MOD = "gear_mod"
|
||||
|
||||
|
||||
SCREEN_VIEWS: Final[Mapping[Family, tuple[str, ...]]] = MappingProxyType(
|
||||
{
|
||||
Family.WEAPON: (
|
||||
"detail",
|
||||
"blueprint",
|
||||
"crafting",
|
||||
"stat_range",
|
||||
"talent_grid",
|
||||
"augmentation",
|
||||
),
|
||||
Family.GEAR: ("detail", "blueprint", "talent", "augmentation"),
|
||||
Family.SKILL_CHIP: ("detail", "set_bonus", "talent"),
|
||||
Family.OS_PROTOCOL: ("detail", "secondary_profile", "talent"),
|
||||
Family.SPECIALIZATION: (
|
||||
"overview",
|
||||
"details",
|
||||
"ability",
|
||||
"focus_details",
|
||||
"focus_tree",
|
||||
"rank_details",
|
||||
),
|
||||
Family.WEAPON_MOD: ("detail",),
|
||||
Family.GEAR_MOD: ("detail",),
|
||||
Family.UNKNOWN: ("unknown",),
|
||||
}
|
||||
)
|
||||
|
||||
GEAR_SLOTS: Final[tuple[str, ...]] = tuple(slot.value for slot in GearSlot)
|
||||
ABSTENTION_REASONS: Final[tuple[str, ...]] = tuple(reason.value for reason in AbstentionReason)
|
||||
|
||||
RECORD_TYPES_BY_VIEW: Final[Mapping[tuple[Family, str], tuple[RecordType, ...]]] = MappingProxyType(
|
||||
{
|
||||
(Family.WEAPON, "detail"): (RecordType.WEAPON, RecordType.WEAPON_TALENT),
|
||||
(Family.WEAPON, "blueprint"): (RecordType.WEAPON, RecordType.WEAPON_TALENT),
|
||||
(Family.WEAPON, "crafting"): (RecordType.WEAPON,),
|
||||
(Family.WEAPON, "stat_range"): (RecordType.WEAPON,),
|
||||
(Family.WEAPON, "talent_grid"): (RecordType.WEAPON_TALENT,),
|
||||
(Family.WEAPON, "augmentation"): (RecordType.WEAPON_AUGMENTATION_PROFILE,),
|
||||
(Family.GEAR, "detail"): (RecordType.GEAR, RecordType.BRAND_SET),
|
||||
(Family.GEAR, "blueprint"): (RecordType.GEAR, RecordType.BRAND_SET),
|
||||
(Family.GEAR, "talent"): (RecordType.GEAR_TALENT,),
|
||||
(Family.GEAR, "augmentation"): (RecordType.GEAR_AUGMENTATION_PROFILE,),
|
||||
(Family.SKILL_CHIP, "detail"): (
|
||||
RecordType.SKILL_CHIP_SET,
|
||||
RecordType.SKILL_CHIP_ROLL_POOL,
|
||||
),
|
||||
(Family.SKILL_CHIP, "set_bonus"): (RecordType.SKILL_CHIP_SET_BONUS,),
|
||||
(Family.SKILL_CHIP, "talent"): (RecordType.SKILL_CHIP_TALENT,),
|
||||
(Family.OS_PROTOCOL, "detail"): (RecordType.OS_PROTOCOL,),
|
||||
(Family.OS_PROTOCOL, "secondary_profile"): (RecordType.OS_PROTOCOL_SECONDARY_PROFILE,),
|
||||
(Family.OS_PROTOCOL, "talent"): (RecordType.OS_PROTOCOL_TALENT,),
|
||||
(Family.SPECIALIZATION, "overview"): (RecordType.SPECIALIZATION,),
|
||||
(Family.SPECIALIZATION, "details"): (RecordType.SPECIALIZATION,),
|
||||
(Family.SPECIALIZATION, "ability"): (RecordType.SPECIALIZATION_ABILITY,),
|
||||
(Family.SPECIALIZATION, "focus_details"): (RecordType.SPECIALIZATION_FOCUS,),
|
||||
(Family.SPECIALIZATION, "focus_tree"): (
|
||||
RecordType.SPECIALIZATION_FOCUS,
|
||||
RecordType.SPECIALIZATION_TREE_NODE,
|
||||
),
|
||||
(Family.SPECIALIZATION, "rank_details"): (RecordType.SPECIALIZATION_TREE_RANK,),
|
||||
(Family.WEAPON_MOD, "detail"): (RecordType.WEAPON_MOD,),
|
||||
(Family.GEAR_MOD, "detail"): (RecordType.GEAR_MOD,),
|
||||
(Family.UNKNOWN, "unknown"): (),
|
||||
}
|
||||
)
|
||||
@@ -1,390 +0,0 @@
|
||||
"""Semantic checks that portable JSON Schema cannot express."""
|
||||
|
||||
from collections.abc import Iterable, Mapping
|
||||
from datetime import datetime
|
||||
|
||||
from . import taxonomy
|
||||
|
||||
SUPPORTED_ARCHIVE_SCHEMA_VERSION = 1
|
||||
SUPPORTED_HANDOFF_SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
class ContractValidationError(ValueError):
|
||||
"""Raised when a document violates a version or referential contract."""
|
||||
|
||||
|
||||
def ensure_supported_version(document: Mapping[str, object], expected: int) -> None:
|
||||
version = document.get("schema_version")
|
||||
if type(version) is not int or version != expected:
|
||||
raise ContractValidationError(
|
||||
f"Unsupported schema_version {version!r}; expected {expected}"
|
||||
)
|
||||
|
||||
|
||||
def _objects(value: object, field: str) -> Iterable[Mapping[str, object]]:
|
||||
if not isinstance(value, list):
|
||||
raise ContractValidationError(f"{field} must be an array")
|
||||
for index, item in enumerate(value):
|
||||
if not isinstance(item, Mapping):
|
||||
raise ContractValidationError(f"{field}[{index}] must be an object")
|
||||
yield item
|
||||
|
||||
|
||||
def _ids(items: Iterable[Mapping[str, object]], field: str) -> set[str]:
|
||||
result: set[str] = set()
|
||||
for item in items:
|
||||
value = item.get(field)
|
||||
if not isinstance(value, str):
|
||||
raise ContractValidationError(f"{field} must be a string")
|
||||
if value in result:
|
||||
raise ContractValidationError(f"Duplicate {field}: {value}")
|
||||
result.add(value)
|
||||
return result
|
||||
|
||||
|
||||
def _references(item: Mapping[str, object], field: str) -> set[str]:
|
||||
raw = item.get(field, [])
|
||||
if not isinstance(raw, list) or any(not isinstance(value, str) for value in raw):
|
||||
raise ContractValidationError(f"{field} must contain string IDs")
|
||||
return set(raw)
|
||||
|
||||
|
||||
def _require_subset(values: set[str], allowed: set[str], context: str) -> None:
|
||||
dangling = values - allowed
|
||||
if dangling:
|
||||
raise ContractValidationError(f"{context} contains dangling references: {sorted(dangling)}")
|
||||
|
||||
|
||||
def validate_classification(classification: Mapping[str, object]) -> None:
|
||||
family_raw = classification.get("family")
|
||||
if not isinstance(family_raw, str):
|
||||
raise ContractValidationError("Unknown classification family")
|
||||
try:
|
||||
family = taxonomy.Family(family_raw)
|
||||
except ValueError as error:
|
||||
raise ContractValidationError("Unknown classification family") from error
|
||||
view = classification.get("view")
|
||||
if not isinstance(view, str) or view not in taxonomy.SCREEN_VIEWS[family]:
|
||||
raise ContractValidationError(f"Unknown {family.value} view: {view!r}")
|
||||
confidence = classification.get("confidence")
|
||||
if (
|
||||
isinstance(confidence, bool)
|
||||
or not isinstance(confidence, int | float)
|
||||
or not 0 <= confidence <= 1
|
||||
):
|
||||
raise ContractValidationError("Classification confidence must be between 0 and 1")
|
||||
gear_slot = classification.get("gear_slot")
|
||||
if family is taxonomy.Family.GEAR:
|
||||
if gear_slot not in taxonomy.GEAR_SLOTS:
|
||||
raise ContractValidationError(f"Unknown Gear slot: {gear_slot!r}")
|
||||
elif gear_slot is not None:
|
||||
raise ContractValidationError("Only Gear classifications may set gear_slot")
|
||||
record_types = classification.get("record_types")
|
||||
if not isinstance(record_types, list) or any(
|
||||
not isinstance(record_type, str) for record_type in record_types
|
||||
):
|
||||
raise ContractValidationError("record_types must contain strings")
|
||||
if len(record_types) != len(set(record_types)):
|
||||
raise ContractValidationError("record_types must be unique")
|
||||
if len(record_types) > 8:
|
||||
raise ContractValidationError("record_types cannot contain more than 8 values")
|
||||
try:
|
||||
normalized_record_types = {taxonomy.RecordType(record_type) for record_type in record_types}
|
||||
except ValueError as error:
|
||||
raise ContractValidationError("Unknown canonical record type") from error
|
||||
allowed = set(taxonomy.RECORD_TYPES_BY_VIEW[(family, view)])
|
||||
if family is taxonomy.Family.UNKNOWN:
|
||||
if record_types:
|
||||
raise ContractValidationError("Unknown screens cannot claim canonical record types")
|
||||
reason = classification.get("abstention_reason")
|
||||
if reason not in taxonomy.ABSTENTION_REASONS:
|
||||
raise ContractValidationError("Unknown screens require an abstention reason")
|
||||
else:
|
||||
if not record_types or not normalized_record_types.issubset(allowed):
|
||||
raise ContractValidationError(
|
||||
f"record_types are incompatible with {family.value}/{view}"
|
||||
)
|
||||
if classification.get("abstention_reason") is not None:
|
||||
raise ContractValidationError("Known screens cannot set abstention_reason")
|
||||
|
||||
|
||||
def _validate_evidence(value: Mapping[str, object]) -> None:
|
||||
_validate_value_state(value, "evidence")
|
||||
confidence = value.get("confidence")
|
||||
if (
|
||||
isinstance(confidence, bool)
|
||||
or not isinstance(confidence, int | float)
|
||||
or not 0 <= confidence <= 1
|
||||
):
|
||||
raise ContractValidationError("Evidence confidence must be between 0 and 1")
|
||||
region = value.get("region")
|
||||
if not isinstance(region, Mapping):
|
||||
raise ContractValidationError("Evidence region must be an object")
|
||||
coordinate_space = region.get("coordinate_space")
|
||||
numeric_coordinates: list[int | float] = []
|
||||
for name in ("x", "y", "width", "height"):
|
||||
number = region.get(name)
|
||||
if isinstance(number, bool) or not isinstance(number, int | float):
|
||||
raise ContractValidationError("Evidence bounds must be numeric")
|
||||
numeric_coordinates.append(number)
|
||||
x, y, width, height = numeric_coordinates
|
||||
if coordinate_space == "normalized":
|
||||
if x < 0 or y < 0 or width <= 0 or height <= 0 or x + width > 1 or y + height > 1:
|
||||
raise ContractValidationError("Normalized evidence bounds must fit within the image")
|
||||
elif coordinate_space == "pixels":
|
||||
if any(not isinstance(number, int) for number in numeric_coordinates):
|
||||
raise ContractValidationError("Pixel evidence bounds must be integers")
|
||||
if x < 0 or y < 0 or width <= 0 or height <= 0:
|
||||
raise ContractValidationError("Pixel evidence bounds must be positive and non-negative")
|
||||
else:
|
||||
raise ContractValidationError(f"Unknown coordinate space: {coordinate_space!r}")
|
||||
|
||||
|
||||
def _validate_value_state(value: Mapping[str, object], context: str) -> None:
|
||||
raw_text = value.get("raw_text")
|
||||
normalized = value.get("normalized_value")
|
||||
missing_reason = value.get("missing_reason")
|
||||
if raw_text is not None and not isinstance(raw_text, str):
|
||||
raise ContractValidationError(f"{context} raw_text must be a string or null")
|
||||
if normalized is None and not isinstance(missing_reason, str):
|
||||
raise ContractValidationError(f"Null {context} requires missing_reason")
|
||||
if normalized is not None and missing_reason is not None:
|
||||
raise ContractValidationError(f"Present {context} cannot set missing_reason")
|
||||
|
||||
|
||||
def _value_state(value: Mapping[str, object], context: str) -> tuple[object, object, object]:
|
||||
_validate_value_state(value, context)
|
||||
return value.get("raw_text"), value.get("normalized_value"), value.get("missing_reason")
|
||||
|
||||
|
||||
def _parse_correction_time(value: object) -> datetime:
|
||||
if not isinstance(value, str):
|
||||
raise ContractValidationError("Correction corrected_at must be a timestamp")
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError as error:
|
||||
raise ContractValidationError("Correction corrected_at must be a timestamp") from error
|
||||
if parsed.tzinfo is None:
|
||||
raise ContractValidationError("Correction corrected_at must include a UTC offset")
|
||||
return parsed
|
||||
|
||||
|
||||
def _validate_correction_history(
|
||||
evidence: Mapping[str, object], seen_correction_ids: set[str]
|
||||
) -> None:
|
||||
history = evidence.get("correction_history")
|
||||
if not isinstance(history, list):
|
||||
raise ContractValidationError("correction_history must be an array")
|
||||
previous_after: tuple[object, object, object] | None = None
|
||||
previous_time: datetime | None = None
|
||||
for index, correction in enumerate(history):
|
||||
if not isinstance(correction, Mapping):
|
||||
raise ContractValidationError(f"correction_history[{index}] must be an object")
|
||||
correction_id = correction.get("correction_id")
|
||||
if not isinstance(correction_id, str):
|
||||
raise ContractValidationError("correction_id must be a string")
|
||||
if correction_id in seen_correction_ids:
|
||||
raise ContractValidationError(f"Duplicate correction_id: {correction_id}")
|
||||
seen_correction_ids.add(correction_id)
|
||||
corrected_at = _parse_correction_time(correction.get("corrected_at"))
|
||||
if previous_time is not None and corrected_at <= previous_time:
|
||||
raise ContractValidationError("Correction history timestamps must be strictly ordered")
|
||||
before = correction.get("before")
|
||||
after = correction.get("after")
|
||||
if not isinstance(before, Mapping) or not isinstance(after, Mapping):
|
||||
raise ContractValidationError("Correction before and after must be value states")
|
||||
before_state = _value_state(before, "correction before")
|
||||
after_state = _value_state(after, "correction after")
|
||||
if previous_after is not None and before_state != previous_after:
|
||||
raise ContractValidationError("Correction history contains a disconnected value state")
|
||||
previous_after = after_state
|
||||
previous_time = corrected_at
|
||||
if previous_after is not None and previous_after != _value_state(evidence, "evidence"):
|
||||
raise ContractValidationError("Correction history final state does not match evidence")
|
||||
|
||||
|
||||
def validate_archive_document(document: Mapping[str, object]) -> None:
|
||||
validate_archive_references(document)
|
||||
for screen in _objects(document.get("screens"), "screens"):
|
||||
classification = screen.get("classification")
|
||||
if not isinstance(classification, Mapping):
|
||||
raise ContractValidationError("screen.classification must be an object")
|
||||
validate_classification(classification)
|
||||
seen_correction_ids: set[str] = set()
|
||||
for value in _objects(document.get("evidence_values"), "evidence_values"):
|
||||
_validate_evidence(value)
|
||||
_validate_correction_history(value, seen_correction_ids)
|
||||
|
||||
|
||||
def validate_handoff_document(document: Mapping[str, object]) -> None:
|
||||
validate_handoff_references(document)
|
||||
expected_boundary: dict[str, object] = {
|
||||
"intended_destination": "authenticated_isac_intake",
|
||||
"mutation_authority": "none",
|
||||
"requires_authenticated_action": True,
|
||||
"preserves_moderation": True,
|
||||
"creates_audit_events": False,
|
||||
}
|
||||
if document.get("trust_boundary") != expected_boundary:
|
||||
raise ContractValidationError("The handoff trust boundary is invalid")
|
||||
seen_correction_ids: set[str] = set()
|
||||
for value in _objects(document.get("evidence_values"), "evidence_values"):
|
||||
_validate_evidence(value)
|
||||
_validate_correction_history(value, seen_correction_ids)
|
||||
|
||||
|
||||
def validate_archive_references(document: Mapping[str, object]) -> None:
|
||||
ensure_supported_version(document, SUPPORTED_ARCHIVE_SCHEMA_VERSION)
|
||||
artifacts = list(_objects(document.get("artifacts"), "artifacts"))
|
||||
captures = list(_objects(document.get("captures"), "captures"))
|
||||
screens = list(_objects(document.get("screens"), "screens"))
|
||||
jobs = list(_objects(document.get("jobs"), "jobs"))
|
||||
extractions = list(_objects(document.get("extractions"), "extractions"))
|
||||
groups = list(_objects(document.get("groups"), "groups"))
|
||||
reviews = list(_objects(document.get("reviews"), "reviews"))
|
||||
exports = list(_objects(document.get("exports"), "exports"))
|
||||
errors = list(_objects(document.get("errors"), "errors"))
|
||||
evidence = list(_objects(document.get("evidence_values"), "evidence_values"))
|
||||
instances = list(_objects(document.get("observed_instances"), "observed_instances"))
|
||||
candidates = list(_objects(document.get("canonical_candidates"), "canonical_candidates"))
|
||||
artifact_ids = _ids(artifacts, "artifact_id")
|
||||
_ids(captures, "capture_id")
|
||||
screen_ids = _ids(screens, "screen_id")
|
||||
_ids(jobs, "job_id")
|
||||
_ids(extractions, "extraction_id")
|
||||
group_ids = _ids(groups, "group_id")
|
||||
_ids(reviews, "review_id")
|
||||
_ids(exports, "export_id")
|
||||
error_ids = _ids(errors, "error_id")
|
||||
evidence_ids = _ids(evidence, "evidence_id")
|
||||
instance_ids = _ids(instances, "instance_id")
|
||||
candidate_ids = _ids(candidates, "candidate_id")
|
||||
artifact_hashes = {
|
||||
str(artifact.get("artifact_id")): str(artifact.get("sha256")) for artifact in artifacts
|
||||
}
|
||||
|
||||
for capture in captures:
|
||||
_require_subset({str(capture.get("artifact_id"))}, artifact_ids, "capture.artifact_id")
|
||||
for artifact in artifacts:
|
||||
parent_id = artifact.get("parent_artifact_id")
|
||||
if parent_id is not None:
|
||||
if str(parent_id) == str(artifact.get("artifact_id")):
|
||||
raise ContractValidationError("artifact.parent_artifact_id cannot reference itself")
|
||||
_require_subset({str(parent_id)}, artifact_ids, "artifact.parent_artifact_id")
|
||||
for screen in screens:
|
||||
_require_subset({str(screen.get("artifact_id"))}, artifact_ids, "screen.artifact_id")
|
||||
for value in evidence:
|
||||
artifact_id = str(value.get("image_artifact_id"))
|
||||
_require_subset(
|
||||
{artifact_id},
|
||||
artifact_ids,
|
||||
"evidence.image_artifact_id",
|
||||
)
|
||||
if artifact_hashes.get(artifact_id) != value.get("image_sha256"):
|
||||
raise ContractValidationError("Evidence image_sha256 does not match its artifact")
|
||||
for job in jobs:
|
||||
last_error_id = job.get("last_error_id")
|
||||
if last_error_id is not None:
|
||||
_require_subset({str(last_error_id)}, error_ids, "job.last_error_id")
|
||||
for extraction in extractions:
|
||||
_require_subset({str(extraction.get("screen_id"))}, screen_ids, "extraction.screen_id")
|
||||
_require_subset(
|
||||
_references(extraction, "evidence_refs"),
|
||||
evidence_ids,
|
||||
"extraction.evidence_refs",
|
||||
)
|
||||
for group in groups:
|
||||
_require_subset(_references(group, "screen_ids"), screen_ids, "group.screen_ids")
|
||||
supersedes_group_ids = _references(group, "supersedes_group_ids")
|
||||
if str(group.get("group_id")) in supersedes_group_ids:
|
||||
raise ContractValidationError("group.supersedes_group_ids cannot reference itself")
|
||||
_require_subset(
|
||||
supersedes_group_ids,
|
||||
group_ids,
|
||||
"group.supersedes_group_ids",
|
||||
)
|
||||
for instance in instances:
|
||||
_require_subset(
|
||||
_references(instance, "source_screen_ids"),
|
||||
screen_ids,
|
||||
"observed_instance.source_screen_ids",
|
||||
)
|
||||
for field in _objects(instance.get("fields"), "observed_instance.fields"):
|
||||
_require_subset(
|
||||
_references(field, "evidence_refs"),
|
||||
evidence_ids,
|
||||
"observed_instance.fields.evidence_refs",
|
||||
)
|
||||
context = instance.get("observed_context")
|
||||
if not isinstance(context, Mapping):
|
||||
raise ContractValidationError("observed_instance.observed_context must be an object")
|
||||
for context_name in ("level", "quality", "tier", "upgrade_state"):
|
||||
context_field = context.get(context_name)
|
||||
if not isinstance(context_field, Mapping):
|
||||
raise ContractValidationError(f"observed_context.{context_name} must be an object")
|
||||
_require_subset(
|
||||
_references(context_field, "evidence_refs"),
|
||||
evidence_ids,
|
||||
f"observed_context.{context_name}.evidence_refs",
|
||||
)
|
||||
for candidate in candidates:
|
||||
_require_subset(
|
||||
_references(candidate, "source_instance_ids"),
|
||||
instance_ids,
|
||||
"canonical_candidate.source_instance_ids",
|
||||
)
|
||||
_require_subset(
|
||||
_references(candidate, "evidence_refs"),
|
||||
evidence_ids,
|
||||
"canonical_candidate.evidence_refs",
|
||||
)
|
||||
for field in _objects(candidate.get("fields"), "canonical_candidate.fields"):
|
||||
_require_subset(
|
||||
_references(field, "evidence_refs"),
|
||||
evidence_ids,
|
||||
"canonical_candidate.fields.evidence_refs",
|
||||
)
|
||||
for review in reviews:
|
||||
_require_subset({str(review.get("candidate_id"))}, candidate_ids, "review.candidate_id")
|
||||
for export in exports:
|
||||
export_artifact_id = export.get("artifact_id")
|
||||
if export_artifact_id is not None:
|
||||
_require_subset({str(export_artifact_id)}, artifact_ids, "export.artifact_id")
|
||||
|
||||
|
||||
def validate_handoff_references(document: Mapping[str, object]) -> None:
|
||||
ensure_supported_version(document, SUPPORTED_HANDOFF_SCHEMA_VERSION)
|
||||
evidence = list(_objects(document.get("evidence_values"), "evidence_values"))
|
||||
records = list(_objects(document.get("records"), "records"))
|
||||
evidence_ids = _ids(evidence, "evidence_id")
|
||||
artifacts = list(_objects(document.get("source_artifacts"), "source_artifacts"))
|
||||
artifact_ids = _ids(artifacts, "artifact_id")
|
||||
artifact_hashes = {
|
||||
str(artifact.get("artifact_id")): str(artifact.get("sha256")) for artifact in artifacts
|
||||
}
|
||||
_ids(records, "handoff_record_id")
|
||||
for value in evidence:
|
||||
artifact_id = str(value.get("image_artifact_id"))
|
||||
_require_subset(
|
||||
{artifact_id},
|
||||
artifact_ids,
|
||||
"evidence.image_artifact_id",
|
||||
)
|
||||
if artifact_hashes.get(artifact_id) != value.get("image_sha256"):
|
||||
raise ContractValidationError("Evidence image_sha256 does not match its artifact")
|
||||
for record in records:
|
||||
for field in _objects(record.get("fields"), "record.fields"):
|
||||
_require_subset(
|
||||
_references(field, "evidence_refs"),
|
||||
evidence_ids,
|
||||
"record.fields.evidence_refs",
|
||||
)
|
||||
for section_name in ("relationships", "mechanics"):
|
||||
section = record.get(section_name)
|
||||
if not isinstance(section, Mapping):
|
||||
raise ContractValidationError(f"record.{section_name} must be an object")
|
||||
_require_subset(
|
||||
_references(section, "evidence_refs"),
|
||||
evidence_ids,
|
||||
f"record.{section_name}.evidence_refs",
|
||||
)
|
||||
@@ -1,4 +0,0 @@
|
||||
"""Wayland clipboard intake and private spool boundaries.
|
||||
|
||||
Submodules stay unimported so the stdin helper can start independently.
|
||||
"""
|
||||
@@ -1,510 +0,0 @@
|
||||
"""Bounded, shell-free supervision for Wayland PNG clipboard intake."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from collections.abc import Iterator, Mapping
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Final, cast
|
||||
|
||||
from game_data_capture.ingest.spool_helper import (
|
||||
PNG_SIGNATURE,
|
||||
acknowledge_receipt,
|
||||
durable_receipts,
|
||||
reconcile_spool,
|
||||
)
|
||||
|
||||
_SAFE_ENV: Final = frozenset(
|
||||
{"PATH", "HOME", "LANG", "LC_ALL", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR"}
|
||||
)
|
||||
_DENIED_ENV = re.compile(
|
||||
r"(?:openai|authorization|token|secret|python(?:home|path|startup|userbase))", re.I
|
||||
)
|
||||
_SHA256 = re.compile(r"^[0-9a-f]{64}$")
|
||||
_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
|
||||
_MAX_METADATA = 16 * 1024
|
||||
_MAX_RECEIPT = 1024
|
||||
|
||||
|
||||
def _integer(value: object, minimum: int, maximum: int) -> bool:
|
||||
return isinstance(value, int) and not isinstance(value, bool) and minimum <= value <= maximum
|
||||
|
||||
|
||||
def _finite(value: object, minimum: float, maximum: float) -> bool:
|
||||
return (
|
||||
isinstance(value, int | float)
|
||||
and not isinstance(value, bool)
|
||||
and math.isfinite(value)
|
||||
and minimum < value <= maximum
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class WatchConfig:
|
||||
spool: Path
|
||||
max_image_bytes: int
|
||||
max_queue_items: int
|
||||
policy_version: str
|
||||
max_restarts: int = 3
|
||||
restart_backoff_seconds: float = 0.25
|
||||
shutdown_timeout_seconds: float = 2.0
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.spool.is_absolute() or len(str(self.spool)) > 240:
|
||||
raise ValueError("spool must be a bounded absolute path")
|
||||
if not _integer(self.max_image_bytes, 8, 64 * 1024 * 1024):
|
||||
raise ValueError("invalid image limit")
|
||||
if not _integer(self.max_queue_items, 1, 256) or not _integer(self.max_restarts, 0, 10):
|
||||
raise ValueError("invalid queue or restart limit")
|
||||
if not _finite(self.restart_backoff_seconds, 0, 60) or not _finite(
|
||||
self.shutdown_timeout_seconds, 0, 30
|
||||
):
|
||||
raise ValueError("invalid timeout")
|
||||
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", self.policy_version):
|
||||
raise ValueError("invalid policy version")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FocusedWindowMetadata:
|
||||
app_id: str | None
|
||||
title: str | None
|
||||
window_id: int | None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class IntakeReceipt:
|
||||
occurrence_id: str
|
||||
receipt_token: str
|
||||
sha256: str
|
||||
byte_size: int
|
||||
media_type: str
|
||||
spool_path: Path
|
||||
policy_version: str
|
||||
processing_version: str
|
||||
focused_window: FocusedWindowMetadata
|
||||
|
||||
|
||||
class VerifiedSpoolReader:
|
||||
"""Descriptor-verified stream for handing one receipt to GDC-003 safely."""
|
||||
|
||||
def __init__(self, receipt: IntakeReceipt) -> None:
|
||||
self.receipt = receipt
|
||||
self._fd: int | None = None
|
||||
|
||||
def __enter__(self) -> VerifiedSpoolReader:
|
||||
self._fd = _verify_spool_file(self.receipt)
|
||||
return self
|
||||
|
||||
def __exit__(self, *_: object) -> None:
|
||||
self.close()
|
||||
|
||||
def __iter__(self) -> Iterator[bytes]:
|
||||
if self._fd is None:
|
||||
raise RuntimeError("verified reader is not open")
|
||||
while chunk := os.read(self._fd, 64 * 1024):
|
||||
yield chunk
|
||||
|
||||
def close(self) -> None:
|
||||
if self._fd is not None:
|
||||
os.close(self._fd)
|
||||
self._fd = None
|
||||
|
||||
|
||||
def restricted_environment(environment: Mapping[str, str] | None = None) -> dict[str, str]:
|
||||
source = os.environ if environment is None else environment
|
||||
return {
|
||||
key: value[:4096]
|
||||
for key, value in source.items()
|
||||
if key in _SAFE_ENV
|
||||
and not _DENIED_ENV.search(key)
|
||||
and isinstance(value, str)
|
||||
and "\x00" not in value
|
||||
}
|
||||
|
||||
|
||||
def _bounded_text(value: object) -> str | None:
|
||||
return " ".join(value.split())[:256] or None if isinstance(value, str) else None
|
||||
|
||||
|
||||
def _bounded_command_output(
|
||||
arguments: list[str], environment: Mapping[str, str], timeout: float
|
||||
) -> bytes | None:
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
arguments,
|
||||
shell=False,
|
||||
env=environment,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
)
|
||||
except OSError:
|
||||
return None
|
||||
output = bytearray()
|
||||
done = threading.Event()
|
||||
|
||||
def collect() -> None:
|
||||
if process.stdout is not None:
|
||||
while len(output) <= _MAX_METADATA:
|
||||
chunk = process.stdout.read(min(4096, _MAX_METADATA + 1 - len(output)))
|
||||
if not chunk:
|
||||
break
|
||||
output.extend(chunk)
|
||||
done.set()
|
||||
|
||||
reader = threading.Thread(target=collect, daemon=True)
|
||||
reader.start()
|
||||
if not done.wait(timeout):
|
||||
with suppress(OSError):
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
with suppress(subprocess.TimeoutExpired):
|
||||
process.wait(timeout=timeout)
|
||||
if process.poll() is None:
|
||||
with suppress(OSError):
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
if process.stdout is not None:
|
||||
process.stdout.close()
|
||||
reader.join(timeout)
|
||||
return (
|
||||
bytes(output)
|
||||
if done.is_set() and process.returncode == 0 and len(output) <= _MAX_METADATA
|
||||
else None
|
||||
)
|
||||
|
||||
|
||||
def focused_window(
|
||||
*, environment: Mapping[str, str] | None = None, timeout_seconds: float = 0.5
|
||||
) -> FocusedWindowMetadata:
|
||||
if not _finite(timeout_seconds, 0, 30):
|
||||
return FocusedWindowMetadata(None, None, None)
|
||||
raw = _bounded_command_output(
|
||||
["niri", "msg", "-j", "focused-window"],
|
||||
restricted_environment(environment),
|
||||
float(timeout_seconds),
|
||||
)
|
||||
if raw is None:
|
||||
return FocusedWindowMetadata(None, None, None)
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
return FocusedWindowMetadata(None, None, None)
|
||||
if not isinstance(payload, dict):
|
||||
return FocusedWindowMetadata(None, None, None)
|
||||
identifier = payload.get("id")
|
||||
return FocusedWindowMetadata(
|
||||
_bounded_text(payload.get("app_id")),
|
||||
_bounded_text(payload.get("title")),
|
||||
identifier if _integer(identifier, 0, 2**63 - 1) else None,
|
||||
)
|
||||
|
||||
|
||||
def _verify_spool_file(receipt: IntakeReceipt) -> int:
|
||||
spool = receipt.spool_path.parent
|
||||
if spool.is_symlink() or not spool.is_dir() or (spool.stat().st_mode & 0o777) != 0o700:
|
||||
raise ValueError("unsafe spool")
|
||||
fd = os.open(receipt.spool_path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
try:
|
||||
info = os.fstat(fd)
|
||||
if (
|
||||
not stat.S_ISREG(info.st_mode)
|
||||
or (info.st_mode & 0o777) != 0o600
|
||||
or info.st_size != receipt.byte_size
|
||||
):
|
||||
raise ValueError("invalid spool file")
|
||||
first = os.read(fd, len(PNG_SIGNATURE))
|
||||
if first != PNG_SIGNATURE:
|
||||
raise ValueError("invalid spool png")
|
||||
hasher = hashlib.sha256(first)
|
||||
while chunk := os.read(fd, 64 * 1024):
|
||||
hasher.update(chunk)
|
||||
if hasher.hexdigest() != receipt.sha256:
|
||||
raise ValueError("spool digest mismatch")
|
||||
os.lseek(fd, 0, os.SEEK_SET)
|
||||
return fd
|
||||
except Exception:
|
||||
os.close(fd)
|
||||
raise
|
||||
|
||||
|
||||
class ClipboardIntake:
|
||||
def __init__(
|
||||
self, config: WatchConfig, *, environment: Mapping[str, str] | None = None
|
||||
) -> None:
|
||||
self.config, self.environment = config, restricted_environment(environment)
|
||||
self.armed = self.paused = False
|
||||
self._watcher: subprocess.Popen[bytes] | None = None
|
||||
self._reader: threading.Thread | None = None
|
||||
self._queue: deque[IntakeReceipt] = deque()
|
||||
self._helper_payloads: deque[dict[str, object]] = deque()
|
||||
self._seen_tokens: set[str] = set()
|
||||
self._seen_order: deque[str] = deque()
|
||||
self._recovered_tokens: set[str] = set()
|
||||
self._restart_count = 0
|
||||
self._restart_after = 0.0
|
||||
self._restarts_exhausted = False
|
||||
|
||||
@property
|
||||
def queue_depth(self) -> int:
|
||||
return len(self._queue)
|
||||
|
||||
@property
|
||||
def helper_queue_depth(self) -> int:
|
||||
return len(self._helper_payloads)
|
||||
|
||||
def arm(self) -> None:
|
||||
self.armed, self.paused = True, False
|
||||
self._start_if_due(time.monotonic())
|
||||
|
||||
def pause(self) -> None:
|
||||
self.paused = True
|
||||
self._stop_watcher()
|
||||
|
||||
def resume(self) -> None:
|
||||
if self.armed:
|
||||
self.paused = False
|
||||
self._start_if_due(time.monotonic())
|
||||
|
||||
def disarm(self) -> None:
|
||||
self.armed = self.paused = False
|
||||
self._stop_watcher()
|
||||
|
||||
def cancel(self) -> None:
|
||||
self.shutdown()
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self.disarm()
|
||||
self._queue.clear()
|
||||
self._helper_payloads.clear()
|
||||
self._seen_tokens.clear()
|
||||
self._seen_order.clear()
|
||||
self._recovered_tokens.clear()
|
||||
|
||||
def tick(self, now: float | None = None) -> None:
|
||||
current = time.monotonic() if now is None else now
|
||||
if self._watcher is not None and self._watcher.poll() is not None:
|
||||
self._stop_watcher()
|
||||
self._crashed(current)
|
||||
self._start_if_due(current)
|
||||
|
||||
def take(self) -> IntakeReceipt | None:
|
||||
return self._queue.popleft() if self._queue else None
|
||||
|
||||
def take_helper_receipt(self) -> dict[str, object] | None:
|
||||
return self._helper_payloads.popleft() if self._helper_payloads else None
|
||||
|
||||
def unreferenced_spool_candidates(self) -> list[Path]:
|
||||
queued = {item.spool_path.name for item in self._queue}
|
||||
return [
|
||||
path
|
||||
for path in self.config.spool.glob("*.png")
|
||||
if not path.is_symlink() and path.name not in queued
|
||||
]
|
||||
|
||||
def open_verified(self, receipt: IntakeReceipt) -> VerifiedSpoolReader:
|
||||
return VerifiedSpoolReader(receipt)
|
||||
|
||||
def accept_helper_receipt(
|
||||
self,
|
||||
payload: Mapping[str, object],
|
||||
*,
|
||||
occurrence_id: str,
|
||||
processing_version: str,
|
||||
metadata: FocusedWindowMetadata | None = None,
|
||||
) -> bool:
|
||||
token, digest, size, name = (
|
||||
payload.get("receipt_token"),
|
||||
payload.get("sha256"),
|
||||
payload.get("byte_size"),
|
||||
payload.get("spool_name"),
|
||||
)
|
||||
if (
|
||||
not self.armed
|
||||
or self.paused
|
||||
or len(self._queue) >= self.config.max_queue_items
|
||||
or payload.get("receipt_version") != 1
|
||||
or not isinstance(token, str)
|
||||
or not _ID.fullmatch(token)
|
||||
or token in self._seen_tokens
|
||||
or not isinstance(digest, str)
|
||||
or not _SHA256.fullmatch(digest)
|
||||
or not _integer(size, 8, self.config.max_image_bytes)
|
||||
or payload.get("media_type") != "image/png"
|
||||
or payload.get("policy_version") != self.config.policy_version
|
||||
or not isinstance(name, str)
|
||||
or name != f"{digest}.png"
|
||||
or not isinstance(occurrence_id, str)
|
||||
or not _ID.fullmatch(occurrence_id)
|
||||
or not isinstance(processing_version, str)
|
||||
or not _ID.fullmatch(processing_version)
|
||||
):
|
||||
return False
|
||||
recovered = token in self._recovered_tokens
|
||||
receipt = IntakeReceipt(
|
||||
occurrence_id,
|
||||
token,
|
||||
digest,
|
||||
cast(int, size),
|
||||
"image/png",
|
||||
self.config.spool / name,
|
||||
self.config.policy_version,
|
||||
processing_version,
|
||||
FocusedWindowMetadata(None, None, None)
|
||||
if recovered
|
||||
else focused_window()
|
||||
if metadata is None
|
||||
else metadata,
|
||||
)
|
||||
try:
|
||||
verified_fd = _verify_spool_file(receipt)
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
os.close(verified_fd)
|
||||
self._seen_tokens.add(token)
|
||||
self._seen_order.append(token)
|
||||
if len(self._seen_order) > self.config.max_queue_items:
|
||||
self._seen_tokens.remove(self._seen_order.popleft())
|
||||
self._queue.append(receipt)
|
||||
return True
|
||||
|
||||
def reconcile(self) -> list[str]:
|
||||
removed = reconcile_spool(self.config.spool)
|
||||
capacity = self.config.max_queue_items - len(self._helper_payloads)
|
||||
if capacity <= 0:
|
||||
return removed
|
||||
for payload in durable_receipts(self.config.spool, max_items=256):
|
||||
if len(self._helper_payloads) >= self.config.max_queue_items:
|
||||
break
|
||||
token = payload["receipt_token"]
|
||||
if isinstance(token, str) and token not in self._seen_tokens:
|
||||
self._helper_payloads.append(payload)
|
||||
self._recovered_tokens.add(token)
|
||||
return removed
|
||||
|
||||
def acknowledge(self, receipt: IntakeReceipt) -> bool:
|
||||
"""Delete this occurrence's durable receipt after repository confirmation only."""
|
||||
if (
|
||||
receipt.spool_path.parent != self.config.spool
|
||||
or receipt.policy_version != self.config.policy_version
|
||||
):
|
||||
return False
|
||||
payload: dict[str, object] = {
|
||||
"receipt_version": 1,
|
||||
"receipt_token": receipt.receipt_token,
|
||||
"sha256": receipt.sha256,
|
||||
"byte_size": receipt.byte_size,
|
||||
"media_type": receipt.media_type,
|
||||
"spool_name": receipt.spool_path.name,
|
||||
"policy_version": receipt.policy_version,
|
||||
}
|
||||
acknowledged = acknowledge_receipt(self.config.spool, payload)
|
||||
if acknowledged:
|
||||
self._recovered_tokens.discard(receipt.receipt_token)
|
||||
return acknowledged
|
||||
|
||||
def _crashed(self, now: float) -> None:
|
||||
if self.armed and not self.paused and self._restart_count < self.config.max_restarts:
|
||||
self._restart_count += 1
|
||||
self._restart_after = now + float(self.config.restart_backoff_seconds) * 2 ** (
|
||||
self._restart_count - 1
|
||||
)
|
||||
else:
|
||||
self._restarts_exhausted = True
|
||||
|
||||
def _start_if_due(self, now: float) -> None:
|
||||
if (
|
||||
not self.armed
|
||||
or self.paused
|
||||
or self._watcher is not None
|
||||
or self._restarts_exhausted
|
||||
or now < self._restart_after
|
||||
):
|
||||
return
|
||||
try:
|
||||
self._watcher = subprocess.Popen(
|
||||
[
|
||||
"wl-paste",
|
||||
"--type",
|
||||
"image/png",
|
||||
"--watch",
|
||||
sys.executable,
|
||||
"-m",
|
||||
"game_data_capture.ingest.spool_helper",
|
||||
"--spool",
|
||||
str(self.config.spool),
|
||||
"--max-bytes",
|
||||
str(self.config.max_image_bytes),
|
||||
"--policy-version",
|
||||
self.config.policy_version,
|
||||
"--media-type",
|
||||
"image/png",
|
||||
],
|
||||
shell=False,
|
||||
env=self.environment,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
)
|
||||
except OSError:
|
||||
self._crashed(now)
|
||||
return
|
||||
self._reader = threading.Thread(
|
||||
target=self._read_receipts, args=(self._watcher,), daemon=True
|
||||
)
|
||||
self._reader.start()
|
||||
|
||||
def _read_receipts(self, process: subprocess.Popen[bytes]) -> None:
|
||||
if process.stdout is None:
|
||||
return
|
||||
while True:
|
||||
line = process.stdout.readline(_MAX_RECEIPT + 1)
|
||||
if not line:
|
||||
return
|
||||
if len(line) > _MAX_RECEIPT and not line.endswith(b"\n"):
|
||||
while line and not line.endswith(b"\n"):
|
||||
line = process.stdout.readline(_MAX_RECEIPT + 1)
|
||||
continue
|
||||
try:
|
||||
payload = json.loads(line)
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
continue
|
||||
if (
|
||||
isinstance(payload, dict)
|
||||
and all(isinstance(key, str) for key in payload)
|
||||
and len(self._helper_payloads) < self.config.max_queue_items
|
||||
):
|
||||
self._helper_payloads.append(payload)
|
||||
|
||||
def _stop_watcher(self) -> None:
|
||||
process, self._watcher = self._watcher, None
|
||||
if process is None:
|
||||
return
|
||||
if process.poll() is None:
|
||||
with suppress(OSError):
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
try:
|
||||
process.wait(timeout=float(self.config.shutdown_timeout_seconds))
|
||||
except subprocess.TimeoutExpired:
|
||||
with suppress(OSError):
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
if process.stdout is not None:
|
||||
process.stdout.close()
|
||||
if self._reader is not None:
|
||||
self._reader.join(timeout=float(self.config.shutdown_timeout_seconds))
|
||||
self._reader = None
|
||||
@@ -1,486 +0,0 @@
|
||||
"""Small stdin-only PNG spool helper; intentionally independent of application services."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager, suppress
|
||||
from pathlib import Path
|
||||
from stat import S_ISDIR, S_ISREG
|
||||
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
RECEIPT_VERSION = 1
|
||||
_TOKEN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
|
||||
_SHA256 = re.compile(r"^[0-9a-f]{64}$")
|
||||
_CHUNK_SIZE = 64 * 1024
|
||||
_MAX_RECEIPT_BYTES = 1024
|
||||
_MAX_SIDECARS = 256
|
||||
_MAX_RECONCILE_ENTRIES = 1024
|
||||
_LOCK_NAME = ".spool.lock"
|
||||
_LOCK_TIMEOUT_SECONDS = 1.0
|
||||
_LOCK_RETRY_SECONDS = 0.01
|
||||
|
||||
|
||||
class SpoolError(ValueError):
|
||||
"""The supplied image or spool boundary is invalid."""
|
||||
|
||||
|
||||
def _private_spool(path: Path) -> None:
|
||||
if not path.is_absolute() or len(str(path)) > 240:
|
||||
raise SpoolError("invalid spool")
|
||||
if path.is_symlink():
|
||||
raise SpoolError("unsafe spool")
|
||||
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
mode = path.lstat().st_mode
|
||||
if path.is_symlink() or not S_ISDIR(mode):
|
||||
raise SpoolError("unsafe spool")
|
||||
path.chmod(0o700)
|
||||
|
||||
|
||||
def _write_all(fd: int, data: bytes) -> None:
|
||||
view = memoryview(data)
|
||||
while view:
|
||||
written = os.write(fd, view)
|
||||
if written <= 0:
|
||||
raise OSError("short spool write")
|
||||
view = view[written:]
|
||||
|
||||
|
||||
def _fsync_directory(path: Path) -> None:
|
||||
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _spool_lock(spool: Path) -> Iterator[None]:
|
||||
"""Hold the private spool lock for one bounded receipt installation."""
|
||||
try:
|
||||
fd = os.open(spool / _LOCK_NAME, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
||||
except OSError as error:
|
||||
raise SpoolError("unsafe spool lock") from error
|
||||
try:
|
||||
info = os.fstat(fd)
|
||||
if not S_ISREG(info.st_mode) or (info.st_mode & 0o777) != 0o600:
|
||||
raise SpoolError("unsafe spool lock")
|
||||
deadline = time.monotonic() + _LOCK_TIMEOUT_SECONDS
|
||||
while True:
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
break
|
||||
except BlockingIOError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise SpoolError("spool busy") from None
|
||||
time.sleep(_LOCK_RETRY_SECONDS)
|
||||
yield
|
||||
finally:
|
||||
with suppress(OSError):
|
||||
fcntl.flock(fd, fcntl.LOCK_UN)
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def _verify_existing(path: Path, digest: str, size: int) -> bool:
|
||||
try:
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
except OSError:
|
||||
return False
|
||||
try:
|
||||
info = os.fstat(fd)
|
||||
if not S_ISREG(info.st_mode) or (info.st_mode & 0o777) != 0o600 or info.st_size != size:
|
||||
return False
|
||||
hasher = hashlib.sha256()
|
||||
prefix = os.read(fd, len(PNG_SIGNATURE))
|
||||
if prefix != PNG_SIGNATURE:
|
||||
return False
|
||||
hasher.update(prefix)
|
||||
while chunk := os.read(fd, _CHUNK_SIZE):
|
||||
hasher.update(chunk)
|
||||
return hasher.hexdigest() == digest
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def receipt_name(token: str) -> str:
|
||||
if not _TOKEN.fullmatch(token):
|
||||
raise SpoolError("invalid receipt identity")
|
||||
return f"{token}.receipt.json"
|
||||
|
||||
|
||||
def _pending_name(token: str) -> str:
|
||||
return f".{token}.receipt.pending"
|
||||
|
||||
|
||||
def _receipt_bytes(receipt: dict[str, object]) -> bytes:
|
||||
encoded = json.dumps(receipt, separators=(",", ":"), sort_keys=True).encode("ascii")
|
||||
if len(encoded) > _MAX_RECEIPT_BYTES:
|
||||
raise SpoolError("receipt exceeds limit")
|
||||
return encoded
|
||||
|
||||
|
||||
def _valid_receipt(payload: object, *, spool: Path, verify_png: bool) -> dict[str, object] | None:
|
||||
if not isinstance(payload, dict) or set(payload) != {
|
||||
"byte_size",
|
||||
"media_type",
|
||||
"policy_version",
|
||||
"receipt_token",
|
||||
"receipt_version",
|
||||
"sha256",
|
||||
"spool_name",
|
||||
}:
|
||||
return None
|
||||
token, digest, size, name = (
|
||||
payload.get("receipt_token"),
|
||||
payload.get("sha256"),
|
||||
payload.get("byte_size"),
|
||||
payload.get("spool_name"),
|
||||
)
|
||||
if (
|
||||
payload.get("receipt_version") != RECEIPT_VERSION
|
||||
or not isinstance(token, str)
|
||||
or not _TOKEN.fullmatch(token)
|
||||
or not isinstance(digest, str)
|
||||
or not _SHA256.fullmatch(digest)
|
||||
or isinstance(size, bool)
|
||||
or not isinstance(size, int)
|
||||
or size < len(PNG_SIGNATURE)
|
||||
or payload.get("media_type") != "image/png"
|
||||
or not isinstance(payload.get("policy_version"), str)
|
||||
or not _TOKEN.fullmatch(payload["policy_version"])
|
||||
or not isinstance(name, str)
|
||||
or name != f"{digest}.png"
|
||||
):
|
||||
return None
|
||||
if verify_png and not _verify_existing(spool / name, digest, size):
|
||||
return None
|
||||
return payload
|
||||
|
||||
|
||||
def _read_sidecar(path: Path, *, spool: Path, verify_png: bool) -> dict[str, object] | None:
|
||||
try:
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
except OSError:
|
||||
return None
|
||||
try:
|
||||
info = os.fstat(fd)
|
||||
if (
|
||||
not S_ISREG(info.st_mode)
|
||||
or (info.st_mode & 0o777) != 0o600
|
||||
or info.st_size > _MAX_RECEIPT_BYTES
|
||||
):
|
||||
return None
|
||||
raw = os.read(fd, _MAX_RECEIPT_BYTES + 1)
|
||||
if len(raw) != info.st_size or len(raw) > _MAX_RECEIPT_BYTES:
|
||||
return None
|
||||
try:
|
||||
return _valid_receipt(json.loads(raw), spool=spool, verify_png=verify_png)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
return None
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def _install_pending_sidecar(spool: Path, receipt: dict[str, object]) -> Path:
|
||||
token = receipt["receipt_token"]
|
||||
assert isinstance(token, str)
|
||||
pending = spool / _pending_name(token)
|
||||
encoded = _receipt_bytes(receipt)
|
||||
fd = os.open(pending, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
_write_all(fd, encoded)
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
# Persist the recoverable pending name before promotion. A crash after this
|
||||
# point cannot claim recovery until its PNG is immutably installed.
|
||||
_fsync_directory(spool)
|
||||
return pending
|
||||
|
||||
|
||||
def _same_receipt(left: dict[str, object], right: dict[str, object]) -> bool:
|
||||
return _receipt_bytes(left) == _receipt_bytes(right)
|
||||
|
||||
|
||||
def _final_sidecar(spool: Path, receipt: dict[str, object]) -> dict[str, object] | None:
|
||||
token = receipt["receipt_token"]
|
||||
assert isinstance(token, str)
|
||||
final = spool / receipt_name(token)
|
||||
if not final.exists() and not final.is_symlink():
|
||||
return None
|
||||
stored = _read_sidecar(final, spool=spool, verify_png=True)
|
||||
if stored is None or not _same_receipt(stored, receipt):
|
||||
raise SpoolError("receipt token conflict")
|
||||
return stored
|
||||
|
||||
|
||||
def _receipt_capacity_available(spool: Path) -> bool:
|
||||
"""Count bounded valid receipt sidecars while removing malformed regular entries."""
|
||||
valid = 0
|
||||
candidates = 0
|
||||
for entry in spool.iterdir():
|
||||
if entry.is_symlink() or not entry.is_file():
|
||||
continue
|
||||
pending = entry.name.startswith(".") and entry.name.endswith(".receipt.pending")
|
||||
final = entry.name.endswith(".receipt.json")
|
||||
if not pending and not final:
|
||||
continue
|
||||
candidates += 1
|
||||
if candidates > _MAX_RECONCILE_ENTRIES:
|
||||
return False
|
||||
token = (
|
||||
entry.name[1 : -len(".receipt.pending")]
|
||||
if pending
|
||||
else entry.name[: -len(".receipt.json")]
|
||||
)
|
||||
receipt = _read_sidecar(entry, spool=spool, verify_png=final)
|
||||
if receipt is None or receipt.get("receipt_token") != token:
|
||||
entry.unlink()
|
||||
_fsync_directory(spool)
|
||||
continue
|
||||
valid += 1
|
||||
if valid >= _MAX_SIDECARS:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _promote_sidecar(spool: Path, receipt: dict[str, object], pending: Path) -> None:
|
||||
token = receipt["receipt_token"]
|
||||
assert isinstance(token, str)
|
||||
final = spool / receipt_name(token)
|
||||
try:
|
||||
os.link(pending, final, follow_symlinks=False)
|
||||
except FileExistsError:
|
||||
try:
|
||||
_final_sidecar(spool, receipt)
|
||||
except SpoolError:
|
||||
pending.unlink()
|
||||
_fsync_directory(spool)
|
||||
raise
|
||||
else:
|
||||
_fsync_directory(spool)
|
||||
pending.unlink()
|
||||
_fsync_directory(spool)
|
||||
|
||||
|
||||
def reconcile_spool(spool: Path) -> list[str]:
|
||||
"""Remove incomplete files and promote only receipt sidecars backed by immutable PNGs."""
|
||||
_private_spool(spool)
|
||||
removed: list[str] = []
|
||||
promoted = 0
|
||||
candidates = 0
|
||||
for entry in spool.iterdir():
|
||||
if entry.is_symlink() or not entry.is_file():
|
||||
continue
|
||||
if entry.name.endswith(".partial"):
|
||||
candidates += 1
|
||||
if candidates > _MAX_RECONCILE_ENTRIES:
|
||||
break
|
||||
entry.unlink()
|
||||
removed.append(entry.name)
|
||||
elif entry.name.startswith(".") and entry.name.endswith(".receipt.pending"):
|
||||
candidates += 1
|
||||
if candidates > _MAX_RECONCILE_ENTRIES:
|
||||
break
|
||||
receipt = _read_sidecar(entry, spool=spool, verify_png=True)
|
||||
token = entry.name[1 : -len(".receipt.pending")]
|
||||
if receipt is not None and receipt.get("receipt_token") == token:
|
||||
final = spool / receipt_name(token)
|
||||
if final.exists() or final.is_symlink():
|
||||
with suppress(SpoolError):
|
||||
_final_sidecar(spool, receipt)
|
||||
entry.unlink()
|
||||
removed.append(entry.name)
|
||||
elif promoted >= _MAX_SIDECARS:
|
||||
continue
|
||||
else:
|
||||
_promote_sidecar(spool, receipt, entry)
|
||||
promoted += 1
|
||||
continue
|
||||
entry.unlink()
|
||||
removed.append(entry.name)
|
||||
return removed
|
||||
|
||||
|
||||
def durable_receipts(spool: Path, *, max_items: int) -> Iterator[dict[str, object]]:
|
||||
"""Yield at most ``max_items`` validated final receipt sidecars without following links."""
|
||||
if (
|
||||
isinstance(max_items, bool)
|
||||
or not isinstance(max_items, int)
|
||||
or not 1 <= max_items <= _MAX_SIDECARS
|
||||
):
|
||||
raise SpoolError("invalid receipt limit")
|
||||
_private_spool(spool)
|
||||
yielded = 0
|
||||
valid = 0
|
||||
candidates = 0
|
||||
for entry in spool.iterdir():
|
||||
if entry.is_symlink() or not entry.is_file() or not entry.name.endswith(".receipt.json"):
|
||||
continue
|
||||
candidates += 1
|
||||
if candidates > _MAX_RECONCILE_ENTRIES:
|
||||
break
|
||||
token = entry.name[: -len(".receipt.json")]
|
||||
receipt = _read_sidecar(entry, spool=spool, verify_png=True)
|
||||
if receipt is not None and receipt.get("receipt_token") == token:
|
||||
valid += 1
|
||||
if valid > _MAX_SIDECARS:
|
||||
break
|
||||
if yielded < max_items:
|
||||
yielded += 1
|
||||
yield receipt
|
||||
else:
|
||||
try:
|
||||
info = entry.lstat()
|
||||
if S_ISREG(info.st_mode):
|
||||
entry.unlink()
|
||||
_fsync_directory(spool)
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
|
||||
def acknowledge_receipt(spool: Path, receipt: dict[str, object]) -> bool:
|
||||
"""Remove exactly one verified durable sidecar; immutable PNG data is never removed here."""
|
||||
_private_spool(spool)
|
||||
token = receipt.get("receipt_token")
|
||||
if not isinstance(token, str) or not _TOKEN.fullmatch(token):
|
||||
return False
|
||||
path = spool / receipt_name(token)
|
||||
stored = _read_sidecar(path, spool=spool, verify_png=True)
|
||||
if stored is None:
|
||||
return False
|
||||
if _receipt_bytes(stored) != _receipt_bytes(receipt):
|
||||
return False
|
||||
try:
|
||||
info = path.lstat()
|
||||
if not S_ISREG(info.st_mode) or (info.st_mode & 0o777) != 0o600:
|
||||
return False
|
||||
path.unlink()
|
||||
_fsync_directory(spool)
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def spool_png(
|
||||
input_stream: object,
|
||||
*,
|
||||
spool: Path,
|
||||
max_bytes: int,
|
||||
receipt_token: str,
|
||||
policy_version: str,
|
||||
media_type: str = "image/png",
|
||||
) -> dict[str, object]:
|
||||
"""Install immutable PNG bytes, then fsync a durable occurrence receipt before stdout."""
|
||||
if (
|
||||
isinstance(max_bytes, bool)
|
||||
or not isinstance(max_bytes, int)
|
||||
or not 8 <= max_bytes <= 64 * 1024 * 1024
|
||||
):
|
||||
raise SpoolError("invalid byte limit")
|
||||
if (
|
||||
media_type != "image/png"
|
||||
or not _TOKEN.fullmatch(receipt_token)
|
||||
or not _TOKEN.fullmatch(policy_version)
|
||||
):
|
||||
raise SpoolError("invalid receipt identity")
|
||||
_private_spool(spool)
|
||||
temporary = spool / f".{secrets.token_hex(16)}.partial"
|
||||
pending: Path | None = None
|
||||
immutable_installed = False
|
||||
hasher = hashlib.sha256()
|
||||
size = 0
|
||||
try:
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
prefix = bytearray()
|
||||
while True:
|
||||
chunk = input_stream.read(_CHUNK_SIZE) # type: ignore[attr-defined]
|
||||
if not isinstance(chunk, bytes):
|
||||
raise SpoolError("invalid input stream")
|
||||
if not chunk:
|
||||
break
|
||||
prefix.extend(chunk[: max(0, len(PNG_SIGNATURE) - len(prefix))])
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
raise SpoolError("image exceeds byte limit")
|
||||
hasher.update(chunk)
|
||||
_write_all(fd, chunk)
|
||||
if len(prefix) < len(PNG_SIGNATURE) or bytes(prefix) != PNG_SIGNATURE:
|
||||
raise SpoolError("invalid png")
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
digest = hasher.hexdigest()
|
||||
name = f"{digest}.png"
|
||||
receipt: dict[str, object] = {
|
||||
"receipt_version": RECEIPT_VERSION,
|
||||
"receipt_token": receipt_token,
|
||||
"sha256": digest,
|
||||
"byte_size": size,
|
||||
"media_type": "image/png",
|
||||
"spool_name": name,
|
||||
"policy_version": policy_version,
|
||||
}
|
||||
with _spool_lock(spool):
|
||||
if _final_sidecar(spool, receipt) is not None:
|
||||
return receipt
|
||||
if not _receipt_capacity_available(spool):
|
||||
raise SpoolError("spool receipt capacity reached")
|
||||
pending = _install_pending_sidecar(spool, receipt)
|
||||
destination = spool / name
|
||||
if destination.exists():
|
||||
if not _verify_existing(destination, digest, size):
|
||||
raise SpoolError("spool collision")
|
||||
else:
|
||||
os.replace(temporary, destination)
|
||||
os.chmod(destination, 0o600)
|
||||
_fsync_directory(spool)
|
||||
immutable_installed = True
|
||||
_promote_sidecar(spool, receipt, pending)
|
||||
return receipt
|
||||
finally:
|
||||
if temporary.exists() and not temporary.is_symlink():
|
||||
temporary.unlink()
|
||||
if (
|
||||
pending is not None
|
||||
and not immutable_installed
|
||||
and pending.exists()
|
||||
and not pending.is_symlink()
|
||||
):
|
||||
pending.unlink()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(add_help=False)
|
||||
parser.add_argument("--spool", required=True)
|
||||
parser.add_argument("--max-bytes", required=True, type=int)
|
||||
parser.add_argument("--receipt-token", default=secrets.token_hex(16))
|
||||
parser.add_argument("--policy-version", required=True)
|
||||
parser.add_argument("--media-type", default="image/png")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
receipt = spool_png(
|
||||
sys.stdin.buffer,
|
||||
spool=Path(args.spool),
|
||||
max_bytes=args.max_bytes,
|
||||
receipt_token=args.receipt_token,
|
||||
policy_version=args.policy_version,
|
||||
media_type=args.media_type,
|
||||
)
|
||||
except (OSError, SpoolError):
|
||||
return 2
|
||||
sys.stdout.write(json.dumps(receipt, separators=(",", ":")) + "\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user