"""Session plan definitions for the implementation plan. HAND-AUTHORED: edit this file, then run build_sessions.py.

A session is one AI agent session: one agent, one context, one bounded piece of work, one pull request.
build_sessions.py cuts every vertical slice into sessions by the rules below and adds the foundation
sessions listed here in front of the first slice.

MAX_REQUIREMENTS = most functional requirements one build session takes. Modules of one deployable unit are
                   packed into a session up to this number; a module with more is split evenly.
MAX_SCREENS      = most screens one screen session takes.
MAX_CONTRACT_MODULES = most modules one contract session covers. A slice crossing more modules, in more than one
                   domain, gets one contract session per domain, side by side; the one for the most downstream domain comes
                   after the others, joins them and writes the scenario test.
                   A slice with a single build session has no contract session: that build session does the contract work.
KINDS            = the session kinds, in the order they come in a slice: code, name, what the session does,
                   what it leaves behind, the check that ends it, and which slices have it.
UNITS            = the deployable units of the architecture (section 5.2), each with its domain and modules. Build
                   sessions are cut by unit: sessions on one unit follow one another, within a slice and across slices, so no two
                   sessions running side by side change the same codebase. Every module is in exactly one unit.
SESSION_PROMPT   = the prompt that starts a session, with <SESSION-ID> and <GROUP> to fill in. Printed in the session
                   plan and used by launch_sessions.py, which also fills in <ISSUE>.
SESSION_PERMISSIONS = the commands an agent session may run without asking, and those it may never run. The
                   launcher writes them into each session's settings file, with <SESSION-ID> and <ISSUE> filled in,
                   so that writes reach only the session's own branch, issue and pull request. Anything else asks.
AUTO_MERGE       = when the pull request of a session is merged without a person, after the checks pass and an
                   independent review agent approves it (launch_sessions.py, review step). A person merges only when
                   the session's kind, its issue's labels or the files it changes are in the lists below, or after
                   `rounds` reviews that asked for changes. A review that raises a question, and a conflict with
                   main, go back to the session.
REVIEW_PROMPT    = the prompt of the review agent, with <SESSION-ID>, <GROUP>, <ISSUE> and <PR> to fill in.
FOUNDATION       = sessions that prepare the repository for agent work. They implement no functional
                   requirement. `reads` are (label, path from docs/) pairs; `after` are foundation session numbers.
"""

MAX_REQUIREMENTS = 4
MAX_SCREENS = 3
MAX_CONTRACT_MODULES = 8

SESSION_PERMISSIONS = dict(
    allow=[
        # look around, read-only
        'Bash(ls *)', 'Bash(ls)', 'Bash(pwd)', 'Bash(tree *)', 'Bash(wc *)', 'Bash(head *)', 'Bash(tail *)', 'Bash(cat *)',
        'Bash(grep *)', 'Bash(rg *)', 'Bash(diff *)', 'Bash(file *)', 'Bash(which *)',
        # git: read anything, write only on the session's own branch
        'Bash(git status *)', 'Bash(git status)', 'Bash(git diff *)', 'Bash(git diff)', 'Bash(git log *)', 'Bash(git show *)',
        'Bash(git branch --show-current)', 'Bash(git rev-parse *)', 'Bash(git ls-files *)', 'Bash(git fetch *)',
        'Bash(git add *)', 'Bash(git commit *)', 'Bash(git merge origin/main)',
        'Bash(git push origin session/<SESSION-ID>)', 'Bash(git push -u origin session/<SESSION-ID>)',
        # GitHub: read issues and pull requests; write only to the session's own issue and pull request
        'Bash(gh issue view *)', 'Bash(gh issue list *)', 'Bash(gh pr view *)', 'Bash(gh pr list *)', 'Bash(gh pr diff *)',
        'Bash(gh issue comment <ISSUE> *)', 'Bash(gh issue edit <ISSUE> --add-label blocked)',
        'Bash(gh pr create *)',
        # the documentation checks every session must leave passing
        'Bash(python3 docs/implementation_plan/tools/check_links.py)', 'Bash(mkdocs build *)', 'Bash(mkdocs build)',
    ],
    deny=[
        'Bash(git push --force *)', 'Bash(git push -f *)', 'Bash(git push * main)', 'Bash(git push origin HEAD:main)',
        'Bash(git reset --hard *)', 'Bash(git checkout main)', 'Bash(git rebase *)', 'Bash(git branch -D *)',
        'Bash(gh pr merge *)', 'Bash(gh issue close *)', 'Bash(gh repo *)', 'Bash(gh secret *)', 'Bash(gh api *)',
        'Bash(rm -rf *)', 'Bash(sudo *)',
        'Bash(python3 docs/implementation_plan/tools/build.py *)', 'Bash(python3 docs/implementation_plan/tools/build.py)',
    ],
)

AUTO_MERGE = dict(
    # Every session pull request is merged by the launcher once its checks pass and the review agent approves it
    # (ADR-HIS-040, decided 2026-11-24). The three lists name what a person merges instead; they are empty, so no
    # person merges. Put a kind, a label or a path back to have a person merge those pull requests again.
    person_kinds=[],      # for example 'Contract', 'Gate evidence'
    person_labels=[],     # for example 'safety-review', 'needs-person'
    person_paths=[],      # for example 'docs/domain_specs/', '.github/', 'docs/implementation_plan/tools/'
    rounds=None,          # reviews that ask for changes before a person takes over; None: the session keeps fixing
    review_timeout=2400,  # seconds one review may take
)

REVIEW_PROMPT = [
    'Review pull request #<PR> of session <SESSION-ID> of the HIS session plan (issue #<ISSUE>). You did not write it.',
    'You own this code base (ADR-HIS-041) and are answerable for what you approve: hold it to the bar you would',
    'set for your own work, and approve only what fits the design of the whole as well as its card.',
    'Change nothing: read only.',
    '',
    '1. Read docs/implementation_plan/delivery/sessions.md, sections 2 to 4, and the card of <SESSION-ID> in',
    '   docs/implementation_plan/delivery/sessions/<GROUP>.md.',
    '2. Read the pull request and its diff (gh pr view <PR>, gh pr diff <PR>), the handover',
    '   docs/implementation_plan/delivery/handovers/<SESSION-ID>.md and, where you need them, the requirements,',
    '   business rules and contracts the card names.',
    '3. Check, against the card and the session rules: the change does what the card lists and nothing outside',
    '   it; every acceptance criterion of the listed requirements has a test that names it; the "Ends when"',
    '   check holds as far as the diff and the handover show; the change touches only the files of its unit or',
    '   its screens, plus its tests, contracts tests and migrations; no specification, contract or safety',
    '   control is changed to fit the code; authorization, audit and telemetry are not left out; no secret,',
    '   real patient data or debugging shortcut is added.',
    '4. Decide: "approve" if it can be merged as it is; "changes" if it cannot. No person reviews it after',
    '   you: what you approve is merged. Where you are not sure a clinical, financial, access or safety',
    '   behaviour, a specification change or a safety control is right, the answer is "changes", with the',
    '   question in the findings, so that the session settles it from the specification or stops on it',
    '   under rule 3.',
    '5. End your answer with one line of JSON and nothing after it:',
    '   {"verdict": "approve" | "changes", "summary": "<one sentence>", "findings": ["<one line each>"]}',
]

SESSION_PROMPT = [
    'Run session <SESSION-ID> of the HIS session plan. Its GitHub issue is #<ISSUE>.',
    '',
    'You own this code base (ADR-HIS-041): what it is for, aligned with the specifications, and how it is',
    'built are your call, and you keep building on it. Take the technical decisions the card leaves open',
    'and record those that shape later sessions as the next decision record in docs/architecture/decisions/.',
    'The specification still decides behaviour (rule 3) and the card still bounds the work (rule 1).',
    '',
    '1. Read docs/implementation_plan/delivery/sessions.md, sections 2 to 4.',
    '2. Read the card of <SESSION-ID> in docs/implementation_plan/delivery/sessions/<GROUP>.md, and the',
    '   comments on issue #<ISSUE> (gh issue view <ISSUE> --comments): they hold answers from people.',
    '3. Read everything the card lists under "Reads", and the handover of each session under "After"',
    '   in docs/implementation_plan/delivery/handovers/.',
    '4. Before changing anything, state the scope in your own words and list anything the card or the',
    '   specification leaves unclear.',
    '5. Do the work of the card and nothing outside it, until the "Ends when" check holds. Work only in',
    '   this checkout and on its branch, and start the integration environment only under the name of',
    '   this session.',
    '6. Stop only if you cannot go on without an answer from a person: a question under rule 3, a',
    '   decision the work depends on that is not settled, or work that cannot be finished in this',
    '   session. Then commit and push the branch, write the question or what remains as a comment on',
    '   issue #<ISSUE>, add the label blocked (gh issue edit <ISSUE> --add-label blocked) and stop.',
    '   Approvals and reviews listed under "Needs a person" are not a reason to stop: they are given',
    '   on the pull request.',
    '7. Otherwise write docs/implementation_plan/delivery/handovers/<SESSION-ID>.md, push the branch and',
    '   open the pull request against main (gh pr create) with "Closes #<ISSUE>" as the first line of its',
    '   description. Under a heading "Needs a person", list each approval or review the card names and',
    '   any question left; write "None" if there is none. Do not edit session-status.csv or',
    '   session-fixes.csv and do not run the plan build: they are written from GitHub when the pull',
    '   request is merged.',
]

KINDS = [
    ('C', 'Contract',
     'Fixes what the slice exposes before any of it is built: the API and event contracts each domain in the slice offers, '
     'a stub for every upstream module the slice needs but does not build, and the end-to-end scenario as an automated test that fails. '
     'Fields follow architecture section 6.6: the shared type library, the attributes of section 7.3 where listed, and for any entity section 7.3 does not detail, '
     'its attributes written into section 7.3 of the owning specification in the same pull request.',
     'Contract files, stubs, the failing scenario test, the section 7.3 additions, and a list of the contract points each build session must meet.',
     'Contracts pass the compatibility check; every contract field traces to a requirement, a business rule or a section 7.3 attribute; stubs run in the integration environment; '
     'the scenario test runs and fails only because the behaviour is not built.',
     'Every slice'),
    ('B', 'Build',
     'Implements the listed requirements of one module behind the contracts: domain logic, persistence, events, authorization, audit, and the tests of section 15.2 that trace to them.',
     'Service code and migrations, unit and contract tests tagged with requirement and test identifiers.',
     'Every acceptance criterion of the listed requirements has a passing test; the listed test scenarios pass; the contract tests pass; '
     'the change touches only the files of its deployable unit, plus its contract tests and migrations.',
     'Every slice'),
    ('U', 'Screens',
     'Builds the listed screens in the application shell from their briefs, against the contracts and their stubs, side by side with the build sessions.',
     'Screen code in the folder of each screen in the domain workspace, component tests, accessibility checks.',
     'Each screen meets its brief and the clinical UX safety rules; component and accessibility checks pass; the screen works against the stubs of the contracts; the change touches only the folders of its screens.',
     'Every slice; each screen has a folder of its own, so screen sessions have no order between them'),
    ('I', 'Integrate',
     'Joins the build and screen sessions of the slice: replaces stubs with the built services, for the screens as well, runs the end-to-end scenario with its failure branches, and repairs what breaks between domains.',
     'A passing scenario test, the interface checks of the slice (acknowledgement, error handling, replay, reconciliation, monitoring), and a list of defects fixed.',
     'The scenario passes from first step to last, through the screens and the built services, with no manual repair; the scenarios of the slices this one comes after still pass.',
     'Every slice'),
    ('R', 'Readiness',
     'Drafts what the slice needs to carry patients safely, which no build session produces: the downtime procedure and restoration reconciliation for each workflow of the slice, '
     'runbook entries for its alerts and recovery, the operational readiness items its gate lists, and the safety scenario reports the gate asks for (identity, critical result, medication, as applicable).',
     'Draft downtime procedures and runbook entries, the readiness items with their evidence, the safety scenario reports, and a draft traceability matrix of the slice.',
     'Every readiness item and gate criterion of the slice that needs a document has one, reviewed by the service owner and ready for the departments to rehearse.',
     'Tier 1 slices'),
    ('G', 'Gate evidence',
     'Run by a session that wrote none of the slice. Runs the slice gate, collects the evidence in the form PRS section 17.3 requires, and reports what fails. It does not fix: a failure returns to the session that owns it.',
     'The evidence record of the slice gate and a pass or fail report against each "done when" line of the slice.',
     'Every "done when" line of the slice has evidence or a recorded failure. Each failure is filed as a fix issue against the session that owns it (session plan, section 3). '
     'The gate itself is passed by the owner who signs it, not by the session.',
     'Every slice; run again after each round of fixes'),
    ('X', 'Fix',
     'Repairs one failure a gate evidence session recorded, in the work of the session that owns it. Finished sessions are not reopened; the fix is a session of its own.',
     'The repair, a test that fails before it and passes after, and a note in the handover of what the gate line now shows.',
     'The failed gate line\'s check passes; the tests of the owning session and of the slice scenario still pass.',
     'When a gate records a failure'),
]

_ISE = 'Platform: '
UNITS = [
    ('Identity', 'ADM', ['MOD-ADM-001', 'MOD-ADM-003']),
    ('Patient administration', 'ADM', ['MOD-ADM-002', 'MOD-ADM-004', 'MOD-ADM-005', 'MOD-ADM-006', 'MOD-ADM-009', 'MOD-ADM-010']),
    ('Scheduling and flow', 'ADM', ['MOD-ADM-007', 'MOD-ADM-008']),
    # Domain 2 is the platform itself, not deployable services; architecture section 5.2 lists no units for it.
    # Each module is its own unit, since each changes a separate part of the platform repository.
    (_ISE + 'deployment topology', 'ISE', ['MOD-ISE-001']),
    (_ISE + 'gateways', 'ISE', ['MOD-ISE-002']),
    (_ISE + 'integration engine', 'ISE', ['MOD-ISE-003']),
    (_ISE + 'event backbone', 'ISE', ['MOD-ISE-004']),
    (_ISE + 'delivery pipeline', 'ISE', ['MOD-ISE-005']),
    (_ISE + 'secrets and keys', 'ISE', ['MOD-ISE-006']),
    (_ISE + 'network and workload protection', 'ISE', ['MOD-ISE-007']),
    (_ISE + 'observability', 'ISE', ['MOD-ISE-008']),
    (_ISE + 'backup and recovery', 'ISE', ['MOD-ISE-009']),
    (_ISE + 'supply-chain controls', 'ISE', ['MOD-ISE-010']),
    ('Clinical record', 'CLI', ['MOD-CLI-001', 'MOD-CLI-002', 'MOD-CLI-003', 'MOD-CLI-004', 'MOD-CLI-005']),
    # MOD-CLI-012 result presentation and review is CMP-CLI-010, which architecture section 5.2 places in Orders (reviewed 2026-11-24)
    ('Orders', 'CLI', ['MOD-CLI-006', 'MOD-CLI-007', 'MOD-CLI-012']),
    ('Medication', 'CLI', ['MOD-CLI-008', 'MOD-CLI-009', 'MOD-CLI-010']),
    ('CDS', 'CLI', ['MOD-CLI-011']),
    ('Laboratory', 'ANC', ['MOD-ANC-001', 'MOD-ANC-002', 'MOD-ANC-005', 'MOD-ANC-007']),
    ('Imaging workflow', 'ANC', ['MOD-ANC-003', 'MOD-ANC-004']),
    ('Blood bank (SaMD)', 'ANC', ['MOD-ANC-006']),
    ('Perioperative, critical care and therapy', 'ANC', ['MOD-ANC-008', 'MOD-ANC-009', 'MOD-ANC-010', 'MOD-ANC-011', 'MOD-ANC-012']),
    ('Device data', 'ANC', ['MOD-ANC-013']),
    ('Revenue cycle', 'FIN', ['MOD-FIN-001', 'MOD-FIN-002', 'MOD-FIN-003', 'MOD-FIN-004', 'MOD-FIN-005', 'MOD-FIN-006', 'MOD-FIN-007', 'MOD-FIN-011']),
    ('Inventory and procurement', 'FIN', ['MOD-FIN-008', 'MOD-FIN-009', 'MOD-FIN-010']),
    ('HIM', 'HIM', [f'MOD-HIM-{n:03d}' for n in range(1, 11)]),
    ('Portal BFF and engagement', 'PEX', [f'MOD-PEX-{n:03d}' for n in range(1, 11)]),
    ('Data platform', 'ANL', ['MOD-ANL-001', 'MOD-ANL-002', 'MOD-ANL-003', 'MOD-ANL-004', 'MOD-ANL-005', 'MOD-ANL-006', 'MOD-ANL-007', 'MOD-ANL-008', 'MOD-ANL-010']),
    ('AI policy gateway and registry', 'ANL', ['MOD-ANL-009']),
    ('EBP content', 'EBP', ['MOD-EBP-001', 'MOD-EBP-002', 'MOD-EBP-003', 'MOD-EBP-004', 'MOD-EBP-005', 'MOD-EBP-006', 'MOD-EBP-012']),
    ('EBP execution', 'EBP', ['MOD-EBP-007', 'MOD-EBP-008', 'MOD-EBP-009', 'MOD-EBP-010', 'MOD-EBP-011']),
    ('Runtime decision services', 'ESS', ['MOD-ESS-001', 'MOD-ESS-002', 'MOD-ESS-003']),
    ('Reference services', 'ESS', ['MOD-ESS-004', 'MOD-ESS-005', 'MOD-ESS-010']),
    ('Audit', 'ESS', ['MOD-ESS-006']),
    ('Coordination services', 'ESS', ['MOD-ESS-007', 'MOD-ESS-008', 'MOD-ESS-009']),
    ('Governance services', 'ESS', ['MOD-ESS-011', 'MOD-ESS-012']),
]

FOUNDATION_INTRO = ('Sessions that prepare the repository so that later sessions can start cold and finish with a check. '
                    'The code repository is this repository (cema-care): code lives beside docs/, which stays as it is. '
                    'They implement no functional requirement; the platform requirements of Domain 2 are delivered and proven in the slices, starting with RC-1.')

FOUNDATION = [
    dict(n=1, after=[],
         title='Repository layout and agent instructions',
         does='Lay out the code in this repository (cema-care), beside docs/, along the deployable units of the architecture: top-level folders for services, web workspaces, contracts, '
              'platform (infrastructure as code and environments), end-to-end tests and decision records. Each deployable unit, each domain workspace and each domain\'s contract folder has its own dependency manifest and lockfile, so that sessions running side by side never change the same file; nothing at the repository root is edited by an ordinary session; docs/, mkdocs.yml and the documentation site stay as they are; read .github/workflows/, mkdocs.yml and .gitignore at the repository root first. '
              'Write the agent instruction file: build and test commands, naming, the session rules of this plan, where handovers and decision records go. '
              'The decision records already exist in docs/architecture/decisions/ (drafted 2026-11-24): point the instruction file at them, and record there, as the next numbered record, '
              'any further decision the layout or the template needs.',
         reads=[('Architecture, sections 5, 6.6, 7.5 and 10.3', 'architecture/system-architecture.md'),
                ('Technology stack', 'implementation_plan/decisions/technology-stack.md'),
                ('Session plan, sections 2 to 4', 'implementation_plan/delivery/sessions.md')],
         produces='The code folders beside docs/, the agent instruction file at the repository root, any new decision records, and .gitignore entries for build output.',
         done='A new session can find, from the instruction file alone, where code goes and how to build and test it; the documentation site still builds and passes its link check. The Enterprise Architecture Board has approved the decision records.',
         human='The Enterprise Architecture Board approves the decision records ADR-HIS-001 to ADR-HIS-038 and any the session adds'),
    dict(n=2, after=[1],
         title='Local integration environment',
         does='One command brings up the backing services a slice needs: PostgreSQL, Kafka with the schema registry, Keycloak with a test realm, the secrets store in development mode, and the telemetry stack. Synthetic data only. '
              'Several sessions run on one server, each in its own checkout, so the environment is separate for each: its containers, networks and volumes are named after the session '
              '(from the HIS_SESSION and COMPOSE_PROJECT_NAME variables the launcher sets), it publishes no fixed host port, and reset touches only its own. '
              'A light profile with PostgreSQL alone is enough for unit and contract tests against stubs; the full profile is for integrate and gate sessions.',
         reads=[('Technology stack', 'implementation_plan/decisions/technology-stack.md'),
                ('Architecture, section 10', 'architecture/system-architecture.md')],
         produces='Environment definition with a light and a full profile, start and reset commands, a smoke check.',
         done='Start, smoke check and reset run clean from a fresh checkout; two environments under different session names run at the same time on one server, and resetting one leaves the other untouched.'),
    dict(n=3, after=[2],
         title='Service template',
         does='A domain service that does nothing but carries everything every service must: health endpoints, token validation, the call to the policy decision point, audit emission, '
              'the transactional outbox and idempotent inbox, schema migrations, telemetry with correlation identifiers, and the test layout. '
              'The service has its own dependency manifest and lockfile, and its unit and contract tests run on the light profile of the integration environment.',
         reads=[('Architecture, sections 6, 7.3 and 8', 'architecture/system-architecture.md'),
                ('Technology stack', 'implementation_plan/decisions/technology-stack.md')],
         produces='The template service and a generator or copy procedure for new services.',
         done='A service made from the template starts in the integration environment, publishes and consumes one test event idempotently, and its tests pass.'),
    dict(n=4, after=[3],
         title='Contract and event tooling',
         does='Conventions and tooling for API and event contracts: file layout, the event envelope, registration in the schema registry, the compatibility check, stub generation from a contract, and contract tests on both sides. '
              'The shared type library of architecture section 6.6 (qualified identifier, coded value, quantity, money, instant and period, references, provenance, status with reason), aligned with FHIR R4 datatypes, '
              'and the facility identifier and facility denial cases that section 7.5 requires.',
         reads=[('Architecture, sections 6.2, 6.3, 6.6 and 7.5', 'architecture/system-architecture.md'),
                ('Event catalogue', 'implementation_plan/delivery/event-catalogue.md')],
         produces='Contract folder with one worked example, the shared type library, compatibility check, stub generator, contract test harness.',
         done='The example contract passes the check, a breaking change to it fails the check, and a stub generated from it answers a contract test.'),
    dict(n=5, after=[3],
         title='Continuous integration pipeline',
         does='The pipeline every pull request runs: build, tests, static analysis, dependency and image scan, secret scan, the software bill of materials, and the contract compatibility check once it exists. '
              'It is built in GitHub Actions beside the existing documentation workflow, which keeps running (ADR-HIS-038). Each job runs only when the files it covers change. '
              'Keep the logic of each job in a script the workflow calls, so that the pipeline can be moved to the self-managed GitLab before production with little rewriting.',
         reads=[('Architecture, section 10.3', 'architecture/system-architecture.md'),
                ('Technology stack', 'implementation_plan/decisions/technology-stack.md')],
         produces='Pipeline definition and its documentation in the agent instruction file.',
         done='A pull request with a failing test, a planted secret or a vulnerable dependency is stopped; a clean one passes; a documentation-only change still runs the documentation jobs and nothing else.'),
    dict(n=6, after=[1],
         title='Application shell skeleton and design system',
         does='The staff application shell frame, the design tokens and base components of the design system, and the component and accessibility test setup. '
              'An empty workspace for each of the ten domains, laid out so that screen sessions can run side by side: every screen has a folder of its own, named by its screen identifier, '
              'and registers its route and navigation entry with the shell from a file in that folder, so adding a screen changes no file outside its folder. '
              'Record this layout as the next numbered decision record.',
         reads=[('Application shell', 'design/application-shell.md'),
                ('Design system', 'design/DESIGN.md'),
                ('Clinical UX safety rules', 'design/clinical-ux-safety-rules.md'),
                ('Architecture, section 11', 'architecture/system-architecture.md')],
         produces='Shell and design-system packages, the ten domain workspaces with one example screen folder, the decision record of the layout, test setup.',
         done='The example screen loads in the shell; a second screen folder added to the same workspace appears in the shell without a change to any other file; the component and accessibility checks run in the pipeline.'),
    dict(n=7, after=[3, 6],
         title='End-to-end test harness and evidence record',
         does='The runner for slice scenarios against the integration environment, synthetic data builders, tagging of tests with requirement and test identifiers, and the evidence record with the fields PRS section 17.3 requires.',
         reads=[('Stage gates, section 1', 'implementation_plan/delivery/stage-gates.md'),
                ('Vertical slices, section 1', 'implementation_plan/delivery/slices.md')],
         produces='Scenario runner, data builders, evidence record generator.',
         done='A sample scenario through the template service and the example workspace runs and produces a complete evidence record.'),
]

# ------------------------------------------------------------------ safety (proposal 7)
# Every build session whose requirements are cited as a safety control in section 11.1 of a specification gets a
# "Safety" row on its card, derived by build_sessions.py: the safety-critical function, its hazard and the tests
# that verify it. SAFETY_REVIEW adds, for the areas below, a duty for the agent and a review by a person before
# merge. `match` holds module (MOD-), requirement (FR-) or screen (UI-) identifiers; a build session matches
# through its modules or requirements, a screen session through its screens or their modules.
SAFETY_REVIEW = [
    dict(area='Blood bank (SaMD)', match=['MOD-ANC-006'],
         duty='Work under design control (an IEC 62304-style lifecycle): trace each change to its requirement and hazard, record the design review and the verification, '
              'and keep the component separately versioned and releasable (architecture section 13)',
         who='Clinical safety officer and the SaMD design authority approve the design review and verification record'),
    dict(area='Decision support', match=['MOD-CLI-011', 'MOD-EBP-007'],
         duty='Classify each function with the Kepmenkes flowchart before building it; a function computing a patient-specific diagnosis, dose or risk score goes into a separate component (DEC-EBP-020). '
              'Missing or stale inputs give "cannot evaluate reliably", never a normal finding; rules are never disabled automatically; critical alerts are never suppressed',
         who='Clinical safety officer reviews the change and the SaMD classification against the hazard log'),
    dict(area='Closed loops', match=['MOD-CLI-010', 'MOD-ANC-007', 'UI-CLI-014', 'UI-ANC-007'],
         duty='Run the loop as a server-side state machine in the owning domain, with end-to-end idempotency keys and durable timers; a mismatch is a hard stop (architecture section 13)',
         who='Clinical safety officer reviews the change against the hazard log'),
    dict(area='Medication prescribing and verification', match=['MOD-CLI-009', 'MOD-CLI-008'],
         duty='Dose, allergy and interaction checks fail safe: an unavailable check blocks or warns, never passes silently',
         who='Clinical safety officer and a pharmacist review the change against the hazard log'),
    # The areas after Emergency access were added on review, 2026-11-24, from section 11.1 hazards the first six left out.
    dict(area='Identity matching, merge and unmerge', match=['FR-ADM-MPI-003', 'FR-ADM-MPI-005', 'UI-ADM-002'],
         duty='Validate any change to matching rules or thresholds on the adjudicated reference set; merge stays reversible and preserves identifiers and authorship',
         who='Clinical safety officer and HIM governance review the change; threshold changes need governance approval'),
    dict(area='Emergency access', match=['FR-ESS-AUZ-002', 'UI-ESS-004'],
         duty='Emergency access is time-limited, reason-captured, fully audited and always reviewed; it never widens access beyond the patient in context',
         who='Privacy officer and clinical safety officer review the change'),
    dict(area='Patient identification', match=['FR-ADM-MPI-001', 'FR-ADM-REG-003', 'FR-ADM-REG-004', 'UI-ADM-001', 'UI-CLI-019'],
         duty='Every patient-facing screen shows the patient context zone with two identifiers; search is by qualified identifier; unidentified and newborn patients get unique provisional identities and are visibly marked',
         who='Clinical safety officer and registration governance review the change'),
    dict(area='Orders and results', match=['MOD-CLI-006', 'MOD-CLI-007', 'MOD-CLI-012'],
         duty='An order is never lost or silently duplicated between ordering and performing service; calculated doses refuse a missing or stale weight or renal function; a corrected or critical result stays flagged until it is reviewed',
         who='Clinical safety officer reviews the change against the hazard log'),
    dict(area='Pathway execution', match=['MOD-EBP-008', 'MOD-EBP-009', 'MOD-EBP-010'],
         duty="A pathway is activated only by a clinician's decision; it proposes, and the owning domain orders through its own safety checks and signature; orders created from a pathway are surfaced when the pathway stops (architecture section 13)",
         who='Clinical safety officer reviews the change against the hazard log'),
    dict(area='Medical device data', match=['MOD-ANC-013'],
         duty='A device reading is attributed to a patient only through a verified device-to-patient association, carries the time from a validated source, and is charted into the clinical record only after validation',
         who='Clinical safety officer and clinical engineering review the change'),
    dict(area='Governed AI', match=['MOD-ANL-009'],
         duty='AI never acts on its own: AI content is marked, enters the record only when a person accepts it, retrieves only what the user may see for the patient in context, and every core workflow runs when AI is unavailable (architecture section 13)',
         who='Clinical safety officer and AI governance review the change'),
    dict(area='Medication supply', match=['MOD-FIN-008'],
         duty='Expired or quarantined stock is blocked from issue; every lot can be traced to its recipients; controlled-substance movements reconcile to the count',
         who='Pharmacist and clinical safety officer review the change'),
]

# ------------------------------------------------------------------ non-functional requirements (proposal 8)
# Section 10 of each specification, by category (matched on the start of the category name, lower case).
# BUILD:      designed into every build session of the domain
# RUNTIME:    checked by the integrate session of each slice of the domain, in the integration environment, under load or failure
# READINESS:  evidenced by the readiness session (Tier 1 slices) or else the gate evidence session
# SCREEN:     designed into every screen session of the domain
# A category in none of the lists makes build_sessions.py fail, so a new category is placed deliberately.
NFR_CLASS = dict(
    BUILD=['security', 'interoperability', 'observability', 'localization', 'time integrity', 'ai safety'],
    RUNTIME=['performance', 'event latency', 'timeliness', 'reliability', 'scalability', 'capacity', 'isolation', 'workload isolation',
             'analytics isolation', 'degraded', 'offline', 'data durability', 'recoverability'],
    READINESS=['availability', 'maintainability', 'portability', 'data portability', 'upgradeability', 'supportability'],
    SCREEN=['usability', 'accessibility'],
)

# ------------------------------------------------------------------ duties of particular slices
# (slice, session kind) -> what that session must also do. Shown as a "Slice duty" row on the card and added to its
# "Ends when". Kinds as in KINDS: C, B, U, I, R, G.
SLICE_DUTIES = {
    # RC-1 gate decision D1 (#232, plan change of 2026-12-02): TEST-ISE-001 was on no card.
    ('RC-3', 'I'): ('Run the core workflows of every slice so far with no commercial licences and with the internet and the external control planes '
                    'disconnected, and record which work and which do not (TEST-ISE-001, FR-ISE-PLT-001; RC-1 gate decision D1 on #232)',
                    'TEST-ISE-001 has a recorded result for each core workflow of the slices so far'),
    # RC-1 gate decision D4 (#232) and the planning question on #27: no card covered services/_template after FN-S03.
    ('RC-4', 'I'): ('Bring the service template and every unit made from it onto the event backbone\'s publication gate (ADR-HIS-063): the .ingress topic '
                    'suffix, the causation identifier of a root event, the two dead-letter headers and reading the rejection return, as listed in '
                    'the follow-ups of the RC-1-S13 handover; then show for each producer that publication by a non-owner is refused and that an event '
                    'without its identifier or schema version is rejected (FR-ISE-EVT-001 PR-EVT-001-2, FR-ISE-EVT-002 AC-03; RC-1 gate decision D4 on #232, #27)',
                    'every unit made from the template publishes through the gate, and both checks pass for each producer'),
    # The decision on #76 (2026-12-02): UI-ISE-002 names the clinical functions affected before a suspension is confirmed.
    ('OR-4', 'C'): ('Add a suspension impact preview to integration.v1 as a compatible minor version (for example GET /v1/interfaces/{interfaceId}/suspension-impact, '
                    'answering the existing SuspensionImpact schema), with its stub (FR-ISE-INT-002 part 3); and give the affected ordering keys before a bulk '
                    'replay, in integration.v1 and in event-operations.v1 for event replays, as a replay scope preview or the ordering key on each exception '
                    'item, with the read audited like the detail view because keys can be patient identifiers (UI-ISE-001 validation rules; the decisions on #76)',
                    'both additions pass the compatibility check and their stubs run'),
    ('OR-4', 'I'): ('Serve the suspension impact preview in the integration engine and show it in UI-ISE-002\'s "Suspend interface" dialog before the person '
                    'confirms, naming the tier, the consumers and the clinical functions affected; this replaces the interim of RC-3-S20, which named the '
                    'clinical functions only after the suspension (FR-ISE-INT-002 part 3, UI-ISE-002); and serve the ordering keys of a bulk replay beforehand, '
                    'audited, and show them with the item count in UI-ISE-001 before the typed confirmation, replacing RC-3-S20\'s interim that listed them '
                    'only after the request (UI-ISE-001 validation rules; the decisions on #76)',
                    'the suspension dialog names the clinical functions, and the bulk replay dialog the ordering keys, before confirmation, against the built engine'),
    ('RC-3', 'R'): ('Build the first measured capacity model (compute, storage, network, backup, logs, analytics) from the load checks of the integrate sessions so far, '
                    'and publish it as evidence for the RC-3 gate (architecture section 18.1 item 2, NFR-ISE-015)',
                    'the capacity model is published with its measurements'),
    ('RC-5', 'G'): ('Run the four clinical persistence acceptance criteria of architecture section 7.6 (authoring, query performance, versioning, export) and record each as pass or fail; '
                    'the chief architect and CMIO accept the model or invoke the fallback on that evidence',
                    'each section 7.6 criterion has a recorded result'),
    ('OR-7', 'I'): ('Load the device time-series store at 1,600 measurements a second from 400 simulated devices while the core transaction targets hold '
                    '(NFR-ANC-003; architecture section 7.1)',
                    'the device load check has run and its result is recorded against the target'),
    ('OR-5', 'R'): ('Prepare the registration (NIE) file for the blood bank SaMD component and the design-control records it needs; production use waits for the NIE '
                    '(technology stack row 24, architecture section 13)',
                    'the NIE file is ready for submission and its status is recorded'),
}
