Complete engagement workbooks, business reports, continuation and recovery workflows
Browse filesFiles changed (19)
- IMPROVEMENTS.md+10
- README.md+6
- SECURITY.md+6
- SERVICE.md+6
- SOURCE-MANIFEST.json+19-15
- VERIFICATION.md+12
- deploy_hf.py+2-1
- docs/superpowers/plans/2026-11-02-engagement-workflows.mdAdded+17
- docs/superpowers/specs/2026-11-02-engagement-workflows-design.mdAdded+14
- index.html+105-4
- static/app.js+299-8
- static/index.html+105-4
- static/local.js+140-6
- static/style.css+7
- tests/browser_engagement.cjsAdded+110
- tests/browser_storage.cjs+14
- tests/browser_ui.cjs+1
- tests/legacy-snapshot.jsonAdded+172
- tests/test_local.cjs+155
34 unmodified lines3536373839404142434445464734 unmodified linesAlert failures with neither actor nor source are counted as unattributed rather than correlated as one identity. Markdown, print and the remediation queue use the same totals: unresolved validation, confirmed static/runtime, rejected, and confirmed-only non-resolved remediation.
Use Add analyst finding for discoveries outside the heuristic patterns. Entries start unresolved/low confidence and require the usual evidence review. The Remediation tab filters confirmed findings by owner, status and overdue date in UTC. Reports captures up to three frozen structured versions, with JSON/Markdown download and print. SHA-256 detects corruption; it does not authenticate authorship or evidence. Restore verifies snapshot digests before committing any imported records.
## Engagement workflow release — 2026-11-02
1. Printed reports include root cause, input-to-impact path, prerequisites, mitigations, mission guidance, role workbooks and business delivery notes. Current printing reads the latest saved assessment; unsaved delivery text remains in the form and is excluded.2. Current imported confirmations with missing structured evidence or short decision notes become unresolved. Incomplete confirmations inside frozen data reject instead of changing historical content. A fixture captured from the previous release proves valid historical hashes remain compatible.3. Cross-tab ID-only hints and focus checks show a saved-change notice. Refresh is explicit and warns before discarding drafts. Finding/workbook/delivery revision conflicts retain unsaved fields.4. Each selected hat has an editable owner, status, evidence reference, expected/observed results and review decision. Completing an entry requires evidence, observed result and decision.5. Continue engagement atomically creates a fresh linked record while preserving the source history and frozen reports, even at the 200-event limit. Current evidence/tracking/workbooks/delivery copy; old history and snapshots remain in the source.6. Delivery stores an analyst-written executive summary, business impact and prioritized recommendations. Client remediation filters confirmed records across local assessments by client, owner, state and overdue UTC date, with 50 rows per page. Continuations can repeat source findings; inspect lineage before combining counts.7. Workspace status shows counts, approximate serialized bytes and optional browser-origin usage/quota estimates. Unknown metadata is shown as unavailable. Warnings flag approaching record/history/size/report limits. Recovery guide and last backup export initiated time improve operator visibility without claiming a file was saved.24 unmodified lines2526272829303132333435363738394041424318 unmodified lines6263646566676824 unmodified lines- **Code review:** bounded lexical Python-text patterns mask comments/quoted examples and recognize simple subprocess imports/multiline calls to nominate potential eval/exec, shell-enabled invocation and embedded-credential concerns. This is not a Python parser, AST analysis, taint tracking or vulnerability validation. Matches are always unresolved candidates and may be false positives.- **Alert triage:** bounded JSON event batches nominate repeated login failures, privilege changes and malware reports. Timestamps, authenticity, duplicates and actual compromise need analyst validation.- **Exercises:** disclosed keyword routing selects ransomware, supply-chain, identity/phishing, cloud or generic tabletop missions. No model or simulated attack runs.- **Five-hat workbooks:** record owner, progress, evidence references, expected/observed results and a review decision for each assigned perspective. Completion requires evidence, an observed result and a decision; these are analyst attestations.- **Five perspectives:** scoped adversary planning, defense, independent review, attacker-perspective lab modeling and joint detection validation. They are analytical perspectives, not running autonomous agents or user permission roles.- **Evidence:** record structured analyst evidence, remediation ownership and retest notes; filter candidates by verdict/severity and hand off work among assigned perspectives. Confirmation is an analyst attestation, not automated proof.- **Analyst findings:** add a bounded evidence-backed candidate manually; it starts unresolved with low confidence and uses the same human review process. Stale finding saves are rejected so a second tab cannot silently overwrite a newer decision. Unsaved finding, manual-entry and handoff drafts prompt before dismissal.- **Remediation queue:** filter confirmed findings by owner, status and overdue date (UTC). Rejected and unresolved candidates are excluded from open remediation totals.- **Report versions:** capture up to three frozen local reports per assessment, export JSON/Markdown or print a saved version. SHA-256 detects corruption, not authenticated authorship or tamper-proof signing.- **Engagement continuation:** create a linked fresh assessment when history or report limits approach. The source retains its original history and frozen reports; the continuation has fresh record/finding IDs and a new history.- **Business delivery:** save an executive summary, business impact and prioritized recommendations; use the client-wide confirmed remediation view to review owners, states and overdue dates across assessments.- **Client delivery:** organize by client label, export Markdown, and print an executive report with verdict counts and coverage limits. Client labels provide organization within one browser workspace.- **Recovery:** download a versioned workspace or client backup, preview a validated file, and restore additive copies atomically. Existing records are never replaced. Legacy single-assessment JSON exports are accepted after validation.
The workspace shows capacity warnings and optional browser-origin storage estimates. Last backup export initiated means the app requested a download; it does not prove a file was saved. The recovery guide explains export, preview and restore as fresh copies. Cross-tab notices offer an explicit refresh and preserve unsaved drafts; current printing reads saved data again.
Raw source, alerts and scenario prose are not retained. Generated evidence omits raw values. Names, scopes and notes may still contain sensitive information: redaction is best-effort. Use synthetic or approved minimal data for pilots.
## Open and run18 unmodified linesPLAYWRIGHT_MODULE=/absolute/path/to/playwright node tests/browser_storage.cjs# With the local server running:PLAYWRIGHT_MODULE=/absolute/path/to/playwright node tests/browser_ui.cjsPLAYWRIGHT_MODULE=/absolute/path/to/playwright node tests/browser_engagement.cjs```
Browser checks use an existing Playwright installation and its Chromium binary; they add no runtime dependency. Set `PLAYWRIGHT_EXECUTABLE_PATH` if using an existing compatible Chromium executable.30 unmodified lines31323334353637383930 unmodified linesEarlier Python/Flask/Gradio files may remain in the development bundle/repository as reference. They are not executed by the static runtime. Gradio/Pillow dependency advisories and hosted CORS issues were investigated during that abandoned hosting approach; do not mistake those checks for a full JavaScript security audit. See VERIFICATION.md for active coverage and the final hosting state.
No public reporting contact or security certification has been configured. Establish a monitored private contact before external customer trials. Do not publish customer evidence or secrets in issues.
## Engagement workflow extensions
Workbook and business delivery changes require the loaded assessment revision and use the same bounded, allowlisted, redacted local record model. A completed hat workbook is an analyst assertion, not automatic control validation. Continuation atomically checks the source revision and workspace capacity before adding a linked new record, leaving the source unchanged. Source records and their snapshots must be retained or backed up separately; continuation does not duplicate historical snapshots. Parent IDs are provenance links, not access permissions.
Cross-tab notifications carry record IDs only and are refresh hints, never authoritative evidence. Fresh reads and revision checks establish the saved state. Storage estimates describe the browser origin and may be missing or approximate; they are not a reservation or a durability guarantee. Backup export timestamps record initiation only. No cloud backup, authenticated reviewer, tenant boundary or new network request is introduced.27 unmodified lines28293031323334353627 unmodified linesStart with synthetic demos and a small set of scoped pilots. Measure analyst time, candidate validation outcomes, report usefulness, agreed remediation completion and repeat engagement interest. Validate willingness to pay before building subscription billing. Do not promise24/7 monitoring, response SLAs or security certification without staffing and independent evidence.
If shared SaaS demand is established, separately budget identity/SSO, tenant isolation, secure durable storage, backups, audit events, ingress/job isolation, observability and incident handling. The current no-cost project deliberately avoids claiming these capabilities.
## Running an engagement
Use each assigned hat workbook to record an owner, progress, evidence reference, expected outcome, observed result and review decision. Add the analyst-written executive summary, business impact and prioritized recommendations before delivery. Reports include the original evidence chain and mission guidance as well as current decisions. The client-wide remediation view groups confirmed findings across local assessments, including linked continuations; check scope and provenance before counting repeated findings as separate business risks.
Start a continuation before reaching activity, snapshot or size limits. It preserves current evidence and tracking in a linked fresh record; retain the source for historical evidence and frozen reports. Use the recovery guide with synthetic copies before customer work. A displayed export time confirms a download was initiated, not that the operator saved or safely retained the file.1234567234567891011910111213141314151617181617181920212 unmodified lines24252627272829303132{ "README.md": "42d51b8ffbfcabcfec2e7478edcd9f186042c0e4ecd68959591896cbd01ea9b5", "index.html": "b68f4fa4547262a982f62b6642988356506dd3b172ce12548d73a7eb9fcec613", "static/index.html": "6070e314211e6d606c2ef85d51d3997f1e721fb5d7679379b05e93094b51fab1", "static/style.css": "9edb2efef1330a7e95c96bfc75623f5580f43c3388959c093a407a018331619a", "static/app.js": "b2f35f740419d387e03f698ea7af26fc9b8a0146e2c7af0de249c2c95fe8af1d", "static/local.js": "3b7af173868dbd040e9b37777e4a99f8198663fbd087755ecf515a5247ef1f78", "README.md": "2d11e1f94d59984794ace4b43ba03caabe6f789a486f8979a6dfd6a2b1a60af0", "index.html": "3f3ca9c20597739ff5f52486639735e9193de0d0fe54b2fc885c3f3e9e749a29", "static/index.html": "33bf757d22f9c7f18d9e7ff483a2412322f350b7ac3a0023fe7486fa25be102a", "static/style.css": "1c76cbdaf5d7583506050cf67469ca4bf794aad2166128450dcb6dd44fca35ce", "static/app.js": "17611b65180c61a335afd8bf4db57011ec8afcdf9ea0e03626f9c79bb0487f6a", "static/local.js": "a341a64d2a4671bc80e104e52877d9bcad7b0d572839e4c3d614532e8d85f0d3", "static/playbooks.js": "3907230561f4573801651297fde26d835d964783a175363b6434c8a4e312e80c", "tests/test_local.cjs": "551de9a5542cc871b5b718fa2eeca10b403c9d1684202d408e785c31f5f0e2bf", "tests/browser_storage.cjs": "338a8d86dcf7e1b0907314157c4377943c2fed16c7510262b8b0a48cb8ab0a80", "tests/browser_ui.cjs": "9bd1e9b605b266166d66dc3582ef49d015035a31fdb6cef0b09c461ed8045fbc", "tests/test_local.cjs": "5610014c165d662f83706570db6f47a34929cb1c44017a8d809be2038739cabb", "tests/browser_storage.cjs": "fe3ad720d8d8a6137907b790bff5220735c556a7a914d2608f141fef431a3ee2", "tests/browser_ui.cjs": "836b6d5bad9830ec53ba2e521d8a0d1182b7287befbf80ba21d9becd1e33fe4f", "tests/detection-fixtures.cjs": "1d9fed45afab9f37d7d2715a8dcf0c2e1e6c80c57821509df44d07e22b12383b", "SECURITY.md": "a6ef94dd35f203c780189275266a9ae5b230f47fdede649014a330de14549d1f", "SERVICE.md": "d4c6c10a5835daa65f30e00ccce944aa36ad84b93f25916ee4ad6975b581d430", "SECURITY.md": "1fd9a3ef18950c21fd20258288b0dab51f8abea8ea84bf4c0fefd0edac27e684", "SERVICE.md": "7bdd60baeca50ef6b6c0ef72c277f3fbbc6e02a16203f19a171eeb47e79faeca", "PROVENANCE.md": "8ff7cec5424c7ddbb7472b3420d0be5e40db7061f823c671936edf126205f1dc", "VERIFICATION.md": "53b4b8f908e6491165b119d252c83943d467eaa410a42f24d605a7eeb9a79aa7", "IMPROVEMENTS.md": "fcc525ae92ffe52963726a5d19dec71a42120dee0bdb30bcbdde296366b2968e", "deploy_hf.py": "071a76bd17d825dc892fdd6d514294248db324ed93251500bb4e2c74671a3bff", "VERIFICATION.md": "b4948765c0345a89f2c75f7c3a6b72614fff6298f7544358e94b8dcba159d5f3", "IMPROVEMENTS.md": "eb26380eb8cb9bcf6964acd002ab8c1cb3d16de8109c89d832aa9578235eb673", "deploy_hf.py": "5cb49b840d7077b01a3c50f41953d573274475d6f9fc5f4c7c12be5f4b13ae5f", "requirements-deploy.txt": "81672301ff63877bdaf3f00b06ebed759f2d2e04f4372c57024fef78c0ea42bf", "tests/test_deploy.py": "95fcbd4f01ade35dd55f35c589fce3c6043f8c95197ab23d84aea032a0321416", "docs/superpowers/specs/2026-10-31-business-improvements-design.md": "036f59ddfb6733bd46209681e1342f1380625adde151a6bfb859f2526647a069",2 unmodified lines "static/logo-print.svg": "aa5c551d2cb6f8c7131a8b24948fdd31667913e97a2ea08f51795069487ef273", "static/favicon.svg": "eb535ad41f1e22491f0c7613aae75b08724128fbc05789d1606eac54b3f520a7", "docs/superpowers/plans/2026-11-02-analyst-reliability.md": "3bdf439649b81d4d4103e29fcd7b93532c136005a3391daccb013b7c7fd6bc8d", "docs/superpowers/specs/2026-11-02-analyst-reliability-design.md": "060254765a96aabece0b3388585273d05abed1e280ab6abe18633e5d2d9349e6" "docs/superpowers/specs/2026-11-02-analyst-reliability-design.md": "060254765a96aabece0b3388585273d05abed1e280ab6abe18633e5d2d9349e6", "tests/browser_engagement.cjs": "94e2dd518c40797c76e010d70b6f6d66fc26d3180c3efc9a47f8d9269132f36f", "tests/legacy-snapshot.json": "8422678b6caf5268cd8cdbc59cee2a6cf03ab00310e6923133ca24cd63a82c2d", "docs/superpowers/plans/2026-11-02-engagement-workflows.md": "edb546e22a04106ac1aa5fec9b0964983ab5aa6554f6d69c455e5dfae274251b", "docs/superpowers/specs/2026-11-02-engagement-workflows-design.md": "3b78b277df3cf59001cbf7b0a69d515143b057a4914bd53946bfcd565eb1d4dd"}63 unmodified lines64656667686970717273747576777863 unmodified linesA near-limit regression verifies that a valid exported record within four bytes of the 5 MB limit still restores. When adding restore provenance would exceed that limit, the imported history and summary are retained without a new annotation; current IDs are still regenerated and snapshot hashes remain verified.
Final integrated UI workflow passes: concurrent stale-save conflict and explicit reload/reopen, canceled Close/X/Escape draft preservation for review/manual/handoff, structured review, concurrent manual entry selection, confirmed owner/status/overdue queue, frozen JSON download, print totals, backup preview/restore, client reset after deletion, anonymous alerts, 390px overflow and no uncaught page errors. Desktop/mobile screenshots were inspected. Final source checks: 34 Node tests, 15 Chromium storage checks, full Chromium UI workflow, 4 optional publisher tests and both JavaScript syntax checks passed. No runtime dependency, Docker, paid resource or external request was added.
## Engagement workflow release — 2026-11-02
Final engine suite: 42 Node tests pass, including incomplete imported confirmation notes, workbook completeness/CAS/redaction, actual previous-release snapshot hash compatibility, full-history continuation with unchanged source, concurrent continuation capacity, business delivery round-trip and optional metadata failures. All 4 optional publisher tests and JavaScript syntax checks pass. A real historical snapshot fixture was generated from the archived previous release, not recomputed using the new normalizer.
The expanded Chromium IndexedDB suite passes 16 checks. The new continuation check creates a source with 200 history events and 99 total records, races two continuations, and observes exactly one fresh copy at 100 records with the source unchanged. Quota/policy exceptions remain labeled fault injection.
The engagement browser workflow checks full printed evidence and missions, role workbook completion and canceled dismissal, delivery conflict/draft preservation, focus-triggered cross-tab warning, canceled/accepted refresh, fresh printing while an unsaved delivery draft remains intact, continuation, recovery guide, backup export initiation metadata, two-client confirmed-only queue, 50-row pagination/filter reset and 390px overflow. Blocked BroadcastChannel startup and unknown storage metadata are fault-injection checks. Desktop/mobile screenshots are inspected. Original UI regressions are also run; its print assertion now waits for the intentional asynchronous fresh saved-record read.
Source review covered optional-field import allowlists, canonical old snapshot preservation, assessment CAS, atomic continuation read/count/add, safe text rendering, no new external asset/network/runtime dependency, optional diagnostic failure handling and client-label limitations. No exploitable vulnerability was confirmed in this bounded local synthetic scope. Other browser engines, real disk exhaustion/eviction, a full accessibility audit and real customer workflows remain unverified. Graphify/upstream scanner runtimes did not run; direct source and regression evidence were used for this known small tree.
Final integrated result: 42 engine tests, 16 Chromium storage checks, original browser UI workflow, new engagement browser workflow (including optional-channel and unknown-metadata fault injection), 4 publisher tests and syntax/HTML checks all pass. Original print tests now await fresh-read completion; the optional metadata test waits for the asynchronously rebuilt status panel. No application failure remained in the final reruns. Clean desktop/mobile screenshots were inspected before publication.7 unmodified lines89101111121314157 unmodified lines 'README.md','index.html','static/index.html','static/style.css','static/app.js', 'static/local.js','static/playbooks.js','static/logo.svg','static/logo-print.svg', 'static/favicon.svg','tests/test_local.cjs', 'tests/browser_storage.cjs','tests/browser_ui.cjs','tests/detection-fixtures.cjs', 'tests/browser_storage.cjs','tests/browser_ui.cjs','tests/browser_engagement.cjs', 'tests/legacy-snapshot.json','tests/detection-fixtures.cjs', 'SECURITY.md','SERVICE.md','PROVENANCE.md','VERIFICATION.md','IMPROVEMENTS.md',)
1234567891011121314151617# Engagement workflow design and execution plan
User approved all seven review recommendations, in order, followed by publication. Preserve static vanilla JavaScript, IndexedDB, Interval branding, private Hugging Face hosting, no runtime dependencies, no Docker and no paid services. Commander defaults below make the approved scope concrete.
1. Complete printed reports with every original evidence field and all mission guidance; retain safe text rendering. Verify print has distinct root cause, input path, prerequisites and mitigations.2. Import confirmations require complete structured review and a substantive decision note (20 characters); incomplete current imports downgrade to unresolved. Frozen historical data with incomplete confirmation must reject rather than silently alter the hash. Preserve existing valid historical snapshot hashes exactly.3. Use BroadcastChannel change hints plus focus refresh detection, explicit refresh preserving drafts, and fresh reads before printing current reports. Notifications contain only assessment IDs, not evidence. Never overwrite an unsaved dialog.4. Add a five-hat workbook: one entry per selected role, owner, planned/in-progress/complete status, evidence reference, expected/observed results and review decision. Complete requires evidence, observed result and decision. Assessment revision CAS guards edits; fields are bounded/redacted and backed up/exported/snapshotted.5. Add continuation: atomically check source revision and record capacity, create a fresh linked assessment with new finding IDs/revisions, preserved current evidence/tracking/business fields, no old snapshots/history, and a provenance entry. Source stays unchanged even at 200 events. Historical snapshots remain in the source. Parent ID/revision are provenance, not access control.6. Add bounded analyst-written executive summary, business impact and prioritized recommendations; CAS guarded and present in Markdown/print/snapshots. Add client-filtered cross-assessment confirmed remediation view with owner/status/overdue filters and assessment links. Client labels remain organizational.7. Show assessment count, approximate serialized record bytes, optional origin usage/quota estimate, event/snapshot/size warnings, last backup export initiated time (never claim file saved), and a recovery guide. Metadata failures are nonfatal.
Shared engine schema: optional `workbook` array of {role,owner,status,evidence,expected,observed,decision}; `delivery` {executive_summary,business_impact,recommendations}; `continuation` {parent_id,parent_revision}. For old snapshot canonical validation, omit missing new fields so hashes remain compatible. Normalize live records with safe defaults. APIs: PATCH /api/assessments/:id/workbook body {expected_revision,entry}; PATCH /api/assessments/:id/delivery body {expected_revision,delivery}; POST /api/assessments/:id/continue body {expected_revision}. Returns {assessment}. workspaceStatus() returns counts and approximate bytes, optional usage/quota (unavailable as null).
Ownership: backend owns local.js/test_local.cjs; frontend owns app.js/style.css/both HTML entries; commander owns browser tests, docs, packaging, verification and publication. Backend adds test-first stages 2,4,5,6,7, frontend implements stages 1,3,4,5,6,7 in interface order; no recursive agents.
Acceptance: fresh full Node/publisher/browser suites; legacy snapshots retain hashes; malformed imports and stale CAS leave records unchanged; continuation works at history cap and races cannot exceed capacity; complete workbook fields and reports round-trip; cross-tab warning preserves drafts, fresh print reads; recovery failures never block saved records; keyboard/narrow/wide screenshots. Review source, refresh allowlist manifest and ZIP, upload verified source only, verify private/Running/new revision and hosted synthetic workflow.1234567891011121314# Engagement workflow design and execution plan
User approved all seven review recommendations, in order, followed by publication. Preserve static vanilla JavaScript, IndexedDB, Interval branding, private Hugging Face hosting, no runtime dependencies, no Docker and no paid services. Commander defaults below make the approved scope concrete.
1. Complete printed reports with every original evidence field and all mission guidance; retain safe text rendering. Verify print has distinct root cause, input path, prerequisites and mitigations.2. Import confirmations require complete structured review and a substantive decision note (20 characters); incomplete current imports downgrade to unresolved. Frozen historical data with incomplete confirmation must reject rather than silently alter the hash. Preserve existing valid historical snapshot hashes exactly.3. Use BroadcastChannel change hints plus focus refresh detection, explicit refresh preserving drafts, and fresh reads before printing current reports. Notifications contain only assessment IDs, not evidence. Never overwrite an unsaved dialog.4. Add a five-hat workbook: one entry per selected role, owner, planned/in-progress/complete status, evidence reference, expected/observed results and review decision. Complete requires evidence, observed result and decision. Assessment revision CAS guards edits; fields are bounded/redacted and backed up/exported/snapshotted.5. Add continuation: atomically check source revision and record capacity, create a fresh linked assessment with new finding IDs/revisions, preserved current evidence/tracking/business fields, no old snapshots/history, and a provenance entry. Source stays unchanged even at 200 events. Historical snapshots remain in the source. Parent ID/revision are provenance, not access control.6. Add bounded analyst-written executive summary, business impact and prioritized recommendations; CAS guarded and present in Markdown/print/snapshots. Add client-filtered cross-assessment confirmed remediation view with owner/status/overdue filters and assessment links. Client labels remain organizational.7. Show assessment count, approximate serialized record bytes, optional origin usage/quota estimate, event/snapshot/size warnings, last backup export initiated time (never claim file saved), and a recovery guide. Metadata failures are nonfatal.
Shared engine schema: optional `workbook` array of {role,owner,status,evidence,expected,observed,decision}; `delivery` {executive_summary,business_impact,recommendations}; `continuation` {parent_id,parent_revision}. For old snapshot canonical validation, omit missing new fields so hashes remain compatible. Normalize live records with safe defaults. APIs: PATCH /api/assessments/:id/workbook body {expected_revision,entry}; PATCH /api/assessments/:id/delivery body {expected_revision,delivery}; POST /api/assessments/:id/continue body {expected_revision}. Returns {assessment}. workspaceStatus() returns counts and approximate bytes, optional usage/quota (unavailable as null).
9 unmodified lines10111213141314151616171818192021478 unmodified lines5005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046059 unmodified lines Napolean · Cyber Command </title> <link href="./static/favicon.svg" rel="icon" type="image/svg+xml"/> <link href="./static/style.css?v=20261102-analyst" rel="stylesheet"/> <script defer="" src="./static/playbooks.js?v=20261102-analyst"> <link href="./static/style.css?v=20261102-engagement" rel="stylesheet"/> <script defer="" src="./static/playbooks.js?v=20261102-engagement"> </script> <script defer="" src="./static/local.js?v=20261102-analyst"> <script defer="" src="./static/local.js?v=20261102-engagement"> </script> <script defer="" src="./static/app.js?v=20261102-analyst"> <script defer="" src="./static/app.js?v=20261102-engagement"> </script> </head> <body>478 unmodified lines </div> </form> </dialog> <dialog aria-labelledby="workbook-title" id="workbook-dialog"> <form id="workbook-form"> <div class="dialog-head"> <h2 id="workbook-title"> Role workbook </h2> <button aria-label="Close role workbook" class="close" data-close="" type="button"> × </button> </div> <p class="error-inline" hidden="" role="alert"> </p> <button hidden="" id="reload-workbook" type="button"> Reload latest workbook </button> <p class="fine"> Analyst-maintained work records. Completing a role requires evidence, an observed result, and a decision. No role agent runs automatically. </p> <label for="workbook-role"> Assigned role </label> <input id="workbook-role" readonly=""/> <label for="workbook-owner"> Owner </label> <input id="workbook-owner" maxlength="120"/> <label for="workbook-status"> Status </label> <select id="workbook-status"> <option value="planned"> Planned </option> <option value="in-progress"> In progress </option> <option value="complete"> Complete </option> </select> <div id="workbook-fields"> <label for="workbook-evidence"> Evidence reference </label> <textarea id="workbook-evidence" maxlength="2000" rows="3"></textarea> <label for="workbook-expected"> Expected result </label> <textarea id="workbook-expected" maxlength="2000" rows="3"></textarea> <label for="workbook-observed"> Observed result </label> <textarea id="workbook-observed" maxlength="2000" rows="3"></textarea> <label for="workbook-decision"> Review decision </label> <textarea id="workbook-decision" maxlength="2000" rows="3"></textarea> </div> <div class="dialog-actions"> <button data-close="" type="button"> Cancel </button> <button class="primary" type="submit"> Save role workbook ↗ </button> </div> </form> </dialog> <dialog aria-labelledby="recovery-title" id="recovery-dialog"> <div class="dialog-head"> <h2 id="recovery-title"> Local workspace recovery </h2> <button aria-label="Close recovery guide" class="close" data-close="" type="button"> × </button> </div> <ol> <li> Export a workspace JSON backup before clearing browser data, changing browsers, or moving devices. Choose All clients for a complete backup. </li> <li> Export initiates a browser download. Confirm the file exists in an approved location yourself; this app cannot check that it was saved. </li> <li> In the destination browser, choose Restore backup, inspect clients and record counts, and confirm. Restore adds copies with new IDs and preserves existing records. </li> <li> Snapshot digests are checked before restore writes. A digest detects corruption; it does not authenticate identity or evidence. </li> <li> Keep customer records in approved browser profiles. Client labels organize records but provide no tenant isolation. Removing site data removes local records; this app has no server backup. </li> </ol> <p class="fine"> Approximate record size and optional browser-origin quota estimates are advisory. Browser storage policies vary. Metadata failures do not block assessments. </p> <button data-close="" type="button"> Close guide </button> </dialog> </body></html>35 unmodified lines3637383939404142434445464722 unmodified lines707172737475767744 unmodified lines12212312412512612712812913013113213313413516 unmodified lines15215315414615515615715815916016116216316442 unmodified lines20720820921021121221310 unmodified lines2242252262122272282292302312322332342352362372382391 unmodified line2412422432442452462472482492502512262522532542552562577 unmodified lines2652662672682412692702712726 unmodified lines2792802812822832842853 unmodified lines289290291292293294295296297117 unmodified lines41541641741841942042197 unmodified lines51952052152248952352452552649 unmodified lines57657757854557958058158258345 unmodified lines62963063163263363463543 unmodified lines67968068168268368468568668768812 unmodified lines70170270366470470570670770870971071171271371471571671771871972072137 unmodified lines75976076176276376476576 unmodified lines84284384484584684784824 unmodified lines87387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111635 unmodified lines if (!globalThis.CyberLocal || typeof CyberLocal.request !== 'function') { throw new Error('The local workspace could not start. Reload this page or check that its local scripts are available.'); } return CyberLocal.request(path, options); const result = await CyberLocal.request(path, options); if (options.method && options.method !== 'GET') { const assessmentId = result.assessment?.id || path.split('/')[3]; broadcastChange(assessmentId); } return result;}function formError(form, message) { const inline = form.querySelector('.error-inline');22 unmodified lines } catch (error) { if (error.code === 'CONFLICT' && form.id === 'verdict-form') $('#reload-finding').hidden = false; if (error.code === 'CONFLICT' && form.id === 'workbook-form') $('#reload-workbook').hidden = false; if (error.code === 'CONFLICT' && form.id === 'delivery-form') $('#reload-delivery').hidden = false; if (inline && !form.closest('[hidden]') && (!form.closest('dialog') || form.closest('dialog').open)) { inline.textContent = error.message; inline.hidden = false;44 unmodified lines return box;}function openCreate() { if (!allowDeliveryDiscard()) return; $('#nav-new').classList.add('active'); if (state.client && !$('#client').value.trim()) $('#client').value = state.client; $('#create-dialog').showModal(); $('#assessment-name').focus();}async function loadOverview() { if (!allowDeliveryDiscard()) return; activate(); state.assessment = null; $('#view').replaceChildren(el('p', 'Opening browser storage…', 'muted'));16 unmodified lines view.append(title); const workspaceActions = el('div', undefined, 'detail-actions'); const backupAction = button('↓ Backup all clients JSON', backupWorkspace); append(workspaceActions, backupAction, button('↑ Restore backup', openRestore)); append(workspaceActions, backupAction, button('↑ Restore backup', openRestore), button('Client remediation', openClientRemediation), button('Recovery guide', openRecovery), button('Refresh register', loadOverview)); view.append(workspaceActions); const statusPanel = el('section', 'Loading local storage status (100 assessment limit)…', 'workspace-status fine'); statusPanel.id = 'workspace-status'; statusPanel.setAttribute('aria-live', 'polite'); view.append(statusPanel); renderWorkspaceStatus(statusPanel); if (!state.assessments.length) { const box = empty('Start with a defined scope.', 'Review a Python snippet, triage structured alerts, or prepare a five-perspective security exercise.', button('Create first assessment ↗', openCreate, 'primary')); box.append(el('small', 'No source connections or scans run automatically.'));42 unmodified lines $('#view').replaceChildren(el('p', 'Loading evidence…', 'muted')); try { state.assessment = (await api(`/api/assessments/${encodeURIComponent(id)}`)).assessment; state.externalChange = false; state.tab = 'ledger'; state.ledgerSearch = state.verdict = state.severity = ''; renderAssessment();10 unmodified lines view.replaceChildren(button('← Assessment register', loadOverview, 'text-button back')); append(view, heading(`${workflows[a.workflow] || a.workflow} / ${date(a.created_at)}`, a.name, `${a.client || 'Unassigned'} / ${a.scope}`), strip(a.roles)); const actions = el('div', undefined, 'detail-actions'); append(actions, button('↓ Export JSON', () => download('json')), button('↓ Export Markdown', () => download('markdown')), button('Print executive report', () => printReport()), button('Add analyst finding', openManual), button('Record handoff', openHandoff), button('Delete assessment', () => $('#delete-dialog').showModal(), 'text-button')); append(actions, button('↓ Export JSON', () => download('json')), button('↓ Export Markdown', () => download('markdown')), button('Print executive report', printCurrentReport), button('Add analyst finding', openManual), button('Refresh saved assessment', refreshAssessment, 'refresh-assessment'), button('Continue engagement', continueEngagement, 'continue-engagement'), button('Record handoff', openHandoff), button('Delete assessment', () => $('#delete-dialog').showModal(), 'text-button')); view.append(actions); $('.refresh-assessment', actions).id = 'refresh-assessment'; $('.continue-engagement', actions).id = 'continue-engagement'; const changeHint = el('p', '', 'change-hint fine'); changeHint.id = 'change-hint'; changeHint.setAttribute('role', 'status'); changeHint.hidden = !state.externalChange; changeHint.textContent = 'Saved workspace data changed in another tab. Use Refresh saved assessment to load it. Unsaved dialog inputs are preserved until you choose to discard.'; view.append(changeHint); const stats = el('div', undefined, 'stats'); [['Candidates', a.findings.length], ['Awaiting decision', a.findings.filter(f => f.verdict === 'unresolved').length], ['Perspectives assigned', a.roles.length]].forEach(([label, value]) => { const cell = el('div', undefined, 'stat');1 unmodified line stats.append(cell); }); append(view, stats, el('p', a.summary, 'muted')); const recordBytes = new TextEncoder().encode(JSON.stringify(a)).length; view.append(el('p', `Record limits: ${(a.activity || []).length} / 200 events · ${(a.snapshots || []).length} / 3 report snapshots · approximately ${recordBytes.toLocaleString()} serialized bytes. Continue the engagement to start fresh event/report capacity; export backups before retention changes.`, 'fine')); if ((a.activity || []).length >= 180 || (a.snapshots || []).length >= 3 || recordBytes >= 4 * 1024 * 1024) view.append(el('p', 'This engagement is nearing an event, frozen-report, or backup-size limit. Export a backup and continue the engagement for fresh history/report capacity.', 'fine')); const tabs = el('div', undefined, 'tabs'); tabs.setAttribute('role', 'tablist'); const panel = el('section'); panel.id = 'assessment-panel'; panel.setAttribute('role', 'tabpanel'); [['ledger', 'Evidence ledger'], ['queue', 'Remediation'], ['reports', 'Reports'], ['missions', 'Missions'], ['coverage', 'Coverage & activity']].forEach(([key, label]) => { [['ledger', 'Evidence ledger'], ['queue', 'Remediation'], ['reports', 'Reports'], ['delivery', 'Delivery'], ['missions', 'Missions'], ['coverage', 'Coverage & activity']].forEach(([key, label]) => { const node = button(label, () => { if (!allowDeliveryDiscard()) return; state.tab = key; renderAssessment(); }, `tab${state.tab === key ? ' active' : ''}`);7 unmodified lines tabs.addEventListener('keydown', event => { if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return; event.preventDefault(); if (!allowDeliveryDiscard()) return; const keys = ['ledger', 'queue', 'reports', 'missions', 'coverage']; const keys = ['ledger', 'queue', 'reports', 'delivery', 'missions', 'coverage']; const index = keys.indexOf(state.tab); state.tab = keys[event.key === 'Home' ? 0 : event.key === 'End' ? keys.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : keys.length - 1)) % keys.length]; renderAssessment();6 unmodified lines if (state.tab === 'ledger') renderLedger(panel, a); if (state.tab === 'queue') renderQueue(panel, a); if (state.tab === 'reports') renderReports(panel, a); if (state.tab === 'delivery') renderDelivery(panel, a); if (state.tab === 'missions') a.missions.forEach(m => { const article = el('article', undefined, 'mission'); const head = el('div', undefined, 'mission-header');3 unmodified lines m.steps.forEach(s => steps.append(el('li', s))); append(article, steps, el('p', `Deliverable: ${m.deliverable}`)); m.limitations.forEach(l => article.append(el('p', `Limit: ${l}`, 'fine'))); const entry = (a.workbook || []).find(item => item.role === m.role) || workbookDefault(m.role); article.append(el('p', `Workbook: ${entry.status} / Owner: ${entry.owner || 'Unassigned'}`, 'fine')); article.append(button(`Edit ${m.role} workbook`, () => openWorkbook(entry))); panel.append(article); }); if (state.tab === 'coverage') {117 unmodified lines if (dialog.id === 'finding-dialog' && !allowFindingDiscard()) return; if (dialog.id === 'manual-dialog' && !allowManualDiscard()) return; if (dialog.id === 'handoff-dialog' && !allowHandoffDiscard()) return; if (dialog.id === 'workbook-dialog' && !allowWorkbookDiscard()) return; dialog.close();}));$('#finding-dialog').addEventListener('cancel', event => {97 unmodified lines const noteChanged = $('#finding-dialog').open && state.finding && reviewSnapshot() !== state.originalReview; const handoffDraft = $('#handoff-dialog').open && $('#handoff-note').value.trim(); const manualDraft = $('#manual-dialog').open && manualSnapshot() !== state.manualOriginal; const workbookDraft = $('#workbook-dialog').open && workbookSnapshot() !== state.workbookOriginal; if (draft || noteChanged || handoffDraft || manualDraft) { if (draft || noteChanged || handoffDraft || manualDraft || workbookDraft || deliveryDirty()) { event.preventDefault(); event.returnValue = ''; }49 unmodified lines try { const text = await CyberLocal.backupText(state.client || undefined); saveText(text, `napolean-backup-${new Date().toISOString().slice(0, 10)}.json`); notify(`Backup exported for ${state.client || 'all clients'}. Restore it with “Restore backup”.`); recordBackupInitiated(); notify(`Backup export initiated for ${state.client || 'all clients'}. This app cannot confirm that the file was saved.`); } catch (error) { notify(error.message, true); }}function openRestore() {45 unmodified lines $('#restore-file').value = '';});function openHandoff() { if (!allowDeliveryDiscard()) return; if (state.assessment.roles.length < 2) { notify('A role handoff requires at least two assigned perspectives.'); return; } $('#handoff-form').reset(); $('#handoff-form .error-inline').hidden = true;43 unmodified lines report.replaceChildren(reportLogo, el('p', 'CLIENT ASSESSMENT', 'eyebrow'), el('h1', a.name)); append(report, el('p', `Client: ${a.client || 'Unassigned'} · Scope: ${a.scope}`), el('p', `Assessment: ${a.id} · Created: ${date(a.created_at)} · Report: ${date(new Date().toISOString())}`)); const totals = CyberLocal.summarize(a); if (a.delivery) { report.append(el('h2', 'Analyst delivery summary')); for (const [key, title] of Object.entries(deliveryLabels)) report.append(el('h3', title), el('p', a.delivery[key] || 'Not supplied.')); } const counts = `Unresolved validation: ${totals.unresolved} / Confirmed static: ${totals.confirmed_static} / Confirmed runtime: ${totals.confirmed_runtime} / Rejected: ${totals.rejected} / Open remediation: ${totals.open_remediation}`; if (snapshot) report.append(el('p', `Frozen report v${snapshot.version} · ${snapshot.created_at} · Source revision ${snapshot.source_revision} · SHA-256 ${snapshot.sha256}. Digest detects corruption; it does not authenticate identity or evidence.`)); append(report, el('h2', 'Executive summary'), el('p', counts), el('p', 'Verdicts and reviewer labels are analyst attestations. They are not independently verified evidence, verified identities, or a security certification. Pattern checks do not execute source or prove exploitability. Remediation status is analyst-maintained.'));12 unmodified lines if (f.verdict.startsWith('confirmed-') && !completeReview) { section.append(el('p', 'Legacy attestation: structured evidence is incomplete; this verdict requires renewed review.')); } for (const [label, value] of [['Location', f.location], ['Evidence', f.evidence], ['Remediation', f.remediation], ['Analyst note', f.review_note], ...Object.entries(f.review || {}).map(([key, value]) => [`Review ${key}`, value]), ...Object.entries(f.tracking || {}).map(([key, value]) => [`Tracking ${key}`, value])]) { for (const [label, value] of [['Location', f.location], ['Root cause', f.root_cause], ['Input-to-impact path', f.input_to_impact], ['Prerequisites', f.prerequisites], ['Mitigations inspected', f.mitigations], ['Evidence', f.evidence], ['Remediation', f.remediation], ['Analyst note', f.review_note], ...Object.entries(f.review || {}).map(([key, value]) => [`Review ${key}`, value]), ...Object.entries(f.tracking || {}).map(([key, value]) => [`Tracking ${key}`, value])]) { section.append(el('p', `${label}: ${displayValue(value)}`)); } report.append(section); }); }); report.append(el('h2', 'Mission guidance and role workbook')); (a.missions || []).forEach(mission => { report.append(el('h3', `${mission.role} / ${mission.title}`), el('p', mission.objective)); mission.steps.forEach((step, index) => report.append(el('p', `${index + 1}. ${step}`))); report.append(el('p', `Deliverable: ${mission.deliverable}`)); mission.limitations.forEach(limit => report.append(el('p', `Limitation: ${limit}`))); const entry = (a.workbook || []).find(item => item.role === mission.role); if (entry) Object.entries(entry).forEach(([key, value]) => report.append(el('p', `Workbook ${key}: ${value || 'Not supplied.'}`))); }); report.append(el('h2', 'Coverage and limitations')); a.coverage.forEach(item => report.append(el('p', displayValue(item)))); report.append(el('h2', 'Activity and handoffs'));37 unmodified lines return !$('#handoff-note').value.trim() || window.confirm('Discard the unsaved role handoff note?');}function openManual() { if (!allowDeliveryDiscard()) return; $('#manual-form').reset(); state.manualOriginal = manualSnapshot(); $('#manual-form .error-inline').hidden = true;76 unmodified lines panel.append(error); const create = button('Create frozen report', () => busy(panel, async () => { const result = await CyberLocal.createSnapshot(assessment.id, assessment.revision || 0); broadcastChange(assessment.id); state.assessment = result.assessment; renderAssessment(); $('#tab-reports').focus();24 unmodified lines panel.append(article); });}
const deliveryLabels = { executive_summary: 'Executive summary', business_impact: 'Business impact', recommendations: 'Prioritized recommendations'};const workbookKeys = ['owner', 'status', 'evidence', 'expected', 'observed', 'decision'];let channel = null;try { if (typeof BroadcastChannel === 'function') channel = new BroadcastChannel('interval-assessment-changes'); } catch (_) { /* Optional hints may be blocked by browser policy. Focus detection remains available. */ }function broadcastChange(assessmentId) { if (typeof assessmentId === 'string' && /^[a-f0-9]{32}$/.test(assessmentId)) { try { channel?.postMessage({ assessmentId }); } catch (_) { /* Change hints are optional. */ } }}function showChangeHint() { state.externalChange = true; const hint = $('#change-hint'); if (hint) hint.hidden = false; else notify('Saved workspace data changed. Refresh the register to load current records.');}if (channel) channel.onmessage = event => { const value = event.data; if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== 1 || !/^[a-f0-9]{32}$/.test(value.assessmentId)) return; if (!state.assessment || state.assessment.id === value.assessmentId) showChangeHint();};window.addEventListener('focus', async () => { try { if (state.assessment) { const latest = (await CyberLocal.request(`/api/assessments/${state.assessment.id}`)).assessment; if ((latest.revision || 0) !== (state.assessment.revision || 0)) showChangeHint(); } else { const latest = (await CyberLocal.request('/api/assessments')).assessments; if (JSON.stringify(latest) !== JSON.stringify(state.assessments)) showChangeHint(); } } catch (_) { /* A later explicit read surfaces unavailable/deleted records. */ }});async function printCurrentReport() { try { const latest = (await api(`/api/assessments/${state.assessment.id}`)).assessment; if (deliveryDirty()) notify('Printing the latest saved assessment. Unsaved delivery text stays in your form and is excluded.'); printReport(latest); } catch (error) { notify(error.message, true); }}function workbookDefault(role) { return { role, owner: '', status: 'planned', evidence: '', expected: '', observed: '', decision: '' }; }function workbookSnapshot() { return JSON.stringify({ role: $('#workbook-role').value, ...Object.fromEntries(workbookKeys.map(key => [key, $(`#workbook-${key}`).value])) });}function allowWorkbookDiscard() { return workbookSnapshot() === state.workbookOriginal || window.confirm('Discard unsaved role workbook changes?');}function openWorkbook(entry) { $('#workbook-form .error-inline').hidden = true; $('#reload-workbook').hidden = true; $('#workbook-role').value = entry.role; workbookKeys.forEach(key => { $(`#workbook-${key}`).value = entry[key] || (key === 'status' ? 'planned' : ''); }); state.workbookRevision = state.assessment.revision || 0; state.workbookOriginal = workbookSnapshot(); updateWorkbookRequired(); if (!$('#workbook-dialog').open) $('#workbook-dialog').showModal(); $('#workbook-owner').focus();}function updateWorkbookRequired() { const complete = $('#workbook-status').value === 'complete'; ['evidence', 'observed', 'decision'].forEach(key => { $(`#workbook-${key}`).required = complete; });}$('#workbook-status').addEventListener('change', updateWorkbookRequired);$('#workbook-dialog').addEventListener('cancel', event => { if (!allowWorkbookDiscard()) event.preventDefault(); });$('#workbook-form').addEventListener('submit', event => { event.preventDefault(); busy(event.currentTarget, async () => { const entry = JSON.parse(workbookSnapshot()); state.assessment = (await api(`/api/assessments/${state.assessment.id}/workbook`, { method: 'PATCH', body: JSON.stringify({ expected_revision: state.workbookRevision, entry }) })).assessment; $('#workbook-dialog').close(); state.tab = 'missions'; renderAssessment(); $('#tab-missions').focus(); notify('Role workbook saved.'); });});$('#reload-workbook').addEventListener('click', async () => { if (!window.confirm('Reload the saved workbook and discard your unsaved workbook changes?')) return; const role = $('#workbook-role').value; let reloaded = false; await busy($('#workbook-form'), async () => { state.assessment = (await api(`/api/assessments/${state.assessment.id}`)).assessment; renderAssessment(); openWorkbook((state.assessment.workbook || []).find(entry => entry.role === role) || workbookDefault(role)); reloaded = true; }); if (reloaded) $('#workbook-owner').focus();});function deliverySnapshot() { const form = $('#delivery-form'); return form ? JSON.stringify(Object.fromEntries(Object.keys(deliveryLabels).map(key => [key, $(`#delivery-${key}`).value]))) : null;}function deliveryDirty() { return $('#delivery-form') && deliverySnapshot() !== state.deliveryOriginal; }function allowDeliveryDiscard() { return !deliveryDirty() || window.confirm('Discard unsaved delivery summary changes?'); }function renderDelivery(panel, assessment) { append(panel, heading('ANALYST WRITTEN / SAVED WITH ASSESSMENT', 'Client delivery', 'Summarize business implications and priorities. This text is an analyst statement, not an automated conclusion.')); const form = el('form'); form.id = 'delivery-form'; const error = el('p', '', 'error-inline'); error.hidden = true; error.setAttribute('role', 'alert'); const reload = button('Reload latest delivery', reloadDelivery); reload.id = 'reload-delivery'; reload.hidden = true; append(form, error, reload); Object.entries(deliveryLabels).forEach(([key, title]) => { const label = el('label', title); label.htmlFor = `delivery-${key}`; const input = el('textarea'); input.id = `delivery-${key}`; input.rows = 5; input.maxLength = 4000; input.value = assessment.delivery?.[key] || ''; append(form, label, input); }); const actions = el('div', undefined, 'dialog-actions'); const save = el('button', 'Save delivery summary ↗', 'primary'); save.type = 'submit'; actions.append(save); form.append(actions); panel.append(form); state.deliveryRevision = assessment.revision || 0; state.deliveryOriginal = deliverySnapshot(); form.addEventListener('submit', event => { event.preventDefault(); busy(form, async () => { const delivery = JSON.parse(deliverySnapshot()); state.assessment = (await api(`/api/assessments/${assessment.id}/delivery`, { method: 'PATCH', body: JSON.stringify({ expected_revision: state.deliveryRevision, delivery }) })).assessment; renderAssessment(); $('#delivery-executive_summary').focus(); notify('Delivery summary saved.'); }); });}async function reloadDelivery() { if (!window.confirm('Reload saved delivery text and discard your unsaved summary?')) return; await busy($('#delivery-form'), async () => { state.assessment = (await api(`/api/assessments/${state.assessment.id}`)).assessment; renderAssessment(); $('#delivery-executive_summary').focus(); });}async function refreshAssessment() { if (!allowDeliveryDiscard()) return; if ($('#finding-dialog').open && !allowFindingDiscard()) return; if ($('#workbook-dialog').open && !allowWorkbookDiscard()) return; if ($('#manual-dialog').open && !allowManualDiscard()) return; if ($('#handoff-dialog').open && !allowHandoffDiscard()) return; try { const latest = (await api(`/api/assessments/${state.assessment.id}`)).assessment; ['#finding-dialog', '#workbook-dialog', '#manual-dialog', '#handoff-dialog'].forEach(id => { if ($(id).open) $(id).close(); }); state.assessment = latest; state.externalChange = false; renderAssessment(); $('#refresh-assessment').focus(); notify('Latest saved assessment loaded.'); } catch (error) { notify(error.message, true); }}async function continueEngagement() { if (!allowDeliveryDiscard()) return; try { const result = await api(`/api/assessments/${state.assessment.id}/continue`, { method: 'POST', body: JSON.stringify({ expected_revision: state.assessment.revision || 0 }) }); state.assessment = result.assessment; state.tab = 'ledger'; state.externalChange = false; state.ledgerSearch = state.verdict = state.severity = ''; renderAssessment(); $('#main').focus(); notify('Linked continuation created. Source assessment preserved.'); } catch (error) { notify(error.message, true); }}function openRecovery() { $('#recovery-dialog').showModal(); }let lastBackupInitiated = null;let backupMetadataAvailable = true;try { lastBackupInitiated = localStorage.getItem('interval-backup-initiated-at'); } catch (_) { backupMetadataAvailable = false; }function recordBackupInitiated() { lastBackupInitiated = new Date().toISOString(); try { localStorage.setItem('interval-backup-initiated-at', lastBackupInitiated); backupMetadataAvailable = true; } catch (_) { backupMetadataAvailable = false; } const panel = $('#workspace-status'); if (panel) renderWorkspaceStatus(panel);}async function renderWorkspaceStatus(panel) { try { const status = await CyberLocal.workspaceStatus(); const countKnown = Number.isFinite(status.count); const bytesKnown = Number.isFinite(status.approximate_bytes); panel.replaceChildren(el('p', `Local assessments: ${countKnown ? status.count : 'Unavailable'} / 100 · Approximate serialized records: ${bytesKnown ? status.approximate_bytes.toLocaleString() + ' bytes' : 'Unavailable'}`)); if (!countKnown || !bytesKnown) panel.append(el('p', 'Record-size metadata is unavailable. Refresh the register to retry; assessment reads and saves remain independently available.')); if (Number.isFinite(status.usage) && Number.isFinite(status.quota)) panel.append(el('p', `Browser-origin usage / quota estimate: ${status.usage.toLocaleString()} / ${status.quota.toLocaleString()} bytes. Includes other origin data and is not a storage guarantee.`)); else panel.append(el('p', 'Browser-origin quota estimate is unavailable. Assessments remain usable.')); panel.append(el('p', `Last backup export initiated: ${lastBackupInitiated || (backupMetadataAvailable ? 'Not recorded' : 'Unavailable because browser metadata storage is blocked')}. This does not confirm that a file was saved.${backupMetadataAvailable ? '' : ' Timestamp persistence is unavailable; any timestamp shown is for this visit only.'}`)); if ((countKnown && status.count >= 90) || (bytesKnown && status.approximate_bytes >= 4 * 1024 * 1024)) panel.append(el('p', 'Workspace nearing record or backup-size limits. Export a client-filtered backup and review local retention.')); } catch (error) { panel.textContent = `Storage metadata unavailable: ${error.message}. Assessment reads and saves remain independently available.`; }}async function openClientRemediation() { if (!allowDeliveryDiscard()) return; $('#view').replaceChildren(el('p', 'Loading saved remediation across local assessments…', 'muted')); try { const summaries = (await api('/api/assessments')).assessments; const records = []; for (const summary of summaries) records.push((await api(`/api/assessments/${summary.id}`)).assessment); const view = $('#view'); view.replaceChildren(button('← Assessment register', loadOverview, 'text-button back')); const panel = el('section'); panel.id = 'client-remediation'; append(panel, heading('BROWSER WORKSPACE / CONFIRMED ONLY', 'Client remediation', 'Client labels organize this browser; they do not provide access control or tenant isolation.')); const toolbar = el('div', undefined, 'toolbar'); const clients = selectControl('Filter workspace remediation by client', [['', 'All clients'], ...[...new Set(records.map(a => a.client || 'Unassigned'))].sort().map(value => [value, value])]); clients.value = [...clients.options].some(option => option.value === state.client) ? state.client : ''; const items = records.flatMap(a => a.findings.filter(f => f.verdict.startsWith('confirmed-')).map(f => ({ a, f }))); const owners = selectControl('Filter workspace remediation by owner', [['', 'All owners'], ...[...new Set(items.map(({ f }) => f.tracking?.owner || ''))].sort().map(value => [JSON.stringify(value), value || 'Unassigned owner'])]); const statuses = selectControl('Filter workspace remediation by status', [['', 'All statuses'], ...['open', 'in-progress', 'resolved', 'retest'].map(value => [value, value])]); const lateLabel = el('label', undefined, 'inline-check'); const late = el('input'); late.type = 'checkbox'; late.id = 'workspace-overdue'; append(lateLabel, late, el('span', 'Overdue only (UTC)')); append(toolbar, clients, owners, statuses, lateLabel); panel.append(toolbar); const results = el('div', undefined, 'table-wrap'); panel.append(results); view.append(panel); let queuePage = 0; const pageSize = 50; const pagination = el('nav', undefined, 'detail-actions'); pagination.setAttribute('aria-label', 'Client remediation pages'); const pageInfo = el('span', '', 'fine'); pageInfo.setAttribute('role', 'status'); const previousPage = button('Previous page', () => { queuePage--; draw(); }); const nextPage = button('Next page', () => { queuePage++; draw(); }); append(pagination, previousPage, pageInfo, nextPage); panel.append(pagination); function draw() { const today = new Date().toISOString().slice(0, 10); const matching = items.filter(({ a, f }) => (!clients.value || (a.client || 'Unassigned') === clients.value) && (!owners.value || (f.tracking?.owner || '') === JSON.parse(owners.value)) && (!statuses.value || (f.tracking?.status || 'open') === statuses.value) && (!late.checked || (f.tracking?.due_date && f.tracking.due_date < today && f.tracking.status !== 'resolved'))); const labels = ['Finding / assessment', 'Client', 'Owner', 'Due date (UTC)', 'Status']; const table = el('table'); const head = el('tr'); labels.forEach(label => head.append(el('th', label))); table.append(append(el('thead'), head)); const body = el('tbody'); const pages = Math.max(1, Math.ceil(matching.length / pageSize)); queuePage = Math.max(0, Math.min(queuePage, pages - 1)); const start = queuePage * pageSize; matching.slice(start, start + pageSize).forEach(({ a, f }) => { const row = el('tr'); const identity = el('td'); append(identity, button(f.title, async () => { await openAssessment(a.id); if (!state.assessment || state.assessment.id !== a.id) return; state.tab = 'queue'; renderAssessment(); const target = state.assessment.findings.find(item => item.id === f.id); if (target) openFinding(target); }, 'row-button'), el('span', a.name, 'subline')); append(row, identity, el('td', a.client || 'Unassigned'), el('td', f.tracking?.owner || 'Unassigned'), el('td', f.tracking?.due_date || 'No target date'), el('td', f.tracking?.status || 'open')); labelCells(row, labels); body.append(row); }); table.append(body); results.replaceChildren(el('p', `${matching.length} confirmed remediation records`, 'fine'), table); pageInfo.textContent = matching.length ? `${start + 1}–${Math.min(start + pageSize, matching.length)} of ${matching.length} / Page ${queuePage + 1} of ${pages}` : '0 records / Page 1 of 1'; previousPage.disabled = queuePage === 0; nextPage.disabled = queuePage >= pages - 1; } clients.addEventListener('change', () => { const priorOwner = owners.value; owners.replaceChildren(); const availableOwners = [...new Set(items.filter(({ a }) => !clients.value || (a.client || 'Unassigned') === clients.value).map(({ f }) => f.tracking?.owner || ''))].sort(); [['', 'All owners'], ...availableOwners.map(value => [JSON.stringify(value), value || 'Unassigned owner'])].forEach(([value, text]) => { const option = el('option', text); option.value = value; owners.append(option); }); owners.value = [...owners.options].some(option => option.value === priorOwner) ? priorOwner : ''; queuePage = 0; draw(); }); [owners, statuses, late].forEach(control => control.addEventListener('change', () => { queuePage = 0; draw(); })); draw(); } catch (error) { notify(error.message, true); await loadOverview(); }}loadOverview();9 unmodified lines10111213141314151616171818192021478 unmodified lines5005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046059 unmodified lines Napolean · Cyber Command </title> <link href="./favicon.svg" rel="icon" type="image/svg+xml"/> <link href="./style.css?v=20261102-analyst" rel="stylesheet"/> <script defer="" src="./playbooks.js?v=20261102-analyst"> <link href="./style.css?v=20261102-engagement" rel="stylesheet"/> <script defer="" src="./playbooks.js?v=20261102-engagement"> </script> <script defer="" src="./local.js?v=20261102-analyst"> <script defer="" src="./local.js?v=20261102-engagement"> </script> <script defer="" src="./app.js?v=20261102-analyst"> <script defer="" src="./app.js?v=20261102-engagement"> </script> </head> <body>478 unmodified lines </div> </form> </dialog> <dialog aria-labelledby="workbook-title" id="workbook-dialog"> <form id="workbook-form"> <div class="dialog-head"> <h2 id="workbook-title"> Role workbook </h2> <button aria-label="Close role workbook" class="close" data-close="" type="button"> × </button> </div> <p class="error-inline" hidden="" role="alert"> </p> <button hidden="" id="reload-workbook" type="button"> Reload latest workbook </button> <p class="fine"> Analyst-maintained work records. Completing a role requires evidence, an observed result, and a decision. No role agent runs automatically. </p> <label for="workbook-role"> Assigned role </label> <input id="workbook-role" readonly=""/> <label for="workbook-owner"> Owner </label> <input id="workbook-owner" maxlength="120"/> <label for="workbook-status"> Status </label> <select id="workbook-status"> <option value="planned"> Planned </option> <option value="in-progress"> In progress </option> <option value="complete"> Complete </option> </select> <div id="workbook-fields"> <label for="workbook-evidence"> Evidence reference </label> <textarea id="workbook-evidence" maxlength="2000" rows="3"></textarea> <label for="workbook-expected"> Expected result </label> <textarea id="workbook-expected" maxlength="2000" rows="3"></textarea> <label for="workbook-observed"> Observed result </label> <textarea id="workbook-observed" maxlength="2000" rows="3"></textarea> <label for="workbook-decision"> Review decision </label> <textarea id="workbook-decision" maxlength="2000" rows="3"></textarea> </div> <div class="dialog-actions"> <button data-close="" type="button"> Cancel </button> <button class="primary" type="submit"> Save role workbook ↗ </button> </div> </form> </dialog> <dialog aria-labelledby="recovery-title" id="recovery-dialog"> <div class="dialog-head"> <h2 id="recovery-title"> Local workspace recovery </h2> <button aria-label="Close recovery guide" class="close" data-close="" type="button"> × </button> </div> <ol> <li> Export a workspace JSON backup before clearing browser data, changing browsers, or moving devices. Choose All clients for a complete backup. </li> <li> Export initiates a browser download. Confirm the file exists in an approved location yourself; this app cannot check that it was saved. </li> <li> In the destination browser, choose Restore backup, inspect clients and record counts, and confirm. Restore adds copies with new IDs and preserves existing records. </li> <li> Snapshot digests are checked before restore writes. A digest detects corruption; it does not authenticate identity or evidence. </li> <li> Keep customer records in approved browser profiles. Client labels organize records but provide no tenant isolation. Removing site data removes local records; this app has no server backup. </li> </ol> <p class="fine"> Approximate record size and optional browser-origin quota estimates are advisory. Browser storage policies vary. Metadata failures do not block assessments. </p> <button data-close="" type="button"> Close guide </button> </dialog> </body></html>26 unmodified lines272829303031323341 unmodified lines75767778798081828384858687888990919293949596979899100101102103104105106107108109110178 unmodified lines28929029126229229329429520 unmodified lines3163173183193203213223233243253263273287 unmodified lines33633733833934034134234334434534634734834935035127 unmodified lines3793803813353823833843859 unmodified lines39539639735135239839940040140217 unmodified lines42042142242342442542642742842943043189 unmodified lines52152252352452552652752852953053153253353453553653753853954054154250 unmodified lines593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643111 unmodified lines7557567577587597607617627637647657667677687697707717727737747757767777787791 unmodified line78178278365178478578626 unmodified lines const error=new Error(message);error.code='CONFLICT';return error; } function normalizeRecord(record) { return {...record,client:record.client||'Unassigned',revision:revision(record.revision),snapshots:record.snapshots||[], return {...record,client:record.client||'Unassigned',revision:revision(record.revision),snapshots:record.snapshots||[],workbook:workbookData(record.workbook,record.roles),delivery:deliveryData(record.delivery), findings:record.findings.map(item=>({...item,revision:revision(item.revision),origin:item.origin||'heuristic',review:reviewData(item.review),tracking:trackingData(item.tracking)}))}; } function id() {41 unmodified lines due_date:dueDate(value.due_date ?? previous.due_date ?? ''),status, retest:clean(value.retest ?? previous.retest ?? '', 'Retest note',2000)}; } function workbookEntry(value,roles) { checkedObject(value,['role','owner','status','evidence','expected','observed','decision'],'Workbook entry'); if(!roles.includes(value.role)) throw new Error('Workbook role must be selected for this assessment.'); const status=value.status===undefined?'planned':value.status; if(!['planned','in-progress','complete'].includes(status)) throw new Error('Unsupported workbook status.'); const entry={role:value.role,owner:clean(value.owner===undefined?'':value.owner,'Workbook owner',120),status}; for(const field of ['evidence','expected','observed','decision']) entry[field]=clean(value[field]===undefined?'':value[field],`Workbook ${field}`,2000); if(status==='complete'&&['evidence','observed','decision'].some(field=>!entry[field])) throw new Error('A complete workbook entry requires evidence, an observed result and a review decision.'); return entry; } function workbookData(value,roles) { if(value===undefined) return roles.map(role=>workbookEntry({role},roles)); const entries=list(value,'Workbook',5,1).map(entry=>workbookEntry(entry,roles)); if(entries.length!==roles.length||new Set(entries.map(entry=>entry.role)).size!==roles.length) throw new Error('Workbook must contain exactly one entry per selected role.'); return roles.map(role=>entries.find(entry=>entry.role===role)); } function expectedAssessmentRevision(value) { if(!Number.isSafeInteger(value)||value<0) throw conflict('An exact assessment revision is required. Reload the latest assessment before saving.'); return value; } function continuationData(value) { checkedObject(value,['parent_id','parent_revision'],'Continuation provenance'); if(!Object.hasOwn(value,'parent_revision')) throw new Error('Continuation parent revision is required.'); return {parent_id:recordId(value.parent_id),parent_revision:revision(value.parent_revision)}; } function deliveryData(value={}) { const fields=['executive_summary','business_impact','recommendations']; checkedObject(value,fields,'Analyst delivery'); return Object.fromEntries(fields.map(field=>[field,clean(value[field]===undefined?'':value[field],`Delivery ${field}`,4000)])); } function redact(value) { return String(value) .replace(/(\b[\w.-]*(?:secret|password|passwd|token|api_?key|access_?key|private_?key)[\w.-]*\s*[=:]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;\r\n]+)/gi, '$1[REDACTED]')178 unmodified lines limitations:['Planning guidance only; requires a qualified analyst and separate approval for live actions.', 'No executable agents, scanners, model inference or upstream security tools are running.']}; }); return {id:id(),name:clean(name,'Name',120,1),client:clientLabel(payload.client),workflow,scope:clean(scope,'Scope',2000,1),created_at:now(),revision:0,snapshots:[],roles:[...roles],findings,missions, return {id:id(),name:clean(name,'Name',120,1),client:clientLabel(payload.client),workflow,scope:clean(scope,'Scope',2000,1),created_at:now(),revision:0,snapshots:[],workbook:workbookData(undefined,roles),delivery:deliveryData(),roles:[...roles],findings,missions, scenario_category:category,summary:`${findings.length} unresolved candidate(s) from limited browser-local checks. Human validation required; this is not a security certification.`, coverage,activity:[{at:now(),action:'created',note:'Scope authorization attested; bounded local analysis completed. Raw submission discarded.'}]}; }20 unmodified lines `Open remediation items: ${totals.open_remediation}`, 'Confirmations are analyst attestations, not automated proof. Client labels organize this browser; they do not isolate tenants.', '','## Evidence ledger']; if(Object.hasOwn(assessment,'delivery')) { const delivery=deliveryData(assessment.delivery); lines.splice(lines.indexOf('## Evidence ledger'),0,'## Analyst delivery', `Executive summary: ${safe(delivery.executive_summary||'(not supplied)')}`, `Business impact: ${safe(delivery.business_impact||'(not supplied)')}`, `Prioritized recommendations: ${safe(delivery.recommendations||'(not supplied)')}`,''); } for (const item of assessment.findings) { lines.push('',`### ${safe(item.title)}`); for (const key of ['severity','confidence','verdict','location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation','review_note']) lines.push(`${key.replaceAll('_',' ')}: ${safe(item[key])}`);7 unmodified lines lines.push('',`### ${mission.role}: ${safe(mission.title)}`,safe(mission.objective),...mission.steps.map(step=>'- '+safe(step)), 'Deliverable: '+safe(mission.deliverable),...mission.limitations.map(limit=>'Limitation: '+safe(limit))); } if(Object.hasOwn(assessment,'workbook')) { lines.push('','## Role workbook'); for(const entry of workbookData(assessment.workbook,assessment.roles)) { lines.push('',`### ${entry.role}`); for(const field of ['owner','status','evidence','expected','observed','decision']) lines.push(`${field}: ${safe(entry[field]||'(not supplied)')}`); } } if(assessment.continuation) lines.push('','## Continuation provenance', `Parent assessment: ${assessment.continuation.parent_id}`,`Parent revision: ${assessment.continuation.parent_revision}`, 'This is copied provenance, not an access-control or authenticity guarantee.'); lines.push('','## Coverage',...assessment.coverage.map(item=>'- '+safe(item)),'','## Activity', ...assessment.activity.map(item=>`- ${safe(item.at)} ${safe(item.action)}: ${safe(item.note)}`)); return lines.join('\n')+'\n';27 unmodified lines return value; } function validateRecord(value,options={}) { const fields=['id','name','client','workflow','scope','created_at','revision','roles','findings','missions','scenario_category','summary','coverage','activity']; const fields=['id','name','client','workflow','scope','created_at','revision','roles','findings','missions','scenario_category','summary','coverage','activity','workbook','delivery','continuation']; if(options.allowSnapshots!==false) fields.push('snapshots'); checkedObject(value,fields,'Assessment'); if(!['code','alerts','exercise'].includes(value.workflow)) throw new Error('Unsupported workflow in backup.');9 unmodified lines for(const key of ['title','location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation','review_note']) result[key]=clean(item[key],`Finding ${key}`,key==='title'?500:4000,key==='review_note'?0:1); result.review=reviewData(item.review); result.tracking=trackingData(item.tracking); if(result.verdict.startsWith('confirmed-') && !hasReview(result.review)) { if(options.snapshotData) throw new Error('Snapshot confirmations require complete structured evidence. Review legacy attestations before freezing this report.'); if(result.verdict.startsWith('confirmed-') && (!hasReview(result.review)||result.review_note.trim().length<20)) { if(options.snapshotData) throw new Error('Snapshot confirmations require complete structured evidence and a substantive decision note (20+ characters). Review legacy attestations before freezing this report.'); result.verdict='unresolved'; } return result;17 unmodified lines const result={id:recordId(value.id),name:clean(value.name,'Name',120,1),client:clientLabel(value.client),workflow:value.workflow, scope:clean(value.scope,'Scope',2000,1),created_at:isoTime(value.created_at),revision:revision(value.revision),roles,findings,missions,scenario_category:category, summary:clean(value.summary,'Summary',4000,1),coverage:list(value.coverage,'Coverage',20,1).map(row=>clean(row,'Coverage note',4000,1)),activity}; if(Object.hasOwn(value,'workbook')) result.workbook=workbookData(value.workbook,roles); if(Object.hasOwn(value,'delivery')) result.delivery=deliveryData(value.delivery); if(Object.hasOwn(value,'continuation')) { result.continuation=continuationData(value.continuation); if(result.continuation.parent_id===result.id) throw new Error('A continuation cannot be its own parent.'); } if(options.allowSnapshots!==false) { result.snapshots=list(value.snapshots===undefined?[]:value.snapshots,'Snapshots',3).map((snapshot,index)=>{ const checked=validateSnapshot(snapshot);89 unmodified lines }; }); } continueFrom(sourceId,expected,maximum,buildCopy) { return this.transaction('readwrite',(store,done,fail)=>{ const source=store.get(sourceId);source.onsuccess=()=>{ try { if(!source.result){fail(new Error('Assessment not found.'));return;} if(revision(source.result.revision)!==expected){fail(conflict('The source assessment changed. Reload before creating a continuation.'));return;} const count=store.count();count.onsuccess=()=>{ try { if(count.result>=maximum){fail(new Error('Browser workspace limit: 100 assessments. Export and delete records before continuing.'));return;} const copy=buildCopy(source.result);store.add(copy);done(copy); } catch(error){fail(error);} }; } catch(error){fail(error);} }; }); } update(id, mutate) { return this.transaction('readwrite',(store,done,fail)=>{ const req=store.get(id); req.onsuccess=()=>{50 unmodified lines }); return {assessment}; } const workbookMatch=/^\/api\/assessments\/([a-f0-9]{32})\/workbook$/.exec(route); if(workbookMatch&&method==='PATCH') { checkedObject(payload,['expected_revision','entry'],'Workbook update'); const expected=expectedAssessmentRevision(payload.expected_revision); const assessment=await this.store.update(workbookMatch[1],record=>{ record=normalizeRecord(record); if(record.revision!==expected) throw conflict('This assessment changed. Reload before saving its workbook.'); if(record.activity.length>=MAX_ACTIVITY) throw new Error('Assessment limit: 200 activity entries. Create a continuation before updating the workbook.'); const entry=workbookEntry(payload.entry,record.roles); record.workbook=record.workbook.map(current=>current.role===entry.role?entry:current); record.activity.push({at:now(),action:'workbook_updated',note:`${entry.role}: ${entry.status}; owner: ${entry.owner||'(unspecified)'}; evidence: ${entry.evidence||'(not supplied)'}; observed: ${entry.observed||'(not supplied)'}; decision: ${entry.decision||'(not supplied)'}.`}); record.revision=advanceRevision(record.revision);assertRecordSize(record);return record; }); return {assessment}; } const deliveryMatch=/^\/api\/assessments\/([a-f0-9]{32})\/delivery$/.exec(route); if(deliveryMatch&&method==='PATCH') { checkedObject(payload,['expected_revision','delivery'],'Delivery update'); if(!Object.hasOwn(payload,'delivery')) throw new Error('An explicit delivery object is required.'); const expected=expectedAssessmentRevision(payload.expected_revision),delivery=deliveryData(payload.delivery); const assessment=await this.store.update(deliveryMatch[1],record=>{ record=normalizeRecord(record); if(record.revision!==expected) throw conflict('This assessment changed. Reload before saving its delivery notes.'); if(record.activity.length>=MAX_ACTIVITY) throw new Error('Assessment limit: 200 activity entries. Create a continuation before updating delivery notes.'); record.delivery=delivery;record.revision=advanceRevision(record.revision); record.activity.push({at:now(),action:'delivery_updated',note:'Analyst executive summary, business impact and prioritized recommendations updated. Text is analyst-authored, not verified business impact.'}); assertRecordSize(record);return record; }); return {assessment}; } const continueMatch=/^\/api\/assessments\/([a-f0-9]{32})\/continue$/.exec(route); if(continueMatch&&method==='POST') { checkedObject(payload,['expected_revision'],'Continuation request'); const expected=expectedAssessmentRevision(payload.expected_revision); const assessment=await this.store.continueFrom(continueMatch[1],expected,MAX_RECORDS,source=>{ const copy=validateRecord(normalizeRecord(source)); copy.continuation={parent_id:source.id,parent_revision:revision(source.revision)}; copy.id=id();copy.revision=0;copy.created_at=now();copy.snapshots=[]; for(const item of copy.findings){item.id=id();item.revision=0;} copy.activity=[{at:now(),action:'continuation_created',note:`Continued from ${source.id} at revision ${revision(source.revision)}. Current evidence and tracking copied; original history and snapshots remain unchanged in the source. Legacy incomplete confirmations require renewed review.`}]; copy.summary=`Continuation with ${copy.findings.length} candidate(s); ${summarize(copy).unresolved} unresolved. Copied analyst attestations require review; source history and frozen reports were not changed.`; assertRecordSize(copy);return copy; }); return {assessment}; } const match=/^\/api\/assessments\/([a-f0-9]{32})(?:\/findings\/([a-f0-9]{32}))?$/.exec(route); if(!match) throw new Error('Unsupported local workspace route.'); const [,assessmentId,findingId]=match;111 unmodified lines if(format==='json') return JSON.stringify(snapshot,null,2); return `# Frozen report snapshot ${snapshot.version}\n\nCreated: ${snapshot.created_at}\nSource revision: ${snapshot.source_revision}\nSHA-256: ${snapshot.sha256}\nDigest detects corruption, not authentication or authorship.\n\n${markdownExport(snapshot.data)}`; } async workspaceStatus() { const result={count:null,approximate_bytes:null,usage:null,quota:null}; try { const rows=await this.store.list();result.count=rows.length; result.approximate_bytes=rows.reduce((sum,record)=>sum+new TextEncoder().encode(JSON.stringify(record)).length,0); } catch(_) { /* Metadata is optional and never prevents normal record access. */ } let timer; try { if(typeof root.navigator?.storage?.estimate==='function') { const estimate=await Promise.race([ Promise.resolve().then(()=>root.navigator.storage.estimate()), new Promise(resolve=>{timer=root.setTimeout(()=>resolve(null),500);}) ]); for(const key of ['usage','quota']) if(Number.isFinite(estimate?.[key])&&estimate[key]>=0) result[key]=estimate[key]; } } catch(_) { /* Browser privacy settings may deny origin usage estimates. */ } finally {if(timer!==undefined) root.clearTimeout(timer);} return result; } } let singleton; const service=()=>singleton || (singleton=new LocalService(new IndexedDBStore()));1 unmodified line request:(path,options)=>service().request(path,options),exportText:(assessmentId,format)=>service().exportText(assessmentId,format), backupText:client=>service().backupText(client),restoreBackup:input=>service().restoreBackup(input), createSnapshot:(assessmentId,expected_revision)=>service().createSnapshot(assessmentId,expected_revision), exportSnapshot:(assessmentId,snapshotId,format)=>service().exportSnapshot(assessmentId,snapshotId,format)}; exportSnapshot:(assessmentId,snapshotId,format)=>service().exportSnapshot(assessmentId,snapshotId,format), workspaceStatus:()=>service().workspaceStatus()};});890 unmodified lines891892893894895896897898899900890 unmodified lines.inline-check input { width: 17px; height: 17px; min-height: 17px; accent-color: #a0a1a7; }.snapshot-hash { overflow-wrap: anywhere; }#reload-finding { margin-bottom: 14px; }
.workspace-status { padding: 16px 0; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); margin: 18px 0; }.workspace-status p { margin: 4px 0; overflow-wrap: anywhere; }.change-hint { padding: 12px 0; border-bottom: 1px solid var(--accent); }#recovery-dialog li { font-size: 13px; line-height: 1.8; margin-bottom: 14px; color: #c2c2c8; }#delivery-form { max-width: 900px; }#reload-workbook, #reload-delivery { margin-bottom: 16px; }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110'use strict';const assert=require('node:assert/strict');const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright');(async()=>{const browser=await chromium.launch({headless:true,...(process.env.PLAYWRIGHT_EXECUTABLE_PATH?{executablePath:process.env.PLAYWRIGHT_EXECUTABLE_PATH}:{})});try{ const context=await browser.newContext({viewport:{width:1440,height:1000}}),page=await context.newPage(),errors=[]; page.on('pageerror',e=>errors.push(e.message)); const app=process.env.APP_URL||'http://127.0.0.1:7860/';await page.goto(app);await page.waitForFunction(()=>!!window.CyberLocal); const fixture=await page.evaluate(async()=>{ let a=(await CyberLocal.request('/api/assessments',{method:'POST',body:{name:'Engagement acceptance fixture',client:'Synthetic enterprise',scope:'Owned synthetic fixture only',workflow:'code',content:'eval(x)',authorization:true,roles:['red','blue','white','black','purple']}})).assessment; a=(await CyberLocal.request(`/api/assessments/${a.id}/findings`,{method:'POST',body:{title:'Print completeness fixture',severity:'medium',location:'Owned revision',root_cause:'ROOT CAUSE ACCEPTANCE MARKER',input_to_impact:'INPUT PATH ACCEPTANCE MARKER',prerequisites:'PREREQUISITE ACCEPTANCE MARKER',mitigations:'MITIGATION ACCEPTANCE MARKER',evidence:'Synthetic evidence only',remediation:'Validate in owned fixture'}})).assessment; return {id:a.id,first:a.findings[0].id}; }); await page.reload();await page.getByRole('button',{name:'Engagement acceptance fixture',exact:true}).click(); await page.evaluate(()=>{window.print=()=>{}}); await page.getByRole('button',{name:'Print executive report',exact:true}).click(); await page.waitForFunction(()=>document.querySelector('#print-report').textContent.includes('ROOT CAUSE ACCEPTANCE MARKER')); const report=await page.locator('#print-report').textContent(); for(const marker of ['ROOT CAUSE','INPUT PATH','PREREQUISITE','MITIGATION']) assert.ok(report.includes(marker+' ACCEPTANCE MARKER')); assert.match(report,/Adversary simulation/,'print includes mission guidance'); console.log('PASS complete printed evidence and mission guidance'); await page.locator('#refresh-assessment').waitFor(); console.log('PASS refresh affordance exists'); await page.locator('#tab-missions').click(); await page.getByRole('button',{name:'Edit red workbook',exact:true}).click(); await page.locator('#workbook-owner').fill('Synthetic red owner'); await page.locator('#workbook-status').selectOption('complete'); await page.locator('#workbook-form button[type=submit]').click(); assert.equal(await page.locator('#workbook-dialog').evaluate(e=>e.open),true,'complete workbook needs evidence/result/decision'); for(const [key,value] of Object.entries({evidence:'Owned fixture revision 1',expected:'Expected benign signal',observed:'Observed synthetic signal',decision:'Synthetic control accepted'})) await page.locator('#workbook-'+key).fill(value); page.once('dialog',d=>d.dismiss());await page.locator('#workbook-dialog [data-close]').first().click(); assert.equal(await page.locator('#workbook-observed').inputValue(),'Observed synthetic signal','canceled workbook close preserves evidence'); await page.locator('#workbook-form button[type=submit]').click(); await page.locator('#workbook-dialog').waitFor({state:'hidden'}); assert.match(await page.locator('#assessment-panel').textContent(),/Synthetic red owner/); console.log('PASS five-hat workbook validation and persistence'); await page.locator('#tab-delivery').click(); await page.locator('#delivery-executive_summary').fill('Synthetic executive summary for the owned engagement.'); await page.locator('#delivery-business_impact').fill('Synthetic business impact, no customer data.'); await page.locator('#delivery-recommendations').fill('1. Validate the scoped control. 2. Retest the owned fixture.'); await page.locator('#delivery-form button[type=submit]').click(); await page.waitForFunction(()=>!document.querySelector('#delivery-form').hasAttribute('aria-busy')); const before=await page.evaluate(async id=>(await CyberLocal.request('/api/assessments/'+id)).assessment,fixture.id); assert.match(before.delivery.executive_summary,/Synthetic executive/); // Deliberately leave a draft while the second tab saves a newer review. await page.locator('#delivery-business_impact').fill('Unsaved local business impact draft.'); const second=await context.newPage();await second.goto(app);await second.waitForFunction(()=>!!window.CyberLocal); await second.evaluate(async({id,first})=>{const a=(await CyberLocal.request('/api/assessments/'+id)).assessment;const f=a.findings.find(f=>f.id===first);await CyberLocal.request(`/api/assessments/${id}/findings/${first}`,{method:'PATCH',body:{expected_revision:f.revision,verdict:'rejected',note:'Newer synthetic review from another tab.'}});},fixture); await page.bringToFront();await page.evaluate(()=>window.dispatchEvent(new Event('focus'))); await page.locator('#change-hint').waitFor(); assert.equal(await page.locator('#delivery-business_impact').inputValue(),'Unsaved local business impact draft.','change hint preserves drafts'); await page.locator('#delivery-form button[type=submit]').click();await page.locator('#reload-delivery').waitFor(); assert.equal(await page.locator('#delivery-business_impact').inputValue(),'Unsaved local business impact draft.','delivery conflict preserves draft'); await page.getByRole('button',{name:'Print executive report',exact:true}).click(); await page.waitForFunction(()=>document.querySelector('#print-report').textContent.includes('Newer synthetic review from another tab.')); assert.equal(await page.locator('#delivery-business_impact').inputValue(),'Unsaved local business impact draft.','fresh printing leaves unsaved delivery intact'); page.once('dialog',d=>d.dismiss());await page.locator('#refresh-assessment').click(); assert.equal(await page.locator('#delivery-business_impact').inputValue(),'Unsaved local business impact draft.','canceled refresh preserves draft'); page.once('dialog',d=>d.accept());await page.locator('#refresh-assessment').click(); await page.waitForFunction(()=>document.querySelector('#delivery-business_impact').value!=='Unsaved local business impact draft.'); await page.getByRole('button',{name:'Print executive report',exact:true}).click(); await page.waitForFunction(()=>document.querySelector('#print-report').textContent.includes('Newer synthetic review from another tab.')); assert.match(await page.locator('#print-report').textContent(),/Synthetic executive summary/); console.log('PASS cross-tab refresh preserves drafts and print uses latest saved data'); await page.locator('#continue-engagement').click(); const continued=await page.evaluate(async()=>{const rows=(await CyberLocal.request('/api/assessments')).assessments;for(const row of rows){const a=(await CyberLocal.request('/api/assessments/'+row.id)).assessment;if(a.continuation)return a;}}); assert.equal(continued.continuation.parent_id,fixture.id);assert.equal(continued.snapshots.length,0);assert.equal(continued.activity.length,1); assert.notEqual(continued.findings[0].id,fixture.first); console.log('PASS engagement continuation keeps provenance and starts fresh history'); await page.locator('#nav-overview').click(); await page.locator('#workspace-status').waitFor();assert.match(await page.locator('#workspace-status').textContent(),/100/); await page.getByRole('button',{name:'Recovery guide',exact:true}).click();await page.locator('#recovery-dialog').waitFor(); await page.locator('#recovery-dialog [data-close]').first().click(); const downloadWait=page.waitForEvent('download');await page.getByRole('button',{name:/Backup.*JSON/}).click();await downloadWait; assert.match(await page.locator('#workspace-status').textContent(),/Last backup export initiated/i); await page.evaluate(async()=>{ for(const client of ['Synthetic enterprise','Other enterprise']){ let a=(await CyberLocal.request('/api/assessments',{method:'POST',body:{name:client+' queue fixture',client,scope:'Owned fixture',workflow:'code',content:'eval(x)',roles:['white'],authorization:true}})).assessment; await CyberLocal.request(`/api/assessments/${a.id}/findings/${a.findings[0].id}`,{method:'PATCH',body:{expected_revision:0,verdict:'confirmed-static',note:'Synthetic owned fixture with complete analyst decision.',review:{reviewer:'Synthetic analyst',reference:'Owned revision1',prerequisites:'Owned input',mitigations:'Owned controls inspected',method:'Manually traced this owned synthetic input path.'},tracking:{owner:client+' owner',status:'in-progress',due_date:'2000-01-01',retest:''}}}); if(client==='Synthetic enterprise') for(let index=0;index<50;index++){ a=(await CyberLocal.request(`/api/assessments/${a.id}/findings`,{method:'POST',body:{title:'Pagination fixture '+index,severity:'low',location:'Owned fixture',root_cause:'Synthetic cause',input_to_impact:'Synthetic path',prerequisites:'Owned permission',mitigations:'Owned controls',evidence:'Synthetic evidence',remediation:'Synthetic recommendation'}})).assessment; const f=a.findings.at(-1);await CyberLocal.request(`/api/assessments/${a.id}/findings/${f.id}`,{method:'PATCH',body:{expected_revision:0,verdict:'confirmed-static',note:'Complete synthetic decision for pagination coverage.',review:{reviewer:'Synthetic analyst',reference:'Owned revision1',prerequisites:'Owned input',mitigations:'Owned controls inspected',method:'Manually traced this owned synthetic input path.'},tracking:{owner:client+' owner',status:'in-progress',due_date:'2000-01-01',retest:''}}}); } } }); await page.getByRole('button',{name:'Client remediation',exact:true}).click();await page.locator('#client-remediation').waitFor(); assert.equal(await page.getByRole('combobox',{name:'Filter workspace remediation by client'}).isVisible(),true); assert.match(await page.locator('#client-remediation').textContent(),/confirmed/i); await page.getByRole('combobox',{name:'Filter workspace remediation by client'}).selectOption('Synthetic enterprise'); const queueText=await page.locator('#client-remediation').textContent();assert.match(queueText,/Synthetic enterprise owner/);assert.doesNotMatch(queueText,/Other enterprise owner/);assert.doesNotMatch(queueText,/Print completeness fixture/); assert.equal(await page.locator('#client-remediation tbody tr').count(),50,'client queue bounds visible rows'); await page.getByRole('button',{name:'Next page',exact:true}).click();assert.equal(await page.locator('#client-remediation tbody tr').count(),1); await page.getByRole('combobox',{name:'Filter workspace remediation by client'}).selectOption('Other enterprise');assert.equal(await page.locator('#client-remediation tbody tr').count(),1,'client filter resets pagination'); await page.waitForFunction(()=>!document.querySelector('#notice').classList.contains('visible')); if(process.env.ARTIFACT_DIR){await page.screenshot({path:process.env.ARTIFACT_DIR+'/engagement-desktop.png',fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth+1),true);await page.screenshot({path:process.env.ARTIFACT_DIR+'/engagement-mobile.png',fullPage:true});} console.log('PASS client remediation, recovery guide, backup timestamp and mobile overflow'); await page.setViewportSize({width:1440,height:1000});await page.locator('#nav-overview').click(); await page.evaluate(()=>{CyberLocal.workspaceStatus=async()=>({count:null,approximate_bytes:null,usage:null,quota:null})}); await page.locator('#nav-overview').click();await page.waitForFunction(()=>document.querySelector('#workspace-status')?.textContent.includes('Unavailable')); assert.doesNotMatch(await page.locator('#workspace-status').textContent(),/serialized records: 0 bytes/,'unknown metadata must not look like zero usage'); console.log('PASS unavailable optional storage metadata remains distinct from zero usage (fault injection)'); const blocked=await browser.newContext(); await blocked.addInitScript(()=>{window.BroadcastChannel=class{constructor(){throw new DOMException('Synthetic blocked channel','SecurityError')}}}); const blockedPage=await blocked.newPage();const blockedErrors=[];blockedPage.on('pageerror',e=>blockedErrors.push(e.message));await blockedPage.goto(app);await blockedPage.getByRole('button',{name:'Create first assessment ↗',exact:true}).waitFor();assert.deepEqual(blockedErrors,[]);await blocked.close(); console.log('PASS optional channel policy denial does not prevent workspace startup'); await second.close(); assert.deepEqual(errors,[]);await context.close();}finally{await browser.close()}})().catch(error=>{console.error(error);process.exitCode=1});283 unmodified lines284285286287288289290291292293294295296297298299300301302303283 unmodified lines return { count: result.count, records: rows.length, freshId: restored.id !== source.id, snapshots: restored.snapshots || [] }; }, record); assert.deepEqual(legacyResult, { count: 1, records: 1, freshId: true, snapshots: [] }); const continuationRace = await legacyPage.evaluate(async () => { const store = new CyberLocal.IndexedDBStore(); const service = new CyberLocal.LocalService(store); const source = (await store.list())[0]; await store.update(source.id, row => { row.activity = Array.from({length:200}, (_,index)=>({at:row.created_at,action:'synthetic_history',note:'Owned fixture event '+index})); return row; }); const extras = Array.from({length:98}, (_,index)=>CyberLocal.analyze({name:'Synthetic capacity '+index,scope:'Owned fixture',workflow:'exercise',roles:['blue'],authorization:true,content:'Generic tabletop'})); await store.addMany(extras,100); const before = JSON.stringify(await store.get(source.id)); const results = await Promise.allSettled([service.request('/api/assessments/'+source.id+'/continue',{method:'POST',body:{expected_revision:source.revision||0}}),service.request('/api/assessments/'+source.id+'/continue',{method:'POST',body:{expected_revision:source.revision||0}})]); const rows = await store.list(); return {successes:results.filter(item=>item.status==='fulfilled').length,count:rows.length,sourceUnchanged:before===JSON.stringify(await store.get(source.id)),copies:rows.filter(row=>row.continuation?.parent_id===source.id).map(row=>({activity:row.activity.length,snapshots:row.snapshots.length}))}; }); assert.deepEqual(continuationRace,{successes:1,count:100,sourceUnchanged:true,copies:[{activity:1,snapshots:0}]}); console.log('PASS actual IndexedDB continuation at full history preserves source and concurrent capacity cannot exceed 100 records'); await legacyContext.close(); console.log('PASS legacy v1 backup restores into a fresh browser context'); assert.deepEqual(externalRequests, []);154 unmodified lines155156157158159160161154 unmodified lines const frozenText=await fs.readFile(await frozen.path(),'utf8'); assert.match(frozenText,/Newer synthetic analyst/); await page.getByRole('button',{name:'Print executive report',exact:true}).click(); await page.waitForFunction(()=>document.querySelector('#print-report').textContent.includes('Newer synthetic analyst')); await page.emulateMedia({media:'print'}); assert.equal(await page.locator('#print-report').isVisible(),true); assert.match(await page.locator('#print-report').innerText(),/Newer synthetic analyst|confirmed-static: 1/);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172{ "format": "napolean-cyber-command", "version": 2, "records": [ { "id": "b1ca56d6703e9f8ab712c382a37e4819", "name": "Legacy snapshot compatibility fixture", "client": "Unassigned", "workflow": "code", "scope": "Synthetic owned fixture", "created_at": "2026-11-02T12:45:06.127Z", "revision": 1, "roles": [ "white" ], "findings": [ { "id": "b5d34399524c41dca8f5edece6a18c95", "severity": "high", "confidence": "low", "verdict": "unresolved", "revision": 0, "origin": "heuristic", "title": "Possible dynamic Python evaluation", "location": "Submitted snippet line 1", "root_cause": "A direct eval/exec call-like pattern was observed after comment/string masking.", "input_to_impact": "Analyst must trace input control, reachability and business impact.", "prerequisites": "No syntax, scope, taint or reachability proof. Shadowed names or invalid code can produce false positives.", "mitigations": "Not evaluated. Inspect validation, authorization, isolation and compensating controls.", "evidence": "Lexical pattern matched; arguments and source text omitted.", "remediation": "Trace input reachability and builtin shadowing; replace dynamic evaluation with explicit parsing.", "review_note": "", "review": { "reviewer": "", "reference": "", "prerequisites": "", "mitigations": "", "method": "" }, "tracking": { "owner": "", "due_date": "", "status": "open", "retest": "" } } ], "missions": [ { "role": "white", "title": "Independent application review", "objective": "Validate source-level candidates and document remediation. Workflow: code.", "steps": [ "Review the 1 unresolved ledger candidate(s), inspect source in your controlled system and trace input reachability.", "Trace inputs through authentication, authorization and trust boundaries.", "Attempt to refute each candidate using validation, reachability and compensating controls.", "Record a verdict with evidence and a scoped regression test before declaring a fix." ], "deliverable": "An evidence-backed review ledger and remediation checklist.", "limitations": [ "Planning guidance only; requires a qualified analyst and separate approval for live actions.", "No executable agents, scanners, model inference or upstream security tools are running." ] } ], "scenario_category": null, "summary": "1 unresolved candidate(s) from limited browser-local checks. Human validation required; this is not a security certification.", "coverage": [ "Limited lexical regex/pattern nomination: quoted strings/comments masked for call detection, direct eval/exec, simple subprocess import aliases and bounded multiline literal shell=True arguments.", "No Python AST or syntax parser, scope/rebinding resolution, taint/dataflow, dependency audit, execution or exploit validation. Wildcard/dynamic imports, f-string expressions, complex assignments and computed shell flags may be missed.", "Maximum 500 call-like constructs, 8192 characters per subprocess call and 100 candidates. No matches do not establish security; manual review is required." ], "activity": [ { "at": "2026-11-02T12:45:06.128Z", "action": "created", "note": "Scope authorization attested; bounded local analysis completed. Raw submission discarded." }, { "at": "2026-11-02T12:45:06.136Z", "action": "report_snapshot_created", "note": "a8bb2bbaf0021f4d49553ef1323006a6: report version 1; source revision 0; SHA-256 fb880be317d7937185bafad10bd058aab57d58332ecc54eba379d9c859cabec3. Digest detects corruption, not authorship." } ], "snapshots": [ { "id": "a8bb2bbaf0021f4d49553ef1323006a6", "version": 1, "created_at": "2026-11-02T12:45:06.130Z", "source_revision": 0, "sha256": "fb880be317d7937185bafad10bd058aab57d58332ecc54eba379d9c859cabec3", "data": { "id": "b1ca56d6703e9f8ab712c382a37e4819", "name": "Legacy snapshot compatibility fixture", "client": "Unassigned", "workflow": "code", "scope": "Synthetic owned fixture", "created_at": "2026-11-02T12:45:06.127Z", "revision": 0, "roles": [ "white" ], "findings": [ { "id": "b5d34399524c41dca8f5edece6a18c95", "severity": "high", "confidence": "low", "verdict": "unresolved", "revision": 0, "origin": "heuristic", "title": "Possible dynamic Python evaluation", "location": "Submitted snippet line 1", "root_cause": "A direct eval/exec call-like pattern was observed after comment/string masking.", "input_to_impact": "Analyst must trace input control, reachability and business impact.", "prerequisites": "No syntax, scope, taint or reachability proof. Shadowed names or invalid code can produce false positives.", "mitigations": "Not evaluated. Inspect validation, authorization, isolation and compensating controls.", "evidence": "Lexical pattern matched; arguments and source text omitted.", "remediation": "Trace input reachability and builtin shadowing; replace dynamic evaluation with explicit parsing.", "review_note": "", "review": { "reviewer": "", "reference": "", "prerequisites": "", "mitigations": "", "method": "" }, "tracking": { "owner": "", "due_date": "", "status": "open", "retest": "" } } ], "missions": [ { "role": "white", "title": "Independent application review", "objective": "Validate source-level candidates and document remediation. Workflow: code.", "steps": [ "Review the 1 unresolved ledger candidate(s), inspect source in your controlled system and trace input reachability.", "Trace inputs through authentication, authorization and trust boundaries.", "Attempt to refute each candidate using validation, reachability and compensating controls.", "Record a verdict with evidence and a scoped regression test before declaring a fix." ], "deliverable": "An evidence-backed review ledger and remediation checklist.", "limitations": [ "Planning guidance only; requires a qualified analyst and separate approval for live actions.", "No executable agents, scanners, model inference or upstream security tools are running." ] } ], "scenario_category": null, "summary": "1 unresolved candidate(s) from limited browser-local checks. Human validation required; this is not a security certification.", "coverage": [ "Limited lexical regex/pattern nomination: quoted strings/comments masked for call detection, direct eval/exec, simple subprocess import aliases and bounded multiline literal shell=True arguments.", "No Python AST or syntax parser, scope/rebinding resolution, taint/dataflow, dependency audit, execution or exploit validation. Wildcard/dynamic imports, f-string expressions, complex assignments and computed shell flags may be missed.", "Maximum 500 call-like constructs, 8192 characters per subprocess call and 100 candidates. No matches do not establish security; manual review is required." ], "activity": [ { "at": "2026-11-02T12:45:06.128Z", "action": "created", "note": "Scope authorization attested; bounded local analysis completed. Raw submission discarded." } ] } } ] } ]}22 unmodified lines2324252627282930313233343536459 unmodified lines49649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464522 unmodified lines for(const row of records) this.rows.set(row.id,structuredClone(row)); return records; }); } continueFrom(sourceId,expected,maximum,buildCopy) {return this.write(()=>{ const source=this.rows.get(sourceId); if(!source) throw new Error('Assessment not found.'); if((source.revision||0)!==expected){const error=new Error('Source changed; reload before continuing.');error.code='CONFLICT';throw error;} if(this.rows.size>=maximum) throw new Error('100 assessment limit'); const record=buildCopy(structuredClone(source)); this.rows.set(record.id,structuredClone(record));return structuredClone(record); });} update(id, fn) { return this.write(() => { if (!this.rows.has(id)) throw new Error('Assessment not found.'); const next = fn(structuredClone(this.rows.get(id)));459 unmodified lines assert.equal(restored.activity.length,record.activity.length); assert.equal(restored.summary,record.summary);});
test('current imported confirmations require substantive decision notes and frozen incomplete claims reject',async()=>{ const store=new MemoryStore(),service=new LocalService(store),record=analyze(payload()); record.findings[0].verdict='confirmed-static';record.findings[0].review=evidence();record.findings[0].review_note='short'; const envelope=rows=>JSON.stringify({format:'napolean-cyber-command',version:2,records:rows}); await service.restoreBackup(envelope([record])); assert.equal((await store.list())[0].findings[0].verdict,'unresolved'); const fresh=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment; await service.request(`/api/assessments/${fresh.id}/findings/${fresh.findings[0].id}`,{method:'PATCH',body:{expected_revision:0,verdict:'confirmed-static',note:'Substantive source review decision.',review:evidence()}}); await service.createSnapshot(fresh.id,1); const backup=JSON.parse(await service.backupText()); backup.records.find(row=>row.id===fresh.id).snapshots[0].data.findings[0].review_note=''; const before=await store.list(); assert.throws(()=>previewBackup(JSON.stringify(backup)),/note|evidence|confirmation/i); await assert.rejects(service.restoreBackup(JSON.stringify(backup)),/note|evidence|confirmation/i); assert.deepEqual(await store.list(),before);});
test('role workbooks enforce completeness, redaction and assessment revision CAS',async()=>{ const store=new MemoryStore(),service=new LocalService(store); const initial=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment; assert.equal(initial.workbook.length,5);assert.ok(initial.workbook.every(entry=>entry.status==='planned')); const path=`/api/assessments/${initial.id}/workbook`; const entry={...initial.workbook[0],owner:'Analyst A',status:'complete',evidence:'Owned test evidence revision 123',expected:'Expected defensive signal',observed:'Observed signal in the owned fixture',decision:'Evidence supports the scoped result.'}; for(const change of [{evidence:''},{observed:''},{decision:''},{status:'done'},{owner:'X'.repeat(121)},{role:'admin'}]) { await assert.rejects(service.request(path,{method:'PATCH',body:{expected_revision:0,entry:{...entry,...change}}})); assert.deepEqual(await store.get(initial.id),initial); } const updated=(await service.request(path,{method:'PATCH',body:{expected_revision:0,entry:{...entry,evidence:'Authorization: Bearer private-token-workbook'}}})).assessment; assert.equal(updated.revision,1);assert.equal(updated.workbook[0].status,'complete'); assert.doesNotMatch(JSON.stringify(updated),/private-token-workbook/); const before=await store.get(initial.id); await assert.rejects(service.request(path,{method:'PATCH',body:{expected_revision:0,entry}}),error=>error.code==='CONFLICT'); assert.deepEqual(await store.get(initial.id),before); const snapshot=await service.createSnapshot(initial.id,1); assert.deepEqual(snapshot.snapshot.data.workbook,updated.workbook); assert.match(await service.exportText(initial.id,'markdown'),/Role workbook|Five-hat workbook/i); assert.match(await service.exportText(initial.id,'markdown'),/Expected defensive signal/); assert.equal(previewBackup(await service.backupText()).count,1);});
test('actual previous-release historical snapshot hashes remain unchanged through new normalization and backups',async()=>{ const fs=require('node:fs'); const fixture=JSON.parse(fs.readFileSync(require('node:path').join(__dirname,'legacy-snapshot.json'),'utf8')); const old=fixture.records[0].snapshots[0],store=new MemoryStore(),service=new LocalService(store); assert.equal(Object.hasOwn(old.data,'workbook'),false);assert.equal(Object.hasOwn(old.data,'delivery'),false); await service.restoreBackup(JSON.stringify(fixture)); const first=(await store.list())[0]; const exported=JSON.parse(await service.exportSnapshot(first.id,old.id,'json')); assert.equal(exported.sha256,old.sha256);assert.deepEqual(exported.data,old.data); const live=(await service.request('/api/assessments/'+first.id)).assessment; assert.equal(live.workbook.length,live.roles.length); await service.restoreBackup(await service.backupText()); const copy=(await store.list()).find(row=>row.id!==first.id); const second=JSON.parse(await service.exportSnapshot(copy.id,old.id,'json')); assert.equal(second.sha256,old.sha256);assert.deepEqual(second.data,old.data);});
test('continuation atomically creates a fresh linked current-state copy while a full source remains unchanged',async()=>{ const store=new MemoryStore(),service=new LocalService(store); const initial=(await service.request('/api/assessments',{method:'POST',body:payload({client:'Client A'})})).assessment; await service.request(`/api/assessments/${initial.id}/findings/${initial.findings[0].id}`,{method:'PATCH',body:{expected_revision:0,verdict:'confirmed-static',note:'Scoped source review with complete evidence.',review:evidence(),tracking:{owner:'Fix owner',status:'in-progress',due_date:'2027-01-01',retest:'Retest pending'}}}); await service.createSnapshot(initial.id,1); await store.update(initial.id,row=>{row.activity=Array.from({length:200},()=>({at:row.created_at,action:'review',note:'Keep original source history'}));return row;}); const source=await store.get(initial.id); const continued=(await service.request(`/api/assessments/${initial.id}/continue`,{method:'POST',body:{expected_revision:source.revision}})).assessment; assert.deepEqual(await store.get(initial.id),source); assert.notEqual(continued.id,source.id);assert.equal(continued.revision,0); assert.deepEqual(continued.continuation,{parent_id:source.id,parent_revision:source.revision}); assert.equal(continued.activity.length,1);assert.equal(continued.activity[0].action,'continuation_created'); assert.deepEqual(continued.snapshots,[]);assert.equal(continued.client,'Client A');assert.deepEqual(continued.workbook,source.workbook); assert.notEqual(continued.findings[0].id,source.findings[0].id);assert.equal(continued.findings[0].revision,0); assert.equal(continued.findings[0].verdict,'confirmed-static');assert.deepEqual(continued.findings[0].tracking,source.findings[0].tracking); assert.match(await service.exportText(continued.id,'markdown'),new RegExp(source.id)); assert.equal(previewBackup(await service.backupText()).count,2);});
test('continuation stale CAS and concurrent capacity failures leave source and register unchanged',async()=>{ const store=new MemoryStore(),service=new LocalService(store); const initial=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment; const path=`/api/assessments/${initial.id}/continue`; for(const expected_revision of [undefined,-1,'0',1]) await assert.rejects(service.request(path,{method:'POST',body:{expected_revision}}),error=>error.code==='CONFLICT'); assert.equal((await store.list()).length,1); for(let index=0;index<98;index++) await store.add(analyze(payload({content:'print(1)'})),100); const source=await store.get(initial.id); const results=await Promise.allSettled([1,2].map(()=>service.request(path,{method:'POST',body:{expected_revision:0}}))); assert.equal(results.filter(result=>result.status==='fulfilled').length,1); assert.equal((await store.list()).length,100);assert.deepEqual(await store.get(initial.id),source);});
test('analyst delivery is bounded, redacted, revision-guarded and carried by reports, snapshots and continuation',async()=>{ const store=new MemoryStore(),service=new LocalService(store); const initial=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment; assert.deepEqual(initial.delivery,{executive_summary:'',business_impact:'',recommendations:''}); const delivery={executive_summary:'Reviewed a scoped access-control candidate.',business_impact:'Potential access to a synthetic customer record.',recommendations:'Validate ownership checks, then add regression coverage.'}; const path=`/api/assessments/${initial.id}/delivery`; for(const invalid of [{...delivery,html:'<script>bad</script>'},{...delivery,business_impact:null},{...delivery,recommendations:'X'.repeat(4001)}]) { await assert.rejects(service.request(path,{method:'PATCH',body:{expected_revision:0,delivery:invalid}})); assert.deepEqual(await store.get(initial.id),initial); } const current=(await service.request(path,{method:'PATCH',body:{expected_revision:0,delivery}})).assessment; assert.equal(current.revision,1);assert.deepEqual(current.delivery,delivery); await assert.rejects(service.request(path,{method:'PATCH',body:{expected_revision:0,delivery}}),error=>error.code==='CONFLICT'); const report=await service.exportText(initial.id,'markdown');assert.match(report,/synthetic customer record/);assert.match(report,/regression coverage/); const snapshot=await service.createSnapshot(initial.id,1);assert.deepEqual(snapshot.snapshot.data.delivery,delivery); const continued=(await service.request(`/api/assessments/${initial.id}/continue`,{method:'POST',body:{expected_revision:2}})).assessment; assert.deepEqual(continued.delivery,delivery); const redacted=(await service.request(`/api/assessments/${continued.id}/delivery`,{method:'PATCH',body:{expected_revision:0,delivery:{...delivery,business_impact:'password="Synthetic secret value"'}}})).assessment; assert.doesNotMatch(JSON.stringify(redacted),/Synthetic secret value/); assert.equal(previewBackup(await service.backupText()).count,2);});
test('workspace status reports approximate local bytes and treats estimate or metadata failures as unavailable',async()=>{ const store=new MemoryStore(),service=new LocalService(store); assert.deepEqual(await service.workspaceStatus(),{count:0,approximate_bytes:0,usage:null,quota:null}); const record=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment; const descriptor=Object.getOwnPropertyDescriptor(globalThis,'navigator'); try { Object.defineProperty(globalThis,'navigator',{configurable:true,value:{storage:{estimate:async()=>({usage:12345,quota:98765})}}}); const result=await service.workspaceStatus(); assert.equal(result.count,1);assert.equal(result.approximate_bytes,Buffer.byteLength(JSON.stringify(record))); assert.equal(result.usage,12345);assert.equal(result.quota,98765); globalThis.navigator.storage.estimate=async()=>{throw new Error('Privacy mode denial');}; const denied=await service.workspaceStatus();assert.equal(denied.count,1);assert.equal(denied.usage,null);assert.equal(denied.quota,null); const broken=new LocalService({list:async()=>{throw new Error('Metadata unavailable');}}); assert.deepEqual(await broken.workspaceStatus(),{count:null,approximate_bytes:null,usage:null,quota:null}); } finally { if(descriptor) Object.defineProperty(globalThis,'navigator',descriptor);else delete globalThis.navigator; }});
test('malformed optional engagement fields reject atomically and missing fields stay absent in historical hashes',async()=>{ const store=new MemoryStore(),service=new LocalService(store),record=analyze(payload()); const envelope=row=>JSON.stringify({format:'napolean-cyber-command',version:2,records:[row]}); for(const mutate of [row=>row.workbook[0].role='admin',row=>row.workbook[0].status='complete', row=>row.workbook.push({...row.workbook[0]}),row=>row.delivery={html:'<script>bad</script>'}, row=>row.continuation={parent_id:row.id,parent_revision:0},row=>row.continuation={parent_id:'a'.repeat(32),parent_revision:-1}, row=>row.continuation={parent_id:'invalid',parent_revision:0}]) { const invalid=structuredClone(record);mutate(invalid); await assert.rejects(service.restoreBackup(envelope(invalid))); assert.equal((await store.list()).length,0); } const legacy=structuredClone(record);delete legacy.workbook;delete legacy.delivery; await service.restoreBackup(envelope(legacy)); const live=(await service.request('/api/assessments/'+(await store.list())[0].id)).assessment; assert.equal(live.workbook.length,live.roles.length);assert.deepEqual(live.delivery,{executive_summary:'',business_impact:'',recommendations:''});});IMPROVEMENTS.md+10
README.md+6
SECURITY.md+6
SERVICE.md+6
SOURCE-MANIFEST.json+19-15
VERIFICATION.md+12
deploy_hf.py+2-1
docs/superpowers/plans/2026-11-02-engagement-workflows.mdAdded+17
docs/superpowers/specs/2026-11-02-engagement-workflows-design.mdAdded+14
index.html+105-4
static/app.js+299-8
static/index.html+105-4
static/local.js+140-6
static/style.css+7
tests/browser_engagement.cjsAdded+110
tests/browser_storage.cjs+14
tests/browser_ui.cjs+1
tests/legacy-snapshot.jsonAdded+172
tests/test_local.cjs+155